@zubari/sdk 0.5.3 → 0.5.5

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 (45) hide show
  1. package/dist/{PayoutsProtocol-B5z8SEA-.d.ts → PayoutsProtocol-DAa-9A5C.d.ts} +8 -1
  2. package/dist/{PayoutsProtocol-CLiMFe54.d.mts → PayoutsProtocol-DKEQhwYH.d.mts} +8 -1
  3. package/dist/{TransactionService-Lr_WS6iR.d.mts → TransactionService-Cmw33HXX.d.mts} +21 -7
  4. package/dist/{TransactionService-BtWUjKt_.d.ts → TransactionService-DbNDRzXh.d.ts} +21 -7
  5. package/dist/{WalletManager-DQQwVkoa.d.ts → WalletManager-CeLlZo2y.d.ts} +23 -2
  6. package/dist/{WalletManager-Sbpx4E1-.d.mts → WalletManager-DIx8nENh.d.mts} +23 -2
  7. package/dist/{contracts-B842YprC.d.mts → contracts-JfZDzaV7.d.ts} +11 -2
  8. package/dist/{contracts-s_CDIruh.d.ts → contracts-pugJnFzl.d.mts} +11 -2
  9. package/dist/{index-CTyZlHKg.d.mts → index-c90msmwW.d.mts} +2 -1
  10. package/dist/{index-CTyZlHKg.d.ts → index-c90msmwW.d.ts} +2 -1
  11. package/dist/index.d.mts +5 -5
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +202 -195
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +189 -182
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/protocols/index.d.mts +2 -2
  18. package/dist/protocols/index.d.ts +2 -2
  19. package/dist/protocols/index.js +24 -11
  20. package/dist/protocols/index.js.map +1 -1
  21. package/dist/protocols/index.mjs +24 -11
  22. package/dist/protocols/index.mjs.map +1 -1
  23. package/dist/react/index.d.mts +3 -3
  24. package/dist/react/index.d.ts +3 -3
  25. package/dist/react/index.js +167 -154
  26. package/dist/react/index.js.map +1 -1
  27. package/dist/react/index.mjs +154 -141
  28. package/dist/react/index.mjs.map +1 -1
  29. package/dist/services/index.d.mts +2 -2
  30. package/dist/services/index.d.ts +2 -2
  31. package/dist/services/index.js +145 -125
  32. package/dist/services/index.js.map +1 -1
  33. package/dist/services/index.mjs +132 -112
  34. package/dist/services/index.mjs.map +1 -1
  35. package/dist/storage/index.js +5 -2
  36. package/dist/storage/index.js.map +1 -1
  37. package/dist/storage/index.mjs +5 -2
  38. package/dist/storage/index.mjs.map +1 -1
  39. package/dist/wallet/index.d.mts +3 -3
  40. package/dist/wallet/index.d.ts +3 -3
  41. package/dist/wallet/index.js +176 -184
  42. package/dist/wallet/index.js.map +1 -1
  43. package/dist/wallet/index.mjs +163 -171
  44. package/dist/wallet/index.mjs.map +1 -1
  45. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,10 +1,4 @@
1
1
  import { HDNodeWallet, Wallet } from 'ethers';
2
- import { mnemonicToSeedSync, validateMnemonic, generateMnemonic } from '@scure/bip39';
3
- import { wordlist } from '@scure/bip39/wordlists/english';
4
- import { HDKey } from '@scure/bip32';
5
- import { bech32, base58check } from '@scure/base';
6
- import { sha256 } from '@noble/hashes/sha256';
7
- import { ripemd160 } from '@noble/hashes/ripemd160';
8
2
  import { createPublicClient, http, formatEther, getAddress } from 'viem';
9
3
  import { mainnet, sepolia } from 'viem/chains';
10
4
 
@@ -154,11 +148,11 @@ var USDT_ADDRESSES = {
154
148
  }
155
149
  };
156
150
  var DERIVATION_PATHS = {
157
- bitcoin: "m/44'/0'/0'/0",
151
+ bitcoin: "m/84'/0'/0'/0",
158
152
  ethereum: "m/44'/60'/0'/0",
159
- ton: "m/44'/607'/0'/0",
153
+ ton: "m/44'/607'/0'",
160
154
  tron: "m/44'/195'/0'/0",
161
- solana: "m/44'/501'/0'/0",
155
+ solana: "m/44'/501'/0'",
162
156
  spark: "m/44'/998'/0'/0"
163
157
  };
