@0xio/sdk 2.6.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,140 @@
1
+ /**
2
+ * 0xio SDK — Wallet Transport Adapter Interface
3
+ *
4
+ * Implement WalletTransportAdapter to add support for a new wallet without
5
+ * touching any core SDK code. Drop the adapter file in src/supports/ and
6
+ * pass it to ZeroXIOWallet via SDKConfig.adapter.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { ZeroXIOWallet } from '@0xio/sdk';
11
+ * import { QubitzAdapter } from '@0xio/sdk/supports/qubitz';
12
+ *
13
+ * const wallet = new ZeroXIOWallet({
14
+ * appName: 'My DApp',
15
+ * adapter: QubitzAdapter,
16
+ * });
17
+ * ```
18
+ */
19
+ /**
20
+ * Outbound request — the SDK passes this to adapter.postRequest() for every
21
+ * outbound wallet call. Adapters translate this into their wallet-specific wire format.
22
+ */
23
+ interface AdapterRequest {
24
+ /** Unique request ID (UUID). Used to correlate the response. */
25
+ id: string;
26
+ /** Method name, e.g. 'connect', 'sendTransaction', 'signMessage' */
27
+ method: string;
28
+ /** Method parameters */
29
+ params: unknown;
30
+ /** Unix timestamp (ms) when the request was created */
31
+ timestamp: number;
32
+ }
33
+ /**
34
+ * Normalized inbound message from a wallet.
35
+ * Adapters translate their wallet-specific wire format into this structure
36
+ * and pass it to the handler registered via listen().
37
+ *
38
+ * A message is either a response (requestId set) or a push event (eventType set).
39
+ */
40
+ interface AdapterIncomingMessage {
41
+ /** Must match the id from the outbound AdapterRequest */
42
+ requestId?: string;
43
+ /** Whether the request succeeded. Required when requestId is set. */
44
+ success?: boolean;
45
+ /** Response payload on success */
46
+ data?: unknown;
47
+ /** Structured error on failure */
48
+ error?: {
49
+ code: string;
50
+ message: string;
51
+ details?: unknown;
52
+ };
53
+ /** Event type, e.g. 'connect', 'disconnect', 'accountChanged', 'balanceChanged' */
54
+ eventType?: string;
55
+ /** Event payload */
56
+ eventData?: unknown;
57
+ }
58
+ /**
59
+ * Wallet transport adapter.
60
+ *
61
+ * Encapsulates the entire wallet-specific communication layer:
62
+ * - How to detect if the wallet is installed
63
+ * - How to send requests (postRequest)
64
+ * - How to receive responses and events (listen)
65
+ *
66
+ * Everything else — request lifecycle, timeouts, retries, rate limiting,
67
+ * event routing — is handled by the SDK core and does not change per wallet.
68
+ *
69
+ * @example Minimal adapter for a hypothetical wallet
70
+ * ```typescript
71
+ * export const MyWalletAdapter: WalletTransportAdapter = {
72
+ * name: 'mywallet',
73
+ * displayName: 'My Wallet',
74
+ * detect: () => !!(window as any).myWallet,
75
+ * postRequest: (req) =>
76
+ * window.postMessage({ source: 'mywallet-request', ...req }, location.origin),
77
+ * listen: (handler) => {
78
+ * const fn = (e: MessageEvent) => {
79
+ * if (e.data?.source !== 'mywallet-response') return;
80
+ * handler({ requestId: e.data.id, success: e.data.ok, data: e.data.result });
81
+ * };
82
+ * window.addEventListener('message', fn);
83
+ * return () => window.removeEventListener('message', fn);
84
+ * },
85
+ * };
86
+ * ```
87
+ */
88
+ interface WalletTransportAdapter {
89
+ /**
90
+ * Machine-readable wallet identifier. Used in logs and adapter selection.
91
+ * Examples: '0xio', 'qubitz', 'fhex'
92
+ */
93
+ readonly name: string;
94
+ /**
95
+ * Human-readable wallet name shown in error messages.
96
+ * Examples: '0xio Wallet', 'Qubitz Wallet', 'FHEX Wallet'
97
+ */
98
+ readonly displayName: string;
99
+ /**
100
+ * Returns true when this wallet's extension / injected provider is present
101
+ * in the current page context. Called periodically by the SDK to check availability.
102
+ */
103
+ detect(): boolean;
104
+ /**
105
+ * Send a request to the wallet.
106
+ * Called once per outbound request — translate AdapterRequest into your
107
+ * wallet's wire format and post it (window.postMessage, direct API call, etc.).
108
+ */
109
+ postRequest(request: AdapterRequest): void;
110
+ /**
111
+ * Optional: send the same request to a trusted parent frame (iframe/desktop bridge).
112
+ * Only implement this if your wallet supports an embedded iframe bridge mode.
113
+ * The SDK calls this when window.parent !== window and a trusted parent origin exists.
114
+ */
115
+ postRequestToParent?(request: AdapterRequest, parentOrigin: string): void;
116
+ /**
117
+ * Set up response and event listening.
118
+ * The SDK calls this once during initialization. Normalise all incoming wallet
119
+ * messages into AdapterIncomingMessage and pass them to handler.
120
+ *
121
+ * @param handler Callback for responses and push events
122
+ * @param options SDK-level options, e.g. additional trusted parent origins
123
+ * @returns A teardown function — the SDK calls it on cleanup()
124
+ */
125
+ listen(handler: (msg: AdapterIncomingMessage) => void, options?: {
126
+ trustedParentOrigins?: string[];
127
+ }): () => void;
128
+ /**
129
+ * Optional: register wallet-ready event listeners (e.g. 'myWalletReady' CustomEvent).
130
+ * Called once during SDK init. When the wallet signals it is ready, call onReady().
131
+ * Returns a cleanup function.
132
+ *
133
+ * If not implemented, the SDK falls back to polling detect() every 2 seconds.
134
+ */
135
+ listenForReady?(onReady: () => void): () => void;
136
+ }
137
+
1
138
  /**
2
139
  * 0xio Wallet SDK - Type Definitions
3
140
  * Comprehensive type system for 0xio wallet integration with Octra Network
@@ -25,7 +162,8 @@ interface NetworkInfo {
25
162
  }
26
163
  interface TransactionData {
27
164
  readonly to: string;
28
- readonly amount: number;
165
+ /** Amount in OCT. Accepts string or number — use string for amounts above 9 billion OCT to avoid JS number precision loss. */
166
+ readonly amount: string | number;
29
167
  readonly message?: string;
