@t402/wdk 2.0.0

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.
@@ -0,0 +1,1285 @@
1
+ import { Address } from 'viem';
2
+ import { ClientEvmSigner, BridgeSigner, Usdt0Bridge } from '@t402/evm';
3
+ export { BridgeQuote, BridgeSigner, LAYERZERO_ENDPOINT_IDS, USDT0_OFT_ADDRESSES, Usdt0Bridge, getBridgeableChains, supportsBridging } from '@t402/evm';
4
+
5
+ /**
6
+ * Type definitions for T402 WDK integration
7
+ */
8
+
9
+ /**
10
+ * EVM chain configuration
11
+ */
12
+ interface EvmChainConfig {
13
+ /** RPC endpoint URL */
14
+ provider: string;
15
+ /** Chain ID */
16
+ chainId: number;
17
+ /** CAIP-2 network identifier */
18
+ network: string;
19
+ }
20
+ /**
21
+ * T402 WDK configuration options
22
+ */
23
+ interface T402WDKConfig {
24
+ /** Ethereum mainnet configuration */
25
+ ethereum?: EvmChainConfig | string;
26
+ /** Arbitrum One configuration */
27
+ arbitrum?: EvmChainConfig | string;
28
+ /** Base mainnet configuration */
29
+ base?: EvmChainConfig | string;
30
+ /** Ink mainnet configuration */
31
+ ink?: EvmChainConfig | string;
32
+ /** Berachain mainnet configuration */
33
+ berachain?: EvmChainConfig | string;
34
+ /** Unichain mainnet configuration */
35
+ unichain?: EvmChainConfig | string;
36
+ /** Polygon mainnet configuration */
37
+ polygon?: EvmChainConfig | string;
38
+ /** Custom chains */
39
+ [key: string]: EvmChainConfig | string | undefined;
40
+ }
41
+ /**
42
+ * Normalized chain configuration
43
+ */
44
+ interface NormalizedChainConfig {
45
+ provider: string;
46
+ chainId: number;
47
+ network: string;
48
+ name: string;
49
+ }
50
+ /**
51
+ * Token balance information
52
+ */
53
+ interface TokenBalance {
54
+ /** Token contract address */
55
+ token: Address;
56
+ /** Token symbol */
57
+ symbol: string;
58
+ /** Balance in smallest units */
59
+ balance: bigint;
60
+ /** Formatted balance (human-readable) */
61
+ formatted: string;
62
+ /** Decimals */
63
+ decimals: number;
64
+ }
65
+ /**
66
+ * Chain balance information
67
+ */
68
+ interface ChainBalance {
69
+ /** Chain name (e.g., "arbitrum") */
70
+ chain: string;
71
+ /** CAIP-2 network identifier */
72
+ network: string;
73
+ /** Native token balance */
74
+ native: bigint;
75
+ /** Token balances */
76
+ tokens: TokenBalance[];
77
+ }
78
+ /**
79
+ * Aggregated balance across all chains
80
+ */
81
+ interface AggregatedBalance {
82
+ /** Total USDT0 balance across all chains */
83
+ totalUsdt0: bigint;
84
+ /** Total USDC balance across all chains */
85
+ totalUsdc: bigint;
86
+ /** Per-chain balances */
87
+ chains: ChainBalance[];
88
+ }
89
+ /**
90
+ * Bridge parameters for cross-chain transfers
91
+ */
92
+ interface BridgeParams {
93
+ /** Source chain name */
94
+ fromChain: string;
95
+ /** Destination chain name */
96
+ toChain: string;
97
+ /** Amount to bridge in smallest units */
98
+ amount: bigint;
99
+ /** Recipient address (optional, defaults to same wallet on target chain) */
100
+ recipient?: Address;
101
+ }
102
+ /**
103
+ * Bridge result
104
+ */
105
+ interface BridgeResult {
106
+ /** Transaction hash on source chain */
107
+ txHash: string;
108
+ /** Estimated time for bridge completion in seconds */
109
+ estimatedTime: number;
110
+ }
111
+ /**
112
+ * EIP-712 typed data domain
113
+ */
114
+ interface TypedDataDomain {
115
+ name: string;
116
+ version: string;
117
+ chainId: number;
118
+ verifyingContract: Address;
119
+ }
120
+ /**
121
+ * EIP-712 typed data types
122
+ */
123
+ type TypedDataTypes = Record<string, Array<{
124
+ name: string;
125
+ type: string;
126
+ }>>;
127
+ /**
128
+ * T402 Signer interface for WDK
129
+ * Compatible with @t402/core signer requirements
130
+ */
131
+ interface T402WDKSigner {
132
+ /** Get wallet address */
133
+ readonly address: Address;
134
+ /** Sign EIP-712 typed data */
135
+ signTypedData(params: {
136
+ domain: TypedDataDomain;
137
+ types: TypedDataTypes;
138
+ primaryType: string;
139
+ message: Record<string, unknown>;
140
+ }): Promise<`0x${string}`>;
141
+ /** Sign a message */
142
+ signMessage?(message: string | Uint8Array): Promise<`0x${string}`>;
143
+ /** Get token balance */
144
+ getTokenBalance?(tokenAddress: Address): Promise<bigint>;
145
+ }
146
+ /**
147
+ * WDK Account interface (matches @tetherto/wdk account structure)
148
+ */
149
+ interface WDKAccount {
150
+ getAddress(): Promise<string>;
151
+ getBalance(): Promise<bigint>;
152
+ getTokenBalance(tokenAddress: string): Promise<bigint>;
153
+ signMessage(message: string): Promise<string>;
154
+ signTypedData(params: {
155
+ domain: Record<string, unknown>;
156
+ types: Record<string, unknown>;
157
+ primaryType: string;
158
+ message: Record<string, unknown>;
159
+ }): Promise<string>;
160
+ sendTransaction(params: {
161
+ to: string;
162
+ value?: bigint | string;
163
+ data?: string;
164
+ }): Promise<string>;
165
+ estimateGas(params: {
166
+ to: string;
167
+ value?: bigint | string;
168
+ data?: string;
169
+ }): Promise<bigint>;
170
+ }
171
+ /**
172
+ * WDK instance interface (matches @tetherto/wdk structure)
173
+ */
174
+ interface WDKInstance {
175
+ registerWallet<T>(name: string, manager: T, config: Record<string, unknown>): WDKInstance;
176
+ registerProtocol<T>(name: string, protocol: T): WDKInstance;
177
+ getAccount(chain: string, index: number): Promise<WDKAccount>;
178
+ executeProtocol(name: string, params: Record<string, unknown>): Promise<{
179
+ txHash: string;
180
+ }>;
181
+ }
182
+ /**
183
+ * WDK constructor type
184
+ */
185
+ interface WDKConstructor {
186
+ new (seedPhrase: string): WDKInstance;
187
+ getRandomSeedPhrase(): string;
188
+ }
189
+ /**
190
+ * Balance cache configuration for T402WDK
191
+ */
192
+ interface T402BalanceCacheConfig {
193
+ /** Whether caching is enabled (default: true) */
194
+ enabled?: boolean;
195
+ /** TTL for native balance in milliseconds (default: 15000 = 15 seconds) */
196
+ nativeBalanceTTL?: number;
197
+ /** TTL for token balance in milliseconds (default: 30000 = 30 seconds) */
198
+ tokenBalanceTTL?: number;
199
+ /** TTL for aggregated balances in milliseconds (default: 60000 = 60 seconds) */
200
+ aggregatedBalanceTTL?: number;
201
+ /** Maximum cache entries (default: 500) */
202
+ maxSize?: number;
203
+ }
204
+ /**
205
+ * Extended T402 WDK configuration with cache options
206
+ */
207
+ interface T402WDKOptions {
208
+ /** Balance cache configuration */
209
+ cache?: T402BalanceCacheConfig;
210
+ }
211
+
212
+ /**
213
+ * TTL Cache implementation for balance caching
214
+ *
215
+ * Provides a generic cache with configurable TTL (Time To Live) for
216
+ * reducing RPC calls and improving performance.
217
+ */
218
+ /**
219
+ * Cache configuration options
220
+ */
221
+ interface CacheConfig {
222
+ /** Default TTL in milliseconds (default: 30000 = 30 seconds) */
223
+ defaultTTL: number;
224
+ /** Maximum number of entries (default: 1000) */
225
+ maxSize: number;
226
+ /** Whether to refresh TTL on access (default: false) */
227
+ refreshOnAccess: boolean;
228
+ }
229
+ /**
230
+ * Default cache configuration
231
+ */
232
+ declare const DEFAULT_CACHE_CONFIG: CacheConfig;
233
+ /**
234
+ * Generic TTL cache implementation
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * const cache = new TTLCache<bigint>({ defaultTTL: 60000 });
239
+ *
240
+ * // Set with default TTL
241
+ * cache.set('balance:arbitrum:0x123', 1000000n);
242
+ *
243
+ * // Set with custom TTL
244
+ * cache.set('balance:ethereum:0x456', 2000000n, 120000);
245
+ *
246
+ * // Get value (returns undefined if expired)
247
+ * const balance = cache.get('balance:arbitrum:0x123');
248
+ *
249
+ * // Check if key exists and is not expired
250
+ * if (cache.has('balance:arbitrum:0x123')) {
251
+ * // Use cached value
252
+ * }
253
+ * ```
254
+ */
255
+ declare class TTLCache<T> {
256
+ private _cache;
257
+ private _config;
258
+ private _cleanupInterval;
259
+ constructor(config?: Partial<CacheConfig>);
260
+ /**
261
+ * Get a value from the cache
262
+ *
263
+ * @param key - Cache key
264
+ * @returns The cached value or undefined if not found/expired
265
+ */
266
+ get(key: string): T | undefined;
267
+ /**
268
+ * Set a value in the cache
269
+ *
270
+ * @param key - Cache key
271
+ * @param value - Value to cache
272
+ * @param ttl - TTL in milliseconds (optional, uses default if not provided)
273
+ */
274
+ set(key: string, value: T, ttl?: number): void;
275
+ /**
276
+ * Check if a key exists and is not expired
277
+ *
278
+ * @param key - Cache key
279
+ * @returns true if key exists and is not expired
280
+ */
281
+ has(key: string): boolean;
282
+ /**
283
+ * Delete a key from the cache
284
+ *
285
+ * @param key - Cache key
286
+ * @returns true if key was deleted
287
+ */
288
+ delete(key: string): boolean;
289
+ /**
290
+ * Delete all keys matching a prefix
291
+ *
292
+ * @param prefix - Key prefix to match
293
+ * @returns Number of keys deleted
294
+ */
295
+ deleteByPrefix(prefix: string): number;
296
+ /**
297
+ * Clear all entries from the cache
298
+ */
299
+ clear(): void;
300
+ /**
301
+ * Get the number of entries in the cache (including expired)
302
+ */
303
+ get size(): number;
304
+ /**
305
+ * Get the number of valid (non-expired) entries
306
+ */
307
+ get validSize(): number;
308
+ /**
309
+ * Get all valid keys
310
+ */
311
+ keys(): string[];
312
+ /**
313
+ * Get remaining TTL for a key in milliseconds
314
+ *
315
+ * @param key - Cache key
316
+ * @returns Remaining TTL in ms, or -1 if not found/expired
317
+ */
318
+ getTTL(key: string): number;
319
+ /**
320
+ * Update TTL for an existing key
321
+ *
322
+ * @param key - Cache key
323
+ * @param ttl - New TTL in milliseconds
324
+ * @returns true if key exists and TTL was updated
325
+ */
326
+ touch(key: string, ttl?: number): boolean;
327
+ /**
328
+ * Get or set a value using a factory function
329
+ *
330
+ * @param key - Cache key
331
+ * @param factory - Function to create value if not cached
332
+ * @param ttl - TTL in milliseconds (optional)
333
+ * @returns The cached or newly created value
334
+ */
335
+ getOrSet(key: string, factory: () => Promise<T>, ttl?: number): Promise<T>;
336
+ /**
337
+ * Get cache statistics
338
+ */
339
+ getStats(): CacheStats;
340
+ /**
341
+ * Stop the cleanup interval
342
+ */
343
+ dispose(): void;
344
+ /**
345
+ * Start periodic cleanup of expired entries
346
+ */
347
+ private _startCleanup;
348
+ /**
349
+ * Remove all expired entries
350
+ */
351
+ private _removeExpired;
352
+ /**
353
+ * Evict oldest entries to make room
354
+ */
355
+ private _evictOldest;
356
+ }
357
+ /**
358
+ * Cache statistics
359
+ */
360
+ interface CacheStats {
361
+ /** Total entries including expired */
362
+ totalSize: number;
363
+ /** Valid (non-expired) entries */
364
+ validSize: number;
365
+ /** Expired entries pending cleanup */
366
+ expiredSize: number;
367
+ /** Maximum cache size */
368
+ maxSize: number;
369
+ /** Default TTL in milliseconds */
370
+ defaultTTL: number;
371
+ /** Time until oldest entry expires (ms) */
372
+ oldestExpiryMs: number;
373
+ /** Time until newest entry expires (ms) */
374
+ newestExpiryMs: number;
375
+ }
376
+ /**
377
+ * Balance cache configuration
378
+ */
379
+ interface BalanceCacheConfig {
380
+ /** Whether caching is enabled (default: true) */
381
+ enabled: boolean;
382
+ /** TTL for native balance in milliseconds (default: 15000 = 15 seconds) */
383
+ nativeBalanceTTL: number;
384
+ /** TTL for token balance in milliseconds (default: 30000 = 30 seconds) */
385
+ tokenBalanceTTL: number;
386
+ /** TTL for aggregated balances in milliseconds (default: 60000 = 60 seconds) */
387
+ aggregatedBalanceTTL: number;
388
+ /** Maximum cache entries (default: 500) */
389
+ maxSize: number;
390
+ }
391
+ /**
392
+ * Default balance cache configuration
393
+ */
394
+ declare const DEFAULT_BALANCE_CACHE_CONFIG: BalanceCacheConfig;
395
+ /**
396
+ * Specialized balance cache for WDK
397
+ *
398
+ * Provides separate TTL settings for different balance types
399
+ * and convenient methods for balance-specific caching.
400
+ *
401
+ * @example
402
+ * ```typescript
403
+ * const cache = new BalanceCache({
404
+ * tokenBalanceTTL: 60000, // 1 minute for token balances
405
+ * });
406
+ *
407
+ * // Cache token balance
408
+ * cache.setTokenBalance('arbitrum', '0xUSDT', '0xWallet', 1000000n);
409
+ *
410
+ * // Get cached balance (returns undefined if expired)
411
+ * const balance = cache.getTokenBalance('arbitrum', '0xUSDT', '0xWallet');
412
+ *
413
+ * // Or use getOrFetch pattern
414
+ * const balance = await cache.getOrFetchTokenBalance(
415
+ * 'arbitrum',
416
+ * '0xUSDT',
417
+ * '0xWallet',
418
+ * async () => await signer.getTokenBalance('0xUSDT')
419
+ * );
420
+ * ```
421
+ */
422
+ declare class BalanceCache {
423
+ private _cache;
424
+ private _aggregatedCache;
425
+ private _config;
426
+ constructor(config?: Partial<BalanceCacheConfig>);
427
+ /**
428
+ * Check if caching is enabled
429
+ */
430
+ get enabled(): boolean;
431
+ /**
432
+ * Get cache configuration
433
+ */
434
+ get config(): BalanceCacheConfig;
435
+ /**
436
+ * Get cached native balance
437
+ */
438
+ getNativeBalance(chain: string, address: string): bigint | undefined;
439
+ /**
440
+ * Set native balance in cache
441
+ */
442
+ setNativeBalance(chain: string, address: string, balance: bigint): void;
443
+ /**
444
+ * Get or fetch native balance
445
+ */
446
+ getOrFetchNativeBalance(chain: string, address: string, fetcher: () => Promise<bigint>): Promise<bigint>;
447
+ /**
448
+ * Get cached token balance
449
+ */
450
+ getTokenBalance(chain: string, token: string, address: string): bigint | undefined;
451
+ /**
452
+ * Set token balance in cache
453
+ */
454
+ setTokenBalance(chain: string, token: string, address: string, balance: bigint): void;
455
+ /**
456
+ * Get or fetch token balance
457
+ */
458
+ getOrFetchTokenBalance(chain: string, token: string, address: string, fetcher: () => Promise<bigint>): Promise<bigint>;
459
+ /**
460
+ * Get cached aggregated balance
461
+ */
462
+ getAggregatedBalance<T>(key: string): T | undefined;
463
+ /**
464
+ * Set aggregated balance in cache
465
+ */
466
+ setAggregatedBalance<T>(key: string, value: T): void;
467
+ /**
468
+ * Get or fetch aggregated balance
469
+ */
470
+ getOrFetchAggregatedBalance<T>(key: string, fetcher: () => Promise<T>): Promise<T>;
471
+ /**
472
+ * Invalidate all balances for a chain
473
+ */
474
+ invalidateChain(chain: string): number;
475
+ /**
476
+ * Invalidate all balances for an address
477
+ */
478
+ invalidateAddress(address: string): number;
479
+ /**
480
+ * Invalidate specific token balance
481
+ */
482
+ invalidateTokenBalance(chain: string, token: string, address: string): boolean;
483
+ /**
484
+ * Clear all caches
485
+ */
486
+ clear(): void;
487
+ /**
488
+ * Get cache statistics
489
+ */
490
+ getStats(): BalanceCacheStats;
491
+ /**
492
+ * Dispose of cache resources
493
+ */
494
+ dispose(): void;
495
+ private _nativeKey;
496
+ private _tokenKey;
497
+ private _aggregatedKey;
498
+ }
499
+ /**
500
+ * Balance cache statistics
501
+ */
502
+ interface BalanceCacheStats {
503
+ balanceCache: CacheStats;
504
+ aggregatedCache: CacheStats;
505
+ config: BalanceCacheConfig;
506
+ }
507
+
508
+ /**
509
+ * WDK Signer implementation for T402 payments
510
+ *
511
+ * This signer wraps the Tether WDK account to provide a T402-compatible
512
+ * signing interface for EVM chains.
513
+ */
514
+
515
+ /**
516
+ * WDK Signer for T402 EVM payments
517
+ *
518
+ * Implements the ClientEvmSigner interface from @t402/evm,
519
+ * wrapping a Tether WDK account for signing operations.
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * import { T402WDK } from '@t402/wdk';
524
+ *
525
+ * const wdk = new T402WDK(seedPhrase, { arbitrum: 'https://arb1.arbitrum.io/rpc' });
526
+ * const signer = await wdk.getSigner('arbitrum');
527
+ *
528
+ * // Use with T402 client
529
+ * const client = createT402HTTPClient({
530
+ * signers: [{ scheme: 'exact', signer }]
531
+ * });
532
+ * ```
533
+ */
534
+ declare class WDKSigner implements ClientEvmSigner {
535
+ private _wdk;
536
+ private _chain;
537
+ private _accountIndex;
538
+ private _account;
539
+ private _address;
540
+ private _timeoutMs;
541
+ /**
542
+ * Create a new WDK signer
543
+ *
544
+ * @param wdk - The WDK instance
545
+ * @param chain - Chain name (e.g., "arbitrum", "ethereum")
546
+ * @param accountIndex - HD wallet account index (default: 0)
547
+ * @param timeoutMs - Timeout for operations in milliseconds (default: 30000)
548
+ */
549
+ constructor(wdk: WDKInstance, chain: string, accountIndex?: number, timeoutMs?: number);
550
+ /**
551
+ * Get the wallet address
552
+ * Throws if signer is not initialized
553
+ */
554
+ get address(): Address;
555
+ /**
556
+ * Check if the signer is initialized
557
+ */
558
+ get isInitialized(): boolean;
559
+ /**
560
+ * Initialize the signer by fetching the account
561
+ * Must be called before using the signer
562
+ *
563
+ * @throws {SignerError} If account fetch fails
564
+ */
565
+ initialize(): Promise<void>;
566
+ /**
567
+ * Get the underlying WDK account
568
+ * Initializes if not already done
569
+ *
570
+ * @throws {SignerError} If initialization fails
571
+ */
572
+ private getAccount;
573
+ /**
574
+ * Sign EIP-712 typed data for T402 payments
575
+ *
576
+ * This is the primary signing method used by T402 for EIP-3009
577
+ * transferWithAuthorization payments.
578
+ *
579
+ * @throws {SigningError} If signing fails
580
+ */
581
+ signTypedData(message: {
582
+ domain: Record<string, unknown>;
583
+ types: Record<string, unknown>;
584
+ primaryType: string;
585
+ message: Record<string, unknown>;
586
+ }): Promise<`0x${string}`>;
587
+ /**
588
+ * Sign a personal message
589
+ *
590
+ * @throws {SigningError} If signing fails
591
+ */
592
+ signMessage(message: string | Uint8Array): Promise<`0x${string}`>;
593
+ /**
594
+ * Get the chain name
595
+ */
596
+ getChain(): string;
597
+ /**
598
+ * Get the chain ID
599
+ */
600
+ getChainId(): number;
601
+ /**
602
+ * Get the account index
603
+ */
604
+ getAccountIndex(): number;
605
+ /**
606
+ * Get native token balance (ETH, etc.)
607
+ *
608
+ * @throws {BalanceError} If balance fetch fails
609
+ */
610
+ getBalance(): Promise<bigint>;
611
+ /**
612
+ * Get ERC20 token balance
613
+ *
614
+ * @throws {BalanceError} If balance fetch fails
615
+ */
616
+ getTokenBalance(tokenAddress: Address): Promise<bigint>;
617
+ /**
618
+ * Estimate gas for a transaction
619
+ *
620
+ * @throws {TransactionError} If gas estimation fails
621
+ */
622
+ estimateGas(params: {
623
+ to: Address;
624
+ value?: bigint;
625
+ data?: string;
626
+ }): Promise<bigint>;
627
+ /**
628
+ * Send a transaction (for advanced use cases)
629
+ *
630
+ * @throws {TransactionError} If transaction fails
631
+ */
632
+ sendTransaction(params: {
633
+ to: Address;
634
+ value?: bigint;
635
+ data?: string;
636
+ }): Promise<{
637
+ hash: `0x${string}`;
638
+ }>;
639
+ }
640
+ /**
641
+ * Create an initialized WDK signer
642
+ *
643
+ * This async factory function creates and initializes a WDK signer,
644
+ * ensuring the address is available immediately.
645
+ *
646
+ * @throws {SignerError} If initialization fails
647
+ *
648
+ * @example
649
+ * ```typescript
650
+ * const signer = await createWDKSigner(wdkInstance, 'arbitrum');
651
+ * console.log('Address:', signer.address); // Works immediately
652
+ * ```
653
+ */
654
+ declare function createWDKSigner(wdk: WDKInstance, chain: string, accountIndex?: number, timeoutMs?: number): Promise<WDKSigner>;
655
+ /**
656
+ * Mock WDK signer for testing purposes
657
+ *
658
+ * Implements the same interface but uses a fixed private key
659
+ * for deterministic testing.
660
+ */
661
+ declare class MockWDKSigner implements ClientEvmSigner {
662
+ readonly address: Address;
663
+ private _privateKey;
664
+ constructor(address: Address, privateKey: `0x${string}`);
665
+ signTypedData(_message: {
666
+ domain: Record<string, unknown>;
667
+ types: Record<string, unknown>;
668
+ primaryType: string;
669
+ message: Record<string, unknown>;
670
+ }): Promise<`0x${string}`>;
671
+ signMessage(_message: string | Uint8Array): Promise<`0x${string}`>;
672
+ }
673
+
674
+ /**
675
+ * T402WDK - Main class for T402 integration with Tether WDK
676
+ *
677
+ * Provides a high-level API for:
678
+ * - Multi-chain wallet management
679
+ * - T402-compatible signers
680
+ * - Balance aggregation
681
+ * - Cross-chain bridging (USDT0)
682
+ */
683
+
684
+ /**
685
+ * T402WDK - Tether WDK integration for T402 payments
686
+ *
687
+ * @example
688
+ * ```typescript
689
+ * import { T402WDK } from '@t402/wdk';
690
+ *
691
+ * // Initialize with seed phrase
692
+ * const seedPhrase = T402WDK.generateSeedPhrase();
693
+ * const wdk = new T402WDK(seedPhrase, {
694
+ * arbitrum: 'https://arb1.arbitrum.io/rpc',
695
+ * base: 'https://mainnet.base.org'
696
+ * });
697
+ *
698
+ * // Get signer for T402 payments
699
+ * const signer = await wdk.getSigner('arbitrum');
700
+ *
701
+ * // Use with T402 client
702
+ * const client = createT402HTTPClient({
703
+ * signers: [{ scheme: 'exact', signer }]
704
+ * });
705
+ * ```
706
+ */
707
+ declare class T402WDK {
708
+ private _wdk;
709
+ private _config;
710
+ private _options;
711
+ private _normalizedChains;
712
+ private _seedPhrase;
713
+ private _signerCache;
714
+ private _balanceCache;
715
+ private _initializationError;
716
+ private static _WDK;
717
+ private static _WalletManagerEvm;
718
+ private static _BridgeUsdt0Evm;
719
+ /**
720
+ * Register the Tether WDK modules
721
+ *
722
+ * This must be called before creating T402WDK instances if you want
723
+ * to use the actual WDK. Otherwise, a mock implementation is used.
724
+ *
725
+ * @throws {WDKInitializationError} If registration fails
726
+ *
727
+ * @example
728
+ * ```typescript
729
+ * import WDK from '@tetherto/wdk';
730
+ * import WalletManagerEvm from '@tetherto/wdk-wallet-evm';
731
+ * import BridgeUsdt0Evm from '@tetherto/wdk-protocol-bridge-usdt0-evm';
732
+ *
733
+ * T402WDK.registerWDK(WDK, WalletManagerEvm, BridgeUsdt0Evm);
734
+ * ```
735
+ */
736
+ static registerWDK(WDK: WDKConstructor, WalletManagerEvm?: unknown, BridgeUsdt0Evm?: unknown): void;
737
+ /**
738
+ * Check if WDK is registered
739
+ */
740
+ static isWDKRegistered(): boolean;
741
+ /**
742
+ * Check if wallet manager is registered
743
+ */
744
+ static isWalletManagerRegistered(): boolean;
745
+ /**
746
+ * Check if bridge protocol is registered
747
+ */
748
+ static isBridgeRegistered(): boolean;
749
+ /**
750
+ * Generate a new random seed phrase
751
+ *
752
+ * @throws {WDKInitializationError} If WDK is not registered
753
+ * @returns A new BIP-39 mnemonic seed phrase
754
+ */
755
+ static generateSeedPhrase(): string;
756
+ /**
757
+ * Create a new T402WDK instance
758
+ *
759
+ * @param seedPhrase - BIP-39 mnemonic seed phrase
760
+ * @param config - Chain configuration (RPC endpoints)
761
+ * @param options - Additional options (cache configuration, etc.)
762
+ * @throws {WDKInitializationError} If seed phrase is invalid
763
+ */
764
+ constructor(seedPhrase: string, config?: T402WDKConfig, options?: T402WDKOptions);
765
+ /**
766
+ * Add default chain configurations for common chains
767
+ */
768
+ private _addDefaultChainsIfNeeded;
769
+ /**
770
+ * Initialize the underlying WDK instance
771
+ */
772
+ private _initializeWDK;
773
+ /**
774
+ * Get the underlying WDK instance
775
+ *
776
+ * @throws {WDKInitializationError} If WDK is not initialized
777
+ */
778
+ get wdk(): WDKInstance;
779
+ /**
780
+ * Check if WDK is properly initialized
781
+ */
782
+ get isInitialized(): boolean;
783
+ /**
784
+ * Get initialization error if any
785
+ */
786
+ get initializationError(): Error | null;
787
+ /**
788
+ * Get all configured chains
789
+ */
790
+ getConfiguredChains(): string[];
791
+ /**
792
+ * Get chain configuration
793
+ */
794
+ getChainConfig(chain: string): NormalizedChainConfig | undefined;
795
+ /**
796
+ * Check if a chain is configured
797
+ */
798
+ isChainConfigured(chain: string): boolean;
799
+ /**
800
+ * Get a T402-compatible signer for a chain
801
+ *
802
+ * @param chain - Chain name (e.g., "arbitrum", "ethereum")
803
+ * @param accountIndex - HD wallet account index (default: 0)
804
+ * @throws {ChainError} If chain is not configured
805
+ * @throws {SignerError} If signer creation fails
806
+ * @returns An initialized WDKSigner
807
+ */
808
+ getSigner(chain: string, accountIndex?: number): Promise<WDKSigner>;
809
+ /**
810
+ * Clear the signer cache
811
+ * Useful for forcing re-initialization of signers
812
+ */
813
+ clearSignerCache(): void;
814
+ /**
815
+ * Get wallet address for a chain
816
+ *
817
+ * @param chain - Chain name
818
+ * @param accountIndex - HD wallet account index (default: 0)
819
+ * @throws {ChainError} If chain is not configured
820
+ * @throws {SignerError} If address fetch fails
821
+ */
822
+ getAddress(chain: string, accountIndex?: number): Promise<Address>;
823
+ /**
824
+ * Get USDT0 balance for a chain
825
+ *
826
+ * Uses cache if enabled to reduce RPC calls.
827
+ *
828
+ * @throws {BalanceError} If balance fetch fails
829
+ */
830
+ getUsdt0Balance(chain: string, accountIndex?: number): Promise<bigint>;
831
+ /**
832
+ * Get USDC balance for a chain
833
+ *
834
+ * Uses cache if enabled to reduce RPC calls.
835
+ *
836
+ * @throws {BalanceError} If balance fetch fails
837
+ */
838
+ getUsdcBalance(chain: string, accountIndex?: number): Promise<bigint>;
839
+ /**
840
+ * Get all token balances for a chain
841
+ *
842
+ * Uses cache if enabled to reduce RPC calls.
843
+ *
844
+ * @throws {ChainError} If chain is not configured
845
+ * @throws {BalanceError} If balance fetch fails
846
+ */
847
+ getChainBalances(chain: string, accountIndex?: number): Promise<ChainBalance>;
848
+ /**
849
+ * Get aggregated balances across all configured chains
850
+ *
851
+ * @param accountIndex - HD wallet account index (default: 0)
852
+ * @param options - Options for balance aggregation
853
+ */
854
+ getAggregatedBalances(accountIndex?: number, options?: {
855
+ continueOnError?: boolean;
856
+ }): Promise<AggregatedBalance>;
857
+ /**
858
+ * Find the best chain for a payment
859
+ *
860
+ * Looks for the chain with sufficient balance, prioritizing USDT0.
861
+ *
862
+ * @param amount - Required amount in smallest units
863
+ * @param preferredToken - Preferred token ("USDT0" | "USDC")
864
+ * @throws {BalanceError} If balance aggregation fails
865
+ */
866
+ findBestChainForPayment(amount: bigint, preferredToken?: "USDT0" | "USDC"): Promise<{
867
+ chain: string;
868
+ token: string;
869
+ balance: bigint;
870
+ } | null>;
871
+ /**
872
+ * Bridge USDT0 between chains
873
+ *
874
+ * Uses LayerZero OFT for cross-chain transfers.
875
+ *
876
+ * @param params - Bridge parameters
877
+ * @throws {BridgeError} If bridge is not available or fails
878
+ * @returns Bridge result with transaction hash
879
+ */
880
+ bridgeUsdt0(params: BridgeParams): Promise<BridgeResult>;
881
+ /**
882
+ * Get chains that support USDT0
883
+ */
884
+ getUsdt0Chains(): string[];
885
+ /**
886
+ * Get chains that support USDT0 bridging
887
+ *
888
+ * Returns configured chains that have LayerZero OFT bridge support.
889
+ */
890
+ getBridgeableChains(): string[];
891
+ /**
892
+ * Check if bridging is supported between two chains
893
+ */
894
+ canBridge(fromChain: string, toChain: string): boolean;
895
+ /**
896
+ * Get all possible bridge destinations from a chain
897
+ */
898
+ getBridgeDestinations(fromChain: string): string[];
899
+ /**
900
+ * Check if balance caching is enabled
901
+ */
902
+ get isCacheEnabled(): boolean;
903
+ /**
904
+ * Get cache configuration
905
+ */
906
+ getCacheConfig(): BalanceCacheConfig;
907
+ /**
908
+ * Get cache statistics
909
+ */
910
+ getCacheStats(): BalanceCacheStats;
911
+ /**
912
+ * Invalidate all cached balances
913
+ *
914
+ * Call this after sending transactions to ensure fresh balance data.
915
+ */
916
+ invalidateBalanceCache(): void;
917
+ /**
918
+ * Invalidate cached balances for a specific chain
919
+ *
920
+ * @param chain - Chain name to invalidate
921
+ * @returns Number of cache entries invalidated
922
+ */
923
+ invalidateChainCache(chain: string): number;
924
+ /**
925
+ * Invalidate cached balances for a specific address
926
+ *
927
+ * @param address - Address to invalidate (case-insensitive)
928
+ * @returns Number of cache entries invalidated
929
+ */
930
+ invalidateAddressCache(address: string): number;
931
+ /**
932
+ * Dispose of cache resources
933
+ *
934
+ * Call this when the T402WDK instance is no longer needed.
935
+ */
936
+ dispose(): void;
937
+ }
938
+
939
+ /**
940
+ * Chain configuration and token addresses for T402 WDK
941
+ */
942
+
943
+ /**
944
+ * Default chain configurations
945
+ */
946
+ declare const DEFAULT_CHAINS: Record<string, Omit<NormalizedChainConfig, "provider">>;
947
+ /**
948
+ * Default RPC endpoints (public endpoints, may have rate limits)
949
+ */
950
+ declare const DEFAULT_RPC_ENDPOINTS: Record<string, string>;
951
+ /**
952
+ * USDT0 token addresses by chain
953
+ * USDT0 is Tether's omnichain token with EIP-3009 support
954
+ */
955
+ declare const USDT0_ADDRESSES: Record<string, Address>;
956
+ /**
957
+ * USDC token addresses by chain
958
+ */
959
+ declare const USDC_ADDRESSES: Record<string, Address>;
960
+ /**
961
+ * Legacy USDT addresses (no EIP-3009 support)
962
+ */
963
+ declare const USDT_LEGACY_ADDRESSES: Record<string, Address>;
964
+ /**
965
+ * All supported tokens per chain with metadata
966
+ */
967
+ interface TokenInfo {
968
+ address: Address;
969
+ symbol: string;
970
+ name: string;
971
+ decimals: number;
972
+ /** Whether token supports EIP-3009 (gasless transfers) */
973
+ supportsEIP3009: boolean;
974
+ }
975
+ declare const CHAIN_TOKENS: Record<string, TokenInfo[]>;
976
+ /**
977
+ * Normalize chain configuration from string or object
978
+ */
979
+ declare function normalizeChainConfig(chainName: string, config: string | EvmChainConfig): NormalizedChainConfig;
980
+ /**
981
+ * Get CAIP-2 network ID from chain name
982
+ */
983
+ declare function getNetworkFromChain(chain: string): string;
984
+ /**
985
+ * Get chain name from CAIP-2 network ID
986
+ */
987
+ declare function getChainFromNetwork(network: string): string | undefined;
988
+ /**
989
+ * Get chain ID from chain name
990
+ */
991
+ declare function getChainId(chain: string): number;
992
+ /**
993
+ * Get all chains that support USDT0
994
+ */
995
+ declare function getUsdt0Chains(): string[];
996
+ /**
997
+ * Get preferred token for a chain (USDT0 > USDC > USDT)
998
+ */
999
+ declare function getPreferredToken(chain: string): TokenInfo | undefined;
1000
+
1001
+ /**
1002
+ * Error classes for T402 WDK integration
1003
+ *
1004
+ * Provides structured error handling with error codes for
1005
+ * programmatic error handling and debugging.
1006
+ */
1007
+ /**
1008
+ * Error codes for WDK operations
1009
+ */
1010
+ declare enum WDKErrorCode {
1011
+ WDK_NOT_REGISTERED = 1001,
1012
+ WDK_NOT_INITIALIZED = 1002,
1013
+ INVALID_SEED_PHRASE = 1003,
1014
+ WALLET_MANAGER_NOT_REGISTERED = 1004,
1015
+ CHAIN_NOT_CONFIGURED = 2001,
1016
+ CHAIN_NOT_SUPPORTED = 2002,
1017
+ INVALID_CHAIN_CONFIG = 2003,
1018
+ UNKNOWN_CHAIN_ID = 2004,
1019
+ SIGNER_NOT_INITIALIZED = 3001,
1020
+ ACCOUNT_FETCH_FAILED = 3002,
1021
+ ADDRESS_FETCH_FAILED = 3003,
1022
+ SIGN_TYPED_DATA_FAILED = 4001,
1023
+ SIGN_MESSAGE_FAILED = 4002,
1024
+ INVALID_TYPED_DATA = 4003,
1025
+ INVALID_MESSAGE = 4004,
1026
+ USER_REJECTED_SIGNATURE = 4005,
1027
+ BALANCE_FETCH_FAILED = 5001,
1028
+ TOKEN_BALANCE_FETCH_FAILED = 5002,
1029
+ INVALID_TOKEN_ADDRESS = 5003,
1030
+ TRANSACTION_FAILED = 6001,
1031
+ GAS_ESTIMATION_FAILED = 6002,
1032
+ INSUFFICIENT_BALANCE = 6003,
1033
+ TRANSACTION_REVERTED = 6004,
1034
+ TRANSACTION_TIMEOUT = 6005,
1035
+ BRIDGE_NOT_AVAILABLE = 7001,
1036
+ BRIDGE_NOT_SUPPORTED = 7002,
1037
+ BRIDGE_FAILED = 7003,
1038
+ INSUFFICIENT_BRIDGE_FEE = 7004,
1039
+ RPC_ERROR = 8001,
1040
+ RPC_TIMEOUT = 8002,
1041
+ RPC_RATE_LIMITED = 8003,
1042
+ RPC_CONNECTION_FAILED = 8004,
1043
+ UNKNOWN_ERROR = 9999
1044
+ }
1045
+ /**
1046
+ * Base error class for WDK operations
1047
+ */
1048
+ declare class WDKError extends Error {
1049
+ readonly code: WDKErrorCode;
1050
+ readonly cause?: Error;
1051
+ readonly context?: Record<string, unknown>;
1052
+ constructor(code: WDKErrorCode, message: string, options?: {
1053
+ cause?: Error;
1054
+ context?: Record<string, unknown>;
1055
+ });
1056
+ /**
1057
+ * Create a JSON-serializable representation
1058
+ */
1059
+ toJSON(): Record<string, unknown>;
1060
+ /**
1061
+ * Check if error is retryable
1062
+ */
1063
+ isRetryable(): boolean;
1064
+ }
1065
+ /**
1066
+ * Error thrown when WDK is not properly initialized
1067
+ */
1068
+ declare class WDKInitializationError extends WDKError {
1069
+ constructor(message: string, options?: {
1070
+ cause?: Error;
1071
+ context?: Record<string, unknown>;
1072
+ });
1073
+ }
1074
+ /**
1075
+ * Error thrown for chain-related issues
1076
+ */
1077
+ declare class ChainError extends WDKError {
1078
+ readonly chain?: string;
1079
+ constructor(code: WDKErrorCode, message: string, options?: {
1080
+ chain?: string;
1081
+ cause?: Error;
1082
+ context?: Record<string, unknown>;
1083
+ });
1084
+ }
1085
+ /**
1086
+ * Error thrown for signer-related issues
1087
+ */
1088
+ declare class SignerError extends WDKError {
1089
+ readonly chain?: string;
1090
+ readonly address?: string;
1091
+ constructor(code: WDKErrorCode, message: string, options?: {
1092
+ chain?: string;
1093
+ address?: string;
1094
+ cause?: Error;
1095
+ context?: Record<string, unknown>;
1096
+ });
1097
+ }
1098
+ /**
1099
+ * Error thrown for signing operations
1100
+ */
1101
+ declare class SigningError extends WDKError {
1102
+ readonly operation: "signTypedData" | "signMessage";
1103
+ constructor(code: WDKErrorCode, message: string, options: {
1104
+ operation: "signTypedData" | "signMessage";
1105
+ cause?: Error;
1106
+ context?: Record<string, unknown>;
1107
+ });
1108
+ }
1109
+ /**
1110
+ * Error thrown for balance operations
1111
+ */
1112
+ declare class BalanceError extends WDKError {
1113
+ readonly chain?: string;
1114
+ readonly token?: string;
1115
+ constructor(code: WDKErrorCode, message: string, options?: {
1116
+ chain?: string;
1117
+ token?: string;
1118
+ cause?: Error;
1119
+ context?: Record<string, unknown>;
1120
+ });
1121
+ }
1122
+ /**
1123
+ * Error thrown for transaction operations
1124
+ */
1125
+ declare class TransactionError extends WDKError {
1126
+ readonly chain?: string;
1127
+ readonly txHash?: string;
1128
+ constructor(code: WDKErrorCode, message: string, options?: {
1129
+ chain?: string;
1130
+ txHash?: string;
1131
+ cause?: Error;
1132
+ context?: Record<string, unknown>;
1133
+ });
1134
+ }
1135
+ /**
1136
+ * Error thrown for bridge operations
1137
+ */
1138
+ declare class BridgeError extends WDKError {
1139
+ readonly fromChain?: string;
1140
+ readonly toChain?: string;
1141
+ constructor(code: WDKErrorCode, message: string, options?: {
1142
+ fromChain?: string;
1143
+ toChain?: string;
1144
+ cause?: Error;
1145
+ context?: Record<string, unknown>;
1146
+ });
1147
+ }
1148
+ /**
1149
+ * Error thrown for RPC-related issues
1150
+ */
1151
+ declare class RPCError extends WDKError {
1152
+ readonly endpoint?: string;
1153
+ readonly rpcCode?: number;
1154
+ constructor(code: WDKErrorCode, message: string, options?: {
1155
+ endpoint?: string;
1156
+ rpcCode?: number;
1157
+ cause?: Error;
1158
+ context?: Record<string, unknown>;
1159
+ });
1160
+ }
1161
+ /**
1162
+ * Wrap an unknown error into a WDKError
1163
+ */
1164
+ declare function wrapError(error: unknown, defaultCode?: WDKErrorCode, defaultMessage?: string, context?: Record<string, unknown>): WDKError;
1165
+ /**
1166
+ * Type guard to check if an error is a WDKError
1167
+ */
1168
+ declare function isWDKError(error: unknown): error is WDKError;
1169
+ /**
1170
+ * Type guard to check if an error has a specific code
1171
+ */
1172
+ declare function hasErrorCode(error: unknown, code: WDKErrorCode): boolean;
1173
+ /**
1174
+ * Retry configuration
1175
+ */
1176
+ interface RetryConfig {
1177
+ /** Maximum number of retries */
1178
+ maxRetries: number;
1179
+ /** Base delay in milliseconds */
1180
+ baseDelay: number;
1181
+ /** Maximum delay in milliseconds */
1182
+ maxDelay: number;
1183
+ /** Whether to use exponential backoff */
1184
+ exponentialBackoff: boolean;
1185
+ }
1186
+ /**
1187
+ * Default retry configuration
1188
+ */
1189
+ declare const DEFAULT_RETRY_CONFIG: RetryConfig;
1190
+ /**
1191
+ * Execute an async function with retry logic
1192
+ */
1193
+ declare function withRetry<T>(fn: () => Promise<T>, config?: Partial<RetryConfig>): Promise<T>;
1194
+ /**
1195
+ * Timeout wrapper for async operations
1196
+ */
1197
+ declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, operation?: string): Promise<T>;
1198
+
1199
+ /**
1200
+ * USDT0 Bridge integration for T402 WDK
1201
+ *
1202
+ * Provides cross-chain USDT0 transfers using:
1203
+ * 1. Tether WDK bridge protocol (if available)
1204
+ * 2. Direct LayerZero OFT integration (fallback)
1205
+ */
1206
+
1207
+ /**
1208
+ * Extended bridge result with quote information
1209
+ */
1210
+ interface BridgeQuoteResult extends BridgeResult {
1211
+ /** Native fee in wei */
1212
+ nativeFee: bigint;
1213
+ /** Minimum amount to receive */
1214
+ minAmountToReceive: bigint;
1215
+ }
1216
+ /**
1217
+ * WDK Bridge wrapper for USDT0 cross-chain transfers
1218
+ *
1219
+ * This class provides a high-level API for bridging USDT0 between chains.
1220
+ * It automatically handles:
1221
+ * - Fee estimation
1222
+ * - Token approval
1223
+ * - Transaction execution
1224
+ * - Receipt handling
1225
+ */
1226
+ declare class WdkBridge {
1227
+ private bridges;
1228
+ /**
1229
+ * Create bridge signer adapter from WDK signer
1230
+ */
1231
+ private createBridgeSigner;
1232
+ /**
1233
+ * Get or create a bridge instance for a chain
1234
+ */
1235
+ private getBridge;
1236
+ /**
1237
+ * Check if a chain supports USDT0 bridging
1238
+ */
1239
+ static supportsBridging(chain: string): boolean;
1240
+ /**
1241
+ * Get all chains that support USDT0 bridging
1242
+ */
1243
+ static getBridgeableChains(): string[];
1244
+ /**
1245
+ * Get supported destinations from a source chain
1246
+ */
1247
+ static getSupportedDestinations(fromChain: string): string[];
1248
+ }
1249
+ /**
1250
+ * Create a direct USDT0 bridge (without WDK)
1251
+ *
1252
+ * Use this when you have a viem wallet client and want to bridge directly.
1253
+ *
1254
+ * @example
1255
+ * ```typescript
1256
+ * import { createDirectBridge } from '@t402/wdk';
1257
+ * import { createWalletClient, http } from 'viem';
1258
+ * import { arbitrum } from 'viem/chains';
1259
+ *
1260
+ * const walletClient = createWalletClient({
1261
+ * chain: arbitrum,
1262
+ * transport: http('https://arb1.arbitrum.io/rpc'),
1263
+ * account: privateKeyToAccount(privateKey),
1264
+ * });
1265
+ *
1266
+ * const bridge = createDirectBridge(walletClient, 'arbitrum');
1267
+ *
1268
+ * const quote = await bridge.quote({
1269
+ * fromChain: 'arbitrum',
1270
+ * toChain: 'ethereum',
1271
+ * amount: 100_000000n,
1272
+ * recipient: walletClient.account.address,
1273
+ * });
1274
+ *
1275
+ * const result = await bridge.send({
1276
+ * fromChain: 'arbitrum',
1277
+ * toChain: 'ethereum',
1278
+ * amount: 100_000000n,
1279
+ * recipient: walletClient.account.address,
1280
+ * });
1281
+ * ```
1282
+ */
1283
+ declare function createDirectBridge(signer: BridgeSigner, chain: string): Usdt0Bridge;
1284
+
1285
+ export { type AggregatedBalance, BalanceCache, type BalanceCacheConfig, type BalanceCacheStats, BalanceError, BridgeError, type BridgeParams, type BridgeQuoteResult, type BridgeResult, CHAIN_TOKENS, type CacheConfig, type CacheStats, type ChainBalance, ChainError, DEFAULT_BALANCE_CACHE_CONFIG, DEFAULT_CACHE_CONFIG, DEFAULT_CHAINS, DEFAULT_RETRY_CONFIG, DEFAULT_RPC_ENDPOINTS, type EvmChainConfig, MockWDKSigner, type NormalizedChainConfig, RPCError, type RetryConfig, SignerError, SigningError, type T402BalanceCacheConfig, T402WDK, type T402WDKConfig, type T402WDKOptions, type T402WDKSigner, TTLCache, type TokenBalance, type TokenInfo, TransactionError, type TypedDataDomain, type TypedDataTypes, USDC_ADDRESSES, USDT0_ADDRESSES, USDT_LEGACY_ADDRESSES, type WDKAccount, type WDKConstructor, WDKError, WDKErrorCode, WDKInitializationError, type WDKInstance, WDKSigner, WdkBridge, createDirectBridge, createWDKSigner, getChainFromNetwork, getChainId, getNetworkFromChain, getPreferredToken, getUsdt0Chains, hasErrorCode, isWDKError, normalizeChainConfig, withRetry, withTimeout, wrapError };