164
158
  function getNetworkConfig(network, isTestnet2 = false) {
@@ -424,8 +418,27 @@ var WdkApiClient = class {
424
418
  constructor(config) {
425
419
  this.config = {
426
420
  baseUrl: config.baseUrl,
427
- timeout: config.timeout || 3e4
421
+ timeout: config.timeout || 3e4,
422
+ authToken: config.authToken
423
+ };
424
+ }
425
+ /**
426
+ * Set or update the auth token for authenticated requests
427
+ */
428
+ setAuthToken(token) {
429
+ this.config.authToken = token;
430
+ }
431
+ /**
432
+ * Build headers for API requests, including Authorization when available
433
+ */
434
+ getHeaders() {
435
+ const headers = {
436
+ "Content-Type": "application/json"
428
437
  };
438
+ if (this.config.authToken) {
439
+ headers["Authorization"] = `Bearer ${this.config.authToken}`;
440
+ }
441
+ return headers;
429
442
  }
430
443
  /**
431
444
  * Generate a new BIP-39 seed phrase using Tether WDK
@@ -434,9 +447,7 @@ var WdkApiClient = class {
434
447
  try {
435
448
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {
436
449
  method: "POST",
437
- headers: {
438
- "Content-Type": "application/json"
439
- }
450
+ headers: this.getHeaders()
440
451
  });
441
452
  return await response.json();
442
453
  } catch (error) {
@@ -453,9 +464,7 @@ var WdkApiClient = class {
453
464
  try {
454
465
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {
455
466
  method: "POST",
456
- headers: {
457
- "Content-Type": "application/json"
458
- },
467
+ headers: this.getHeaders(),
459
468
  body: JSON.stringify({ seed })
460
469
  });
461
470
  return await response.json();
@@ -473,9 +482,7 @@ var WdkApiClient = class {
473
482
  try {
474
483
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {
475
484
  method: "POST",
476
- headers: {
477
- "Content-Type": "application/json"
478
- },
485
+ headers: this.getHeaders(),
479
486
  body: JSON.stringify({ seed, chain, network })
480
487
  });
481
488
  return await response.json();
@@ -493,9 +500,7 @@ var WdkApiClient = class {
493
500
  try {
494
501
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {
495
502
  method: "POST",
496
- headers: {
497
- "Content-Type": "application/json"
498
- },
503
+ headers: this.getHeaders(),
499
504
  body: JSON.stringify({ seed, network })
500
505
  });
501
506
  return await response.json();
@@ -513,9 +518,7 @@ var WdkApiClient = class {
513
518
  try {
514
519
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/send`, {
515
520
  method: "POST",
516
- headers: {
517
- "Content-Type": "application/json"
518
- },
521
+ headers: this.getHeaders(),
519
522
  body: JSON.stringify({ seed, chain, to, amount, network })
520
523
  });
521
524
  return await response.json();
@@ -534,9 +537,7 @@ var WdkApiClient = class {
534
537
  try {
535
538
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/history`, {
536
539
  method: "POST",
537
- headers: {
538
- "Content-Type": "application/json"
539
- },
540
+ headers: this.getHeaders(),
540
541
  body: JSON.stringify({ seed, chain, network, limit })
541
542
  });
542
543
  return await response.json();
@@ -555,9 +556,7 @@ var WdkApiClient = class {
555
556
  try {
556
557
  const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/tx-status`, {
557
558
  method: "POST",
558
- headers: {
559
- "Content-Type": "application/json"
560
- },
559
+ headers: this.getHeaders(),
561
560
  body: JSON.stringify({ txHash, chain, network })
562
561
  });
563
562
  return await response.json();
@@ -571,11 +570,14 @@ var WdkApiClient = class {
571
570
  };
572
571
  var DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || "https://ckgwifsxka.us-east-2.awsapprunner.com";
573
572
  var wdkApiClient = null;
574
- function getWdkApiClient(baseUrl) {
573
+ function getWdkApiClient(baseUrl, authToken) {
575
574
  if (!wdkApiClient || baseUrl && wdkApiClient["config"].baseUrl !== baseUrl) {
576
575
  wdkApiClient = new WdkApiClient({
577
- baseUrl: baseUrl || DEFAULT_API_URL
576
+ baseUrl: baseUrl || DEFAULT_API_URL,
577
+ authToken
578
578
  });
579
+ } else if (authToken !== void 0) {
580
+ wdkApiClient.setAuthToken(authToken);
579
581
  }
580
582
  return wdkApiClient;
581
583
  }
@@ -594,20 +596,45 @@ __export(BrowserAddressDerivation_exports, {
594
596
  isValidSeed: () => isValidSeed
595
597
  });
596
598
  var DERIVATION_PATHS2 = {
597
- ethereum: "m/44'/60'/0'/0/0",
598
- bitcoin_mainnet: "m/84'/0'/0'/0/0",
599
+ ethereum: `${DERIVATION_PATHS.ethereum}/0`,
600
+ bitcoin_mainnet: `${DERIVATION_PATHS.bitcoin}/0`,
599
601
  bitcoin_testnet: "m/84'/1'/0'/0/0",
600
- ton: "m/44'/607'/0'/0'/0'",
601
- tron: "m/44'/195'/0'/0/0",
602
- solana: "m/44'/501'/0'/0'",
603
- spark: "m/44'/998'/0'/0/0"
602
+ ton: `${DERIVATION_PATHS.ton}/0'/0'`,
603
+ tron: `${DERIVATION_PATHS.tron}/0`,
604
+ solana: `${DERIVATION_PATHS.solana}/0'`,
605
+ spark: `${DERIVATION_PATHS.spark}/0`
604
606
  };
607
+ var _crypto = null;
608
+ async function loadCrypto() {
609
+ if (_crypto) return _crypto;
610
+ const [bip39, bip39Words, bip32, scureBase, sha256Mod, ripemd160Mod] = await Promise.all([
611
+ import('@scure/bip39'),
612
+ import('@scure/bip39/wordlists/english.js'),
613
+ import('@scure/bip32'),
614
+ import('@scure/base'),
615
+ import('@noble/hashes/sha256'),
616
+ import('@noble/hashes/ripemd160')
617
+ ]);
618
+ _crypto = {
619
+ mnemonicToSeedSync: bip39.mnemonicToSeedSync,
620
+ validateMnemonic: bip39.validateMnemonic,
621
+ generateMnemonic: bip39.generateMnemonic,
622
+ wordlist: bip39Words.wordlist,
623
+ HDKey: bip32.HDKey,
624
+ bech32: scureBase.bech32,
625
+ base58check: scureBase.base58check,
626
+ sha256: sha256Mod.sha256,
627
+ ripemd160: ripemd160Mod.ripemd160
628
+ };
629
+ return _crypto;
630
+ }
605
631
  function deriveEthereumAddress(seed) {
606
632
  const hdNode = HDNodeWallet.fromPhrase(seed, void 0, DERIVATION_PATHS2.ethereum);
607
633
  return hdNode.address;
608
634
  }
609
- function deriveBitcoinAddress(seed, network = "mainnet") {
635
+ async function deriveBitcoinAddress(seed, network = "mainnet") {
610
636
  try {
637
+ const { mnemonicToSeedSync, HDKey, sha256, ripemd160, bech32 } = await loadCrypto();
611
638
  const seedBytes = mnemonicToSeedSync(seed);
612
639
  const hdKey = HDKey.fromMasterSeed(seedBytes);
613
640
  const path = network === "testnet" ? DERIVATION_PATHS2.bitcoin_testnet : DERIVATION_PATHS2.bitcoin_mainnet;
@@ -629,13 +656,14 @@ function deriveBitcoinAddress(seed, network = "mainnet") {
629
656
  }
630
657
  async function deriveSolanaAddress(seed) {
631
658
  try {
632
- const [ed25519, nacl, bs58Module] = await Promise.all([
659
+ const [crypto2, ed25519, nacl, bs58Module] = await Promise.all([
660
+ loadCrypto(),
633
661
  import('ed25519-hd-key'),
634
662
  import('tweetnacl'),
635
663
  import('bs58')
636
664
  ]);
637
665
  const bs58 = bs58Module.default || bs58Module;
638
- const seedBytes = mnemonicToSeedSync(seed);
666
+ const seedBytes = crypto2.mnemonicToSeedSync(seed);
639
667
  const derived = ed25519.derivePath(DERIVATION_PATHS2.solana, Buffer.from(seedBytes).toString("hex"));
640
668
  const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));
641
669
  return bs58.encode(keypair.publicKey);
@@ -646,17 +674,18 @@ async function deriveSolanaAddress(seed) {
646
674
  }
647
675
  async function deriveTonAddress(seed) {
648
676
  try {
649
- const [ed25519, nacl] = await Promise.all([
677
+ const [crypto2, ed25519, nacl] = await Promise.all([
678
+ loadCrypto(),
650
679
  import('ed25519-hd-key'),
651
680
  import('tweetnacl')
652
681
  ]);
653
- const seedBytes = mnemonicToSeedSync(seed);
682
+ const seedBytes = crypto2.mnemonicToSeedSync(seed);
654
683
  const derived = ed25519.derivePath(DERIVATION_PATHS2.ton, Buffer.from(seedBytes).toString("hex"));
655
684
  const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));
656
685
  const publicKey = keypair.publicKey;
657
686
  const workchain = 0;
658
687
  const flags = 17;
659
- const hash = sha256(publicKey);
688
+ const hash = crypto2.sha256(publicKey);
660
689
  const addressData = new Uint8Array(34);
661
690
  addressData[0] = flags;
662
691
  addressData[1] = workchain;
@@ -684,8 +713,9 @@ function crc16(data) {
684
713
  }
685
714
  return crc;
686
715
  }
687
- function deriveTronAddress(seed) {
716
+ async function deriveTronAddress(seed) {
688
717
  try {
718
+ const { sha256, base58check } = await loadCrypto();
689
719
  const hdNode = HDNodeWallet.fromPhrase(seed, void 0, DERIVATION_PATHS2.tron);
690
720
  const ethAddressHex = hdNode.address.slice(2).toLowerCase();
691
721
  const addressBytes = new Uint8Array(21);
@@ -700,8 +730,9 @@ function deriveTronAddress(seed) {
700
730
  throw error;
701
731
  }
702
732
  }
703
- function deriveSparkAddress(seed, network = "mainnet") {
733
+ async function deriveSparkAddress(seed, network = "mainnet") {
704
734
  try {
735
+ const { mnemonicToSeedSync, HDKey, sha256, ripemd160, bech32 } = await loadCrypto();
705
736
  const seedBytes = mnemonicToSeedSync(seed);
706
737
  const hdKey = HDKey.fromMasterSeed(seedBytes);
707
738
  const child = hdKey.derive(DERIVATION_PATHS2.spark);
@@ -729,46 +760,37 @@ async function deriveAllAddresses(seed, network = "mainnet") {
729
760
  solana: null,
730
761
  spark: null
731
762
  };
763
+ await loadCrypto();
732
764
  try {
733
765
  addresses.ethereum = deriveEthereumAddress(seed);
734
766
  } catch (e) {
735
767
  console.error("ETH derivation failed:", e);
736
768
  }
737
- try {
738
- addresses.bitcoin = deriveBitcoinAddress(seed, network);
739
- } catch (e) {
740
- console.error("BTC derivation failed:", e);
741
- }
742
- try {
743
- addresses.spark = deriveSparkAddress(seed, network);
744
- } catch (e) {
745
- console.error("Spark derivation failed:", e);
746
- }
747
- try {
748
- addresses.tron = deriveTronAddress(seed);
749
- } catch (e) {
750
- console.error("TRON derivation failed:", e);
751
- }
752
- const [solResult, tonResult] = await Promise.allSettled([
769
+ const [btcResult, sparkResult, tronResult, solResult, tonResult] = await Promise.allSettled([
770
+ deriveBitcoinAddress(seed, network),
771
+ deriveSparkAddress(seed, network),
772
+ deriveTronAddress(seed),
753
773
  deriveSolanaAddress(seed),
754
774
  deriveTonAddress(seed)
755
775
  ]);
756
- if (solResult.status === "fulfilled") {
757
- addresses.solana = solResult.value;
758
- } else {
759
- console.error("SOL derivation failed:", solResult.reason);
760
- }
761
- if (tonResult.status === "fulfilled") {
762
- addresses.ton = tonResult.value;
763
- } else {
764
- console.error("TON derivation failed:", tonResult.reason);
765
- }
776
+ if (btcResult.status === "fulfilled") addresses.bitcoin = btcResult.value;
777
+ else console.error("BTC derivation failed:", btcResult.reason);
778
+ if (sparkResult.status === "fulfilled") addresses.spark = sparkResult.value;
779
+ else console.error("Spark derivation failed:", sparkResult.reason);
780
+ if (tronResult.status === "fulfilled") addresses.tron = tronResult.value;
781
+ else console.error("TRON derivation failed:", tronResult.reason);
782
+ if (solResult.status === "fulfilled") addresses.solana = solResult.value;
783
+ else console.error("SOL derivation failed:", solResult.reason);
784
+ if (tonResult.status === "fulfilled") addresses.ton = tonResult.value;
785
+ else console.error("TON derivation failed:", tonResult.reason);
766
786
  return addresses;
767
787
  }
768
- function isValidSeed(seed) {
788
+ async function isValidSeed(seed) {
789
+ const { validateMnemonic, wordlist } = await loadCrypto();
769
790
  return validateMnemonic(seed, wordlist);
770
791
  }
771
- function generateSeedPhrase() {
792
+ async function generateSeedPhrase() {
793
+ const { generateMnemonic, wordlist } = await loadCrypto();
772
794
  return generateMnemonic(wordlist);
773
795
  }
774
796
 
@@ -1012,7 +1034,7 @@ var ZubariWdkService = class {
1012
1034
  };
1013
1035
  if (!addresses.spark) {
1014
1036
  try {
1015
- addresses.spark = deriveSparkAddress(seed, this.config.network);
1037
+ addresses.spark = await deriveSparkAddress(seed, this.config.network);
1016
1038
  } catch (e) {
1017
1039
  console.warn("Browser Spark derivation fallback failed:", e);
1018
1040
  }
@@ -1113,11 +1135,6 @@ var ZubariWdkService = class {
1113
1135
  async sendTransaction(seed, chain, to, amount) {
1114
1136
  await this.initialize();
1115
1137
  const startTime = Date.now();
1116
- console.log(`[ZubariWdkService] Sending ${chain} transaction`, {
1117
- to: `${to.slice(0, 10)}...${to.slice(-6)}`,
1118
- amount,
1119
- network: this.config.network
1120
- });
1121
1138
  try {
1122
1139
  const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/send`, {
1123
1140
  method: "POST",
@@ -1137,10 +1154,6 @@ var ZubariWdkService = class {
1137
1154
  console.warn(`[ZubariWdkService] Invalid ${chain} tx hash format:`, txHash);
1138
1155
  }
1139
1156
  }
1140
- console.log(`[ZubariWdkService] ${chain} transaction ${data.success ? "SUCCESS" : "FAILED"}`, {
1141
- txHash: txHash ? `${txHash.slice(0, 16)}...` : "N/A",
1142
- elapsed: `${elapsed}ms`
1143
- });
1144
1157
  if (!data.success) {
1145
1158
  const errorCode2 = parseChainError(chain, data.error || "");
1146
1159
  return {
@@ -1163,12 +1176,6 @@ var ZubariWdkService = class {
1163
1176
  const errorData = await response.json().catch(() => ({}));
1164
1177
  const errorMessage = errorData.error || `HTTP ${response.status}`;
1165
1178
  const errorCode = parseChainError(chain, errorMessage);
1166
- console.error(`[ZubariWdkService] ${chain} transaction FAILED`, {
1167
- status: response.status,
1168
- error: errorMessage,
1169
- errorCode,
1170
- elapsed: `${elapsed}ms`
1171
- });
1172
1179
  return {
1173
1180
  success: false,
1174
1181
  error: errorMessage,
@@ -1176,14 +1183,8 @@ var ZubariWdkService = class {
1176
1183
  chain
1177
1184
  };
1178
1185
  } catch (error) {
1179
- const elapsed = Date.now() - startTime;
1180
1186
  const errorMessage = error instanceof Error ? error.message : "Transaction failed";
1181
1187
  const errorCode = parseChainError(chain, errorMessage);
1182
- console.error(`[ZubariWdkService] ${chain} transaction ERROR`, {
1183
- error: errorMessage,
1184
- errorCode,
1185
- elapsed: `${elapsed}ms`
1186
- });
1187
1188
  return {
1188
1189
  success: false,
1189
1190
  error: errorMessage,
@@ -1229,15 +1230,22 @@ var ZubariWdkService = class {
1229
1230
  // Private Helper Methods
1230
1231
  // ==========================================
1231
1232
  getDerivationPath(chain) {
1232
- const paths = {
1233
- bitcoin: this.config.network === "testnet" ? "m/84'/1'/0'/0/0" : "m/84'/0'/0'/0/0",
1234
- ethereum: "m/44'/60'/0'/0/0",
1235
- ton: "m/44'/607'/0'/0'/0'",
1236
- tron: "m/44'/195'/0'/0/0",
1237
- solana: "m/44'/501'/0'/0'",
1238
- spark: "m/44'/998'/0'/0/0"
1239
- };
1240
- return paths[chain];
1233
+ const basePath = DERIVATION_PATHS[chain];
1234
+ if (chain === "bitcoin" && this.config.network === "testnet") {
1235
+ return "m/84'/1'/0'/0/0";
1236
+ }
1237
+ switch (chain) {
1238
+ case "ton":
1239
+ return `${basePath}/0'/0'`;
1240
+ case "solana":
1241
+ return `${basePath}/0'`;
1242
+ case "bitcoin":
1243
+ case "ethereum":
1244
+ case "tron":
1245
+ case "spark":
1246
+ default:
1247
+ return `${basePath}/0`;
1248
+ }
1241
1249
  }
1242
1250
  getChainSymbol(chain) {
1243
1251
  const symbols = {
@@ -1262,13 +1270,13 @@ var ZubariWdkService = class {
1262
1270
  address = deriveEthereumAddress(seed);
1263
1271
  break;
1264
1272
  case "bitcoin":
1265
- address = deriveBitcoinAddress(seed, this.config.network);
1273
+ address = await deriveBitcoinAddress(seed, this.config.network);
1266
1274
  break;
1267
1275
  case "tron":
1268
- address = deriveTronAddress(seed);
1276
+ address = await deriveTronAddress(seed);
1269
1277
  break;
1270
1278
  case "spark":
1271
- address = deriveSparkAddress(seed, this.config.network);
1279
+ address = await deriveSparkAddress(seed, this.config.network);
1272
1280
  break;
1273
1281
  case "solana":
1274
1282
  address = await deriveSolanaAddress(seed);
@@ -1304,12 +1312,21 @@ function createZubariWdkService(config) {
1304
1312
  }
1305
1313
 
1306
1314
  // src/wallet/ZubariWallet.ts
1307
- var ZubariWallet = class {
1315
+ var ZubariWallet = class _ZubariWallet {
1308
1316
  seed;
1309
1317
  config;
1310
1318
  accounts = /* @__PURE__ */ new Map();
1311
1319
  wdkService;
1312
1320
  initialized = false;
1321
+ /** Mapping from NetworkType to SupportedChain (identity map, shared across methods) */
1322
+ static CHAIN_MAP = {
1323
+ ethereum: "ethereum",
1324
+ bitcoin: "bitcoin",
1325
+ ton: "ton",
1326
+ tron: "tron",
1327
+ solana: "solana",
1328
+ spark: "spark"
1329
+ };
1313
1330
  constructor(seed, config) {
1314
1331
  this.seed = seed;
1315
1332
  this.config = {
@@ -1342,15 +1359,7 @@ var ZubariWallet = class {
1342
1359
  async deriveAccount(network, index = 0) {
1343
1360
  const basePath = DERIVATION_PATHS[network];
1344
1361
  const derivationPath = `${basePath}/${index}`;
1345
- const chainMap = {
1346
- ethereum: "ethereum",
1347
- bitcoin: "bitcoin",
1348
- ton: "ton",
1349
- tron: "tron",
1350
- solana: "solana",
1351
- spark: "spark"
1352
- };
1353
- const chain = chainMap[network];
1362
+ const chain = _ZubariWallet.CHAIN_MAP[network];
1354
1363
  if (!chain) {
1355
1364
  throw new Error(`Unsupported network: ${network}`);
1356
1365
  }
@@ -1402,15 +1411,7 @@ var ZubariWallet = class {
1402
1411
  */
1403
1412
  async getBalance(network) {
1404
1413
  const networkConfig = getNetworkConfig(network, this.config.network === "testnet");
1405
- const chainMap = {
1406
- ethereum: "ethereum",
1407
- bitcoin: "bitcoin",
1408
- ton: "ton",
1409
- tron: "tron",
1410
- solana: "solana",
1411
- spark: "spark"
1412
- };
1413
- const chain = chainMap[network];
1414
+ const chain = _ZubariWallet.CHAIN_MAP[network];
1414
1415
  if (!chain) {
1415
1416
  throw new Error(`Unsupported network: ${network}`);
1416
1417
  }
@@ -1497,15 +1498,7 @@ var ZubariWallet = class {
1497
1498
  */
1498
1499
  async send(network, params) {
1499
1500
  const { to, amount } = params;
1500
- const chainMap = {
1501
- ethereum: "ethereum",
1502
- bitcoin: "bitcoin",
1503
- ton: "ton",
1504
- tron: "tron",
1505
- solana: "solana",
1506
- spark: "spark"
1507
- };
1508
- const chain = chainMap[network];
1501
+ const chain = _ZubariWallet.CHAIN_MAP[network];
1509
1502
  if (!chain) {
1510
1503
  throw new Error(`Unsupported network: ${network}`);
1511
1504
  }
@@ -1810,7 +1803,10 @@ var KeyManager = class {
1810
1803
  static KEY_LENGTH = 256;
1811
1804
  static IV_LENGTH = 12;
1812
1805
  static SALT_LENGTH = 16;
1813
- static PBKDF2_ITERATIONS = 1e5;
1806
+ // OWASP 2023 recommends 600,000 iterations for PBKDF2-SHA256 to resist
1807
+ // brute-force attacks with modern GPU hardware.
1808
+ // See: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
1809
+ static PBKDF2_ITERATIONS = 6e5;
1814
1810
  /**
1815
1811
  * Encrypt a seed phrase with a password
1816
1812
  */
@@ -2049,7 +2045,7 @@ var WebEncryptedStorageAdapter = class {
2049
2045
  {
2050
2046
  name: "PBKDF2",
2051
2047
  salt: salt.buffer,
2052
- iterations: 1e5,
2048
+ iterations: 6e5,
2053
2049
  hash: "SHA-256"
2054
2050
  },
2055
2051
  keyMaterial,
@@ -2362,6 +2358,16 @@ var WalletManager = class _WalletManager {
2362
2358
  }
2363
2359
  /**
2364
2360
  * Lock wallet (clear seed from memory)
2361
+ *
2362
+ * SECURITY NOTE: JavaScript strings are immutable and cannot be overwritten
2363
+ * in place. Setting `this.currentSeed = null` removes the reference, but
2364
+ * the original string may persist in memory until garbage collected.
2365
+ * There is no reliable way to zero out a JS string.
2366
+ *
2367
+ * TODO: In a future version, store the seed as a Uint8Array instead of a
2368
+ * string. Uint8Array contents can be explicitly zeroed (e.g.,
2369
+ * `seedBytes.fill(0)`) before releasing the reference, which provides
2370
+ * stronger guarantees that sensitive material is scrubbed from memory.
2365
2371
  */
2366
2372
  lock() {
2367
2373
  this.currentSeed = null;
@@ -2578,7 +2584,6 @@ var WalletManager = class _WalletManager {
2578
2584
  async saveAddressesToStorage(addresses) {
2579
2585
  try {
2580
2586
  await this.storage.setItem(STORAGE_KEYS.DERIVED_ADDRESSES, JSON.stringify(addresses));
2581
- console.log("Saved derived addresses to storage:", Object.keys(addresses));
2582
2587
  } catch (error) {
2583
2588
  console.warn("Failed to save addresses to storage:", error);
2584
2589
  }
@@ -2618,9 +2623,7 @@ var WalletManager = class _WalletManager {
2618
2623
  const stored = await this.storage.getItem(STORAGE_KEYS.DERIVED_ADDRESSES);
2619
2624
  if (stored) {
2620
2625
  const rawAddresses = JSON.parse(stored);
2621
- console.log("[WalletManager] Raw addresses from storage:", rawAddresses);
2622
2626
  const addresses = this.normalizeAddresses(rawAddresses);
2623
- console.log("[WalletManager] Normalized addresses:", addresses);
2624
2627
  await this.saveAddressesToStorage(addresses);
2625
2628
  return addresses;
2626
2629
  }
@@ -2645,11 +2648,8 @@ var WalletManager = class _WalletManager {
2645
2648
  if (storedAddresses && Object.keys(storedAddresses).length > 1) {
2646
2649
  const expectedEthAddress = _WalletManager.deriveAddress(this.currentSeed);
2647
2650
  if (storedAddresses.ethereum === expectedEthAddress) {
2648
- console.log("Using addresses from storage (verified by Ethereum address)");
2649
2651
  this.derivedAddresses = storedAddresses;
2650
2652
  return storedAddresses;
2651
- } else {
2652
- console.log("Stored addresses do not match current seed, re-deriving...");
2653
2653
  }
2654
2654
  }
2655
2655
  return await this.deriveAllAddressesWithWdk();
@@ -2661,9 +2661,7 @@ var WalletManager = class _WalletManager {
2661
2661
  getAddressForChain(chain) {
2662
2662
  const cachedValue = this.derivedAddresses[chain];
2663
2663
  if (cachedValue) {
2664
- console.log(`[WalletManager] getAddressForChain(${chain}) cached value:`, cachedValue, "type:", typeof cachedValue);
2665
2664
  const addr = this.normalizeAddress(cachedValue);
2666
- console.log(`[WalletManager] getAddressForChain(${chain}) normalized:`, addr);
2667
2665
  if (addr) {
2668
2666
  this.derivedAddresses[chain] = addr;
2669
2667
  return addr;
@@ -2790,10 +2788,8 @@ var WalletManager = class _WalletManager {
2790
2788
  const mempoolSpent = data.mempool_stats?.spent_txo_sum || 0;
2791
2789
  const satoshis = chainFunded - chainSpent + (mempoolFunded - mempoolSpent);
2792
2790
  balance = (satoshis / 1e8).toFixed(8);
2793
- console.log(`Bitcoin balance for ${address}: ${balance} BTC (${satoshis} sats) via ${apiUrl}`);
2794
2791
  break;
2795
2792
  }
2796
- console.log(`No transactions found on ${apiUrl}, trying next...`);
2797
2793
  }
2798
2794
  } catch (error) {
2799
2795
  console.warn(`Failed to fetch from ${apiUrl}:`, error);
@@ -2896,7 +2892,6 @@ var WalletManager = class _WalletManager {
2896
2892
  if (data.ok && data.result !== void 0) {
2897
2893
  const nanotons = BigInt(data.result);
2898
2894
  balance = (Number(nanotons) / 1e9).toFixed(9);
2899
- console.log(`TON balance for ${address}: ${balance} TON`);
2900
2895
  }
2901
2896
  }
2902
2897
  } catch (error) {
@@ -2953,7 +2948,6 @@ var WalletManager = class _WalletManager {
2953
2948
  const data = await response.json();
2954
2949
  if (data.success && data.balance !== void 0) {
2955
2950
  balance = (parseFloat(data.balance) / 1e8).toFixed(8);
2956
- console.log(`Spark balance for ${address}: ${balance} BTC`);
2957
2951
  }
2958
2952
  }
2959
2953
  } catch (error) {
@@ -2974,28 +2968,29 @@ var WalletManager = class _WalletManager {
2974
2968
  };
2975
2969
  }
2976
2970
  /**
2977
- * Fetch balances for all enabled chains
2971
+ * Fetch balances for all enabled chains in parallel.
2972
+ * Uses Promise.allSettled so that one chain failing does not block others.
2978
2973
  */
2979
2974
  async fetchAllBalances() {
2980
- const balances = [];
2981
- for (const chain of this.config.enabledChains) {
2982
- try {
2983
- const balance = await this.fetchBalanceForChain(chain);
2984
- balances.push(balance);
2985
- } catch (error) {
2986
- console.error(`Failed to fetch balance for ${chain}:`, error);
2987
- const networkConfig = this.getChainConfig(chain);
2988
- balances.push({
2989
- chain,
2990
- symbol: networkConfig.nativeCurrency.symbol,
2991
- balance: "0",
2992
- balanceUsd: 0,
2993
- address: this.getAddressForChain(chain) || "",
2994
- decimals: networkConfig.nativeCurrency.decimals
2995
- });
2975
+ const results = await Promise.allSettled(
2976
+ this.config.enabledChains.map((chain) => this.fetchBalanceForChain(chain))
2977
+ );
2978
+ return results.map((result, index) => {
2979
+ const chain = this.config.enabledChains[index];
2980
+ if (result.status === "fulfilled") {
2981
+ return result.value;
2996
2982
  }
2997
- }
2998
- return balances;
2983
+ console.error(`Failed to fetch balance for ${chain}:`, result.reason);
2984
+ const networkConfig = this.getChainConfig(chain);
2985
+ return {
2986
+ chain,
2987
+ symbol: networkConfig.nativeCurrency.symbol,
2988
+ balance: "0",
2989
+ balanceUsd: 0,
2990
+ address: this.getAddressForChain(chain) || "",
2991
+ decimals: networkConfig.nativeCurrency.decimals
2992
+ };
2993
+ });
2999
2994
  }
3000
2995
  /**
3001
2996
  * Get extended wallet state with multi-chain info
@@ -3049,7 +3044,6 @@ var WalletManager = class _WalletManager {
3049
3044
  });
3050
3045
  if (response.ok) {
3051
3046
  const data = await response.json();
3052
- console.log(`Transaction sent on ${chain}:`, data);
3053
3047
  let txHash = data.txHash || data.transactionHash || data.hash;
3054
3048
  if (txHash && typeof txHash === "object" && "hash" in txHash) {
3055
3049
  txHash = txHash.hash;
@@ -6664,10 +6658,23 @@ var ZubariSubscriptionProtocol = class {
6664
6658
  contractAddress;
6665
6659
  chainId;
6666
6660
  abi = ZubariSubscription_default;
6661
+ /** Cached ethers Interface instance (lazy-initialized) */
6662
+ _iface = null;
6667
6663
  constructor(contractAddress, chainId) {
6668
6664
  this.contractAddress = contractAddress;
6669
6665
  this.chainId = chainId;
6670
6666
  }
6667
+ /**
6668
+ * Get or create the cached ethers Interface for encoding/decoding contract calls.
6669
+ * The Interface is created once on first use and reused for all subsequent calls.
6670
+ */
6671
+ async getInterface() {
6672
+ if (!this._iface) {
6673
+ const { Interface } = await import('ethers');
6674
+ this._iface = new Interface(this.abi);
6675
+ }
6676
+ return this._iface;
6677
+ }
6671
6678
  /**
6672
6679
  * Get the contract ABI
6673
6680
  */
@@ -6695,7 +6702,7 @@ var ZubariSubscriptionProtocol = class {
6695
6702
  if (plan.duration <= 0) {
6696
6703
  throw new Error("Plan duration must be greater than 0");
6697
6704
  }
6698
- const iface = new (await import('ethers')).Interface(this.abi);
6705
+ const iface = await this.getInterface();
6699
6706
  const durationDays = Math.ceil(plan.duration / (24 * 60 * 60));
6700
6707
  const data = iface.encodeFunctionData("createPlan", [
6701
6708
  plan.name,
@@ -6720,7 +6727,7 @@ var ZubariSubscriptionProtocol = class {
6720
6727
  * @param signer Wallet signer
6721
6728
  */
6722
6729
  async deactivatePlan(planId, signer) {
6723
- const iface = new (await import('ethers')).Interface(this.abi);
6730
+ const iface = await this.getInterface();
6724
6731
  const data = iface.encodeFunctionData("deactivatePlan", [planId]);
6725
6732
  const result = await signer.sendTransaction({
6726
6733
  to: this.contractAddress,
@@ -6744,7 +6751,7 @@ var ZubariSubscriptionProtocol = class {
6744
6751
  if (months <= 0) {
6745
6752
  throw new Error("Subscription duration must be at least 1 month");
6746
6753
  }
6747
- const iface = new (await import('ethers')).Interface(this.abi);
6754
+ const iface = await this.getInterface();
6748
6755
  const data = iface.encodeFunctionData("subscribe", [planId, months]);
6749
6756
  const result = await signer.sendTransaction({
6750
6757
  to: this.contractAddress,
@@ -6763,7 +6770,7 @@ var ZubariSubscriptionProtocol = class {
6763
6770
  * @param signer Wallet signer
6764
6771
  */
6765
6772
  async cancel(subscriptionId, signer) {
6766
- const iface = new (await import('ethers')).Interface(this.abi);
6773
+ const iface = await this.getInterface();
6767
6774
  const data = iface.encodeFunctionData("cancel", [subscriptionId]);
6768
6775
  const result = await signer.sendTransaction({
6769
6776
  to: this.contractAddress,
@@ -6783,7 +6790,7 @@ var ZubariSubscriptionProtocol = class {
6783
6790
  * @param signer Wallet signer
6784
6791
  */
6785
6792
  async setAutoRenew(subscriptionId, autoRenew, signer) {
6786
- const iface = new (await import('ethers')).Interface(this.abi);
6793
+ const iface = await this.getInterface();
6787
6794
  const data = iface.encodeFunctionData("setAutoRenew", [subscriptionId, autoRenew]);
6788
6795
  const result = await signer.sendTransaction({
6789
6796
  to: this.contractAddress,
@@ -6803,7 +6810,7 @@ var ZubariSubscriptionProtocol = class {
6803
6810
  * @param provider JSON-RPC provider
6804
6811
  */
6805
6812
  async isSubscribed(subscriber, creator, provider) {
6806
- const iface = new (await import('ethers')).Interface(this.abi);
6813
+ const iface = await this.getInterface();
6807
6814
  const data = iface.encodeFunctionData("isSubscribed", [subscriber, creator]);
6808
6815
  try {
6809
6816
  const result = await provider.call({
@@ -6823,7 +6830,7 @@ var ZubariSubscriptionProtocol = class {
6823
6830
  * @param provider JSON-RPC provider
6824
6831
  */
6825
6832
  async getActiveSubscriptionId(subscriber, creator, provider) {
6826
- const iface = new (await import('ethers')).Interface(this.abi);
6833
+ const iface = await this.getInterface();
6827
6834
  const data = iface.encodeFunctionData("activeSubscription", [subscriber, creator]);
6828
6835
  try {
6829
6836
  const result = await provider.call({
@@ -6846,7 +6853,7 @@ var ZubariSubscriptionProtocol = class {
6846
6853
  * @param provider JSON-RPC provider
6847
6854
  */
6848
6855
  async getSubscription(subscriptionId, provider) {
6849
- const iface = new (await import('ethers')).Interface(this.abi);
6856
+ const iface = await this.getInterface();
6850
6857
  const data = iface.encodeFunctionData("getSubscription", [subscriptionId]);
6851
6858
  try {
6852
6859
  const result = await provider.call({
@@ -6892,7 +6899,7 @@ var ZubariSubscriptionProtocol = class {
6892
6899
  * @param provider JSON-RPC provider
6893
6900
  */
6894
6901
  async getPlan(planId, provider) {
6895
- const iface = new (await import('ethers')).Interface(this.abi);
6902
+ const iface = await this.getInterface();
6896
6903
  const data = iface.encodeFunctionData("getPlan", [planId]);
6897
6904
  try {
6898
6905
  const result = await provider.call({
@@ -6928,7 +6935,7 @@ var ZubariSubscriptionProtocol = class {
6928
6935
  * @param provider JSON-RPC provider
6929
6936
  */
6930
6937
  async getCreatorPlanIds(creator, provider) {
6931
- const iface = new (await import('ethers')).Interface(this.abi);
6938
+ const iface = await this.getInterface();
6932
6939
  const data = iface.encodeFunctionData("getCreatorPlans", [creator]);
6933
6940
  try {
6934
6941
  const result = await provider.call({
@@ -6962,7 +6969,7 @@ var ZubariSubscriptionProtocol = class {
6962
6969
  * @param provider JSON-RPC provider
6963
6970
  */
6964
6971
  async getPlatformFeeBps(provider) {
6965
- const iface = new (await import('ethers')).Interface(this.abi);
6972
+ const iface = await this.getInterface();
6966
6973
  const data = iface.encodeFunctionData("platformFeeBps", []);
6967
6974
  try {
6968
6975
  const result = await provider.call({