@otoplo/wallet-common 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.d.ts +889 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +259 -195
  4. package/dist/index.js.map +1 -1
  5. package/package.json +8 -9
  6. package/src/services/rostrum.ts +42 -22
  7. package/src/services/wallet.ts +758 -694
  8. package/dist/types/index.d.ts +0 -5
  9. package/dist/types/index.d.ts.map +0 -1
  10. package/dist/types/persistence/index.d.ts +0 -3
  11. package/dist/types/persistence/index.d.ts.map +0 -1
  12. package/dist/types/persistence/repository.d.ts +0 -43
  13. package/dist/types/persistence/repository.d.ts.map +0 -1
  14. package/dist/types/persistence/wallet-db.d.ts +0 -44
  15. package/dist/types/persistence/wallet-db.d.ts.map +0 -1
  16. package/dist/types/services/asset.d.ts +0 -21
  17. package/dist/types/services/asset.d.ts.map +0 -1
  18. package/dist/types/services/cache.d.ts +0 -14
  19. package/dist/types/services/cache.d.ts.map +0 -1
  20. package/dist/types/services/discovery.d.ts +0 -18
  21. package/dist/types/services/discovery.d.ts.map +0 -1
  22. package/dist/types/services/index.d.ts +0 -10
  23. package/dist/types/services/index.d.ts.map +0 -1
  24. package/dist/types/services/key.d.ts +0 -17
  25. package/dist/types/services/key.d.ts.map +0 -1
  26. package/dist/types/services/market.d.ts +0 -33
  27. package/dist/types/services/market.d.ts.map +0 -1
  28. package/dist/types/services/rostrum.d.ts +0 -39
  29. package/dist/types/services/rostrum.d.ts.map +0 -1
  30. package/dist/types/services/session.d.ts +0 -48
  31. package/dist/types/services/session.d.ts.map +0 -1
  32. package/dist/types/services/transaction.d.ts +0 -41
  33. package/dist/types/services/transaction.d.ts.map +0 -1
  34. package/dist/types/services/tx-transformer.d.ts +0 -22
  35. package/dist/types/services/tx-transformer.d.ts.map +0 -1
  36. package/dist/types/services/wallet.d.ts +0 -107
  37. package/dist/types/services/wallet.d.ts.map +0 -1
  38. package/dist/types/types/dapp.types.d.ts +0 -19
  39. package/dist/types/types/dapp.types.d.ts.map +0 -1
  40. package/dist/types/types/db.types.d.ts +0 -138
  41. package/dist/types/types/db.types.d.ts.map +0 -1
  42. package/dist/types/types/index.d.ts +0 -6
  43. package/dist/types/types/index.d.ts.map +0 -1
  44. package/dist/types/types/notification.types.d.ts +0 -21
  45. package/dist/types/types/notification.types.d.ts.map +0 -1
  46. package/dist/types/types/rostrum.types.d.ts +0 -132
  47. package/dist/types/types/rostrum.types.d.ts.map +0 -1
  48. package/dist/types/types/wallet.types.d.ts +0 -80
  49. package/dist/types/types/wallet.types.d.ts.map +0 -1
  50. package/dist/types/utils/asset.d.ts +0 -5
  51. package/dist/types/utils/asset.d.ts.map +0 -1
  52. package/dist/types/utils/common.d.ts +0 -64
  53. package/dist/types/utils/common.d.ts.map +0 -1
  54. package/dist/types/utils/enums.d.ts +0 -16
  55. package/dist/types/utils/enums.d.ts.map +0 -1
  56. package/dist/types/utils/index.d.ts +0 -7
  57. package/dist/types/utils/index.d.ts.map +0 -1
  58. package/dist/types/utils/keypath.d.ts +0 -5
  59. package/dist/types/utils/keypath.d.ts.map +0 -1
  60. package/dist/types/utils/seed.d.ts +0 -5
  61. package/dist/types/utils/seed.d.ts.map +0 -1
  62. package/dist/types/utils/vault.d.ts +0 -10
  63. package/dist/types/utils/vault.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -2,16 +2,18 @@ import { Address as e, AddressType as t, BufferUtils as n, BufferWriter as r, Co
2
2
  import y from "js-big-decimal";
3
3
  import { ConnectionStatus as te, ElectrumClient as ne, TransportScheme as b } from "@otoplo/electrum-client";
4
4
  import { generateMnemonic as re, mnemonicToSeedSync as ie, validateMnemonic as ae } from "@scure/bip39";
5
- import { DAppProvider as oe } from "wallet-comms-sdk";
6
5
  import { wordlist as x } from "@scure/bip39/wordlists/english.js";
6
+ import { DAppProvider as oe } from "wallet-comms-sdk";
7
7
  // src/utils/enums.ts
8
- var S = /* @__PURE__ */ function(e) {
8
+ let se = /* @__PURE__ */ function(e) {
9
9
  return e[e.MAIN = 0] = "MAIN", e[e.VAULT = 1] = "VAULT", e[e.DAPP = 2] = "DAPP", e;
10
- }({}), C = /* @__PURE__ */ function(e) {
10
+ }({}), ce = /* @__PURE__ */ function(e) {
11
11
  return e[e.RECEIVE = 0] = "RECEIVE", e[e.CHANGE = 1] = "CHANGE", e;
12
- }({}), w = /* @__PURE__ */ function(e) {
12
+ }({}), le = /* @__PURE__ */ function(e) {
13
13
  return e.SignMessage = "signMessage", e.AddToken = "addToken", e.SignTransaction = "signTransaction", e.SendTransaction = "sendTransaction", e;
14
- }({}), se = -1, ce = 9223372036854775807n, T = {
14
+ }({});
15
+ // src/utils/common.ts
16
+ const ue = -1, de = 9223372036854775807n, S = {
15
17
  usd: {
16
18
  symbol: "$",
17
19
  name: "US Dollar"
@@ -48,46 +50,46 @@ var S = /* @__PURE__ */ function(e) {
48
50
  symbol: "¥",
49
51
  name: "Japanese Yen"
50
52
  }
51
- }, E = Object.keys(T);
52
- function D() {
53
+ }, C = Object.keys(S);
54
+ function w() {
53
55
  return s.defaultNetwork == s.testnet;
54
56
  }
55
- function le(e) {
56
- return D() ? e == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52" : e == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
57
+ function fe(e) {
58
+ return w() ? e == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52" : e == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
57
59
  }
58
- function O(n, r = t.PayToScriptTemplate) {
60
+ function T(n, r = t.PayToScriptTemplate) {
59
61
  return e.isValid(n, s.defaultNetwork, r);
60
62
  }
61
- function ue() {
62
- return `https://${D() ? "testnet-" : ""}explorer.nexa.org`;
63
+ function pe() {
64
+ return `https://${w() ? "testnet-" : ""}explorer.nexa.org`;
63
65
  }
64
- function k() {
66
+ function E() {
65
67
  return Math.floor(Date.now() / 1e3);
66
68
  }
67
- function A(e) {
69
+ function D(e) {
68
70
  return !e || e.length === 0;
69
71
  }
70
- function de(e, t = 0) {
72
+ function me(e, t = 0) {
71
73
  if (!e || e.length <= t) return e || "";
72
74
  let n = Math.floor((t - 3) / 2), r = e.slice(0, n), i = e.slice(e.length - n);
73
75
  return r + "..." + i;
74
76
  }
75
- function fe(e) {
77
+ function he(e) {
76
78
  return e.length === 0 ? "" : e.charAt(0).toUpperCase() + e.substring(1);
77
79
  }
78
- function j(t) {
80
+ function O(t) {
79
81
  return i.isHexa(t) ? n.hexToBuffer(t) : e.fromString(t).data;
80
82
  }
81
- function M(e) {
82
- return i.isHexa(e) ? e : n.bufferToHex(j(e));
83
+ function k(e) {
84
+ return i.isHexa(e) ? e : n.bufferToHex(O(e));
83
85
  }
84
- function pe(n) {
85
- return i.isHexa(n) ? new e(j(n), s.defaultNetwork, t.GroupIdAddress).toString() : n;
86
+ function ge(n) {
87
+ return i.isHexa(n) ? new e(O(n), s.defaultNetwork, t.GroupIdAddress).toString() : n;
86
88
  }
87
- function N(e) {
89
+ function A(e) {
88
90
  return e == null || e === "" ? "" : BigInt(e) <= 0n ? "0" : e.toString();
89
91
  }
90
- function P(e) {
92
+ function j(e) {
91
93
  let t = BigInt(0), n = BigInt(0);
92
94
  return e.forEach((e) => {
93
95
  t += BigInt(e.confirmed), n += BigInt(e.unconfirmed);
@@ -96,7 +98,7 @@ function P(e) {
96
98
  unconfirmed: n.toString()
97
99
  };
98
100
  }
99
- function F(e) {
101
+ function M(e) {
100
102
  let t = {};
101
103
  return e.forEach((e) => {
102
104
  for (let n in e) t[n] ? (t[n].confirmed = (BigInt(t[n].confirmed) + BigInt(e[n].confirmed)).toString(), t[n].unconfirmed = (BigInt(t[n].unconfirmed) + BigInt(e[n].unconfirmed)).toString()) : t[n] = {
@@ -105,7 +107,7 @@ function F(e) {
105
107
  };
106
108
  }), t;
107
109
  }
108
- var I = {
110
+ const N = {
109
111
  ".gif": {
110
112
  media: "image",
111
113
  mime: "image/gif"
@@ -175,21 +177,25 @@ var I = {
175
177
  mime: "audio/mp4"
176
178
  }
177
179
  };
178
- function me(e) {
180
+ function P(e) {
179
181
  let t = e.lastIndexOf(".");
180
- return t === -1 ? "unknown" : I[e.slice(t).toLowerCase()]?.media ?? "unknown";
182
+ if (t === -1) return "unknown";
183
+ let n = e.slice(t).toLowerCase();
184
+ return N[n]?.media ?? "unknown";
181
185
  }
182
- function he(e) {
186
+ function F(e) {
183
187
  let t = e.lastIndexOf(".");
184
- return t === -1 ? "application/octet-stream" : I[e.slice(t).toLowerCase()]?.mime ?? "application/octet-stream";
188
+ if (t === -1) return "application/octet-stream";
189
+ let n = e.slice(t).toLowerCase();
190
+ return N[n]?.mime ?? "application/octet-stream";
185
191
  }
186
- function ge(e) {
192
+ function I(e) {
187
193
  return new Promise((t) => setTimeout(t, e));
188
194
  }
189
- function _e(e) {
195
+ function L(e) {
190
196
  return new y(e).stripTrailingZero().getPrettyValue();
191
197
  }
192
- function ve(e, t, n, r = "en-US") {
198
+ function _e(e, t, n, r = "en-US") {
193
199
  let i = y.multiply(e, t);
194
200
  return new Intl.NumberFormat(r, {
195
201
  style: "currency",
@@ -197,7 +203,7 @@ function ve(e, t, n, r = "en-US") {
197
203
  }).format(Number(i));
198
204
  }
199
205
  // src/persistence/wallet-db.ts
200
- var ye = class {
206
+ var ve = class {
201
207
  constructor(e) {
202
208
  this.repository = e;
203
209
  }
@@ -246,7 +252,7 @@ var ye = class {
246
252
  accountId: e,
247
253
  tokenIdHex: t.tokenIdHex,
248
254
  type: "token",
249
- addedTime: k()
255
+ addedTime: E()
250
256
  };
251
257
  await this.repository.upsertToken(t), await this.saveAsset(n);
252
258
  }
@@ -305,7 +311,7 @@ var ye = class {
305
311
  async getAccounts() {
306
312
  return (await this.repository.getAccounts()).map((e) => ({
307
313
  ...e,
308
- type: S.DAPP,
314
+ type: 2,
309
315
  balance: JSON.parse(e.balance),
310
316
  tokensBalance: JSON.parse(e.tokensBalance)
311
317
  }));
@@ -341,7 +347,7 @@ var ye = class {
341
347
  async getReceiveAddresses() {
342
348
  return (await this.repository.getReceiveAddresses()).map((e) => ({
343
349
  ...e,
344
- type: S.MAIN,
350
+ type: 0,
345
351
  balance: JSON.parse(e.balance),
346
352
  tokensBalance: JSON.parse(e.tokensBalance)
347
353
  }));
@@ -349,7 +355,7 @@ var ye = class {
349
355
  async getChangeAddresses() {
350
356
  return (await this.repository.getChangeAddresses()).map((e) => ({
351
357
  ...e,
352
- type: S.MAIN,
358
+ type: 0,
353
359
  balance: JSON.parse(e.balance),
354
360
  tokensBalance: JSON.parse(e.tokensBalance)
355
361
  }));
@@ -360,7 +366,7 @@ var ye = class {
360
366
  async getVaults() {
361
367
  return (await this.repository.getVaults()).map((e) => ({
362
368
  ...e,
363
- type: S.VAULT,
369
+ type: 1,
364
370
  balance: JSON.parse(e.balance),
365
371
  tokensBalance: JSON.parse(e.tokensBalance)
366
372
  }));
@@ -386,7 +392,7 @@ var ye = class {
386
392
  removeSetting(e) {
387
393
  return this.repository.deleteSetting(e);
388
394
  }
389
- }, be = class {
395
+ }, ye = class {
390
396
  constructor(e) {
391
397
  this.tokens = /* @__PURE__ */ new Map(), this.nfts = /* @__PURE__ */ new Map(), this.walletDb = e;
392
398
  }
@@ -394,25 +400,34 @@ var ye = class {
394
400
  this.tokens.clear(), this.nfts.clear();
395
401
  }
396
402
  async getToken(e) {
397
- if (e = M(e), this.tokens.has(e)) return this.tokens.get(e);
403
+ if (e = k(e), this.tokens.has(e)) return this.tokens.get(e);
398
404
  let t = await this.walletDb.getToken(e);
399
405
  return t && this.tokens.set(e, t), t;
400
406
  }
401
407
  async getNft(e) {
402
- if (e = M(e), this.nfts.has(e)) return this.nfts.get(e);
408
+ if (e = k(e), this.nfts.has(e)) return this.nfts.get(e);
403
409
  let t = await this.walletDb.getNft(e);
404
410
  return t && this.nfts.set(e, t), t;
405
411
  }
406
412
  removeToken(e) {
407
- this.tokens.delete(M(e));
413
+ this.tokens.delete(k(e));
408
414
  }
409
415
  removeNft(e) {
410
- this.nfts.delete(M(e));
416
+ this.nfts.delete(k(e));
411
417
  }
412
- }, xe = class e {
418
+ }, be = class e {
413
419
  constructor(e) {
414
420
  this.walletDb = e;
415
421
  }
422
+ onUpdate(e) {
423
+ this.updateCallback = e;
424
+ }
425
+ notify(e) {
426
+ this.updateCallback?.(e);
427
+ }
428
+ isConnected() {
429
+ return this.client?.status === te.CONNECTED;
430
+ }
416
431
  getFeatures() {
417
432
  return this.execute("server.features");
418
433
  }
@@ -488,13 +503,13 @@ var ye = class {
488
503
  return this.execute("blockchain.transaction.broadcast", e);
489
504
  }
490
505
  subscribeHeaders(e) {
491
- return this.client.subscribe((t) => {
492
- let n = Array.isArray(t) ? t[0] : t;
493
- e(typeof n?.height == "number" ? n.height : 0);
506
+ return this.client.subscribe(([t]) => {
507
+ let n = t?.height;
508
+ e(typeof n == "number" ? n : 0);
494
509
  }, "blockchain.headers.subscribe");
495
510
  }
496
511
  subscribeAddress(e, t) {
497
- return this.client.subscribe(t, "blockchain.address.subscribe", e);
512
+ return this.client.subscribe(([e, n]) => t(e, n), "blockchain.address.subscribe", e);
498
513
  }
499
514
  async getLatency() {
500
515
  try {
@@ -506,18 +521,24 @@ var ye = class {
506
521
  }
507
522
  async connect(e) {
508
523
  try {
509
- e ||= await this.getCurrentInstance(), this.client = new ne("com.otoplo.wallet", "1.4.3", e.host, e.port, e.scheme, 45e3, 1e4), await this.client.connect();
524
+ await this.disconnect(), e ||= await this.getCurrentInstance(), this.client = new ne({
525
+ application: "com.otoplo.wallet",
526
+ version: "1.4.3",
527
+ host: e.host,
528
+ port: e.port,
529
+ scheme: e.scheme
530
+ }), this.client.on("connected", () => this.notify({ type: "connected" })), this.client.on("disconnected", () => this.notify({ type: "disconnected" })), await this.client.connect();
510
531
  } catch (e) {
511
532
  throw e instanceof Error ? console.info(e.message) : console.error(e), e;
512
533
  }
513
534
  }
514
- async disconnect(e) {
515
- try {
516
- return await this.client?.disconnect(e) ?? !1;
517
- } catch (e) {
518
- return console.error(e), !1;
519
- }
535
+ async disconnect() {
536
+ await this.client?.disconnect();
520
537
  }
538
+ /**
539
+ * Walk a cursor-paginated rostrum query: start with "start" and follow the returned cursor until it is null.
540
+ * If the cursor expires mid-walk (e.g. reorg / mempool change), the walk is restarted from the beginning.
541
+ */
521
542
  async paginate(e, t, n, r = 3) {
522
543
  for (let i = 0;; i++) try {
523
544
  let r = [], i = "start";
@@ -532,16 +553,13 @@ var ye = class {
532
553
  }
533
554
  }
534
555
  async execute(e, ...t) {
535
- await this.waitForConnection();
536
- let n = await this.client.request(e, ...t);
537
- if (n instanceof Error) throw n;
538
- return n;
556
+ return await this.waitForConnection(), this.client.request(e, ...t);
539
557
  }
540
558
  waitForConnection(e = 5e3) {
541
559
  let t = Date.now();
542
560
  return new Promise((n, r) => {
543
561
  let i = () => {
544
- if (this.client?.connectionStatus == te.CONNECTED) return n();
562
+ if (this.isConnected()) return n();
545
563
  if (Date.now() - t > e) return r(/* @__PURE__ */ Error("Rostrum Connection timeout"));
546
564
  setTimeout(i, 250);
547
565
  };
@@ -559,7 +577,7 @@ var ye = class {
559
577
  return t ? JSON.parse(t) : e.getPredefinedInstances()[0];
560
578
  }
561
579
  static getPredefinedInstances() {
562
- return D() ? [{
580
+ return w() ? [{
563
581
  scheme: b.WSS,
564
582
  host: "testnet-electrum.nexa.org",
565
583
  port: 30004,
@@ -578,10 +596,10 @@ var ye = class {
578
596
  }
579
597
  };
580
598
  // src/utils/keypath.ts
581
- function L(e, t, n) {
599
+ function R(e, t, n) {
582
600
  return `${e}'/${t}/${n}`;
583
601
  }
584
- function R(e) {
602
+ function z(e) {
585
603
  let t = e.split("/");
586
604
  return {
587
605
  account: parseInt(t[0].replace("'", "")),
@@ -590,7 +608,7 @@ function R(e) {
590
608
  };
591
609
  }
592
610
  // src/services/key.ts
593
- var z = class {
611
+ var B = class {
594
612
  constructor() {
595
613
  this.accountKeys = /* @__PURE__ */ new Map(), this.walletKeys = /* @__PURE__ */ new Map();
596
614
  }
@@ -620,16 +638,16 @@ var z = class {
620
638
  }
621
639
  getKey(e) {
622
640
  if (!this.seed) throw Error("KeysManager not initialized");
623
- let t = typeof e == "string" ? e : L(e.account, e.type, e.index), n = this.walletKeys.get(t);
641
+ let t = typeof e == "string" ? e : R(e.account, e.type, e.index), n = this.walletKeys.get(t);
624
642
  if (!n) {
625
- let { account: r, type: i, index: a } = typeof e == "string" ? R(e) : e;
643
+ let { account: r, type: i, index: a } = typeof e == "string" ? z(e) : e;
626
644
  n = this.getAccountKey(r).deriveChild(i, !1).deriveChild(a, !1), this.walletKeys.set(t, n);
627
645
  }
628
646
  return n;
629
647
  }
630
648
  };
631
649
  // src/utils/asset.ts
632
- function B(e, t) {
650
+ function xe(e, t) {
633
651
  return e && typeof e == "string" ? e.startsWith("http") ? e.replace("http://", "https://") : e.startsWith("ipfs://") ? e : `${new URL(t).origin}${e}` : "";
634
652
  }
635
653
  function Se(e) {
@@ -645,7 +663,7 @@ function H(e, t) {
645
663
  return `${U()}/assets/${e}/${t}`;
646
664
  }
647
665
  function U() {
648
- return `https://${D() ? "testapi" : "api"}.otoplo.com`;
666
+ return `https://${w() ? "testapi" : "api"}.otoplo.com`;
649
667
  }
650
668
  // src/services/asset.ts
651
669
  var we = class {
@@ -722,8 +740,8 @@ var we = class {
722
740
  let n = Object.keys(t), r = await this.walletDb.getAssets(e, "nft"), i = r?.filter((e) => !n.includes(e.tokenIdHex)) ?? [];
723
741
  for (let t of i) await this.deleteNft(e, t.tokenIdHex);
724
742
  for (let [n, i] of Object.entries(t)) {
725
- let t = M(n), a = i && BigInt(i.confirmed) + BigInt(i.unconfirmed) > 0n, o = r?.some((e) => e.tokenIdHex == t);
726
- !a && !o || a && o || (!a && o ? await this.deleteNft(e, t) : await this.handleNftReceive(e, t, k()));
743
+ let t = k(n), a = i && BigInt(i.confirmed) + BigInt(i.unconfirmed) > 0n, o = r?.some((e) => e.tokenIdHex == t);
744
+ !a && !o || a && o || (!a && o ? await this.deleteNft(e, t) : await this.handleNftReceive(e, t, E()));
727
745
  }
728
746
  }
729
747
  async saveToken(e, t) {
@@ -757,7 +775,9 @@ var we = class {
757
775
  throw Error(`Unexpected Error: ${e}`);
758
776
  }
759
777
  }
760
- }, W = 274710;
778
+ };
779
+ // src/utils/vault.ts
780
+ const W = 274710;
761
781
  function G() {
762
782
  return d.empty().add(c.OP_FROMALTSTACK).add(c.OP_DROP).add(c.OP_FROMALTSTACK).add(c.OP_CHECKLOCKTIMEVERIFY).add(c.OP_DROP).add(c.OP_FROMALTSTACK).add(c.OP_CHECKSIGVERIFY);
763
783
  }
@@ -828,17 +848,17 @@ var Ee = class {
828
848
  address: e.addresses[0],
829
849
  nexaAmount: e.value_satoshi.toString(),
830
850
  assetId: e.token_id_hex ?? "",
831
- assetAmount: N(e.groupQuantity)
851
+ assetAmount: A(e.groupQuantity)
832
852
  };
833
853
  t.includes(n.address) ? r.push(n) : i.push(n);
834
854
  }
835
855
  for (let e of n.vout) {
836
- if (A(e.scriptPubKey.addresses)) continue;
856
+ if (D(e.scriptPubKey.addresses)) continue;
837
857
  let n = {
838
858
  address: e.scriptPubKey.addresses[0],
839
859
  nexaAmount: e.value_satoshi.toString(),
840
860
  assetId: e.scriptPubKey.token_id_hex ?? "",
841
- assetAmount: N(e.scriptPubKey.groupQuantity)
861
+ assetAmount: A(e.scriptPubKey.groupQuantity)
842
862
  };
843
863
  t.includes(n.address) ? a.push(n) : o.push(n);
844
864
  }
@@ -849,7 +869,7 @@ var Ee = class {
849
869
  accountId: 0,
850
870
  txId: n.txid,
851
871
  txIdem: n.txidem,
852
- time: c ? n.time : k(),
872
+ time: c ? n.time : E(),
853
873
  height: c ? n.height : 0,
854
874
  type: s,
855
875
  fee: n.fee_satoshi.toString(),
@@ -874,12 +894,12 @@ var Ee = class {
874
894
  return this.finalizeTransaction(i, Array.from(a.values()));
875
895
  }
876
896
  prepareTransaction(n, r, i, a) {
877
- if (!O(n) && !O(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
897
+ if (!T(n) && !T(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
878
898
  if (i && BigInt(r) < 1n || !i && parseInt(r) < h.DUST_AMOUNT) throw Error("The amount is too low.");
879
899
  if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > h.MAX_MONEY) throw Error("The amount is too high.");
880
900
  let o = new g();
881
901
  if (a && o.addData(a), i) {
882
- if (!O(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
902
+ if (!T(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
883
903
  if (e.getOutputType(n) === 0) throw Error("Token must be sent to script template address");
884
904
  o.to(n, h.DUST_AMOUNT, i, BigInt(r));
885
905
  } else o.to(n, r);
@@ -887,7 +907,7 @@ var Ee = class {
887
907
  }
888
908
  async populateNexaInputsAndChange(e, t, n, r) {
889
909
  let i = t.filter((e) => BigInt(e.balance.confirmed) + BigInt(e.balance.unconfirmed) > 0n);
890
- if (A(i)) throw Error("Not enough Nexa balance.");
910
+ if (D(i)) throw Error("Not enough Nexa balance.");
891
911
  let a = /* @__PURE__ */ new Map(), o = r.isConsolidate ? 0 : Number(e.transaction.outputs.find((e) => e.value > 0n).value);
892
912
  for (let t of i) {
893
913
  let i = await this.rostrumService.getNexaUtxos(t.address);
@@ -934,8 +954,8 @@ var Ee = class {
934
954
  throw Error(JSON.stringify(s));
935
955
  }
936
956
  async populateTokenInputsAndChange(e, t, n, r, i) {
937
- let a = M(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
938
- if (A(o)) throw Error("Not enough token balance.");
957
+ let a = k(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
958
+ if (D(o)) throw Error("Not enough token balance.");
939
959
  let s = /* @__PURE__ */ new Map(), c = 0n;
940
960
  for (let t of o) {
941
961
  let a = await this.rostrumService.getTokenUtxos(t.address, r);
@@ -1145,10 +1165,10 @@ var je = class {
1145
1165
  }
1146
1166
  });
1147
1167
  });
1148
- t.onSignMessage((e) => r(w.SignMessage, e)), t.onAddToken((e) => r(w.AddToken, e)), t.onSendTransaction((e) => r(w.SendTransaction, e)), t.onSignTransaction((e) => r(w.SignTransaction, e)), t.onGetAccount(() => {
1168
+ t.onSignMessage((e) => r("signMessage", e)), t.onAddToken((e) => r("addToken", e)), t.onSendTransaction((e) => r("sendTransaction", e)), t.onSignTransaction((e) => r("signTransaction", e)), t.onGetAccount(() => {
1149
1169
  let t = {
1150
- account: S.DAPP,
1151
- type: C.RECEIVE,
1170
+ account: 2,
1171
+ type: 0,
1152
1172
  index: e.id
1153
1173
  };
1154
1174
  return {
@@ -1212,7 +1232,7 @@ var je = class {
1212
1232
  address: e.address,
1213
1233
  nexaAmount: i.amount.toString(),
1214
1234
  assetId: n,
1215
- assetAmount: N(i.group_quantity) || i.amount.toString()
1235
+ assetAmount: A(i.group_quantity) || i.amount.toString()
1216
1236
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1217
1237
  }
1218
1238
  r.scriptSig.findPlaceholder() > 0 && e.inputsToSign.add(t);
@@ -1221,11 +1241,11 @@ var je = class {
1221
1241
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1222
1242
  let n = e.txDetails.tx.outputs[t].toObject();
1223
1243
  if (n.address !== e.address) continue;
1224
- let r = n.groupId ? M(n.groupId) : "NEXA", i = {
1244
+ let r = n.groupId ? k(n.groupId) : "NEXA", i = {
1225
1245
  address: n.address,
1226
1246
  nexaAmount: n.value.toString(),
1227
1247
  assetId: r,
1228
- assetAmount: N(n.groupAmount) || n.value.toString()
1248
+ assetAmount: A(n.groupAmount) || n.value.toString()
1229
1249
  };
1230
1250
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1231
1251
  }
@@ -1291,19 +1311,19 @@ var je = class {
1291
1311
  t !== "NEXA" && (n.asset = await this.assetService.getAssetInfo(t)), n.amount > 0n ? e.txDetails.receive.push(n) : n.amount < 0n && e.txDetails.send.push(n);
1292
1312
  }
1293
1313
  }
1294
- }, $ = 5, Ne = class {
1314
+ }, $ = class {
1295
1315
  constructor(e, t) {
1296
1316
  this.rostrumService = e, this.keyManager = t;
1297
1317
  }
1298
1318
  async discoverWalletIndex(e, t) {
1299
1319
  let n = 0, r = -1, i = [];
1300
1320
  for (;;) {
1301
- let a = await Promise.all(Array.from({ length: z.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1302
- if (a.some((e) => e)) r = n, i = a, n += z.GAP_LIMIT;
1321
+ let a = await Promise.all(Array.from({ length: B.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1322
+ if (a.some((e) => e)) r = n, i = a, n += B.GAP_LIMIT;
1303
1323
  else break;
1304
1324
  }
1305
1325
  if (r === -1) return -1;
1306
- for (let e = z.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1326
+ for (let e = B.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1307
1327
  return r;
1308
1328
  }
1309
1329
  async discoverVaults() {
@@ -1313,13 +1333,17 @@ var je = class {
1313
1333
  n && t.set(n.address, n);
1314
1334
  }), t;
1315
1335
  }
1336
+ /**
1337
+ * Scan vault key indexes and ask rostrum for scripts matching the vault template + the key's constraint.
1338
+ * Indexes are checked in parallel batches, stopping after VAULT_GAP_LIMIT consecutive indexes with no scripts.
1339
+ */
1316
1340
  async checkForVaults() {
1317
1341
  let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(K()), r = 0;
1318
- for (let i = 0; r < $; i += $) {
1319
- let a = await Promise.all(Array.from({ length: $ }, (e, r) => {
1342
+ for (let i = 0; r < 5; i += 5) {
1343
+ let a = await Promise.all(Array.from({ length: 5 }, (e, r) => {
1320
1344
  let a = this.keyManager.getKey({
1321
- account: S.VAULT,
1322
- type: C.RECEIVE,
1345
+ account: 1,
1346
+ type: 0,
1323
1347
  index: i + r
1324
1348
  }), o = n.bufferToHex(J(a.publicKey));
1325
1349
  return this.rostrumService.listTemplateScripts(t, o);
@@ -1331,8 +1355,8 @@ var je = class {
1331
1355
  parseVaultDetails(t) {
1332
1356
  let n = d.fromHex(t), i = new r().writeVarLengthBuf(n.toBuffer()).toBuffer(), a = new e(i).toString(), o = n.getVisibleArgs(), s = Number(f.decode(o.chunks[0].buf)), c = p.isSmallIntOp(o.chunks[1].opcodenum) ? p.decodeOP_N(o.chunks[1].opcodenum) : Number(f.decode(o.chunks[1].buf)), l = [s, c];
1333
1357
  if (a == X(this.keyManager.getKey({
1334
- account: S.VAULT,
1335
- type: C.RECEIVE,
1358
+ account: 1,
1359
+ type: 0,
1336
1360
  index: c
1337
1361
  }).publicKey, l)) return {
1338
1362
  address: a,
@@ -1345,25 +1369,31 @@ var je = class {
1345
1369
  },
1346
1370
  tokensBalance: {},
1347
1371
  height: 0,
1348
- type: S.VAULT
1372
+ type: 1
1349
1373
  };
1350
1374
  }
1351
- }, Pe = class e {
1375
+ }, Ne = class e {
1376
+ static {
1377
+ this.DEBOUNCE_MS = 1e3;
1378
+ }
1352
1379
  static {
1353
- this.DEBOUNCE_MS = 2e3;
1380
+ this.RETRY_DELAY_MS = 1e3;
1381
+ }
1382
+ static {
1383
+ this.MAX_RETRY_DELAY_MS = 1e4;
1354
1384
  }
1355
1385
  constructor(e, t, n, r, i, a) {
1356
- this.keyManager = e, this.walletDb = t, this.rostrumService = n, this.assetService = r, this.transactionService = i, this.sessionManager = a, this.isConnected = !1, this.isSubscribed = !1, this.onSubscribeEvent = (e) => {
1357
- if (!Array.isArray(e) || e.length < 2) return;
1358
- let [t, n] = e, r = this.getAllAddresses().find((e) => e.address === t);
1359
- r && r.statusHash !== n && this.registerUpdate({
1360
- address: r,
1361
- result: n
1386
+ this.keyManager = e, this.walletDb = t, this.rostrumService = n, this.assetService = r, this.transactionService = i, this.sessionManager = a, this.updatesStarted = !1, this.isConnected = !1, this.isSubscribed = !1, this.connectionId = 0, this.onSubscribeEvent = (e, t) => {
1387
+ if (typeof t != "string") return;
1388
+ let n = this.getAllAddresses().find((t) => t.address === e);
1389
+ n && n.statusHash !== t && this.registerUpdate({
1390
+ address: n,
1391
+ result: t
1362
1392
  });
1363
- }, this.discoveryService = new Ne(this.rostrumService, this.keyManager), this.accounts = /* @__PURE__ */ new Map(), this.accountsAddressToId = /* @__PURE__ */ new Map(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults = /* @__PURE__ */ new Map(), this.pendingUpdates = /* @__PURE__ */ new Map(), this.addressResolvers = /* @__PURE__ */ new Map();
1393
+ }, this.discoveryService = new $(this.rostrumService, this.keyManager), this.accounts = /* @__PURE__ */ new Map(), this.accountsAddressToId = /* @__PURE__ */ new Map(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults = /* @__PURE__ */ new Map(), this.pendingUpdates = /* @__PURE__ */ new Map();
1364
1394
  }
1365
1395
  clear() {
1366
- this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.pendingUpdates.clear(), this.addressResolvers.clear(), this.notify({ type: "clear_wallet" });
1396
+ this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.stopUpdates(), this.notify({ type: "clear_wallet" });
1367
1397
  }
1368
1398
  onUpdate(e) {
1369
1399
  this.updateCallback = e;
@@ -1393,20 +1423,20 @@ var je = class {
1393
1423
  let t = this.accounts.get(e);
1394
1424
  return [{
1395
1425
  address: t.address,
1396
- keyPath: L(S.DAPP, 0, t.id),
1426
+ keyPath: R(2, 0, t.id),
1397
1427
  balance: t.balance,
1398
1428
  tokensBalance: t.tokensBalance
1399
1429
  }];
1400
1430
  }
1401
1431
  return this.getMainAddresses().filter((e) => e.used).map((e) => ({
1402
1432
  address: e.address,
1403
- keyPath: L(S.MAIN, e.space, e.idx),
1433
+ keyPath: R(0, e.space, e.idx),
1404
1434
  balance: e.balance,
1405
1435
  tokensBalance: e.tokensBalance
1406
1436
  }));
1407
1437
  }
1408
1438
  async reloadRostrum(e) {
1409
- e && await this.rostrumService.setCurrentInstance(e), await this.disconnectRostrum(), await this.initRostrum(), await this.subscribeAllAddresses();
1439
+ e && await this.rostrumService.setCurrentInstance(e), await this.disconnectRostrum(), await this.initRostrum(), this.startUpdates(), await this.subscribeAllAddresses();
1410
1440
  }
1411
1441
  async initRostrum() {
1412
1442
  this.isConnected ||= (await this.rostrumService.connect(), await this.rostrumService.subscribeHeaders((e) => this.notify({
@@ -1414,17 +1444,56 @@ var je = class {
1414
1444
  tip: e
1415
1445
  })), !0);
1416
1446
  }
1447
+ /**
1448
+ * Connects and syncs the loaded wallet, retrying with exponential backoff until it succeeds or
1449
+ * `disconnectRostrum()` is called. Never throws.
1450
+ *
1451
+ * Each attempt skips what's already done (connected, subscribed), so a retry continues where the last one failed.
1452
+ * Calling it while waiting to retry makes the next attempt immediately (e.g. when the app returns to the foreground).
1453
+ *
1454
+ * For flows where the user is waiting on the result (e.g. discovery), use `initRostrum()`, which makes a single attempt.
1455
+ *
1456
+ * @returns resolves once connected and synced, or when stopped by `disconnectRostrum()`.
1457
+ */
1458
+ connect() {
1459
+ if (this.connecting?.id === this.connectionId) return this.retryNow?.(), this.connecting.promise;
1460
+ let e = {
1461
+ id: this.connectionId,
1462
+ promise: this.connectLoop(this.connectionId)
1463
+ };
1464
+ return this.connecting = e, e.promise.finally(() => {
1465
+ this.connecting === e && (this.connecting = void 0);
1466
+ }), e.promise;
1467
+ }
1468
+ async connectLoop(t) {
1469
+ let n = e.RETRY_DELAY_MS;
1470
+ for (; t === this.connectionId;) {
1471
+ try {
1472
+ await this.initRostrum(), await this.reconnectSync();
1473
+ return;
1474
+ } catch (e) {
1475
+ console.info(`Connection failed, retrying in ${n}ms:`, e instanceof Error ? e.message : e);
1476
+ }
1477
+ if (t !== this.connectionId) return;
1478
+ await new Promise((e) => {
1479
+ let t = setTimeout(() => this.retryNow?.(), n);
1480
+ this.retryNow = () => {
1481
+ clearTimeout(t), this.retryNow = void 0, e();
1482
+ };
1483
+ }), n = Math.min(n * 2, e.MAX_RETRY_DELAY_MS);
1484
+ }
1485
+ }
1417
1486
  async disconnectRostrum() {
1418
- await this.rostrumService.disconnect(!0), this.isConnected = !1, this.isSubscribed = !1;
1487
+ this.connectionId++, this.retryNow?.(), await this.rostrumService.disconnect(), this.isConnected = !1, this.isSubscribed = !1, this.stopUpdates();
1419
1488
  }
1420
1489
  async discoverWallet() {
1421
- let e = this.discoveryService.discoverWalletIndex(S.MAIN, C.RECEIVE), t = this.discoveryService.discoverWalletIndex(S.MAIN, C.CHANGE), n = this.discoveryService.discoverWalletIndex(S.DAPP, C.RECEIVE), r = this.discoveryService.discoverVaults(), [i, a, o, s] = await Promise.all([
1490
+ let e = this.discoveryService.discoverWalletIndex(0, 0), t = this.discoveryService.discoverWalletIndex(0, 1), n = this.discoveryService.discoverWalletIndex(2, 0), r = this.discoveryService.discoverVaults(), [i, a, o, s] = await Promise.all([
1422
1491
  e,
1423
1492
  t,
1424
1493
  n,
1425
1494
  r
1426
1495
  ]);
1427
- this.receiveAddresses = this.deriveAddresses(C.RECEIVE, 0, i + z.GAP_LIMIT + 1), this.changeAddresses = this.deriveAddresses(C.CHANGE, 0, a + z.GAP_LIMIT + 1), this.accounts = this.deriveAccounts(0, o < 0 ? 1 : o + 1), this.accounts.forEach((e) => this.accountsAddressToId.set(e.address, e.id)), this.vaults = s, await this.saveAddresses(this.receiveAddresses), await this.saveAddresses(this.changeAddresses), await this.saveAccounts(this.accounts), await this.saveVaults(this.vaults), this.initState();
1496
+ this.receiveAddresses = this.deriveAddresses(0, 0, i + B.GAP_LIMIT + 1), this.changeAddresses = this.deriveAddresses(1, 0, a + B.GAP_LIMIT + 1), this.accounts = this.deriveAccounts(0, o < 0 ? 1 : o + 1), this.accounts.forEach((e) => this.accountsAddressToId.set(e.address, e.id)), this.vaults = s, await this.saveAddresses(this.receiveAddresses), await this.saveAddresses(this.changeAddresses), await this.saveAccounts(this.accounts), await this.saveVaults(this.vaults), this.initState();
1428
1497
  }
1429
1498
  async loadWallet() {
1430
1499
  this.receiveAddresses = await this.walletDb.getReceiveAddresses(), this.changeAddresses = await this.walletDb.getChangeAddresses();
@@ -1433,14 +1502,25 @@ var je = class {
1433
1502
  let t = await this.walletDb.getVaults();
1434
1503
  this.vaults = new Map(t.map((e) => [e.address, e])), this.initState();
1435
1504
  }
1436
- initialSync() {
1437
- return this.subscribeAllAddresses(!0);
1505
+ /**
1506
+ * First sync after discovery: subscriptions only queue updates, which are then processed
1507
+ * in one batch before the update loop starts.
1508
+ */
1509
+ async initialSync() {
1510
+ await this.subscribeAllAddresses(), await this.processPendingUpdates(!0), this.startUpdates();
1438
1511
  }
1439
1512
  reconnectSync() {
1440
- return Promise.all([this.sessionManager.reload(this.accounts), this.subscribeAllAddresses()]);
1441
- }
1442
- async subscribeAllAddresses(e) {
1443
- this.isSubscribed || (this.isSubscribed = !0, await this.subscribeAddresses(this.getAllAddresses(), e));
1513
+ return this.startUpdates(), Promise.all([this.sessionManager.reload(this.accounts), this.subscribeAllAddresses()]);
1514
+ }
1515
+ async subscribeAllAddresses() {
1516
+ if (!this.isSubscribed) {
1517
+ this.isSubscribed = !0;
1518
+ try {
1519
+ await this.subscribeAddresses(this.getAllAddresses());
1520
+ } catch (e) {
1521
+ throw this.isSubscribed = !1, e;
1522
+ }
1523
+ }
1444
1524
  }
1445
1525
  initState() {
1446
1526
  let e = this.getMainAddresses();
@@ -1450,8 +1530,8 @@ var je = class {
1450
1530
  id: -1,
1451
1531
  name: "HD Wallet",
1452
1532
  address: this.getReceiveAddress(),
1453
- balance: P(e.map((e) => e.balance)),
1454
- tokensBalance: F(e.map((e) => e.tokensBalance)),
1533
+ balance: j(e.map((e) => e.balance)),
1534
+ tokensBalance: M(e.map((e) => e.tokensBalance)),
1455
1535
  sessions: {}
1456
1536
  }
1457
1537
  });
@@ -1480,7 +1560,7 @@ var je = class {
1480
1560
  let r = [];
1481
1561
  for (let i = t; i < t + n; i++) {
1482
1562
  let t = {
1483
- address: this.keyManager.deriveAddress(S.MAIN, e, i),
1563
+ address: this.keyManager.deriveAddress(0, e, i),
1484
1564
  space: e,
1485
1565
  idx: i,
1486
1566
  used: !1,
@@ -1491,7 +1571,7 @@ var je = class {
1491
1571
  unconfirmed: "0"
1492
1572
  },
1493
1573
  tokensBalance: {},
1494
- type: S.MAIN
1574
+ type: 0
1495
1575
  };
1496
1576
  r.push(t);
1497
1577
  }
@@ -1503,7 +1583,7 @@ var je = class {
1503
1583
  let e = {
1504
1584
  id: r,
1505
1585
  name: `Account ${r + 1}`,
1506
- address: this.keyManager.deriveAddress(S.DAPP, C.RECEIVE, r),
1586
+ address: this.keyManager.deriveAddress(2, 0, r),
1507
1587
  height: 0,
1508
1588
  hidden: 0,
1509
1589
  statusHash: "",
@@ -1512,7 +1592,7 @@ var je = class {
1512
1592
  unconfirmed: "0"
1513
1593
  },
1514
1594
  tokensBalance: {},
1515
- type: S.DAPP
1595
+ type: 2
1516
1596
  };
1517
1597
  n.set(e.id, e);
1518
1598
  }
@@ -1527,66 +1607,50 @@ var je = class {
1527
1607
  async saveVaults(e) {
1528
1608
  for (let t of e.values()) await this.walletDb.saveVault(t);
1529
1609
  }
1530
- async subscribeAddresses(e, t = !1) {
1531
- let n = e.map(async (e) => ({
1532
- addr: e,
1533
- result: await this.rostrumService.subscribeAddress(e.address, this.onSubscribeEvent)
1534
- })), r = [], i = await Promise.all(n);
1535
- for (let { addr: e, result: n } of i) if (n && typeof n == "string" && e.statusHash != n) {
1536
- if (t) {
1537
- let t = new Promise((t) => {
1538
- this.addressResolvers.set(e.address, t);
1539
- });
1540
- if (r.push(t), !this.discoveryResolver) {
1541
- let e = new Promise((e) => {
1542
- this.discoveryResolver = e;
1543
- });
1544
- r.push(e);
1545
- }
1546
- }
1547
- this.registerUpdate({
1548
- address: e,
1549
- result: n
1550
- });
1551
- }
1552
- await Promise.all(r);
1610
+ /**
1611
+ * The subscribe callback (onSubscribeEvent) receives each address's initial status,
1612
+ * so changed addresses are registered for update from there.
1613
+ */
1614
+ async subscribeAddresses(e) {
1615
+ await Promise.all(e.map((e) => this.rostrumService.subscribeAddress(e.address, this.onSubscribeEvent)));
1553
1616
  }
1554
- registerUpdate(t) {
1555
- this.pendingUpdates.set(t.address.address, t), clearTimeout(this.updateTimer), this.updateTimer = setTimeout(() => {
1617
+ registerUpdate(e) {
1618
+ this.pendingUpdates.set(e.address.address, e), this.updatesStarted && this.scheduleUpdates();
1619
+ }
1620
+ scheduleUpdates() {
1621
+ clearTimeout(this.updateTimer), this.updateTimer = setTimeout(() => {
1556
1622
  this.processPendingUpdates();
1557
1623
  }, e.DEBOUNCE_MS);
1558
1624
  }
1559
- async processPendingUpdates() {
1625
+ startUpdates() {
1626
+ this.updatesStarted || (this.updatesStarted = !0, this.pendingUpdates.size > 0 && this.scheduleUpdates());
1627
+ }
1628
+ stopUpdates() {
1629
+ this.updatesStarted = !1, clearTimeout(this.updateTimer), this.updateTimer = void 0, this.pendingUpdates.clear();
1630
+ }
1631
+ async processPendingUpdates(e = !1) {
1560
1632
  if (this.pendingUpdates.size !== 0) try {
1561
1633
  this.notify({
1562
1634
  type: "sync_wallet",
1563
1635
  loading: !0
1564
1636
  }), console.log(`Processing ${this.pendingUpdates.size} pending updates...`);
1565
- let e = Array.from(this.pendingUpdates);
1637
+ let t = Array.from(this.pendingUpdates);
1566
1638
  this.pendingUpdates.clear();
1567
- let t = [], n = [], r = [];
1568
- for (let [, i] of e) if (this.isAccountAddress(i.address)) {
1569
- let e = this.fetchAndUpdateAccount(i.address, i.result);
1570
- t.push(e);
1571
- } else if (this.isVaultAddress(i.address)) {
1572
- let e = this.fetchAndUpdateVault(i.address, i.result);
1573
- n.push(e);
1639
+ let n = [], r = [], i = [];
1640
+ for (let [, e] of t) if (this.isAccountAddress(e.address)) {
1641
+ let t = this.fetchAndUpdateAccount(e.address, e.result);
1642
+ n.push(t);
1643
+ } else if (this.isVaultAddress(e.address)) {
1644
+ let t = this.fetchAndUpdateVault(e.address, e.result);
1645
+ r.push(t);
1574
1646
  } else {
1575
- let e = this.fetchAndUpdateAddress(i.address, i.result);
1576
- r.push(e);
1647
+ let t = this.fetchAndUpdateAddress(e.address, e.result);
1648
+ i.push(t);
1577
1649
  }
1578
- let i = !1;
1579
- if (this.addressResolvers.size > 0) {
1580
- for (let [t] of e) {
1581
- let e = this.addressResolvers.get(t);
1582
- e && (e(), this.addressResolvers.delete(t));
1583
- }
1584
- i = this.addressResolvers.size === 0;
1585
- }
1586
- let a = await Promise.all(t);
1587
- await Promise.all(n);
1588
- let o = await Promise.all(r), s = [this.postProcessWalletUpdate(o), this.postProcessAccountsUpdate(a)];
1589
- i && s.push(this.recoverTokens()), await Promise.all(s), i && this.discoveryResolver && (this.discoveryResolver(), this.discoveryResolver = void 0);
1650
+ let a = await Promise.all(n);
1651
+ await Promise.all(r);
1652
+ let o = await Promise.all(i), s = [this.postProcessWalletUpdate(o), this.postProcessAccountsUpdate(a)];
1653
+ e && s.push(this.recoverTokens()), await Promise.all(s);
1590
1654
  } catch (e) {
1591
1655
  console.error("Error processing pending updates:", e);
1592
1656
  } finally {
@@ -1601,8 +1665,8 @@ var je = class {
1601
1665
  let t = /* @__PURE__ */ new Map();
1602
1666
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1603
1667
  let n = Array.from(t.values());
1604
- await this.checkGapLimit(C.RECEIVE), await this.checkGapLimit(C.CHANGE);
1605
- let r = this.getMainAddresses(), i = P(r.map((e) => e.balance)), a = F(r.map((e) => e.tokensBalance));
1668
+ await this.checkGapLimit(0), await this.checkGapLimit(1);
1669
+ let r = this.getMainAddresses(), i = j(r.map((e) => e.balance)), a = M(r.map((e) => e.tokensBalance));
1606
1670
  this.notify({
1607
1671
  type: "account_balance_updated",
1608
1672
  accountId: -1,
@@ -1635,25 +1699,25 @@ var je = class {
1635
1699
  i.push(a), await Promise.all(i);
1636
1700
  }
1637
1701
  async fetchAndUpdateAddress(e, t) {
1638
- e.statusHash = t, e.balance = await this.rostrumService.getBalance(e.address), e.tokensBalance = await this.rostrumService.getTokensBalance(e.address);
1702
+ e.balance = await this.rostrumService.getBalance(e.address), e.tokensBalance = await this.rostrumService.getTokensBalance(e.address);
1639
1703
  let n = await this.transactionService.fetchTransactionsHistory(e.address, e.height);
1640
- return e.height = n.lastHeight, e.used ||= n.txs.length > 0, await this.walletDb.saveAddress(e), {
1704
+ return e.height = n.lastHeight, e.used ||= n.txs.length > 0, e.statusHash = t, await this.walletDb.saveAddress(e), {
1641
1705
  address: e,
1642
1706
  txs: n.txs
1643
1707
  };
1644
1708
  }
1645
1709
  async fetchAndUpdateAccount(e, t) {
1646
- e.statusHash = t, e.balance = await this.rostrumService.getBalance(e.address), e.tokensBalance = await this.rostrumService.getTokensBalance(e.address);
1710
+ e.balance = await this.rostrumService.getBalance(e.address), e.tokensBalance = await this.rostrumService.getTokensBalance(e.address);
1647
1711
  let n = await this.transactionService.fetchTransactionsHistory(e.address, e.height);
1648
- return e.height = n.lastHeight, await this.walletDb.saveAccount(e), {
1712
+ return e.height = n.lastHeight, e.statusHash = t, await this.walletDb.saveAccount(e), {
1649
1713
  address: e,
1650
1714
  txs: n.txs
1651
1715
  };
1652
1716
  }
1653
1717
  async fetchAndUpdateVault(e, t) {
1654
- e.statusHash = t, e.balance = await this.rostrumService.getBalance(e.address);
1718
+ e.balance = await this.rostrumService.getBalance(e.address);
1655
1719
  let n = await this.transactionService.fetchTransactionsHistory(e.address, e.height);
1656
- return e.height = n.lastHeight, await this.walletDb.saveVault(e), this.notify({
1720
+ return e.height = n.lastHeight, e.statusHash = t, await this.walletDb.saveVault(e), this.notify({
1657
1721
  type: "vault_balance_updated",
1658
1722
  address: e.address,
1659
1723
  balance: e.balance
@@ -1663,16 +1727,16 @@ var je = class {
1663
1727
  };
1664
1728
  }
1665
1729
  async checkGapLimit(e) {
1666
- let t = e === C.RECEIVE ? this.receiveAddresses : this.changeAddresses, n = e === C.RECEIVE ? "Receive" : "Change", r = t.filter((e) => !e.used).length;
1667
- if (r < z.GAP_LIMIT) {
1668
- let i = z.GAP_LIMIT - r, a = t[t.length - 1].idx;
1730
+ let t = e === 0 ? this.receiveAddresses : this.changeAddresses, n = e === 0 ? "Receive" : "Change", r = t.filter((e) => !e.used).length;
1731
+ if (r < B.GAP_LIMIT) {
1732
+ let i = B.GAP_LIMIT - r, a = t[t.length - 1].idx;
1669
1733
  console.log(`Deriving ${i} more ${n} addresses...`);
1670
1734
  let o = this.deriveAddresses(e, a + 1, i);
1671
- e === C.RECEIVE ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
1735
+ e === 0 ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
1672
1736
  }
1673
1737
  }
1674
1738
  async addNewAccount(e, t) {
1675
- let n = this.keyManager.deriveAddress(S.DAPP, C.RECEIVE, e), r = {
1739
+ let n = this.keyManager.deriveAddress(2, 0, e), r = {
1676
1740
  id: e,
1677
1741
  name: t,
1678
1742
  address: n,
@@ -1684,7 +1748,7 @@ var je = class {
1684
1748
  unconfirmed: "0"
1685
1749
  },
1686
1750
  tokensBalance: {},
1687
- type: S.DAPP
1751
+ type: 2
1688
1752
  };
1689
1753
  this.accounts.set(e, r), this.accountsAddressToId.set(n, e), await this.walletDb.saveAccount(r), this.notify({
1690
1754
  type: "new_account",
@@ -1741,7 +1805,7 @@ var je = class {
1741
1805
  unconfirmed: "0"
1742
1806
  },
1743
1807
  tokensBalance: {},
1744
- type: S.VAULT
1808
+ type: 1
1745
1809
  };
1746
1810
  await this.addVault(r);
1747
1811
  }
@@ -1763,20 +1827,20 @@ var je = class {
1763
1827
  }
1764
1828
  async recoverTokens() {
1765
1829
  let e = [];
1766
- e.push(this.assetService.syncTokens(-1, F(this.getMainAddresses().map((e) => e.tokensBalance))));
1830
+ e.push(this.assetService.syncTokens(-1, M(this.getMainAddresses().map((e) => e.tokensBalance))));
1767
1831
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1768
1832
  await Promise.all(e);
1769
1833
  }
1770
1834
  isVaultAddress(e) {
1771
- return e.type == S.VAULT;
1835
+ return e.type == 1;
1772
1836
  }
1773
1837
  isAccountAddress(e) {
1774
- return e.type == S.DAPP;
1838
+ return e.type == 2;
1775
1839
  }
1776
1840
  isMainAddress(e) {
1777
- return e.type == S.MAIN;
1841
+ return e.type == 0;
1778
1842
  }
1779
- }, Fe = class e {
1843
+ }, Pe = class e {
1780
1844
  static {
1781
1845
  this.POLL_INTERVAL_MS = 12e4;
1782
1846
  }
@@ -1798,7 +1862,7 @@ var je = class {
1798
1862
  async init() {
1799
1863
  this.stop();
1800
1864
  let t = await this.walletDb.getSetting(e.CURRENCY_SETTING);
1801
- this.currency = E.includes(t) ? t : "usd", this.notify({
1865
+ this.currency = C.includes(t) ? t : "usd", this.notify({
1802
1866
  type: "currency_updated",
1803
1867
  currency: this.currency
1804
1868
  }), this.running = !0, this.poll();
@@ -1857,6 +1921,6 @@ var je = class {
1857
1921
  }), a;
1858
1922
  }
1859
1923
  };
1860
- export { S as AccountType, we as AssetService, T as CURRENCIES, se as HD_WALLET_ID, z as KeyManager, C as KeySpace, ce as MAX_INT64, Fe as MarketService, xe as RostrumService, je as SessionManager, w as SessionRequestType, Ee as TransactionService, Me as TransactionTransformer, W as VAULT_FIRST_BLOCK, be as WalletCache, ye as WalletDB, Pe as WalletManager, ve as calculateFiatValue, fe as capitalizeFirstLetter, E as currencyCodes, k as currentTimestamp, Oe as encryptMnemonic, Te as estimateDateByFutureBlock, De as generateNewMnemonic, X as generateVaultAddress, q as generateVaultConstraint, Y as generateVaultVisibleArgs, j as getAddressBuffer, H as getAssetFileUrl, V as getAssetMetadataUrl, ue as getExplorerUrl, me as getFileMediaType, he as getFileMimeType, J as getVaultConstraintHash, G as getVaultTemplate, K as getVaultTemplateHash, le as isGenesisHashValid, Z as isMnemonicValid, A as isNullOrEmpty, D as isTestnet, O as isValidNexaAddress, L as keyPathToString, Se as parseTokenDataUrl, _e as prettifyAmount, ge as sleep, R as stringToKeyPath, P as sumBalance, F as sumTokensBalance, N as tokenAmountToAssetAmount, pe as tokenHexToAddr, M as tokenIdToHex, B as transformTokenIconUrl, de as truncateStringMiddle, Ae as validateAndDecryptMnemonic };
1924
+ export { se as AccountType, we as AssetService, S as CURRENCIES, ue as HD_WALLET_ID, B as KeyManager, ce as KeySpace, de as MAX_INT64, Pe as MarketService, be as RostrumService, je as SessionManager, le as SessionRequestType, Ee as TransactionService, Me as TransactionTransformer, W as VAULT_FIRST_BLOCK, ye as WalletCache, ve as WalletDB, Ne as WalletManager, _e as calculateFiatValue, he as capitalizeFirstLetter, C as currencyCodes, E as currentTimestamp, Oe as encryptMnemonic, Te as estimateDateByFutureBlock, De as generateNewMnemonic, X as generateVaultAddress, q as generateVaultConstraint, Y as generateVaultVisibleArgs, O as getAddressBuffer, H as getAssetFileUrl, V as getAssetMetadataUrl, pe as getExplorerUrl, P as getFileMediaType, F as getFileMimeType, J as getVaultConstraintHash, G as getVaultTemplate, K as getVaultTemplateHash, fe as isGenesisHashValid, Z as isMnemonicValid, D as isNullOrEmpty, w as isTestnet, T as isValidNexaAddress, R as keyPathToString, Se as parseTokenDataUrl, L as prettifyAmount, I as sleep, z as stringToKeyPath, j as sumBalance, M as sumTokensBalance, A as tokenAmountToAssetAmount, ge as tokenHexToAddr, k as tokenIdToHex, xe as transformTokenIconUrl, me as truncateStringMiddle, Ae as validateAndDecryptMnemonic };
1861
1925
 
1862
1926
  //# sourceMappingURL=index.js.map