/** * 0xio Wallet SDK - Type Definitions * Comprehensive type system for 0xio wallet integration with Octra Network */ interface WalletAddress { readonly address: string; readonly publicKey?: string; } interface Balance { readonly public: number; readonly private?: number; readonly total: number; readonly currency: 'OCT'; } interface NetworkInfo { readonly id: string; readonly name: string; readonly rpcUrl: string; readonly explorerUrl?: string; readonly explorerAddressUrl?: string; readonly indexerUrl?: string; readonly supportsPrivacy: boolean; readonly color: string; readonly isTestnet: boolean; } interface TransactionData { readonly to: string; readonly amount: number; readonly message?: string; readonly feeLevel?: 1 | 3; readonly isPrivate?: boolean; } /** * Contract method arguments — flat array of AML-compatible values. * Supports primitives and base64-encoded binary data (e.g. FHE ciphers, proofs). * Use `[arg1, arg2]` NOT `[[arg1, arg2]]` — flat, not nested. */ type ContractParam = string | number | boolean; type ContractParams = ReadonlyArray; interface ContractCallData { /** Contract address (oct-prefixed, 47 chars) */ readonly contract: string; /** Contract method name (e.g. 'swap', 'open_private_account') */ readonly method: string; /** * Method arguments — flat primitives, NOT array-wrapped. * For FHE/PVAC operations, encode binary data as base64 strings: * `[base64(pvacPubkey), base64(zeroCipher), base64(zeroProof)]` */ readonly params: ContractParams; /** * Native OCT to send with the call (in micro-units, 1 OCT = 1000000). * Set to 0 for calls that don't transfer native tokens. */ readonly amount?: string | number; /** * Operation units / gas limit (default: 10000). * Higher values for complex contract operations. * The approval popup shows this as the fee, separate from `amount`. */ readonly ou?: string | number; } interface ContractViewCallData { /** Contract address (oct-prefixed, 47 chars) */ readonly contract: string; /** Contract method name (e.g. 'balance_of', 'get_active_bin', 'is_paused') */ readonly method: string; /** Method arguments — flat primitives, NOT array-wrapped */ readonly params: ContractParams; /** Caller address for view context (defaults to connected wallet) */ readonly caller?: string; } interface SignedTransaction { readonly from: string; readonly to_: string; readonly amount: string; readonly nonce: string; readonly ou: string; readonly timestamp: string; readonly message?: string; readonly signature: string; readonly public_key: string; } type TransactionFinality = 'pending' | 'confirmed' | 'rejected'; interface TransactionResult { readonly txHash: string; readonly success: boolean; readonly finality?: TransactionFinality; readonly message?: string; readonly explorerUrl?: string; } interface TransactionHistory { readonly transactions: Transaction[]; readonly totalCount: number; readonly page: number; readonly hasMore: boolean; } interface Transaction { readonly hash: string; readonly from: string; readonly to: string; readonly amount: number; readonly fee: number; readonly timestamp: number; readonly status: 'pending' | 'confirmed' | 'failed'; readonly finality?: TransactionFinality; readonly message?: string; readonly blockHeight?: number; } interface ConnectionInfo { isConnected: boolean; address?: string; publicKey?: string; balance?: Balance; networkInfo?: NetworkInfo; connectedAt?: number; } interface ConnectOptions { readonly requestPermissions?: Permission[]; readonly networkId?: string; } type Permission = 'read_address' | 'read_balance' | 'send_transactions' | 'sign_messages' | 'view_private_balance' | 'private_transfers'; type WalletEventType = 'connect' | 'disconnect' | 'accountChanged' | 'balanceChanged' | 'networkChanged' | 'transactionConfirmed' | 'error' | 'extensionLocked' | 'extensionUnlocked'; interface WalletEvent { readonly type: WalletEventType; readonly data: T; readonly timestamp: number; } interface ConnectEvent { readonly address: string; readonly publicKey?: string; readonly balance: Balance; readonly networkInfo: NetworkInfo; readonly permissions: Permission[]; } interface DisconnectEvent { readonly reason: 'user_action' | 'extension_unavailable' | 'network_error' | 'extension_locked'; } interface AccountChangedEvent { readonly previousAddress?: string; readonly newAddress: string; readonly balance: Balance; } interface BalanceChangedEvent { readonly address: string; readonly previousBalance: Balance | undefined; readonly newBalance: Balance; } interface NetworkChangedEvent { readonly previousNetwork?: NetworkInfo; readonly newNetwork: NetworkInfo; } interface TransactionConfirmedEvent { readonly transaction: Transaction; } interface ErrorEvent { readonly code: ErrorCode; readonly message: string; readonly details?: any; } declare enum ErrorCode { EXTENSION_NOT_FOUND = "EXTENSION_NOT_FOUND", CONNECTION_REFUSED = "CONNECTION_REFUSED", USER_REJECTED = "USER_REJECTED", INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE", INVALID_ADDRESS = "INVALID_ADDRESS", INVALID_AMOUNT = "INVALID_AMOUNT", NETWORK_ERROR = "NETWORK_ERROR", TRANSACTION_FAILED = "TRANSACTION_FAILED", SIGNATURE_FAILED = "SIGNATURE_FAILED", PERMISSION_DENIED = "PERMISSION_DENIED", WALLET_LOCKED = "WALLET_LOCKED", RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED", UNKNOWN_ERROR = "UNKNOWN_ERROR", MALFORMED_TRANSACTION = "MALFORMED_TRANSACTION", SELF_TRANSFER = "SELF_TRANSFER", SENDER_NOT_FOUND = "SENDER_NOT_FOUND", INVALID_SIGNATURE = "INVALID_SIGNATURE", DUPLICATE_TRANSACTION = "DUPLICATE_TRANSACTION", NONCE_TOO_FAR = "NONCE_TOO_FAR", INTERNAL_ERROR = "INTERNAL_ERROR" } declare class ZeroXIOWalletError extends Error { readonly code: ErrorCode; readonly details?: any | undefined; constructor(code: ErrorCode, message: string, details?: any | undefined); } interface PrivateBalanceInfo { readonly hasPrivateBalance: boolean; readonly encryptedAmount?: string; readonly canDecrypt: boolean; } interface PrivateTransferData { readonly to: string; readonly amount: number; readonly message?: string; } interface PendingPrivateTransfer { readonly id: string; readonly from: string; readonly encryptedAmount: string; readonly message?: string; readonly timestamp: number; readonly canClaim: boolean; } interface SDKConfig { readonly appName: string; readonly appDescription?: string; readonly appVersion?: string; readonly appUrl?: string; readonly appIcon?: string; readonly requiredPermissions?: Permission[]; readonly networkId?: string; readonly debug?: boolean; } interface ExtensionRequest { readonly id: string; readonly method: string; readonly params: any; readonly timestamp: number; } interface ExtensionResponse { readonly id: string; readonly success: boolean; readonly data?: T; readonly error?: { code: ErrorCode; message: string; details?: any; }; readonly timestamp: number; } /** * 0xio Wallet SDK - Event System * Type-safe event emitter for wallet events */ type EventListener = (event: WalletEvent) => void; declare class EventEmitter { private listeners; private debug; constructor(debug?: boolean); /** * Add event listener */ on(eventType: WalletEventType, listener: EventListener): void; /** * Remove event listener */ off(eventType: WalletEventType, listener: EventListener): void; /** * Add one-time event listener */ once(eventType: WalletEventType, listener: EventListener): void; /** * Emit event to all listeners */ emit(eventType: WalletEventType, data: T): void; /** * Remove all listeners for a specific event type */ removeAllListeners(eventType?: WalletEventType): void; /** * Get number of listeners for an event type */ listenerCount(eventType: WalletEventType): number; /** * Get all event types that have listeners */ eventTypes(): WalletEventType[]; /** * Check if there are any listeners for an event type */ hasListeners(eventType: WalletEventType): boolean; } /** * 0xio Wallet SDK - Main Wallet Class * Primary interface for DApp developers to interact with 0xio Wallet */ declare class ZeroXIOWallet extends EventEmitter { private communicator; private config; private connectionInfo; private isInitialized; private logger; constructor(config: SDKConfig); /** * Initialize the SDK * Must be called before using any other methods */ initialize(): Promise; /** * Check if SDK is initialized */ isReady(): boolean; /** * Connect to wallet */ connect(options?: ConnectOptions): Promise; /** * Disconnect from wallet */ disconnect(): Promise; /** * Check if connected to wallet */ isConnected(): boolean; /** * Get current connection info */ getConnectionInfo(): ConnectionInfo; /** * Check connection status with extension */ getConnectionStatus(): Promise; /** * Switch the extension's active network (e.g. 'mainnet' → 'devnet'). * Works silently — no popup, no user confirmation needed. * The extension broadcasts 'networkChanged' event to all connected dApps. */ switchNetwork(networkId: string): Promise<{ network: string; switched: boolean; }>; /** * Get the extension's current network ID ('mainnet' or 'devnet') */ getNetworkId(): string | null; /** * Get current wallet address */ getAddress(): string | null; /** * Get current balance */ getBalance(forceRefresh?: boolean): Promise; /** * Get network information */ getNetworkInfo(): Promise; /** * Send transaction */ sendTransaction(txData: TransactionData): Promise; /** * Call a smart contract method (state-changing). * The extension builds, signs, and submits the transaction via octra_submit. */ callContract(callData: ContractCallData): Promise; /** * Read-only contract view call (no signing, no approval popup). * Use this to query contract state without submitting a transaction. */ contractCallView(viewData: ContractViewCallData): Promise; /** * Read contract storage by key. */ getContractStorage(contract: string, key: string): Promise; /** * Get transaction history */ getTransactionHistory(page?: number, limit?: number): Promise; /** * Get private balance information */ getPrivateBalanceInfo(): Promise; /** * Encrypt public balance to private */ encryptBalance(amount: number): Promise; /** * Decrypt private balance to public */ decryptBalance(amount: number): Promise; /** * Send a private (encrypted) transfer to another address. * The extension builds the PVAC ciphertext subtraction + range proof + zero proof, * then submits the encrypted transaction to the network. The recipient's encrypted * balance is updated by the node using re-encryption under their public key. * Requires 'private_transfers' permission. * @since 2.6.0 */ sendPrivateTransfer(transferData: PrivateTransferData): Promise; /** * Get pending private transfers that can be claimed by this wallet. * Returns transfers where the connected address is the recipient. * @since 2.6.0 */ getPendingPrivateTransfers(): Promise; /** * Claim a pending private transfer, adding it to the wallet's encrypted balance. * @since 2.6.0 */ claimPrivateTransfer(transferId: string): Promise; /** * Sign an arbitrary message with the wallet's private key * The user will be prompted to approve the signature request in the extension * @param message - The message to sign (non-empty string) * @returns Promise resolving to the base64-encoded Ed25519 signature * @throws ZeroXIOWalletError with code SIGNATURE_FAILED if signing fails * @example * ```typescript * const signature = await wallet.signMessage('Hello, 0xio!'); * console.log('Signature:', signature); * ``` */ signMessage(message: string): Promise; private ensureInitialized; private ensureConnected; private setupExtensionEventListeners; /** * Handle account changed event from extension */ private handleAccountChanged; /** * Handle network changed event from extension */ private handleNetworkChanged; /** * Handle balance changed event from extension */ private handleBalanceChanged; /** * Handle extension locked event */ private handleExtensionLocked; /** * Handle extension unlocked event */ private handleExtensionUnlocked; /** * Handle transaction confirmed event */ private handleTransactionConfirmed; /** * Clean up SDK resources */ cleanup(): void; } /** * 0xio Wallet SDK - Extension Communication Module * * @fileoverview Manages secure communication between the SDK and browser extension. * Implements message passing, request/response handling, rate limiting, and origin validation * to ensure secure wallet interactions. * * @module communication * @version 2.6.0 * @license MIT */ /** * ExtensionCommunicator - Manages communication with the 0xio Wallet browser extension * * @class * @extends EventEmitter * * @description * Handles all communication between the SDK and wallet extension including: * - Request/response message passing with origin validation * - Rate limiting to prevent DoS attacks * - Automatic retry logic with exponential backoff * - Extension detection and availability monitoring * - Cryptographically secure request ID generation * * @example * ```typescript * const communicator = new ExtensionCommunicator(true); // debug mode * await communicator.initialize(); * * const response = await communicator.sendRequest('get_balance', {}); * console.log(response); * ``` */ declare class ExtensionCommunicator extends EventEmitter { /** Legacy request counter (deprecated, kept for fallback) */ private requestId; /** Map of pending requests awaiting responses */ private pendingRequests; /** Initialization state flag */ private isInitialized; /** Logger instance for debugging */ private logger; /** Interval handle for periodic extension detection */ private extensionDetectionInterval; /** Current extension availability state */ private isExtensionAvailableState; /** Message listener reference for cleanup */ private messageListener; /** Trusted parent origins for iframe communication */ private trustedOrigins; /** Parent origin learned from walletReady signal */ private _parentOrigin; /** Maximum number of concurrent pending requests */ private readonly MAX_CONCURRENT_REQUESTS; /** Time window for rate limiting (milliseconds) */ private readonly RATE_LIMIT_WINDOW; /** Maximum requests allowed per time window */ private readonly MAX_REQUESTS_PER_WINDOW; /** Timestamps of recent requests for rate limiting */ private requestTimestamps; /** * Creates a new ExtensionCommunicator instance * * @param {boolean} debug - Enable debug logging */ constructor(debug?: boolean, trustedOrigins?: string[]); /** * Add trusted origins for iframe/bridge communication * Call this before connecting if your dApp runs inside a trusted frame */ setTrustedOrigins(origins: string[]): void; /** * Initialize communication with the wallet extension * * @description * Performs initial setup and verification: * 1. Waits for extension to become available * 2. Sends ping to verify communication * 3. Establishes message handlers * * Must be called before any other methods. * * @returns {Promise} True if initialization succeeded, false otherwise * @throws {ZeroXIOWalletError} If extension is not available after timeout * * @example * ```typescript * const success = await communicator.initialize(); * if (!success) { * console.error('Failed to initialize wallet connection'); * } * ``` */ initialize(): Promise; /** * Check if extension is available */ isExtensionAvailable(): boolean; private static readonly NO_RETRY_METHODS; /** * Send request to extension */ sendRequest(method: string, params?: any, timeout?: number): Promise; /** * Send request to extension with automatic retry logic */ sendRequestWithRetry(method: string, params?: any, maxRetries?: number, timeout?: number): Promise; /** * Setup message listener for responses from extension */ private setupMessageListener; /** * Handle extension event */ private handleExtensionEvent; /** * Handle response from extension */ private handleExtensionResponse; /** * Post message to extension via content script */ private postMessageToExtension; /** * Check if we're in a context that can communicate with extension */ private hasExtensionContext; /** * Check and enforce rate limits to prevent denial-of-service attacks * * @private * @throws {ZeroXIOWalletError} RATE_LIMIT_EXCEEDED if limits are exceeded * * @description * Implements two-tier rate limiting: * 1. Concurrent requests: Maximum 50 pending requests at once * 2. Request frequency: Maximum 20 requests per second * * Rate limiting protects both the SDK and extension from: * - Accidental infinite loops in dApp code * - Malicious DoS attacks * - Resource exhaustion * * @security Critical security function - enforces resource limits */ private checkRateLimit; /** * Generate cryptographically secure unique request ID * * @private * @returns {string} A unique, unpredictable request identifier * * @description * Uses Web Crypto API for secure random ID generation: * 1. Primary: crypto.randomUUID() - UUID v4 format * 2. Fallback: crypto.getRandomValues() - 128-bit random hex * 3. Last resort: timestamp + counter (logs warning) * * Security importance: * - Prevents request ID prediction attacks * - Mitigates replay attacks * - Makes session hijacking more difficult * * @security Critical - IDs must be cryptographically unpredictable */ private generateRequestId; /** * Start continuous extension detection */ private startExtensionDetection; /** * Check if extension is currently available */ private checkExtensionAvailability; /** * Detect extension signals/indicators */ private detectExtensionSignals; /** * Wait for extension to become available */ private waitForExtensionAvailability; /** * Get browser diagnostics for error reporting */ private getBrowserDiagnostics; /** * Get extension state diagnostics */ private getExtensionDiagnostics; /** * Cleanup pending requests */ cleanup(): void; /** * Get debug information */ getDebugInfo(): { initialized: boolean; available: boolean; pendingRequests: number; hasExtensionContext: boolean; extensionDiagnostics: any; }; } /** * Network configuration for 0xio SDK */ declare const NETWORKS: Record; declare const DEFAULT_NETWORK_ID = "mainnet"; /** * Get network configuration by ID */ declare function getNetworkConfig(networkId?: string): NetworkInfo; /** * Get all available networks */ declare function getAllNetworks(): NetworkInfo[]; /** * Check if network ID is valid */ declare function isValidNetworkId(networkId: string): boolean; /** * Default balance structure */ declare function createDefaultBalance(total?: number): Balance; /** * SDK Configuration constants */ declare const SDK_CONFIG: { readonly version: "2.6.0"; readonly defaultNetworkId: "mainnet"; readonly communicationTimeout: 30000; readonly retryAttempts: 3; readonly retryDelay: 1000; }; /** * Get default network configuration */ declare function getDefaultNetwork(): NetworkInfo; /** * 0xio Wallet SDK - Utilities * Helper functions for validation, formatting, and common operations */ /** * Validate wallet address for Octra blockchain */ declare function isValidAddress(address: string): boolean; /** * Validate transaction amount */ declare function isValidAmount(amount: number): boolean; /** * Validate transaction message */ declare function isValidMessage(message: string): boolean; /** * Validate fee level */ declare function isValidFeeLevel(feeLevel: number): boolean; /** * Format OCT amount for display */ declare function formatOCT(amount: number, decimals?: number): string; /** * Format address for display (truncated) */ declare function formatAddress(address: string, prefixLength?: number, suffixLength?: number): string; /** * Format timestamp for display */ declare function formatTimestamp(timestamp: number): string; /** * Format transaction hash for display */ declare function formatTxHash(hash: string, length?: number): string; /** * Convert OCT to micro OCT (for network transmission) */ declare function toMicroOCT(amount: number): string; /** * Convert micro OCT to OCT (for display) */ declare function fromMicroOCT(microAmount: string | number): number; /** * Create standardized error messages */ declare function createErrorMessage(code: ErrorCode, context?: string): string; /** * Check if error is a specific type */ declare function isErrorType(error: any, code: ErrorCode): boolean; /** * Create a promise that resolves after a delay */ declare function delay(ms: number): Promise; /** * Retry an async operation with exponential backoff */ declare function retry(operation: () => Promise, maxRetries?: number, baseDelay?: number): Promise; /** * Timeout wrapper for promises */ declare function withTimeout(promise: Promise, timeoutMs: number, timeoutMessage?: string): Promise; /** * Check if running in browser environment */ declare function isBrowser(): boolean; /** * Check if browser supports required features */ declare function checkBrowserSupport(): { supported: boolean; missingFeatures: string[]; }; /** * Generate mock data for development/testing */ declare function generateMockData(): { address: string; balance: { public: number; private: number; total: number; currency: "OCT"; }; networkInfo: { id: string; name: string; rpcUrl: string; explorerUrl: string; explorerAddressUrl: string; indexerUrl: string; supportsPrivacy: boolean; color: string; isTestnet: boolean; }; }; /** * Create development logger */ declare function createLogger(prefix: string, debug: boolean): { log: (...args: any[]) => void; warn: (...args: any[]) => void; error: (...args: any[]) => void; debug: (...args: any[]) => void; table: (data: any) => void; group: (label: string) => void; groupEnd: () => void; }; declare const SDK_VERSION = "2.6.0"; declare const MIN_EXTENSION_VERSION = "2.0.1"; declare const MIN_EXTENSION_VERSION_DEVNET = "2.2.1"; declare const SUPPORTED_EXTENSION_VERSIONS = "^2.0.1"; declare function createZeroXIOWallet(config: { appName: string; appDescription?: string; debug?: boolean; autoConnect?: boolean; }): Promise; declare const createOctraWallet: typeof createZeroXIOWallet; declare function checkSDKCompatibility(): { compatible: boolean; issues: string[]; recommendations: string[]; }; export { DEFAULT_NETWORK_ID, ErrorCode, EventEmitter, ExtensionCommunicator, MIN_EXTENSION_VERSION, MIN_EXTENSION_VERSION_DEVNET, NETWORKS, SDK_CONFIG, SDK_VERSION, SUPPORTED_EXTENSION_VERSIONS, ZeroXIOWallet, ZeroXIOWalletError, checkBrowserSupport, checkSDKCompatibility, createDefaultBalance, createErrorMessage, createLogger, createOctraWallet, createZeroXIOWallet, delay, formatAddress, formatOCT, formatTimestamp, formatTxHash, formatOCT as formatZeroXIO, fromMicroOCT, fromMicroOCT as fromMicroZeroXIO, generateMockData, getAllNetworks, getDefaultNetwork, getNetworkConfig, isBrowser, isErrorType, isValidAddress, isValidAmount, isValidFeeLevel, isValidMessage, isValidNetworkId, retry, toMicroOCT, toMicroOCT as toMicroZeroXIO, withTimeout }; export type { AccountChangedEvent, Balance, BalanceChangedEvent, ConnectEvent, ConnectOptions, ConnectionInfo, ContractCallData, ContractParam, ContractParams, ContractViewCallData, DisconnectEvent, ErrorEvent, ExtensionRequest, ExtensionResponse, NetworkChangedEvent, NetworkInfo, PendingPrivateTransfer, Permission, PrivateBalanceInfo, PrivateTransferData, SDKConfig, SignedTransaction, Transaction, TransactionConfirmedEvent, TransactionData, TransactionFinality, TransactionHistory, TransactionResult, WalletAddress, WalletEvent, WalletEventType };