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