@zubari/sdk 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +324 -0
  3. package/dist/SecureStorage-jO783AhC.d.mts +89 -0
  4. package/dist/SecureStorage-jO783AhC.d.ts +89 -0
  5. package/dist/SwapService-C0G8IXW2.d.mts +35 -0
  6. package/dist/SwapService-DZD0OJI_.d.ts +35 -0
  7. package/dist/WalletManager-DJjdq89b.d.mts +6106 -0
  8. package/dist/WalletManager-TiAdzqrn.d.ts +6106 -0
  9. package/dist/index-BLuxEdLp.d.mts +156 -0
  10. package/dist/index-BLuxEdLp.d.ts +156 -0
  11. package/dist/index-DO3T2HVe.d.ts +135 -0
  12. package/dist/index-fXVD8_D0.d.mts +135 -0
  13. package/dist/index.d.mts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +2411 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/index.mjs +2386 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/protocols/index.d.mts +181 -0
  20. package/dist/protocols/index.d.ts +181 -0
  21. package/dist/protocols/index.js +415 -0
  22. package/dist/protocols/index.js.map +1 -0
  23. package/dist/protocols/index.mjs +410 -0
  24. package/dist/protocols/index.mjs.map +1 -0
  25. package/dist/react/index.d.mts +49 -0
  26. package/dist/react/index.d.ts +49 -0
  27. package/dist/react/index.js +1573 -0
  28. package/dist/react/index.js.map +1 -0
  29. package/dist/react/index.mjs +1570 -0
  30. package/dist/react/index.mjs.map +1 -0
  31. package/dist/services/index.d.mts +198 -0
  32. package/dist/services/index.d.ts +198 -0
  33. package/dist/services/index.js +554 -0
  34. package/dist/services/index.js.map +1 -0
  35. package/dist/services/index.mjs +547 -0
  36. package/dist/services/index.mjs.map +1 -0
  37. package/dist/storage/index.d.mts +57 -0
  38. package/dist/storage/index.d.ts +57 -0
  39. package/dist/storage/index.js +442 -0
  40. package/dist/storage/index.js.map +1 -0
  41. package/dist/storage/index.mjs +435 -0
  42. package/dist/storage/index.mjs.map +1 -0
  43. package/dist/wallet/index.d.mts +8 -0
  44. package/dist/wallet/index.d.ts +8 -0
  45. package/dist/wallet/index.js +1678 -0
  46. package/dist/wallet/index.js.map +1 -0
  47. package/dist/wallet/index.mjs +1674 -0
  48. package/dist/wallet/index.mjs.map +1 -0
  49. package/package.json +136 -0