30
168
  readonly feeLevel?: 1 | 3;
31
169
  readonly isPrivate?: boolean;
@@ -49,8 +187,8 @@ interface ContractCallData {
49
187
  */
50
188
  readonly params: ContractParams;
51
189
  /**
52
- * Native OCT to send with the call (in micro-units, 1 OCT = 1000000).
53
- * Set to 0 for calls that don't transfer native tokens.
190
+ * Native OCT to send with the call (in OCT, same unit as sendTransaction.amount).
191
+ * Set to '0' for calls that don't transfer native tokens.
54
192
  */
55
193
  readonly amount?: string | number;
56
194
  /**
@@ -81,10 +219,18 @@ interface SignedTransaction {
81
219
  readonly signature: string;
82
220
  readonly public_key: string;
83
221
  }
84
- type TransactionFinality = 'pending' | 'confirmed' | 'rejected';
222
+ type TransactionFinality = 'pending' | 'confirmed' | 'rejected' | 'dropped';
85
223
  interface TransactionResult {
86
- readonly txHash: string;
87
- readonly success: boolean;
224
+ /** RFC-O-1 canonical hash field */
225
+ readonly hash?: string;
226
+ /** RFC-O-1 canonical accepted field */
227
+ readonly accepted?: boolean;
228
+ /** RFC-O-1 status field */
229
+ readonly status?: TransactionFinality;
230
+ /** @deprecated Use hash */
231
+ readonly txHash?: string;
232
+ /** @deprecated Use accepted */
233
+ readonly success?: boolean;
88
234
  readonly finality?: TransactionFinality;
89
235
  readonly message?: string;
90
236
  readonly explorerUrl?: string;
@@ -99,10 +245,12 @@ interface Transaction {
99
245
  readonly hash: string;
100
246
  readonly from: string;
101
247
  readonly to: string;
102
- readonly amount: number;
103
- readonly fee: number;
248
+ /** Amount in OCT as returned by the node (may be string or number depending on extension version). */
249
+ readonly amount: string | number;
250
+ /** Fee in OCT as returned by the node (may be string or number depending on extension version). */
251
+ readonly fee: string | number;
104
252
  readonly timestamp: number;
105
- readonly status: 'pending' | 'confirmed' | 'failed';
253
+ readonly status: 'pending' | 'confirmed' | 'failed' | 'dropped';
106
254
  readonly finality?: TransactionFinality;
107
255
  readonly message?: string;
108
256
  readonly blockHeight?: number;
@@ -114,13 +262,17 @@ interface ConnectionInfo {
114
262
  balance?: Balance;
115
263
  networkInfo?: NetworkInfo;
116
264
  connectedAt?: number;
265
+ permissions?: Permission[];
117
266
  }
118
267
  interface ConnectOptions {
268
+ /** RFC-O-1 canonical field name */
269
+ readonly permissions?: Permission[];
270
+ /** @deprecated Use permissions */
119
271
  readonly requestPermissions?: Permission[];
120
272
  readonly networkId?: string;
121
273
  }
122
- type Permission = 'read_address' | 'read_balance' | 'send_transactions' | 'sign_messages' | 'view_private_balance' | 'private_transfers';
123
- type WalletEventType = 'connect' | 'disconnect' | 'accountChanged' | 'balanceChanged' | 'networkChanged' | 'transactionConfirmed' | 'error' | 'extensionLocked' | 'extensionUnlocked';
274
+ type Permission = 'read_address' | 'read_balance' | 'read_public_key' | 'send_transactions' | 'sign_messages' | 'contract_calls' | 'view_private_balance' | 'view_encrypted_balance' | 'private_transfers' | 'encrypt_balance' | 'decrypt_balance' | 'stealth_scan' | 'stealth_claim';
275
+ type WalletEventType = 'connect' | 'disconnect' | 'accountChanged' | 'balanceChanged' | 'networkChanged' | 'transactionConfirmed' | 'permissionsChanged' | 'message' | 'error' | 'extensionLocked' | 'extensionUnlocked';
124
276
  interface WalletEvent<T = any> {
125
277
  readonly type: WalletEventType;
126
278
  readonly data: T;
@@ -128,7 +280,7 @@ interface WalletEvent<T = any> {
128
280
  }
129
281
  interface ConnectEvent {
130
282
  readonly address: string;
131
- readonly publicKey?: string;
283
+ readonly publicKey: string | undefined;
132
284
  readonly balance: Balance;
133
285
  readonly networkInfo: NetworkInfo;
134
286
  readonly permissions: Permission[];
@@ -140,6 +292,7 @@ interface AccountChangedEvent {
140
292
  readonly previousAddress?: string;
141
293
  readonly newAddress: string;
142
294
  readonly balance: Balance;
295
+ readonly publicKey?: string;
143
296
  }
144
297
  interface BalanceChangedEvent {
145
298
  readonly address: string;
@@ -192,7 +345,8 @@ interface PrivateBalanceInfo {
192
345
  }
193
346
  interface PrivateTransferData {
194
347
  readonly to: string;
195
- readonly amount: number;
348
+ /** Amount in OCT. Accepts string or number — use string for amounts above 9 billion OCT to avoid JS number precision loss. */
349
+ readonly amount: string | number;
196
350
  readonly message?: string;
197
351
  }
198
352
  interface PendingPrivateTransfer {
@@ -212,6 +366,22 @@ interface SDKConfig {
212
366
  readonly requiredPermissions?: Permission[];
213
367
  readonly networkId?: string;
214
368
  readonly debug?: boolean;
369
+ /**
370
+ * Exact origins allowed as parent iframe bridge (e.g. 'https://app.example.com').
371
+ * When set, only these origins (plus tauri://) are trusted — implicit localhost trust
372
+ * is disabled. Leave unset for development (all localhost trusted by default).
373
+ */
374
+ readonly trustedParentOrigins?: string[];
375
+ /**
376
+ * Custom wallet transport adapter.
377
+ * Defaults to ZeroXIOAdapter (0xio extension postMessage protocol).
378
+ * Pass an adapter from src/supports/ to target a different wallet.
379
+ *
380
+ * @example
381
+ * import { QubitzAdapter } from '@0xio/sdk/supports/qubitz';
382
+ * new ZeroXIOWallet({ appName: 'My DApp', adapter: QubitzAdapter });
383
+ */
384
+ readonly adapter?: WalletTransportAdapter;
215
385
  }
216
386
  interface ExtensionRequest {
217
387
  readonly id: string;
@@ -231,74 +401,31 @@ interface ExtensionResponse<T = any> {
231
401
  readonly timestamp: number;
232
402
  }
233
403
 
234
- /**
235
- * 0xio Wallet SDK - Event System
236
- * Type-safe event emitter for wallet events
237
- */
238
-
239
404
  type EventListener<T = any> = (event: WalletEvent<T>) => void;
240
405
  declare class EventEmitter {
241
406
  private listeners;
242
- private debug;
243
- constructor(debug?: boolean);
244
- /**
245
- * Add event listener
246
- */
407
+ constructor(_debug?: boolean);
247
408
  on<T = any>(eventType: WalletEventType, listener: EventListener<T>): void;
248
- /**
249
- * Remove event listener
250
- */
251
409
  off<T = any>(eventType: WalletEventType, listener: EventListener<T>): void;
252
- /**
253
- * Add one-time event listener
254
- */
255
410
  once<T = any>(eventType: WalletEventType, listener: EventListener<T>): void;
256
- /**
257
- * Emit event to all listeners
258
- */
259
411
  emit<T = any>(eventType: WalletEventType, data: T): void;
260
- /**
261
- * Remove all listeners for a specific event type
262
- */
263
412
  removeAllListeners(eventType?: WalletEventType): void;
264
- /**
265
- * Get number of listeners for an event type
266
- */
267
413
  listenerCount(eventType: WalletEventType): number;
268
- /**
269
- * Get all event types that have listeners
270
- */
271
414
  eventTypes(): WalletEventType[];
272
- /**
273
- * Check if there are any listeners for an event type
274
- */
275
415
  hasListeners(eventType: WalletEventType): boolean;
276
416
  }
277
417
 
278
- /**
279
- * 0xio Wallet SDK - Main Wallet Class
280
- * Primary interface for DApp developers to interact with 0xio Wallet
281
- */
282
-
283
418
  declare class ZeroXIOWallet extends EventEmitter {
284
419
  private communicator;
285
420
  private config;
286
421
  private connectionInfo;
287
422
  private isInitialized;
423
+ private _initPromise;
424
+ private _sessionVersion;
288
425
  private logger;
289
426
  constructor(config: SDKConfig);
290
- /**
291
- * Initialize the SDK
292
- * Must be called before using any other methods
293
- */
294
427
  initialize(): Promise<boolean>;
295
- /**
296
- * Check if SDK is initialized
297
- */
298
428
  isReady(): boolean;
299
- /**
300
- * Connect to wallet
301
- */
302
429
  connect(options?: ConnectOptions): Promise<ConnectEvent>;
303
430
  /**
304
431
  * Disconnect from wallet
@@ -329,22 +456,22 @@ declare class ZeroXIOWallet extends EventEmitter {
329
456
  * Get the extension's current network ID ('mainnet' or 'devnet')
330
457
  */
331
458
  getNetworkId(): string | null;
332
- /**
333
- * Get current wallet address
334
- */
335
459
  getAddress(): string | null;
336
- /**
337
- * Get current balance
338
- */
339
460
  getBalance(forceRefresh?: boolean): Promise<Balance>;
461
+ getNetworkInfo(): Promise<NetworkInfo>;
462
+ sendTransaction(txData: TransactionData): Promise<TransactionResult>;
340
463
  /**
341
- * Get network information
464
+ * Sign a transaction without broadcasting it (RFC-O-1 octra_signTransaction).
465
+ * Returns the signed transaction object for manual submission via submitTransaction().
342
466
  */
343
- getNetworkInfo(): Promise<NetworkInfo>;
467
+ signTransaction(txData: TransactionData): Promise<{
468
+ signedTx: any;
469
+ }>;
344
470
  /**
345
- * Send transaction
471
+ * Broadcast a pre-signed transaction (RFC-O-1 octra_submitTransaction).
472
+ * Use after signTransaction() to submit the signed tx to the network.
346
473
  */
347
- sendTransaction(txData: TransactionData): Promise<TransactionResult>;
474
+ submitTransaction(signedTx: any): Promise<TransactionResult>;
348
475
  /**
349
476
  * Call a smart contract method (state-changing).
350
477
  * The extension builds, signs, and submits the transaction via octra_submit.
@@ -363,18 +490,15 @@ declare class ZeroXIOWallet extends EventEmitter {
363
490
  * Get transaction history
364
491
  */
365
492
  getTransactionHistory(page?: number, limit?: number): Promise<TransactionHistory>;
366
- /**
367
- * Get private balance information
368
- */
369
493
  getPrivateBalanceInfo(): Promise<PrivateBalanceInfo>;
370
494
  /**
371
495
  * Encrypt public balance to private
372
496
  */
373
- encryptBalance(amount: number): Promise<boolean>;
497
+ encryptBalance(amount: string | number): Promise<TransactionResult>;
374
498
  /**
375
499
  * Decrypt private balance to public
376
500
  */
377
- decryptBalance(amount: number): Promise<boolean>;
501
+ decryptBalance(amount: string | number): Promise<TransactionResult>;
378
502
  /**
379
503
  * Send a private (encrypted) transfer to another address.
380
504
  * The extension builds the PVAC ciphertext subtraction + range proof + zero proof,
@@ -408,238 +532,92 @@ declare class ZeroXIOWallet extends EventEmitter {
408
532
  * ```
409
533
  */
410
534
  signMessage(message: string): Promise<string>;
535
+ /**
536
+ * Sign a domain-separated authentication message.
537
+ * Unlike `signMessage()`, this prepends a standard header that binds the signature
538
+ * to the calling service and a one-time nonce, preventing cross-service replay attacks.
539
+ *
540
+ * @param service - Identifies the relying service (e.g. 'MyDApp' or 'api.mydapp.com')
541
+ * @param nonce - Unique one-time value — use a server-generated UUID or challenge
542
+ * @returns Promise resolving to the base64-encoded Ed25519 signature
543
+ */
544
+ signAuthMessage(service: string, nonce: string): Promise<string>;
411
545
  private ensureInitialized;
412
546
  private ensureConnected;
413
547
  private setupExtensionEventListeners;
414
- /**
415
- * Handle account changed event from extension
416
- */
417
548
  private handleAccountChanged;
418
- /**
419
- * Handle network changed event from extension
420
- */
421
549
  private handleNetworkChanged;
422
- /**
423
- * Handle balance changed event from extension
424
- */
425
550
  private handleBalanceChanged;
426
- /**
427
- * Handle extension locked event
428
- */
429
551
  private handleExtensionLocked;
430
- /**
431
- * Handle extension unlocked event
432
- */
433
552
  private handleExtensionUnlocked;
434
- /**
435
- * Handle transaction confirmed event
436
- */
437
553
  private handleTransactionConfirmed;
438
554
  /**
439
- * Clean up SDK resources
555
+ * Reject numeric amounts that cannot be represented exactly in micro-OCT.
556
+ * e.g. 0.1 + 0.2 = 0.30000000000000004 — the extension would sign the wrong value.
557
+ * String amounts bypass this check (caller is responsible for correctness).
440
558
  */
559
+ private assertExactOCTAmount;
441
560
  cleanup(): void;
442
561
  }
443
562
 
444
- /**
445
- * 0xio Wallet SDK - Extension Communication Module
446
- *
447
- * @fileoverview Manages secure communication between the SDK and browser extension.
448
- * Implements message passing, request/response handling, rate limiting, and origin validation
449
- * to ensure secure wallet interactions.
450
- *
451
- * @module communication
452
- * @version 2.6.0
453
- * @license MIT
454
- */
455
-
456
- /**
457
- * ExtensionCommunicator - Manages communication with the 0xio Wallet browser extension
458
- *
459
- * @class
460
- * @extends EventEmitter
461
- *
462
- * @description
463
- * Handles all communication between the SDK and wallet extension including:
464
- * - Request/response message passing with origin validation
465
- * - Rate limiting to prevent DoS attacks
466
- * - Automatic retry logic with exponential backoff
467
- * - Extension detection and availability monitoring
468
- * - Cryptographically secure request ID generation
469
- *
470
- * @example
471
- * ```typescript
472
- * const communicator = new ExtensionCommunicator(true); // debug mode
473
- * await communicator.initialize();
474
- *
475
- * const response = await communicator.sendRequest('get_balance', {});
476
- * console.log(response);
477
- * ```
478
- */
479
563
  declare class ExtensionCommunicator extends EventEmitter {
480
- /** Legacy request counter (deprecated, kept for fallback) */
481
- private requestId;
482
- /** Map of pending requests awaiting responses */
483
564
  private pendingRequests;
484
- /** Initialization state flag */
485
565
  private isInitialized;
486
- /** Logger instance for debugging */
487
566
  private logger;
488
- /** Interval handle for periodic extension detection */
489
567
  private extensionDetectionInterval;
490
- /** Current extension availability state */
491
568
  private isExtensionAvailableState;
492
- /** Message listener reference for cleanup */
493
- private messageListener;
494
- /** Trusted parent origins for iframe communication */
495
569
  private trustedOrigins;
496
- /** Parent origin learned from walletReady signal */
497
570
  private _parentOrigin;
498
- /** Maximum number of concurrent pending requests */
499
- private readonly MAX_CONCURRENT_REQUESTS;
500
- /** Time window for rate limiting (milliseconds) */
501
- private readonly RATE_LIMIT_WINDOW;
502
- /** Maximum requests allowed per time window */
503
- private readonly MAX_REQUESTS_PER_WINDOW;
504
- /** Timestamps of recent requests for rate limiting */
505
- private requestTimestamps;
571
+ /** Pluggable transport defaults to the 0xio postMessage protocol. */
572
+ private adapter;
573
+ /** Teardown fn returned by adapter.listen() */
574
+ private _adapterTeardown;
575
+ /** Teardown fn returned by adapter.listenForReady() */
576
+ private _adapterReadyTeardown;
506
577
  /**
507
- * Creates a new ExtensionCommunicator instance
508
- *
509
- * @param {boolean} debug - Enable debug logging
578
+ * Set when a trusted walletReady has been received from window.parent.
579
+ * The polling fallback must NOT clear this flag.
510
580
  */
511
- constructor(debug?: boolean, trustedOrigins?: string[]);
581
+ private _parentTrusted;
582
+ /** walletReady postMessage listener stored for cleanup */
583
+ private _walletReadyMessageListener;
512
584
  /**
513
- * Add trusted origins for iframe/bridge communication
514
- * Call this before connecting if your dApp runs inside a trusted frame
585
+ * In-flight interactive request lock.
586
+ * Methods that open approval popups are serialized only one at a time.
515
587
  */
588
+ private _interactiveInFlight;
589
+ private readonly MAX_CONCURRENT_REQUESTS;
590
+ private readonly RATE_LIMIT_WINDOW;
591
+ private readonly MAX_REQUESTS_PER_WINDOW;
592
+ private requestTimestamps;
593
+ constructor(debug?: boolean, trustedOrigins?: string[], adapter?: WalletTransportAdapter);
516
594
  setTrustedOrigins(origins: string[]): void;
517
- /**
518
- * Initialize communication with the wallet extension
519
- *
520
- * @description
521
- * Performs initial setup and verification:
522
- * 1. Waits for extension to become available
523
- * 2. Sends ping to verify communication
524
- * 3. Establishes message handlers
525
- *
526
- * Must be called before any other methods.
527
- *
528
- * @returns {Promise<boolean>} True if initialization succeeded, false otherwise
529
- * @throws {ZeroXIOWalletError} If extension is not available after timeout
530
- *
531
- * @example
532
- * ```typescript
533
- * const success = await communicator.initialize();
534
- * if (!success) {
535
- * console.error('Failed to initialize wallet connection');
536
- * }
537
- * ```
538
- */
539
595
  initialize(): Promise<boolean>;
540
- /**
541
- * Check if extension is available
542
- */
543
596
  isExtensionAvailable(): boolean;
544
597
  private static readonly NO_RETRY_METHODS;
545
- /**
546
- * Send request to extension
547
- */
598
+ private static readonly INTERACTIVE_METHODS;
548
599
  sendRequest<T = any>(method: string, params?: any, timeout?: number): Promise<T>;
549
- /**
550
- * Send request to extension with automatic retry logic
551
- */
552
600
  sendRequestWithRetry<T = any>(method: string, params?: any, maxRetries?: number, timeout?: number): Promise<T>;
553
- /**
554
- * Setup message listener for responses from extension
555
- */
556
601
  private setupMessageListener;
557
- /**
558
- * Handle extension event
559
- */
602
+ private static readonly VALID_EVENT_TYPES;
560
603
  private handleExtensionEvent;
561
- /**
562
- * Handle response from extension
563
- */
564
604
  private handleExtensionResponse;
565
- /**
566
- * Post message to extension via content script
567
- */
568
605
  private postMessageToExtension;
569
- /**
570
- * Check if we're in a context that can communicate with extension
571
- */
572
606
  private hasExtensionContext;
573
- /**
574
- * Check and enforce rate limits to prevent denial-of-service attacks
575
- *
576
- * @private
577
- * @throws {ZeroXIOWalletError} RATE_LIMIT_EXCEEDED if limits are exceeded
578
- *
579
- * @description
580
- * Implements two-tier rate limiting:
581
- * 1. Concurrent requests: Maximum 50 pending requests at once
582
- * 2. Request frequency: Maximum 20 requests per second
583
- *
584
- * Rate limiting protects both the SDK and extension from:
585
- * - Accidental infinite loops in dApp code
586
- * - Malicious DoS attacks
587
- * - Resource exhaustion
588
- *
589
- * @security Critical security function - enforces resource limits
590
- */
591
607
  private checkRateLimit;
592
- /**
593
- * Generate cryptographically secure unique request ID
594
- *
595
- * @private
596
- * @returns {string} A unique, unpredictable request identifier
597
- *
598
- * @description
599
- * Uses Web Crypto API for secure random ID generation:
600
- * 1. Primary: crypto.randomUUID() - UUID v4 format
601
- * 2. Fallback: crypto.getRandomValues() - 128-bit random hex
602
- * 3. Last resort: timestamp + counter (logs warning)
603
- *
604
- * Security importance:
605
- * - Prevents request ID prediction attacks
606
- * - Mitigates replay attacks
607
- * - Makes session hijacking more difficult
608
- *
609
- * @security Critical - IDs must be cryptographically unpredictable
610
- */
611
608
  private generateRequestId;
612
- /**
613
- * Start continuous extension detection
614
- */
615
609
  private startExtensionDetection;
616
- /**
617
- * Check if extension is currently available
618
- */
619
610
  private checkExtensionAvailability;
620
- /**
621
- * Detect extension signals/indicators
622
- */
623
611
  private detectExtensionSignals;
624
- /**
625
- * Wait for extension to become available
626
- */
627
612
  private waitForExtensionAvailability;
628
- /**
629
- * Get browser diagnostics for error reporting
630
- */
631
613
  private getBrowserDiagnostics;
632
- /**
633
- * Get extension state diagnostics
634
- */
635
614
  private getExtensionDiagnostics;
636
615
  /**
637
- * Cleanup pending requests
616
+ * Clean up SDK resources.
617
+ * After cleanup() the instance is terminal — do not call initialize() again.
618
+ * Construct a new instance instead.
638
619
  */
639
620
  cleanup(): void;
640
- /**
641
- * Get debug information
642
- */
643
621
  getDebugInfo(): {
644
622
  initialized: boolean;
645
623
  available: boolean;
@@ -649,123 +627,138 @@ declare class ExtensionCommunicator extends EventEmitter {
649
627
  };
650
628
  }
651
629
 
630
+ /**
631
+ * 0xio Wallet transport adapter.
632
+ *
633
+ * Implements the postMessage protocol used by the 0xio browser extension (>= v2.4.0).
634
+ *
635
+ * Outbound wire format:
636
+ * window.postMessage({ source: '0xio-sdk-request', request: { id, method, params, timestamp } }, origin)
637
+ *
638
+ * Inbound wire format:
639
+ * window.postMessage({ source: '0xio-sdk-bridge', response: { id, success, data, error }, sessionNonce })
640
+ * window.postMessage({ source: '0xio-sdk-bridge', event: { type, data } })
641
+ *
642
+ * H-2: Session nonce validation — injected.ts broadcasts the nonce received from the
643
+ * isolated content script. Once set, any '0xio-sdk-bridge' response with a missing or
644
+ * mismatched nonce is rejected, preventing response injection by malicious page scripts.
645
+ */
646
+
647
+ /**
648
+ * Creates a 0xio adapter. The factory accepts optional extra trusted parent origins
649
+ * so the communicator can forward its own trustedOrigins setting to origin validation.
650
+ */
651
+ declare function createZeroXIOAdapter(extraTrustedOrigins?: string[]): WalletTransportAdapter;
652
+ /** Default 0xio adapter instance (no extra trusted origins). */
653
+ declare const ZeroXIOAdapter: WalletTransportAdapter;
654
+
655
+ /**
656
+ * RFC-O-1 OctraProvider transport adapter.
657
+ *
658
+ * Targets any wallet that exposes `window.octra` per the RFC-O-1 specification:
659
+ * window.octra.isOctra === true
660
+ * window.octra.request({ method, params }) → Promise<unknown>
661
+ * window.octra.on(event, listener) / removeListener(event, listener)
662
+ *
663
+ * This adapter translates the SDK's internal method names into RFC-O-1 method
664
+ * names and maps events back to the SDK event vocabulary.
665
+ *
666
+ * Non-standard SDK methods (ping, register_dapp, getTransactionHistory, etc.)
667
+ * are passed through as-is; the wallet's request() handles or rejects them.
668
+ */
669
+
670
+ declare function createOctraProviderAdapter(): WalletTransportAdapter;
671
+ /** Default RFC-O-1 adapter instance. */
672
+ declare const OctraProviderAdapter: WalletTransportAdapter;
673
+
674
+ /**
675
+ * 0xio SDK — Wallet Adapter Registry
676
+ *
677
+ * Add new wallet adapters here. Detection order determines which wallet takes
678
+ * priority when multiple wallets are installed at the same time.
679
+ */
680
+
681
+ /**
682
+ * Auto-detects the first available wallet in the current page.
683
+ * Returns null if no supported wallet is found.
684
+ *
685
+ * @example
686
+ * const adapter = detectWalletAdapter();
687
+ * if (!adapter) throw new Error('No supported wallet found');
688
+ * const wallet = new ZeroXIOWallet({ appName: 'My DApp', adapter });
689
+ */
690
+ declare function detectWalletAdapter(): WalletTransportAdapter | null;
691
+ /** Returns all registered adapter instances. */
692
+ declare function getAllAdapters(): WalletTransportAdapter[];
693
+
652
694
  /**
653
695
  * Network configuration for 0xio SDK
654
696
  */
655
697
 
656
- declare const NETWORKS: Record<string, NetworkInfo>;
698
+ /**
699
+ * Immutable public copy of the built-in network table.
700
+ * Modifications to returned objects do not affect SDK-internal state.
701
+ */
702
+ declare const NETWORKS: Readonly<Record<string, Readonly<NetworkInfo>>>;
657
703
  declare const DEFAULT_NETWORK_ID = "mainnet";
658
704
  /**
659
- * Get network configuration by ID
705
+ * Get network configuration by ID.
706
+ * Returns a frozen copy — callers cannot mutate SDK-internal state.
660
707
  */
661
708
  declare function getNetworkConfig(networkId?: string): NetworkInfo;
662
709
  /**
663
- * Get all available networks
710
+ * Get all available networks.
711
+ * Returns frozen copies — callers cannot mutate SDK-internal state.
664
712
  */
665
713
  declare function getAllNetworks(): NetworkInfo[];
666
714
  /**
667
- * Check if network ID is valid
715
+ * Check if network ID is valid (own property check, prevents prototype pollution).
668
716
  */
669
717
  declare function isValidNetworkId(networkId: string): boolean;
670
718
 
671
719
  /**
672
- * Default balance structure
720
+ * Default balance structure.
721
+ * Accepts a numeric total or undefined — never pass a Balance object here.
673
722
  */
674
723
  declare function createDefaultBalance(total?: number): Balance;
675
- /**
676
- * SDK Configuration constants
677
- */
678
724
  declare const SDK_CONFIG: {
679
- readonly version: "2.6.0";
725
+ readonly version: "2.7.1";
680
726
  readonly defaultNetworkId: "mainnet";
681
727
  readonly communicationTimeout: 30000;
682
728
  readonly retryAttempts: 3;
683
729
  readonly retryDelay: 1000;
684
730
  };
685
- /**
686
- * Get default network configuration
687
- */
688
731
  declare function getDefaultNetwork(): NetworkInfo;
689
732
 
690
- /**
691
- * 0xio Wallet SDK - Utilities
692
- * Helper functions for validation, formatting, and common operations
693
- */
694
-
695
- /**
696
- * Validate wallet address for Octra blockchain
697
- */
698
733
  declare function isValidAddress(address: string): boolean;
699
734
  /**
700
- * Validate transaction amount
701
- */
702
- declare function isValidAmount(amount: number): boolean;
703
- /**
704
- * Validate transaction message
735
+ * Validate transaction amount.
736
+ * Accepts both number and string representations.
737
+ * String amounts avoid JS number precision loss for very large values.
705
738
  */
739
+ declare function isValidAmount(amount: string | number): boolean;
706
740
  declare function isValidMessage(message: string): boolean;
707
- /**
708
- * Validate fee level
709
- */
710
741
  declare function isValidFeeLevel(feeLevel: number): boolean;
711
742
  /**
712
- * Format OCT amount for display
713
- */
714
- declare function formatOCT(amount: number, decimals?: number): string;
715
- /**
716
- * Format address for display (truncated)
743
+ * Derive the canonical Octra address from a base64-encoded Ed25519 public key.
744
+ * Algorithm: SHA-256(pubkey_bytes) → base58 → prepend "oct"
745
+ * Source of truth: ocho-push-server/src/index.ts#deriveAddressFromPubkey
717
746
  */
747
+ declare function deriveOctraAddress(publicKeyBase64: string): Promise<string>;
748
+ declare function formatOCT(amount: number | string, decimals?: number): string;
718
749
  declare function formatAddress(address: string, prefixLength?: number, suffixLength?: number): string;
719
- /**
720
- * Format timestamp for display
721
- */
722
750
  declare function formatTimestamp(timestamp: number): string;
723
- /**
724
- * Format transaction hash for display
725
- */
726
751
  declare function formatTxHash(hash: string, length?: number): string;
727
- /**
728
- * Convert OCT to micro OCT (for network transmission)
729
- */
730
752
  declare function toMicroOCT(amount: number): string;
731
- /**
732
- * Convert micro OCT to OCT (for display)
733
- */
734
753
  declare function fromMicroOCT(microAmount: string | number): number;
735
- /**
736
- * Create standardized error messages
737
- */
738
754
  declare function createErrorMessage(code: ErrorCode, context?: string): string;
739
- /**
740
- * Check if error is a specific type
741
- */
742
755
  declare function isErrorType(error: any, code: ErrorCode): boolean;
743
- /**
744
- * Create a promise that resolves after a delay
745
- */
746
756
  declare function delay(ms: number): Promise<void>;
747
- /**
748
- * Retry an async operation with exponential backoff
749
- */
750
- declare function retry<T>(operation: () => Promise<T>, maxRetries?: number, baseDelay?: number): Promise<T>;
751
- /**
752
- * Timeout wrapper for promises
753
- */
754
- declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMessage?: string): Promise<T>;
755
- /**
756
- * Check if running in browser environment
757
- */
758
757
  declare function isBrowser(): boolean;
759
- /**
760
- * Check if browser supports required features
761
- */
762
758
  declare function checkBrowserSupport(): {
763
759
  supported: boolean;
764
760
  missingFeatures: string[];
765
761
  };
766
- /**
767
- * Generate mock data for development/testing
768
- */
769
762
  declare function generateMockData(): {
770
763
  address: string;
771
764
  balance: {
@@ -786,9 +779,6 @@ declare function generateMockData(): {
786
779
  isTestnet: boolean;
787
780
  };
788
781
  };
789
- /**
790
- * Create development logger
791
- */
792
782
  declare function createLogger(prefix: string, debug: boolean): {
793
783
  log: (...args: any[]) => void;
794
784
  warn: (...args: any[]) => void;
@@ -799,7 +789,7 @@ declare function createLogger(prefix: string, debug: boolean): {
799
789
  groupEnd: () => void;
800
790
  };
801
791
 
802
- declare const SDK_VERSION = "2.6.0";
792
+ declare const SDK_VERSION = "2.7.1";
803
793
  declare const MIN_EXTENSION_VERSION = "2.0.1";
804
794
  declare const MIN_EXTENSION_VERSION_DEVNET = "2.2.1";
805
795
  declare const SUPPORTED_EXTENSION_VERSIONS = "^2.0.1";
@@ -808,13 +798,13 @@ declare function createZeroXIOWallet(config: {
808
798
  appDescription?: string;
809
799
  debug?: boolean;
810
800
  autoConnect?: boolean;
801
+ adapter?: WalletTransportAdapter;
811
802
  }): Promise<ZeroXIOWallet>;
812
- declare const createOctraWallet: typeof createZeroXIOWallet;
813
803
  declare function checkSDKCompatibility(): {
814
804
  compatible: boolean;
815
805
  issues: string[];
816
806
  recommendations: string[];
817
807
  };
818
808
 
819
- 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 };
820
- 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 };
809
+ export { DEFAULT_NETWORK_ID, ErrorCode, EventEmitter, ExtensionCommunicator, MIN_EXTENSION_VERSION, MIN_EXTENSION_VERSION_DEVNET, NETWORKS, OctraProviderAdapter, SDK_CONFIG, SDK_VERSION, SUPPORTED_EXTENSION_VERSIONS, ZeroXIOAdapter, ZeroXIOWallet, ZeroXIOWalletError, checkBrowserSupport, checkSDKCompatibility, createDefaultBalance, createErrorMessage, createLogger, createOctraProviderAdapter, createZeroXIOAdapter, createZeroXIOWallet, delay, deriveOctraAddress, detectWalletAdapter, formatAddress, formatOCT, formatTimestamp, formatTxHash, formatOCT as formatZeroXIO, fromMicroOCT, fromMicroOCT as fromMicroZeroXIO, generateMockData, getAllAdapters, getAllNetworks, getDefaultNetwork, getNetworkConfig, isBrowser, isErrorType, isValidAddress, isValidAmount, isValidFeeLevel, isValidMessage, isValidNetworkId, toMicroOCT, toMicroOCT as toMicroZeroXIO };
810
+ export type { AccountChangedEvent, AdapterIncomingMessage, AdapterRequest, 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, WalletTransportAdapter };