@@ -0,0 +1,1674 @@
1
+ import { Wallet, HDNodeWallet } from 'ethers';
2
+ import { createPublicClient, http, formatEther } from 'viem';
3
+ import { mainnet, sepolia } from 'viem/chains';
4
+
5
+ // src/config/networks.ts
6
+ var NETWORKS = {
7
+ bitcoin: {
8
+ name: "Bitcoin",
9
+ chainId: 0,
10
+ coinType: 0,
11
+ // m/44'/0'
12
+ rpcUrl: "https://blockstream.info/api",
13
+ explorerUrl: "https://blockstream.info",
14
+ nativeCurrency: {
15
+ name: "Bitcoin",
16
+ symbol: "BTC",
17
+ decimals: 8
18
+ },
19
+ isEvm: false
20
+ },
21
+ ethereum: {
22
+ name: "Ethereum",
23
+ chainId: 1,
24
+ coinType: 60,
25
+ // m/44'/60'
26
+ rpcUrl: "https://eth.llamarpc.com",
27
+ explorerUrl: "https://etherscan.io",
28
+ nativeCurrency: {
29
+ name: "Ether",
30
+ symbol: "ETH",
31
+ decimals: 18
32
+ },
33
+ isEvm: true
34
+ },
35
+ ton: {
36
+ name: "TON",
37
+ chainId: -239,
38
+ coinType: 607,
39
+ // m/44'/607'
40
+ rpcUrl: "https://toncenter.com/api/v2",
41
+ explorerUrl: "https://tonscan.org",
42
+ nativeCurrency: {
43
+ name: "Toncoin",
44
+ symbol: "TON",
45
+ decimals: 9
46
+ },
47
+ isEvm: false
48
+ },
49
+ tron: {
50
+ name: "TRON",
51
+ chainId: 728126428,
52
+ coinType: 195,
53
+ // m/44'/195'
54
+ rpcUrl: "https://api.trongrid.io",
55
+ explorerUrl: "https://tronscan.org",
56
+ nativeCurrency: {
57
+ name: "TRON",
58
+ symbol: "TRX",
59
+ decimals: 6
60
+ },
61
+ isEvm: false
62
+ },
63
+ solana: {
64
+ name: "Solana",
65
+ chainId: 0,
66
+ coinType: 501,
67
+ // m/44'/501'
68
+ rpcUrl: "https://api.mainnet-beta.solana.com",
69
+ explorerUrl: "https://solscan.io",
70
+ nativeCurrency: {
71
+ name: "Solana",
72
+ symbol: "SOL",
73
+ decimals: 9
74
+ },
75
+ isEvm: false
76
+ },
77
+ spark: {
78
+ name: "Spark (Lightning)",
79
+ chainId: 0,
80
+ coinType: 998,
81
+ // m/44'/998'
82
+ rpcUrl: "",
83
+ explorerUrl: "",
84
+ nativeCurrency: {
85
+ name: "Bitcoin",
86
+ symbol: "BTC",
87
+ decimals: 8
88
+ },
89
+ isEvm: false
90
+ }
91
+ };
92
+ var TESTNET_NETWORKS = {
93
+ ethereum: {
94
+ name: "Sepolia",
95
+ chainId: 11155111,
96
+ // Using eth-sepolia.g.alchemy.com public endpoint (more reliable than rpc.sepolia.org)
97
+ // Fallback order: 1. Alchemy public, 2. Infura public, 3. BlockPi
98
+ rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
99
+ explorerUrl: "https://sepolia.etherscan.io"
100
+ },
101
+ solana: {
102
+ name: "Solana Devnet",
103
+ rpcUrl: "https://api.devnet.solana.com",
104
+ explorerUrl: "https://solscan.io?cluster=devnet"
105
+ }
106
+ };
107
+ var DERIVATION_PATHS = {
108
+ bitcoin: "m/44'/0'/0'/0",
109
+ ethereum: "m/44'/60'/0'/0",
110
+ ton: "m/44'/607'/0'/0",
111
+ tron: "m/44'/195'/0'/0",
112
+ solana: "m/44'/501'/0'/0",
113
+ spark: "m/44'/998'/0'/0"
114
+ };
115
+ function getNetworkConfig(network, isTestnet = false) {
116
+ const mainnetConfig = NETWORKS[network];
117
+ if (!isTestnet) return mainnetConfig;
118
+ const testnetOverrides = TESTNET_NETWORKS[network];
119
+ if (!testnetOverrides) return mainnetConfig;
120
+ return {
121
+ ...mainnetConfig,
122
+ ...testnetOverrides
123
+ };
124
+ }
125
+
126
+ // src/config/contracts.ts
127
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
128
+ var ZUBARI_CONTRACTS = {
129
+ testnet: {
130
+ // Ethereum Sepolia (11155111) - Deployed 2024-12-09
131
+ registry: "0xEdDf443D48832f23D4A0bED4C4c5eF200B38A7d3",
132
+ nft: "0xdc37e25650D685e4c38124aC314477Ea5f508a9e",
133
+ marketplace: ZERO_ADDRESS,
134
+ // Not yet deployed
135
+ tips: "0xFDc353edC63Cd3D4bba35bB43861369516a9Dc85",
136
+ subscriptions: "0x8C05F8aD2F295fB7f3596043a7c37C98A5F7fAB8",
137
+ payouts: "0x804Fe503936E8b8d3D5Dbb62AF4fB6Fe7265Fb2c",
138
+ entryPoint: "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
139
+ paymaster: ZERO_ADDRESS,
140
+ // Not yet deployed
141
+ accountFactory: ZERO_ADDRESS,
142
+ // Not yet deployed
143
+ usdt: "0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0",
144
+ // USDT on Sepolia
145
+ weth: "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14"
146
+ },
147
+ mainnet: {
148
+ // Ethereum Mainnet (1)
149
+ registry: ZERO_ADDRESS,
150
+ nft: ZERO_ADDRESS,
151
+ marketplace: ZERO_ADDRESS,
152
+ tips: ZERO_ADDRESS,
153
+ subscriptions: ZERO_ADDRESS,
154
+ payouts: ZERO_ADDRESS,
155
+ entryPoint: "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
156
+ paymaster: ZERO_ADDRESS,
157
+ accountFactory: ZERO_ADDRESS,
158
+ usdt: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
159
+ // USDT on Ethereum
160
+ weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
161
+ }
162
+ };
163
+ function getContractAddresses(network) {
164
+ return ZUBARI_CONTRACTS[network];
165
+ }
166
+
167
+ // src/wallet/ZubariWallet.ts
168
+ var ZubariWallet = class {
169
+ seed;
170
+ config;
171
+ accounts = /* @__PURE__ */ new Map();
172
+ initialized = false;
173
+ constructor(seed, config) {
174
+ this.seed = seed;
175
+ this.config = {
176
+ network: config.network || "mainnet",
177
+ enabledNetworks: config.enabledNetworks || ["ethereum"],
178
+ gasless: config.gasless ?? false,
179
+ paymasterUrl: config.paymasterUrl,
180
+ bundlerUrl: config.bundlerUrl,
181
+ rpcUrls: config.rpcUrls
182
+ };
183
+ }
184
+ /**
185
+ * Initialize the wallet by deriving accounts for all enabled networks
186
+ */
187
+ async initialize() {
188
+ if (this.initialized) return;
189
+ for (const network of this.config.enabledNetworks) {
190
+ await this.deriveAccount(network);
191
+ }
192
+ this.initialized = true;
193
+ }
194
+ /**
195
+ * Derive account for a specific network using BIP-44
196
+ */
197
+ async deriveAccount(network, index = 0) {
198
+ getNetworkConfig(network, this.config.network === "testnet");
199
+ const basePath = DERIVATION_PATHS[network];
200
+ const derivationPath = `${basePath}/${index}`;
201
+ const account = {
202
+ network,
203
+ address: "",
204
+ // Will be derived using WDK
205
+ publicKey: "",
206
+ derivationPath
207
+ };
208
+ this.accounts.set(network, account);
209
+ return account;
210
+ }
211
+ /**
212
+ * Get account for a specific network
213
+ */
214
+ async getAccount(network, index = 0) {
215
+ const existing = this.accounts.get(network);
216
+ if (existing && existing.derivationPath.endsWith(`/${index}`)) {
217
+ return existing;
218
+ }
219
+ return this.deriveAccount(network, index);
220
+ }
221
+ /**
222
+ * Get address for a specific network
223
+ */
224
+ async getAddress(network) {
225
+ const account = await this.getAccount(network);
226
+ return account.address;
227
+ }
228
+ /**
229
+ * Get all addresses for enabled networks
230
+ */
231
+ async getAllAddresses() {
232
+ const addresses = {};
233
+ for (const network of this.config.enabledNetworks) {
234
+ addresses[network] = await this.getAddress(network);
235
+ }
236
+ return addresses;
237
+ }
238
+ /**
239
+ * Get balance for a specific network
240
+ */
241
+ async getBalance(network) {
242
+ const networkConfig = getNetworkConfig(network, this.config.network === "testnet");
243
+ return {
244
+ network,
245
+ native: {
246
+ symbol: networkConfig.nativeCurrency.symbol,
247
+ balance: BigInt(0),
248
+ balanceFormatted: "0",
249
+ balanceUsd: 0
250
+ },
251
+ tokens: []
252
+ };
253
+ }
254
+ /**
255
+ * Get balances for all enabled networks
256
+ */
257
+ async getAllBalances() {
258
+ const balances = [];
259
+ for (const network of this.config.enabledNetworks) {
260
+ balances.push(await this.getBalance(network));
261
+ }
262
+ return balances;
263
+ }
264
+ /**
265
+ * Get total portfolio value in USD
266
+ */
267
+ async getTotalPortfolioUsd() {
268
+ const balances = await this.getAllBalances();
269
+ let total = 0;
270
+ for (const balance of balances) {
271
+ total += balance.native.balanceUsd;
272
+ for (const token of balance.tokens) {
273
+ total += token.balanceUsd;
274
+ }
275
+ }
276
+ return total;
277
+ }
278
+ /**
279
+ * Send native currency on a specific network
280
+ */
281
+ async send(network, params) {
282
+ const { to, amount, gasless } = params;
283
+ gasless ?? (this.config.gasless && network === "ethereum");
284
+ return {
285
+ hash: "",
286
+ network,
287
+ status: "pending"
288
+ };
289
+ }
290
+ /**
291
+ * Send ERC-20 token on EVM networks
292
+ */
293
+ async sendToken(network, token, to, amount) {
294
+ const networkConfig = getNetworkConfig(network, this.config.network === "testnet");
295
+ if (!networkConfig.isEvm) {
296
+ throw new Error(`sendToken is only supported on EVM networks. ${network} is not an EVM chain.`);
297
+ }
298
+ return {
299
+ hash: "",
300
+ network,
301
+ status: "pending"
302
+ };
303
+ }
304
+ /**
305
+ * Send Bitcoin on-chain using WalletManagerBtc
306
+ * @param to - Destination address (bc1q... for native segwit)
307
+ * @param amount - Amount in satoshis
308
+ */
309
+ async sendBitcoin(to, amount) {
310
+ if (!this.isValidBitcoinAddress(to)) {
311
+ throw new Error("Invalid Bitcoin address. Expected bc1q... (native segwit) format.");
312
+ }
313
+ return this.send("bitcoin", { to, amount });
314
+ }
315
+ /**
316
+ * Validate Bitcoin address format
317
+ */
318
+ isValidBitcoinAddress(address) {
319
+ if (address.startsWith("bc1q") || address.startsWith("tb1q")) {
320
+ return address.length >= 42 && address.length <= 62;
321
+ }
322
+ if (address.startsWith("1") || address.startsWith("m") || address.startsWith("n")) {
323
+ return address.length >= 25 && address.length <= 34;
324
+ }
325
+ if (address.startsWith("3") || address.startsWith("2")) {
326
+ return address.length >= 25 && address.length <= 34;
327
+ }
328
+ return false;
329
+ }
330
+ /**
331
+ * Get Bitcoin address (native segwit bc1q...)
332
+ */
333
+ async getBitcoinAddress() {
334
+ const account = await this.getAccount("bitcoin");
335
+ return account.address;
336
+ }
337
+ /**
338
+ * Pay Lightning invoice via Spark network
339
+ * Uses WDK WalletManagerSpark (m/44'/998')
340
+ * @param invoice - Lightning invoice string (lnbc...)
341
+ */
342
+ async sendLightning(invoice) {
343
+ if (!this.isValidLightningInvoice(invoice)) {
344
+ throw new Error("Invalid Lightning invoice format. Expected lnbc... or lntb...");
345
+ }
346
+ const invoiceDetails = this.decodeLightningInvoice(invoice);
347
+ return {
348
+ hash: "",
349
+ // Will be payment hash from Spark
350
+ network: "spark",
351
+ status: "pending",
352
+ metadata: {
353
+ invoice,
354
+ amount: invoiceDetails.amount,
355
+ destination: invoiceDetails.destination
356
+ }
357
+ };
358
+ }
359
+ /**
360
+ * Create Lightning invoice via Spark
361
+ * @param amount - Amount in millisatoshis
362
+ * @param memo - Optional payment memo
363
+ * @returns Lightning invoice string (lnbc...)
364
+ */
365
+ async createLightningInvoice(amount, memo) {
366
+ if (amount <= 0) {
367
+ throw new Error("Invoice amount must be greater than 0");
368
+ }
369
+ const isTestnet = this.config.network === "testnet";
370
+ const prefix = isTestnet ? "lntb" : "lnbc";
371
+ return `${prefix}${amount}m1...`;
372
+ }
373
+ /**
374
+ * Validate Lightning invoice format
375
+ */
376
+ isValidLightningInvoice(invoice) {
377
+ const lowerInvoice = invoice.toLowerCase();
378
+ return lowerInvoice.startsWith("lnbc") || // Mainnet
379
+ lowerInvoice.startsWith("lntb") || // Testnet
380
+ lowerInvoice.startsWith("lnbcrt");
381
+ }
382
+ /**
383
+ * Decode Lightning invoice (basic parsing)
384
+ */
385
+ decodeLightningInvoice(invoice) {
386
+ return {
387
+ amount: BigInt(0),
388
+ destination: "",
389
+ expiry: 3600
390
+ };
391
+ }
392
+ /**
393
+ * Get Lightning (Spark) balance
394
+ */
395
+ async getLightningBalance() {
396
+ return {
397
+ available: BigInt(0),
398
+ pending: BigInt(0)
399
+ };
400
+ }
401
+ /**
402
+ * Get configuration
403
+ */
404
+ getConfig() {
405
+ return { ...this.config };
406
+ }
407
+ /**
408
+ * Check if wallet is initialized
409
+ */
410
+ isInitialized() {
411
+ return this.initialized;
412
+ }
413
+ /**
414
+ * Get contract addresses for current network
415
+ */
416
+ getContractAddresses() {
417
+ return getContractAddresses(this.config.network);
418
+ }
419
+ };
420
+
421
+ // src/security/KeyManager.ts
422
+ var KeyManager = class {
423
+ static ALGORITHM = "AES-GCM";
424
+ static KEY_LENGTH = 256;
425
+ static IV_LENGTH = 12;
426
+ static SALT_LENGTH = 16;
427
+ static PBKDF2_ITERATIONS = 1e5;
428
+ /**
429
+ * Encrypt a seed phrase with a password
430
+ */
431
+ static async encryptSeed(seed, password) {
432
+ const encoder = new TextEncoder();
433
+ const seedData = encoder.encode(seed);
434
+ const salt = crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH));
435
+ const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
436
+ const key = await this.deriveKey(password, salt);
437
+ const encrypted = await crypto.subtle.encrypt(
438
+ { name: this.ALGORITHM, iv },
439
+ key,
440
+ seedData
441
+ );
442
+ const combined = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
443
+ combined.set(salt, 0);
444
+ combined.set(iv, salt.length);
445
+ combined.set(new Uint8Array(encrypted), salt.length + iv.length);
446
+ return btoa(String.fromCharCode(...combined));
447
+ }
448
+ /**
449
+ * Decrypt a seed phrase with a password
450
+ */
451
+ static async decryptSeed(encryptedData, password) {
452
+ const combined = new Uint8Array(
453
+ atob(encryptedData).split("").map((c) => c.charCodeAt(0))
454
+ );
455
+ const salt = combined.slice(0, this.SALT_LENGTH);
456
+ const iv = combined.slice(this.SALT_LENGTH, this.SALT_LENGTH + this.IV_LENGTH);
457
+ const encrypted = combined.slice(this.SALT_LENGTH + this.IV_LENGTH);
458
+ const key = await this.deriveKey(password, salt);
459
+ const decrypted = await crypto.subtle.decrypt(
460
+ { name: this.ALGORITHM, iv },
461
+ key,
462
+ encrypted
463
+ );
464
+ const decoder = new TextDecoder();
465
+ return decoder.decode(decrypted);
466
+ }
467
+ /**
468
+ * Derive encryption key from password using PBKDF2
469
+ */
470
+ static async deriveKey(password, salt) {
471
+ const encoder = new TextEncoder();
472
+ const passwordData = encoder.encode(password);
473
+ const keyMaterial = await crypto.subtle.importKey(
474
+ "raw",
475
+ passwordData,
476
+ "PBKDF2",
477
+ false,
478
+ ["deriveKey"]
479
+ );
480
+ return crypto.subtle.deriveKey(
481
+ {
482
+ name: "PBKDF2",
483
+ salt: salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength),
484
+ iterations: this.PBKDF2_ITERATIONS,
485
+ hash: "SHA-256"
486
+ },
487
+ keyMaterial,
488
+ { name: this.ALGORITHM, length: this.KEY_LENGTH },
489
+ false,
490
+ ["encrypt", "decrypt"]
491
+ );
492
+ }
493
+ /**
494
+ * Validate a BIP-39 seed phrase (basic validation)
495
+ */
496
+ static validateSeedPhrase(seed) {
497
+ const words = seed.trim().split(/\s+/);
498
+ const validWordCounts = [12, 15, 18, 21, 24];
499
+ return validWordCounts.includes(words.length);
500
+ }
501
+ /**
502
+ * Generate a random encryption key (for backup purposes)
503
+ */
504
+ static generateBackupKey() {
505
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
506
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
507
+ }
508
+ };
509
+
510
+ // src/storage/SecureStorage.ts
511
+ var KeychainStorageAdapter = class {
512
+ serviceName;
513
+ constructor(serviceName = "com.zubari.wallet") {
514
+ this.serviceName = serviceName;
515
+ }
516
+ async setItem(key, value) {
517
+ if (typeof global !== "undefined" && global.KeychainModule) {
518
+ await global.KeychainModule.setItem(this.serviceName, key, value);
519
+ } else {
520
+ throw new Error("Keychain not available on this platform");
521
+ }
522
+ }
523
+ async getItem(key) {
524
+ if (typeof global !== "undefined" && global.KeychainModule) {
525
+ return global.KeychainModule.getItem(this.serviceName, key);
526
+ }
527
+ throw new Error("Keychain not available on this platform");
528
+ }
529
+ async removeItem(key) {
530
+ if (typeof global !== "undefined" && global.KeychainModule) {
531
+ await global.KeychainModule.removeItem(this.serviceName, key);
532
+ } else {
533
+ throw new Error("Keychain not available on this platform");
534
+ }
535
+ }
536
+ async hasItem(key) {
537
+ const value = await this.getItem(key);
538
+ return value !== null;
539
+ }
540
+ async clear() {
541
+ if (typeof global !== "undefined" && global.KeychainModule) {
542
+ await global.KeychainModule.clear(this.serviceName);
543
+ } else {
544
+ throw new Error("Keychain not available on this platform");
545
+ }
546
+ }
547
+ };
548
+ var KeystoreStorageAdapter = class {
549
+ alias;
550
+ constructor(alias = "zubari_wallet_keys") {
551
+ this.alias = alias;
552
+ }
553
+ async setItem(key, value) {
554
+ if (typeof global !== "undefined" && global.KeystoreModule) {
555
+ await global.KeystoreModule.setItem(this.alias, key, value);
556
+ } else {
557
+ throw new Error("Keystore not available on this platform");
558
+ }
559
+ }
560
+ async getItem(key) {
561
+ if (typeof global !== "undefined" && global.KeystoreModule) {
562
+ return global.KeystoreModule.getItem(this.alias, key);
563
+ }
564
+ throw new Error("Keystore not available on this platform");
565
+ }
566
+ async removeItem(key) {
567
+ if (typeof global !== "undefined" && global.KeystoreModule) {
568
+ await global.KeystoreModule.removeItem(this.alias, key);
569
+ } else {
570
+ throw new Error("Keystore not available on this platform");
571
+ }
572
+ }
573
+ async hasItem(key) {
574
+ const value = await this.getItem(key);
575
+ return value !== null;
576
+ }
577
+ async clear() {
578
+ if (typeof global !== "undefined" && global.KeystoreModule) {
579
+ await global.KeystoreModule.clear(this.alias);
580
+ } else {
581
+ throw new Error("Keystore not available on this platform");
582
+ }
583
+ }
584
+ };
585
+ var WebEncryptedStorageAdapter = class {
586
+ encryptionKey = null;
587
+ storagePrefix;
588
+ constructor(storagePrefix = "zubari_") {
589
+ this.storagePrefix = storagePrefix;
590
+ }
591
+ /**
592
+ * Initialize with a password-derived key
593
+ */
594
+ async initialize(password) {
595
+ const encoder = new TextEncoder();
596
+ const salt = this.getSalt();
597
+ const keyMaterial = await crypto.subtle.importKey(
598
+ "raw",
599
+ encoder.encode(password),
600
+ "PBKDF2",
601
+ false,
602
+ ["deriveKey"]
603
+ );
604
+ this.encryptionKey = await crypto.subtle.deriveKey(
605
+ {
606
+ name: "PBKDF2",
607
+ salt: salt.buffer,
608
+ iterations: 1e5,
609
+ hash: "SHA-256"
610
+ },
611
+ keyMaterial,
612
+ { name: "AES-GCM", length: 256 },
613
+ false,
614
+ ["encrypt", "decrypt"]
615
+ );
616
+ }
617
+ getSalt() {
618
+ const saltKey = `${this.storagePrefix}salt`;
619
+ let saltHex = localStorage.getItem(saltKey);
620
+ if (!saltHex) {
621
+ const salt = crypto.getRandomValues(new Uint8Array(16));
622
+ saltHex = Array.from(salt).map((b) => b.toString(16).padStart(2, "0")).join("");
623
+ localStorage.setItem(saltKey, saltHex);
624
+ }
625
+ return new Uint8Array(
626
+ saltHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
627
+ );
628
+ }
629
+ async setItem(key, value) {
630
+ if (!this.encryptionKey) {
631
+ throw new Error("Storage not initialized. Call initialize() first.");
632
+ }
633
+ const encoder = new TextEncoder();
634
+ const iv = crypto.getRandomValues(new Uint8Array(12));
635
+ const encrypted = await crypto.subtle.encrypt(
636
+ { name: "AES-GCM", iv },
637
+ this.encryptionKey,
638
+ encoder.encode(value)
639
+ );
640
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
641
+ combined.set(iv);
642
+ combined.set(new Uint8Array(encrypted), iv.length);
643
+ const base64 = btoa(String.fromCharCode(...combined));
644
+ localStorage.setItem(`${this.storagePrefix}${key}`, base64);
645
+ }
646
+ async getItem(key) {
647
+ if (!this.encryptionKey) {
648
+ throw new Error("Storage not initialized. Call initialize() first.");
649
+ }
650
+ const base64 = localStorage.getItem(`${this.storagePrefix}${key}`);
651
+ if (!base64) return null;
652
+ try {
653
+ const combined = new Uint8Array(
654
+ atob(base64).split("").map((c) => c.charCodeAt(0))
655
+ );
656
+ const iv = combined.slice(0, 12);
657
+ const encrypted = combined.slice(12);
658
+ const decrypted = await crypto.subtle.decrypt(
659
+ { name: "AES-GCM", iv },
660
+ this.encryptionKey,
661
+ encrypted
662
+ );
663
+ const decoder = new TextDecoder();
664
+ return decoder.decode(decrypted);
665
+ } catch {
666
+ return null;
667
+ }
668
+ }
669
+ async removeItem(key) {
670
+ localStorage.removeItem(`${this.storagePrefix}${key}`);
671
+ }
672
+ async hasItem(key) {
673
+ return localStorage.getItem(`${this.storagePrefix}${key}`) !== null;
674
+ }
675
+ async clear() {
676
+ const keysToRemove = [];
677
+ for (let i = 0; i < localStorage.length; i++) {
678
+ const key = localStorage.key(i);
679
+ if (key?.startsWith(this.storagePrefix)) {
680
+ keysToRemove.push(key);
681
+ }
682
+ }
683
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
684
+ }
685
+ };
686
+ var MemoryStorageAdapter = class {
687
+ storage = /* @__PURE__ */ new Map();
688
+ async setItem(key, value) {
689
+ this.storage.set(key, value);
690
+ }
691
+ async getItem(key) {
692
+ return this.storage.get(key) || null;
693
+ }
694
+ async removeItem(key) {
695
+ this.storage.delete(key);
696
+ }
697
+ async hasItem(key) {
698
+ return this.storage.has(key);
699
+ }
700
+ async clear() {
701
+ this.storage.clear();
702
+ }
703
+ };
704
+ function createSecureStorage() {
705
+ if (typeof global !== "undefined" && global.nativeModuleProxy !== void 0) {
706
+ const Platform = global.Platform;
707
+ if (Platform?.OS === "ios") {
708
+ return new KeychainStorageAdapter();
709
+ } else if (Platform?.OS === "android") {
710
+ return new KeystoreStorageAdapter();
711
+ }
712
+ }
713
+ if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
714
+ return new WebEncryptedStorageAdapter();
715
+ }
716
+ return new MemoryStorageAdapter();
717
+ }
718
+
719
+ // src/services/WdkApiClient.ts
720
+ var WdkApiClient = class {
721
+ config;
722
+ constructor(config) {
723
+ this.config = {
724
+ baseUrl: config.baseUrl,
725
+ timeout: config.timeout || 3e4
726
+ };
727
+ }
728
+ /**
729
+ * Generate a new BIP-39 seed phrase using Tether WDK
730
+ */
731
+ async generateSeed() {
732
+ try {
733
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {
734
+ method: "POST",
735
+ headers: {
736
+ "Content-Type": "application/json"
737
+ }
738
+ });
739
+ return await response.json();
740
+ } catch (error) {
741
+ return {
742
+ success: false,
743
+ error: error instanceof Error ? error.message : "Failed to generate seed"
744
+ };
745
+ }
746
+ }
747
+ /**
748
+ * Validate a BIP-39 seed phrase
749
+ */
750
+ async validateSeed(seed) {
751
+ try {
752
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {
753
+ method: "POST",
754
+ headers: {
755
+ "Content-Type": "application/json"
756
+ },
757
+ body: JSON.stringify({ seed })
758
+ });
759
+ return await response.json();
760
+ } catch (error) {
761
+ return {
762
+ success: false,
763
+ error: error instanceof Error ? error.message : "Failed to validate seed"
764
+ };
765
+ }
766
+ }
767
+ /**
768
+ * Derive address for a specific chain using Tether WDK
769
+ */
770
+ async deriveAddress(seed, chain, network = "testnet") {
771
+ try {
772
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {
773
+ method: "POST",
774
+ headers: {
775
+ "Content-Type": "application/json"
776
+ },
777
+ body: JSON.stringify({ seed, chain, network })
778
+ });
779
+ return await response.json();
780
+ } catch (error) {
781
+ return {
782
+ success: false,
783
+ error: error instanceof Error ? error.message : "Failed to derive address"
784
+ };
785
+ }
786
+ }
787
+ /**
788
+ * Derive addresses for all chains using Tether WDK
789
+ */
790
+ async deriveAllAddresses(seed, network = "testnet") {
791
+ try {
792
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {
793
+ method: "POST",
794
+ headers: {
795
+ "Content-Type": "application/json"
796
+ },
797
+ body: JSON.stringify({ seed, network })
798
+ });
799
+ return await response.json();
800
+ } catch (error) {
801
+ return {
802
+ success: false,
803
+ error: error instanceof Error ? error.message : "Failed to derive addresses"
804
+ };
805
+ }
806
+ }
807
+ };
808
+ var DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
809
+ var wdkApiClient = null;
810
+ function getWdkApiClient(baseUrl) {
811
+ if (!wdkApiClient || baseUrl && wdkApiClient["config"].baseUrl !== baseUrl) {
812
+ wdkApiClient = new WdkApiClient({
813
+ baseUrl: baseUrl || DEFAULT_API_URL
814
+ });
815
+ }
816
+ return wdkApiClient;
817
+ }
818
+
819
+ // src/services/WdkService.ts
820
+ var WdkManager;
821
+ var WalletManagerBtc;
822
+ var WalletManagerEvm;
823
+ var WalletManagerSolana;
824
+ var WalletManagerTon;
825
+ var WalletManagerTron;
826
+ var WalletManagerSpark;
827
+ var wdkLoaded = false;
828
+ var wdkLoadError = null;
829
+ var dynamicImport = new Function("specifier", "return import(specifier)");
830
+ async function loadWdkModules() {
831
+ if (wdkLoaded) return;
832
+ if (wdkLoadError) throw wdkLoadError;
833
+ try {
834
+ const [wdk, btc, evm, solana, ton, tron, spark] = await Promise.all([
835
+ dynamicImport("@tetherto/wdk"),
836
+ dynamicImport("@tetherto/wdk-wallet-btc"),
837
+ dynamicImport("@tetherto/wdk-wallet-evm"),
838
+ dynamicImport("@tetherto/wdk-wallet-solana"),
839
+ dynamicImport("@tetherto/wdk-wallet-ton"),
840
+ dynamicImport("@tetherto/wdk-wallet-tron"),
841
+ dynamicImport("@tetherto/wdk-wallet-spark")
842
+ ]);
843
+ WdkManager = wdk.default;
844
+ WalletManagerBtc = btc.default;
845
+ WalletManagerEvm = evm.default;
846
+ WalletManagerSolana = solana.default;
847
+ WalletManagerTon = ton.default;
848
+ WalletManagerTron = tron.default;
849
+ WalletManagerSpark = spark.default;
850
+ wdkLoaded = true;
851
+ } catch (error) {
852
+ wdkLoadError = error instanceof Error ? error : new Error("Failed to load WDK modules");
853
+ console.error("Failed to load WDK modules:", error);
854
+ throw wdkLoadError;
855
+ }
856
+ }
857
+ var DERIVATION_PATHS2 = {
858
+ bitcoin: "m/84'/0'/0'/0/0",
859
+ // BIP-84 for native SegWit
860
+ ethereum: "m/44'/60'/0'/0/0",
861
+ ton: "m/44'/607'/0'",
862
+ // Updated for v1.0.0-beta.6+
863
+ tron: "m/44'/195'/0'/0/0",
864
+ solana: "m/44'/501'/0'/0'",
865
+ // Updated for v1.0.0-beta.4+
866
+ spark: "m/44'/998'/0'/0/0"
867
+ };
868
+ var DEFAULT_RPC_URLS = {
869
+ mainnet: {
870
+ ethereum: "https://eth.llamarpc.com",
871
+ solana: "https://api.mainnet-beta.solana.com",
872
+ ton: "https://toncenter.com/api/v2/jsonRPC",
873
+ tron: "https://api.trongrid.io"
874
+ },
875
+ testnet: {
876
+ ethereum: "https://ethereum-sepolia-rpc.publicnode.com",
877
+ solana: "https://api.devnet.solana.com",
878
+ ton: "https://testnet.toncenter.com/api/v2/jsonRPC",
879
+ tron: "https://api.shasta.trongrid.io"
880
+ }
881
+ };
882
+ var WdkService = class {
883
+ seed = null;
884
+ config;
885
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
886
+ wallets = {};
887
+ constructor(config = {}) {
888
+ this.config = {
889
+ network: config.network || "testnet",
890
+ rpcUrls: config.rpcUrls
891
+ };
892
+ }
893
+ /**
894
+ * Check if WDK modules are loaded
895
+ */
896
+ static isLoaded() {
897
+ return wdkLoaded;
898
+ }
899
+ /**
900
+ * Ensure WDK modules are loaded
901
+ */
902
+ async ensureLoaded() {
903
+ await loadWdkModules();
904
+ }
905
+ /**
906
+ * Load WDK modules (call this before using sync methods)
907
+ */
908
+ async loadModules() {
909
+ await loadWdkModules();
910
+ }
911
+ /**
912
+ * Generate a random BIP-39 seed phrase (12 words)
913
+ */
914
+ async generateSeedPhrase() {
915
+ await this.ensureLoaded();
916
+ return WdkManager.getRandomSeedPhrase();
917
+ }
918
+ /**
919
+ * Validate a BIP-39 seed phrase
920
+ */
921
+ async isValidSeed(seed) {
922
+ await this.ensureLoaded();
923
+ return WdkManager.isValidSeed(seed);
924
+ }
925
+ /**
926
+ * Validate seed phrase (sync version - basic check)
927
+ */
928
+ isValidSeedSync(seed) {
929
+ const words = seed.trim().split(/\s+/);
930
+ return words.length === 12 || words.length === 24;
931
+ }
932
+ /**
933
+ * Initialize the service with a seed phrase
934
+ */
935
+ async initialize(seed) {
936
+ await this.ensureLoaded();
937
+ if (!WdkManager.isValidSeed(seed)) {
938
+ throw new Error("Invalid seed phrase");
939
+ }
940
+ this.seed = seed;
941
+ this.wallets = {};
942
+ }
943
+ /**
944
+ * Get RPC URL for a chain
945
+ */
946
+ getRpcUrl(chain) {
947
+ const networkUrls = DEFAULT_RPC_URLS[this.config.network];
948
+ if (this.config.rpcUrls?.[chain]) {
949
+ return this.config.rpcUrls[chain];
950
+ }
951
+ return networkUrls[chain] || "";
952
+ }
953
+ /**
954
+ * Get or create wallet instance for a specific chain
955
+ */
956
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
957
+ async getWallet(chain) {
958
+ if (!this.seed) {
959
+ throw new Error("WDK service not initialized. Call initialize() first.");
960
+ }
961
+ if (this.wallets[chain]) {
962
+ return this.wallets[chain];
963
+ }
964
+ const isTestnet = this.config.network === "testnet";
965
+ try {
966
+ switch (chain) {
967
+ case "ethereum": {
968
+ const rpcUrl = this.getRpcUrl("ethereum");
969
+ const wallet = new WalletManagerEvm(this.seed, { provider: rpcUrl });
970
+ this.wallets[chain] = wallet;
971
+ return wallet;
972
+ }
973
+ case "bitcoin": {
974
+ const wallet = new WalletManagerBtc(this.seed, {
975
+ network: isTestnet ? "testnet" : "bitcoin"
976
+ });
977
+ this.wallets[chain] = wallet;
978
+ return wallet;
979
+ }
980
+ case "solana": {
981
+ const rpcUrl = this.getRpcUrl("solana");
982
+ const wallet = new WalletManagerSolana(this.seed, {
983
+ rpcUrl
984
+ });
985
+ this.wallets[chain] = wallet;
986
+ return wallet;
987
+ }
988
+ case "ton": {
989
+ const url = this.getRpcUrl("ton");
990
+ const wallet = new WalletManagerTon(this.seed, {
991
+ tonClient: { url }
992
+ });
993
+ this.wallets[chain] = wallet;
994
+ return wallet;
995
+ }
996
+ case "tron": {
997
+ const fullHost = this.getRpcUrl("tron");
998
+ const wallet = new WalletManagerTron(this.seed, {
999
+ provider: fullHost
1000
+ });
1001
+ this.wallets[chain] = wallet;
1002
+ return wallet;
1003
+ }
1004
+ case "spark": {
1005
+ const wallet = new WalletManagerSpark(this.seed, {
1006
+ network: isTestnet ? "TESTNET" : "MAINNET"
1007
+ });
1008
+ this.wallets[chain] = wallet;
1009
+ return wallet;
1010
+ }
1011
+ default:
1012
+ throw new Error(`Unsupported chain: ${chain}`);
1013
+ }
1014
+ } catch (error) {
1015
+ console.error(`Failed to initialize ${chain} wallet:`, error);
1016
+ throw error;
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Derive address for a specific chain
1021
+ */
1022
+ async deriveAddress(chain) {
1023
+ const path = DERIVATION_PATHS2[chain];
1024
+ try {
1025
+ const wallet = await this.getWallet(chain);
1026
+ const account = await wallet.getAccount(0);
1027
+ const address = await account.getAddress();
1028
+ return {
1029
+ chain,
1030
+ address,
1031
+ path
1032
+ };
1033
+ } catch (error) {
1034
+ console.error(`Error deriving ${chain} address:`, error);
1035
+ throw error;
1036
+ }
1037
+ }
1038
+ /**
1039
+ * Derive addresses for all supported chains
1040
+ */
1041
+ async deriveAllAddresses() {
1042
+ const chains = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
1043
+ const addresses = {
1044
+ ethereum: null,
1045
+ bitcoin: null,
1046
+ ton: null,
1047
+ tron: null,
1048
+ solana: null,
1049
+ spark: null
1050
+ };
1051
+ const results = await Promise.allSettled(
1052
+ chains.map(async (chain) => {
1053
+ const result = await this.deriveAddress(chain);
1054
+ return { chain, address: result.address };
1055
+ })
1056
+ );
1057
+ for (const result of results) {
1058
+ if (result.status === "fulfilled") {
1059
+ addresses[result.value.chain] = result.value.address;
1060
+ } else {
1061
+ console.error("Failed to derive address:", result.reason);
1062
+ }
1063
+ }
1064
+ return addresses;
1065
+ }
1066
+ /**
1067
+ * Derive addresses for specific chains only
1068
+ */
1069
+ async deriveAddressesForChains(chains) {
1070
+ const addresses = {};
1071
+ const results = await Promise.allSettled(
1072
+ chains.map(async (chain) => {
1073
+ const result = await this.deriveAddress(chain);
1074
+ return { chain, address: result.address };
1075
+ })
1076
+ );
1077
+ for (const result of results) {
1078
+ if (result.status === "fulfilled") {
1079
+ addresses[result.value.chain] = result.value.address;
1080
+ }
1081
+ }
1082
+ return addresses;
1083
+ }
1084
+ /**
1085
+ * Get fee rates for a specific chain
1086
+ */
1087
+ async getFeeRates(chain) {
1088
+ if (!this.seed) {
1089
+ throw new Error("WDK service not initialized. Call initialize() first.");
1090
+ }
1091
+ try {
1092
+ const wallet = await this.getWallet(chain);
1093
+ const feeRates = await wallet.getFeeRates();
1094
+ return {
1095
+ slow: (feeRates.slow || feeRates.low || "0").toString(),
1096
+ medium: (feeRates.medium || feeRates.normal || feeRates.standard || "0").toString(),
1097
+ fast: (feeRates.fast || feeRates.high || "0").toString()
1098
+ };
1099
+ } catch (error) {
1100
+ console.error(`Error fetching fee rates for ${chain}:`, error);
1101
+ throw error;
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Get the current network configuration
1106
+ */
1107
+ getNetwork() {
1108
+ return this.config.network;
1109
+ }
1110
+ /**
1111
+ * Check if service is initialized
1112
+ */
1113
+ isInitialized() {
1114
+ return this.seed !== null;
1115
+ }
1116
+ /**
1117
+ * Clean up and dispose of wallet instances
1118
+ */
1119
+ dispose() {
1120
+ for (const wallet of Object.values(this.wallets)) {
1121
+ if (wallet && typeof wallet.dispose === "function") {
1122
+ try {
1123
+ wallet.dispose();
1124
+ } catch {
1125
+ }
1126
+ }
1127
+ }
1128
+ this.wallets = {};
1129
+ this.seed = null;
1130
+ }
1131
+ };
1132
+
1133
+ // src/wallet/WalletManager.ts
1134
+ var STORAGE_KEYS = {
1135
+ ENCRYPTED_SEED: "encrypted_seed",
1136
+ ACTIVE_WALLET: "active_wallet"
1137
+ };
1138
+ var SUPPORTED_CHAINS = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
1139
+ var WalletManager = class _WalletManager {
1140
+ config;
1141
+ storage;
1142
+ currentSeed = null;
1143
+ derivedAddress = null;
1144
+ derivedAddresses = {};
1145
+ selectedChain = "ethereum";
1146
+ wdkService;
1147
+ constructor(config = {}) {
1148
+ const isTestnet = config.network !== "mainnet";
1149
+ const ethereumConfig = getNetworkConfig("ethereum", isTestnet);
1150
+ this.config = {
1151
+ network: config.network || "testnet",
1152
+ rpcUrl: config.rpcUrl || ethereumConfig.rpcUrl,
1153
+ storage: config.storage || createSecureStorage(),
1154
+ enabledChains: config.enabledChains || SUPPORTED_CHAINS,
1155
+ apiUrl: config.apiUrl || process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"
1156
+ };
1157
+ this.storage = this.config.storage;
1158
+ this.wdkService = new WdkService({
1159
+ network: this.config.network
1160
+ });
1161
+ }
1162
+ /**
1163
+ * Generate a new BIP-39 seed phrase (12 words) using ethers.js
1164
+ * For native WDK generation, use generateSeedWithWdk() instead
1165
+ */
1166
+ static generateSeed() {
1167
+ const wallet = Wallet.createRandom();
1168
+ const mnemonic = wallet.mnemonic;
1169
+ if (!mnemonic) {
1170
+ throw new Error("Failed to generate mnemonic");
1171
+ }
1172
+ return mnemonic.phrase;
1173
+ }
1174
+ /**
1175
+ * Generate a new BIP-39 seed phrase using native Tether WDK
1176
+ * This is the recommended method for generating seed phrases
1177
+ */
1178
+ async generateSeedWithWdk() {
1179
+ return await this.wdkService.generateSeedPhrase();
1180
+ }
1181
+ /**
1182
+ * Validate seed phrase using native WDK (async, more accurate)
1183
+ */
1184
+ async validateSeedWithWdk(seed) {
1185
+ return await this.wdkService.isValidSeed(seed);
1186
+ }
1187
+ /**
1188
+ * Validate a BIP-39 seed phrase
1189
+ */
1190
+ static validateSeed(seed) {
1191
+ return KeyManager.validateSeedPhrase(seed);
1192
+ }
1193
+ /**
1194
+ * Derive Ethereum address from seed phrase using BIP-44 path
1195
+ * Path: m/44'/60'/0'/0/0
1196
+ */
1197
+ static deriveAddress(seed) {
1198
+ const hdNode = HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
1199
+ return hdNode.address;
1200
+ }
1201
+ /**
1202
+ * Get the HDNodeWallet for signing transactions
1203
+ */
1204
+ static getWallet(seed) {
1205
+ return HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
1206
+ }
1207
+ /**
1208
+ * Initialize storage with password (required for web platform)
1209
+ */
1210
+ async initializeStorage(password) {
1211
+ if (this.storage instanceof WebEncryptedStorageAdapter) {
1212
+ await this.storage.initialize(password);
1213
+ }
1214
+ }
1215
+ /**
1216
+ * Create a new wallet with generated seed
1217
+ */
1218
+ async createWallet(password) {
1219
+ const seed = _WalletManager.generateSeed();
1220
+ const address = _WalletManager.deriveAddress(seed);
1221
+ const encrypted = await KeyManager.encryptSeed(seed, password);
1222
+ await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
1223
+ this.currentSeed = seed;
1224
+ this.derivedAddress = address;
1225
+ return { seed, address };
1226
+ }
1227
+ /**
1228
+ * Import an existing wallet from seed phrase
1229
+ */
1230
+ async importWallet(seed, password) {
1231
+ if (!_WalletManager.validateSeed(seed)) {
1232
+ throw new Error("Invalid seed phrase");
1233
+ }
1234
+ const address = _WalletManager.deriveAddress(seed);
1235
+ const encrypted = await KeyManager.encryptSeed(seed, password);
1236
+ await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
1237
+ this.currentSeed = seed;
1238
+ this.derivedAddress = address;
1239
+ return { address };
1240
+ }
1241
+ /**
1242
+ * Unlock wallet with password
1243
+ */
1244
+ async unlock(password) {
1245
+ const encrypted = await this.storage.getItem(STORAGE_KEYS.ENCRYPTED_SEED);
1246
+ if (!encrypted) {
1247
+ throw new Error("No wallet found");
1248
+ }
1249
+ try {
1250
+ const seed = await KeyManager.decryptSeed(encrypted, password);
1251
+ const address = _WalletManager.deriveAddress(seed);
1252
+ this.currentSeed = seed;
1253
+ this.derivedAddress = address;
1254
+ return { address };
1255
+ } catch {
1256
+ throw new Error("Invalid password");
1257
+ }
1258
+ }
1259
+ /**
1260
+ * Lock wallet (clear seed from memory)
1261
+ */
1262
+ lock() {
1263
+ this.currentSeed = null;
1264
+ this.wdkService.dispose();
1265
+ }
1266
+ /**
1267
+ * Check if wallet exists in storage
1268
+ */
1269
+ async hasWallet() {
1270
+ return this.storage.hasItem(STORAGE_KEYS.ENCRYPTED_SEED);
1271
+ }
1272
+ /**
1273
+ * Delete wallet from storage
1274
+ */
1275
+ async deleteWallet() {
1276
+ await this.storage.removeItem(STORAGE_KEYS.ENCRYPTED_SEED);
1277
+ this.currentSeed = null;
1278
+ this.derivedAddress = null;
1279
+ this.derivedAddresses = {};
1280
+ this.wdkService.dispose();
1281
+ }
1282
+ /**
1283
+ * Get current wallet state
1284
+ */
1285
+ getState() {
1286
+ return {
1287
+ isInitialized: this.derivedAddress !== null,
1288
+ isLocked: this.currentSeed === null && this.derivedAddress !== null,
1289
+ address: this.derivedAddress,
1290
+ balance: null
1291
+ // Use fetchBalance for current balance
1292
+ };
1293
+ }
1294
+ /**
1295
+ * Get current address (if unlocked)
1296
+ */
1297
+ getAddress() {
1298
+ return this.derivedAddress;
1299
+ }
1300
+ /**
1301
+ * Check if wallet is unlocked
1302
+ */
1303
+ isUnlocked() {
1304
+ return this.currentSeed !== null;
1305
+ }
1306
+ /**
1307
+ * Get the seed phrase (only if unlocked)
1308
+ */
1309
+ getSeed() {
1310
+ return this.currentSeed;
1311
+ }
1312
+ /**
1313
+ * Fetch balance for current address with timeout handling
1314
+ */
1315
+ async fetchBalance() {
1316
+ if (!this.derivedAddress) {
1317
+ throw new Error("Wallet not initialized");
1318
+ }
1319
+ const chain = this.config.network === "mainnet" ? mainnet : sepolia;
1320
+ const client = createPublicClient({
1321
+ chain,
1322
+ transport: http(this.config.rpcUrl, {
1323
+ timeout: 15e3,
1324
+ // 15 second timeout
1325
+ retryCount: 2,
1326
+ retryDelay: 1e3
1327
+ })
1328
+ });
1329
+ try {
1330
+ const balance = await client.getBalance({
1331
+ address: this.derivedAddress
1332
+ });
1333
+ return formatEther(balance);
1334
+ } catch (error) {
1335
+ console.warn("Failed to fetch balance:", error);
1336
+ return "0";
1337
+ }
1338
+ }
1339
+ /**
1340
+ * Create viem public client for the current network
1341
+ */
1342
+ getPublicClient() {
1343
+ const chain = this.config.network === "mainnet" ? mainnet : sepolia;
1344
+ return createPublicClient({
1345
+ chain,
1346
+ transport: http(this.config.rpcUrl, {
1347
+ timeout: 15e3,
1348
+ // 15 second timeout
1349
+ retryCount: 2,
1350
+ retryDelay: 1e3
1351
+ })
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Get ethers wallet for signing (only if unlocked)
1356
+ */
1357
+ getEthersWallet() {
1358
+ if (!this.currentSeed) return null;
1359
+ return _WalletManager.getWallet(this.currentSeed);
1360
+ }
1361
+ /**
1362
+ * Set active wallet preference
1363
+ */
1364
+ async setActiveWalletPreference(wallet) {
1365
+ await this.storage.setItem(STORAGE_KEYS.ACTIVE_WALLET, wallet);
1366
+ }
1367
+ /**
1368
+ * Get active wallet preference
1369
+ */
1370
+ async getActiveWalletPreference() {
1371
+ const stored = await this.storage.getItem(STORAGE_KEYS.ACTIVE_WALLET);
1372
+ return stored === "metamask" || stored === "wdk" ? stored : "metamask";
1373
+ }
1374
+ // ==========================================
1375
+ // Multi-Chain Support Methods (Powered by Tether WDK)
1376
+ // ==========================================
1377
+ /**
1378
+ * Derive address for a specific chain (async version)
1379
+ *
1380
+ * Calls the backend WDK API for proper derivation when available.
1381
+ * Falls back to local ethers-based derivation if API is unavailable.
1382
+ */
1383
+ static async deriveAddressForChainAsync(seed, chain, network = "testnet", apiUrl) {
1384
+ try {
1385
+ const wdkApi = getWdkApiClient(apiUrl);
1386
+ const response = await wdkApi.deriveAddress(seed, chain, network);
1387
+ if (response.success && response.address) {
1388
+ return response.address;
1389
+ }
1390
+ console.warn(`WDK API failed for ${chain}, using local derivation:`, response.error);
1391
+ } catch (error) {
1392
+ console.warn(`WDK API unavailable for ${chain}, using local derivation:`, error);
1393
+ }
1394
+ return _WalletManager.deriveAddressForChain(seed, chain);
1395
+ }
1396
+ /**
1397
+ * Format address for non-WDK chains (fallback)
1398
+ *
1399
+ * Note: This fallback produces PLACEHOLDER addresses derived from the seed.
1400
+ * For real blockchain interaction, use the WDK API via deriveAddressForChainAsync().
1401
+ * These addresses should NOT be used for receiving funds without verification.
1402
+ */
1403
+ static formatAddressForChain(address, chain) {
1404
+ if (chain === "ethereum") {
1405
+ return address;
1406
+ }
1407
+ const addressBytes = address.toLowerCase().replace("0x", "");
1408
+ switch (chain) {
1409
+ case "bitcoin": {
1410
+ const btcChars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
1411
+ let btcAddr = "tb1q";
1412
+ for (let i = 0; i < 38; i++) {
1413
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % btcChars.length;
1414
+ btcAddr += btcChars[idx];
1415
+ }
1416
+ return btcAddr;
1417
+ }
1418
+ case "ton": {
1419
+ const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1420
+ let tonAddr = "EQ";
1421
+ for (let i = 0; i < 46; i++) {
1422
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 4 % base64Chars.length;
1423
+ tonAddr += base64Chars[idx];
1424
+ }
1425
+ return tonAddr;
1426
+ }
1427
+ case "tron": {
1428
+ const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1429
+ let tronAddr = "T";
1430
+ for (let i = 0; i < 33; i++) {
1431
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
1432
+ tronAddr += base58Chars[idx];
1433
+ }
1434
+ return tronAddr;
1435
+ }
1436
+ case "solana": {
1437
+ const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1438
+ let solAddr = "";
1439
+ for (let i = 0; i < 44; i++) {
1440
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
1441
+ solAddr += base58Chars[idx];
1442
+ }
1443
+ return solAddr;
1444
+ }
1445
+ case "spark": {
1446
+ const bech32Chars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
1447
+ let sparkAddr = "sp1q";
1448
+ for (let i = 0; i < 58; i++) {
1449
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % bech32Chars.length;
1450
+ sparkAddr += bech32Chars[idx];
1451
+ }
1452
+ return sparkAddr;
1453
+ }
1454
+ default:
1455
+ return address;
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Derive address for a specific chain (sync version for backwards compatibility)
1460
+ * Uses ethers for basic derivation, use deriveAddressForChainAsync for WDK
1461
+ *
1462
+ * Note: For non-Ethereum chains, this produces placeholder addresses that are
1463
+ * deterministic but not cryptographically valid. Use WDK API for real addresses.
1464
+ */
1465
+ static deriveAddressForChain(seed, chain) {
1466
+ const ethPath = DERIVATION_PATHS["ethereum"];
1467
+ const ethNode = HDNodeWallet.fromPhrase(seed, void 0, `${ethPath}/0`);
1468
+ if (chain === "ethereum") {
1469
+ return ethNode.address;
1470
+ }
1471
+ return _WalletManager.formatAddressForChain(ethNode.address, chain);
1472
+ }
1473
+ /**
1474
+ * Derive addresses for all enabled chains (sync version)
1475
+ */
1476
+ deriveAllAddresses() {
1477
+ if (!this.currentSeed) {
1478
+ throw new Error("Wallet is locked");
1479
+ }
1480
+ const addresses = {};
1481
+ for (const chain of this.config.enabledChains) {
1482
+ addresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
1483
+ }
1484
+ this.derivedAddresses = addresses;
1485
+ return addresses;
1486
+ }
1487
+ /**
1488
+ * Derive addresses for all enabled chains using native Tether WDK (recommended)
1489
+ * This uses the WDK directly without needing a backend API.
1490
+ * Returns REAL cryptographically valid addresses for all chains.
1491
+ */
1492
+ async deriveAllAddressesWithWdk() {
1493
+ if (!this.currentSeed) {
1494
+ throw new Error("Wallet is locked");
1495
+ }
1496
+ try {
1497
+ await this.wdkService.initialize(this.currentSeed);
1498
+ const enabledChainsSet = new Set(this.config.enabledChains);
1499
+ const wdkAddresses = await this.wdkService.deriveAllAddresses();
1500
+ const addresses = {};
1501
+ for (const [chain, address] of Object.entries(wdkAddresses)) {
1502
+ if (enabledChainsSet.has(chain) && address) {
1503
+ addresses[chain] = address;
1504
+ }
1505
+ }
1506
+ this.derivedAddresses = addresses;
1507
+ return addresses;
1508
+ } catch (error) {
1509
+ console.error("Native WDK derivation failed:", error);
1510
+ throw error;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Derive addresses for all enabled chains using Tether WDK
1515
+ * Tries native WDK first, then falls back to API, then to placeholders
1516
+ */
1517
+ async deriveAllAddressesAsync() {
1518
+ if (!this.currentSeed) {
1519
+ throw new Error("Wallet is locked");
1520
+ }
1521
+ try {
1522
+ return await this.deriveAllAddressesWithWdk();
1523
+ } catch (wdkError) {
1524
+ console.warn("Native WDK failed, trying API:", wdkError);
1525
+ }
1526
+ try {
1527
+ const wdkApi = getWdkApiClient(this.config.apiUrl);
1528
+ const response = await wdkApi.deriveAllAddresses(this.currentSeed, this.config.network);
1529
+ if (response.success && response.addresses) {
1530
+ const addresses = {};
1531
+ for (const chain of this.config.enabledChains) {
1532
+ const address = response.addresses[chain];
1533
+ if (address) {
1534
+ addresses[chain] = address;
1535
+ }
1536
+ }
1537
+ this.derivedAddresses = addresses;
1538
+ return addresses;
1539
+ }
1540
+ console.warn("WDK API call failed:", response.error);
1541
+ } catch (apiError) {
1542
+ console.warn("WDK API unavailable:", apiError);
1543
+ }
1544
+ console.warn("WARNING: Using placeholder addresses. These are NOT valid for receiving funds!");
1545
+ return this.deriveAllAddresses();
1546
+ }
1547
+ /**
1548
+ * Get address for a specific chain
1549
+ */
1550
+ getAddressForChain(chain) {
1551
+ if (!this.currentSeed) {
1552
+ return this.derivedAddresses[chain] || null;
1553
+ }
1554
+ if (!this.derivedAddresses[chain]) {
1555
+ this.derivedAddresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
1556
+ }
1557
+ return this.derivedAddresses[chain] || null;
1558
+ }
1559
+ /**
1560
+ * Get all derived addresses
1561
+ */
1562
+ getAllAddresses() {
1563
+ return { ...this.derivedAddresses };
1564
+ }
1565
+ /**
1566
+ * Set the selected chain
1567
+ */
1568
+ setSelectedChain(chain) {
1569
+ if (!this.config.enabledChains.includes(chain)) {
1570
+ throw new Error(`Chain ${chain} is not enabled`);
1571
+ }
1572
+ this.selectedChain = chain;
1573
+ }
1574
+ /**
1575
+ * Get the currently selected chain
1576
+ */
1577
+ getSelectedChain() {
1578
+ return this.selectedChain;
1579
+ }
1580
+ /**
1581
+ * Get enabled chains
1582
+ */
1583
+ getEnabledChains() {
1584
+ return [...this.config.enabledChains];
1585
+ }
1586
+ /**
1587
+ * Get chain configuration
1588
+ */
1589
+ getChainConfig(chain) {
1590
+ return getNetworkConfig(chain, this.config.network === "testnet");
1591
+ }
1592
+ /**
1593
+ * Fetch balance for a specific chain
1594
+ * Note: Currently only Ethereum is implemented
1595
+ */
1596
+ async fetchBalanceForChain(chain) {
1597
+ const address = this.getAddressForChain(chain);
1598
+ if (!address) {
1599
+ throw new Error(`No address for chain ${chain}`);
1600
+ }
1601
+ const networkConfig = this.getChainConfig(chain);
1602
+ let balance = "0";
1603
+ if (chain === "ethereum") {
1604
+ const viemChain = this.config.network === "mainnet" ? mainnet : sepolia;
1605
+ const client = createPublicClient({
1606
+ chain: viemChain,
1607
+ transport: http(this.config.rpcUrl, {
1608
+ timeout: 15e3,
1609
+ // 15 second timeout
1610
+ retryCount: 2,
1611
+ retryDelay: 1e3
1612
+ })
1613
+ });
1614
+ try {
1615
+ const rawBalance = await client.getBalance({
1616
+ address
1617
+ });
1618
+ balance = formatEther(rawBalance);
1619
+ } catch (error) {
1620
+ console.warn(`Failed to fetch ${chain} balance:`, error);
1621
+ }
1622
+ }
1623
+ return {
1624
+ chain,
1625
+ symbol: networkConfig.nativeCurrency.symbol,
1626
+ balance,
1627
+ balanceUsd: 0,
1628
+ // TODO: Implement price fetching
1629
+ address,
1630
+ decimals: networkConfig.nativeCurrency.decimals
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Fetch balances for all enabled chains
1635
+ */
1636
+ async fetchAllBalances() {
1637
+ const balances = [];
1638
+ for (const chain of this.config.enabledChains) {
1639
+ try {
1640
+ const balance = await this.fetchBalanceForChain(chain);
1641
+ balances.push(balance);
1642
+ } catch (error) {
1643
+ console.error(`Failed to fetch balance for ${chain}:`, error);
1644
+ const networkConfig = this.getChainConfig(chain);
1645
+ balances.push({
1646
+ chain,
1647
+ symbol: networkConfig.nativeCurrency.symbol,
1648
+ balance: "0",
1649
+ balanceUsd: 0,
1650
+ address: this.getAddressForChain(chain) || "",
1651
+ decimals: networkConfig.nativeCurrency.decimals
1652
+ });
1653
+ }
1654
+ }
1655
+ return balances;
1656
+ }
1657
+ /**
1658
+ * Get extended wallet state with multi-chain info
1659
+ */
1660
+ getExtendedState() {
1661
+ return {
1662
+ isInitialized: this.derivedAddress !== null,
1663
+ isLocked: this.currentSeed === null && this.derivedAddress !== null,
1664
+ address: this.derivedAddress,
1665
+ balance: null,
1666
+ addresses: this.derivedAddresses,
1667
+ selectedChain: this.selectedChain
1668
+ };
1669
+ }
1670
+ };
1671
+
1672
+ export { SUPPORTED_CHAINS, WalletManager, ZubariWallet };
1673
+ //# sourceMappingURL=index.mjs.map
1674
+ //# sourceMappingURL=index.mjs.map