@otoplo/wallet-common 0.6.1 → 0.8.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.
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
- import { Address as e, AddressType as t, BufferUtils as n, BufferWriter as r, CommonUtils as i, HDPrivateKey as a, Hash as o, Networks as s, Opcode as c, Output as l, OutputSighashType as u, Script as d, ScriptFactory as ee, ScriptNum as f, ScriptOpcode as p, SighashType as m, Transaction as h, TransactionBuilder as g, TxSigner as _, UnitUtils as v } from "libnexa-ts";
2
- import y from "js-big-decimal";
1
+ import { Address as e, AddressType as t, BufferUtils as n, BufferWriter as r, CommonUtils as i, HDPrivateKey as a, Hash as o, Networks as s, Opcode as c, Output as l, OutputSighashType as u, Script as d, ScriptFactory as ee, ScriptNum as f, ScriptOpcode as p, SighashType as m, Transaction as h, TransactionBuilder as g, TxSigner as _, UnitType as v, UnitUtils as y } from "libnexa-ts";
3
2
  import { ConnectionStatus as te, ElectrumClient as ne, TransportScheme as b } from "@otoplo/electrum-client";
4
3
  import { generateMnemonic as re, mnemonicToSeedSync as ie, validateMnemonic as ae } from "@scure/bip39";
5
4
  import { wordlist as x } from "@scure/bip39/wordlists/english.js";
@@ -13,7 +12,7 @@ let se = /* @__PURE__ */ function(e) {
13
12
  return e.SignMessage = "signMessage", e.AddToken = "addToken", e.SignTransaction = "signTransaction", e.SendTransaction = "sendTransaction", e;
14
13
  }({});
15
14
  // src/utils/common.ts
16
- const ue = -1, de = 9223372036854775807n, S = {
15
+ const ue = -1, de = 9223372036854775807n, fe = 2, S = {
17
16
  usd: {
18
17
  symbol: "$",
19
18
  name: "US Dollar"
@@ -54,42 +53,65 @@ const ue = -1, de = 9223372036854775807n, S = {
54
53
  function w() {
55
54
  return s.defaultNetwork == s.testnet;
56
55
  }
57
- function fe(e) {
56
+ /** `NEXA` on mainnet, `tNEXA` on testnet. */
57
+ function T() {
58
+ return w() ? "tNEXA" : "NEXA";
59
+ }
60
+ function E(e) {
58
61
  return w() ? e == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52" : e == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
59
62
  }
60
- function T(n, r = t.PayToScriptTemplate) {
63
+ function D(n, r = t.PayToScriptTemplate) {
61
64
  return e.isValid(n, s.defaultNetwork, r);
62
65
  }
63
66
  function pe() {
64
67
  return `https://${w() ? "testnet-" : ""}explorer.nexa.org`;
65
68
  }
66
- function E() {
69
+ function O() {
67
70
  return Math.floor(Date.now() / 1e3);
68
71
  }
69
- function D(e) {
72
+ /** Estimated minutes until `future` block, from the block time. 0 once it's reached. */
73
+ function me(e, t) {
74
+ return Math.max(t - e, 0) * 2;
75
+ }
76
+ /**
77
+ * Estimated date of a future block, e.g. `Mar 14, 2027`.
78
+ * `locale` and `options` go to `toLocaleDateString` — defaults to `en-US` like `calculateFiatValue`.
79
+ */
80
+ function he(e, t, n = "en-US", r = {
81
+ month: "short",
82
+ day: "numeric",
83
+ year: "numeric"
84
+ }) {
85
+ return new Date(Date.now() + me(e, t) * 6e4).toLocaleDateString(n, r);
86
+ }
87
+ function k(e) {
70
88
  return !e || e.length === 0;
71
89
  }
72
- function me(e, t = 0) {
90
+ function ge(e, t = 0) {
73
91
  if (!e || e.length <= t) return e || "";
74
92
  let n = Math.floor((t - 3) / 2), r = e.slice(0, n), i = e.slice(e.length - n);
75
93
  return r + "..." + i;
76
94
  }
77
- function he(e) {
95
+ function _e(e) {
78
96
  return e.length === 0 ? "" : e.charAt(0).toUpperCase() + e.substring(1);
79
97
  }
80
- function O(t) {
98
+ function A(t) {
81
99
  return i.isHexa(t) ? n.hexToBuffer(t) : e.fromString(t).data;
82
100
  }
83
- function k(e) {
84
- return i.isHexa(e) ? e : n.bufferToHex(O(e));
101
+ function j(e) {
102
+ return i.isHexa(e) ? e : n.bufferToHex(A(e));
85
103
  }
86
- function ge(n) {
87
- return i.isHexa(n) ? new e(O(n), s.defaultNetwork, t.GroupIdAddress).toString() : n;
104
+ function ve(n) {
105
+ return i.isHexa(n) ? new e(A(n), s.defaultNetwork, t.GroupIdAddress).toString() : n;
88
106
  }
89
- function A(e) {
107
+ function M(e) {
90
108
  return e == null || e === "" ? "" : BigInt(e) <= 0n ? "0" : e.toString();
91
109
  }
92
- function j(e) {
110
+ /** Confirmed plus unconfirmed, in base units. The unconfirmed part can be negative (spent, not yet confirmed). */
111
+ function N(e) {
112
+ return BigInt(e.confirmed) + BigInt(e.unconfirmed);
113
+ }
114
+ function P(e) {
93
115
  let t = BigInt(0), n = BigInt(0);
94
116
  return e.forEach((e) => {
95
117
  t += BigInt(e.confirmed), n += BigInt(e.unconfirmed);
@@ -98,7 +120,7 @@ function j(e) {
98
120
  unconfirmed: n.toString()
99
121
  };
100
122
  }
101
- function M(e) {
123
+ function F(e) {
102
124
  let t = {};
103
125
  return e.forEach((e) => {
104
126
  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] = {
@@ -107,7 +129,7 @@ function M(e) {
107
129
  };
108
130
  }), t;
109
131
  }
110
- const N = {
132
+ const I = {
111
133
  ".gif": {
112
134
  media: "image",
113
135
  mime: "image/gif"
@@ -177,33 +199,23 @@ const N = {
177
199
  mime: "audio/mp4"
178
200
  }
179
201
  };
180
- function P(e) {
202
+ function ye(e) {
181
203
  let t = e.lastIndexOf(".");
182
204
  if (t === -1) return "unknown";
183
205
  let n = e.slice(t).toLowerCase();
184
- return N[n]?.media ?? "unknown";
206
+ return I[n]?.media ?? "unknown";
185
207
  }
186
- function F(e) {
208
+ function be(e) {
187
209
  let t = e.lastIndexOf(".");
188
210
  if (t === -1) return "application/octet-stream";
189
211
  let n = e.slice(t).toLowerCase();
190
- return N[n]?.mime ?? "application/octet-stream";
212
+ return I[n]?.mime ?? "application/octet-stream";
191
213
  }
192
- function I(e) {
214
+ function xe(e) {
193
215
  return new Promise((t) => setTimeout(t, e));
194
216
  }
195
- function L(e) {
196
- return new y(e).stripTrailingZero().getPrettyValue();
197
- }
198
- function _e(e, t, n, r = "en-US") {
199
- let i = y.multiply(e, t);
200
- return new Intl.NumberFormat(r, {
201
- style: "currency",
202
- currency: n
203
- }).format(Number(i));
204
- }
205
217
  // src/persistence/wallet-db.ts
206
- var ve = class {
218
+ var Se = class {
207
219
  constructor(e) {
208
220
  this.repository = e;
209
221
  }
@@ -252,7 +264,7 @@ var ve = class {
252
264
  accountId: e,
253
265
  tokenIdHex: t.tokenIdHex,
254
266
  type: "token",
255
- addedTime: E()
267
+ addedTime: O()
256
268
  };
257
269
  await this.repository.upsertToken(t), await this.saveAsset(n);
258
270
  }
@@ -392,7 +404,7 @@ var ve = class {
392
404
  removeSetting(e) {
393
405
  return this.repository.deleteSetting(e);
394
406
  }
395
- }, ye = class {
407
+ }, Ce = class {
396
408
  constructor(e) {
397
409
  this.tokens = /* @__PURE__ */ new Map(), this.nfts = /* @__PURE__ */ new Map(), this.walletDb = e;
398
410
  }
@@ -400,22 +412,22 @@ var ve = class {
400
412
  this.tokens.clear(), this.nfts.clear();
401
413
  }
402
414
  async getToken(e) {
403
- if (e = k(e), this.tokens.has(e)) return this.tokens.get(e);
415
+ if (e = j(e), this.tokens.has(e)) return this.tokens.get(e);
404
416
  let t = await this.walletDb.getToken(e);
405
417
  return t && this.tokens.set(e, t), t;
406
418
  }
407
419
  async getNft(e) {
408
- if (e = k(e), this.nfts.has(e)) return this.nfts.get(e);
420
+ if (e = j(e), this.nfts.has(e)) return this.nfts.get(e);
409
421
  let t = await this.walletDb.getNft(e);
410
422
  return t && this.nfts.set(e, t), t;
411
423
  }
412
424
  removeToken(e) {
413
- this.tokens.delete(k(e));
425
+ this.tokens.delete(j(e));
414
426
  }
415
427
  removeNft(e) {
416
- this.nfts.delete(k(e));
428
+ this.nfts.delete(j(e));
417
429
  }
418
- }, be = class e {
430
+ }, we = class e {
419
431
  constructor(e) {
420
432
  this.walletDb = e;
421
433
  }
@@ -521,7 +533,7 @@ var ve = class {
521
533
  }
522
534
  async connect(e) {
523
535
  try {
524
- await this.disconnect(), e ||= await this.getCurrentInstance(), this.client = new ne({
536
+ await this.disconnect(), e ||= await this.getCurrentInstance(), this.params = e, this.client = new ne({
525
537
  application: "com.otoplo.wallet",
526
538
  version: "1.4.3",
527
539
  host: e.host,
@@ -536,6 +548,38 @@ var ve = class {
536
548
  await this.client?.disconnect();
537
549
  }
538
550
  /**
551
+ * Checks whether the wallet can use a server (e.g. before switching to it): that it's reachable, on the wallet's
552
+ * network and indexes scripts. Never throws.
553
+ *
554
+ * The server this service is connected to answers on its connection; any other one is checked on a temporary
555
+ * connection, closed after.
556
+ */
557
+ async checkInstance(t) {
558
+ if (this.isConnected() && this.params && e.isSameInstance(this.params, t)) return this.check();
559
+ let n = new e(this.walletDb);
560
+ try {
561
+ return await n.connect(t), await n.check();
562
+ } catch {
563
+ return { status: "offline" };
564
+ } finally {
565
+ await n.disconnect();
566
+ }
567
+ }
568
+ async check() {
569
+ try {
570
+ let e = await this.getFeatures();
571
+ if (!E(e.genesis_hash)) return { status: "wrong_network" };
572
+ if (!e.script_index) return { status: "unsupported" };
573
+ let t = await this.getLatency();
574
+ return t ? {
575
+ status: "online",
576
+ latency: t
577
+ } : { status: "offline" };
578
+ } catch {
579
+ return { status: "offline" };
580
+ }
581
+ }
582
+ /**
539
583
  * Walk a cursor-paginated rostrum query: start with "start" and follow the returned cursor until it is null.
540
584
  * If the cursor expires mid-walk (e.g. reorg / mempool change), the walk is restarted from the beginning.
541
585
  */
@@ -576,6 +620,10 @@ var ve = class {
576
620
  let t = await this.walletDb.getSetting("rostrum-params");
577
621
  return t ? JSON.parse(t) : e.getPredefinedInstances()[0];
578
622
  }
623
+ /** Whether both point to the same server (the label aside). */
624
+ static isSameInstance(e, t) {
625
+ return e.scheme === t.scheme && e.host.toLowerCase() === t.host.toLowerCase() && e.port === t.port;
626
+ }
579
627
  static getPredefinedInstances() {
580
628
  return w() ? [{
581
629
  scheme: b.WSS,
@@ -596,10 +644,10 @@ var ve = class {
596
644
  }
597
645
  };
598
646
  // src/utils/keypath.ts
599
- function R(e, t, n) {
647
+ function L(e, t, n) {
600
648
  return `${e}'/${t}/${n}`;
601
649
  }
602
- function z(e) {
650
+ function R(e) {
603
651
  let t = e.split("/");
604
652
  return {
605
653
  account: parseInt(t[0].replace("'", "")),
@@ -608,7 +656,7 @@ function z(e) {
608
656
  };
609
657
  }
610
658
  // src/services/key.ts
611
- var B = class {
659
+ var z = class {
612
660
  constructor() {
613
661
  this.accountKeys = /* @__PURE__ */ new Map(), this.walletKeys = /* @__PURE__ */ new Map();
614
662
  }
@@ -638,35 +686,35 @@ var B = class {
638
686
  }
639
687
  getKey(e) {
640
688
  if (!this.seed) throw Error("KeysManager not initialized");
641
- let t = typeof e == "string" ? e : R(e.account, e.type, e.index), n = this.walletKeys.get(t);
689
+ let t = typeof e == "string" ? e : L(e.account, e.type, e.index), n = this.walletKeys.get(t);
642
690
  if (!n) {
643
- let { account: r, type: i, index: a } = typeof e == "string" ? z(e) : e;
691
+ let { account: r, type: i, index: a } = typeof e == "string" ? R(e) : e;
644
692
  n = this.getAccountKey(r).deriveChild(i, !1).deriveChild(a, !1), this.walletKeys.set(t, n);
645
693
  }
646
694
  return n;
647
695
  }
648
696
  };
649
697
  // src/utils/asset.ts
650
- function xe(e, t) {
698
+ function Te(e, t) {
651
699
  return e && typeof e == "string" ? e.startsWith("http") ? e.replace("http://", "https://") : e.startsWith("ipfs://") ? e : `${new URL(t).origin}${e}` : "";
652
700
  }
653
- function Se(e) {
654
- return e ? Ce(e) : null;
701
+ function Ee(e) {
702
+ return e ? De(e) : null;
655
703
  }
656
- function Ce(e, t = "https://ipfs.nebula.markets/") {
704
+ function De(e, t = "https://ipfs.nebula.markets/") {
657
705
  return e?.startsWith("ipfs://") ? t + e.substring(7) : e;
658
706
  }
659
- function V(e) {
660
- return `${U()}/metadata/${e}`;
707
+ function B(e) {
708
+ return `${H()}/metadata/${e}`;
661
709
  }
662
- function H(e, t) {
663
- return `${U()}/assets/${e}/${t}`;
710
+ function V(e, t) {
711
+ return `${H()}/assets/${e}/${t}`;
664
712
  }
665
- function U() {
713
+ function H() {
666
714
  return `https://${w() ? "testapi" : "api"}.otoplo.com`;
667
715
  }
668
716
  // src/services/asset.ts
669
- var we = class {
717
+ var Oe = class {
670
718
  constructor(e, t) {
671
719
  this.walletDb = e, this.walletCache = t;
672
720
  }
@@ -722,7 +770,7 @@ var we = class {
722
770
  async syncTokens(e, t) {
723
771
  for (let n in t) {
724
772
  let r = t[n];
725
- if (r && BigInt(r.confirmed) + BigInt(r.unconfirmed) > 0n) {
773
+ if (r && N(r) > 0n) {
726
774
  let t = await this.getAssetInfo(n);
727
775
  if (t && t.type == "token") {
728
776
  let n = {
@@ -740,8 +788,8 @@ var we = class {
740
788
  let n = Object.keys(t), r = await this.walletDb.getAssets(e, "nft"), i = r?.filter((e) => !n.includes(e.tokenIdHex)) ?? [];
741
789
  for (let t of i) await this.deleteNft(e, t.tokenIdHex);
742
790
  for (let [n, i] of Object.entries(t)) {
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()));
791
+ let t = j(n), a = i && N(i) > 0n, o = r?.some((e) => e.tokenIdHex == t);
792
+ !a && !o || a && o || (!a && o ? await this.deleteNft(e, t) : await this.handleNftReceive(e, t, O()));
745
793
  }
746
794
  }
747
795
  async saveToken(e, t) {
@@ -757,10 +805,10 @@ var we = class {
757
805
  await this.walletDb.deleteNft(e, t), this.walletCache.removeNft(t);
758
806
  }
759
807
  getAssetFile(e, t) {
760
- return this.performGet(H(e, t), "raw");
808
+ return this.performGet(V(e, t), "raw");
761
809
  }
762
810
  getAssetMetadata(e) {
763
- return this.performGet(V(e), "json");
811
+ return this.performGet(B(e), "json");
764
812
  }
765
813
  async performGet(e, t) {
766
814
  try {
@@ -777,35 +825,38 @@ var we = class {
777
825
  }
778
826
  };
779
827
  // src/utils/vault.ts
780
- const W = 274710;
781
- function G() {
828
+ const U = 274710;
829
+ function W() {
782
830
  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);
783
831
  }
784
- function K() {
785
- let e = G();
832
+ function G() {
833
+ let e = W();
786
834
  return o.sha256ripemd160(e.toBuffer());
787
835
  }
788
- function q(e) {
836
+ function K(e) {
789
837
  return d.empty().add(e.toBuffer());
790
838
  }
791
- function J(e) {
792
- let t = q(e);
839
+ function q(e) {
840
+ let t = K(e);
793
841
  return o.sha256ripemd160(t.toBuffer());
794
842
  }
795
- function Y(e) {
843
+ function J(e) {
796
844
  return e.map((e) => e <= 16 ? p.smallInt(e) : f.encode(e));
797
845
  }
798
- function X(t, n) {
846
+ function Y(t, n) {
799
847
  if (n.length !== 2) return;
800
- let r = K(), i = J(t), a = Y(n);
848
+ let r = G(), i = q(t), a = J(n);
801
849
  return e.fromScriptTemplate(r, i, a).toString();
802
850
  }
803
- function Te(e, t) {
804
- let n = (t - e) * 2, r = /* @__PURE__ */ new Date();
805
- return r.setMinutes(r.getMinutes() + n), r.toLocaleDateString();
851
+ /**
852
+ * A vault is spendable once the chain reached its lock block: a transaction with that lock time
853
+ * can go into the next block (`OP_CHECKLOCKTIMEVERIFY` in the template). `false` while the height is unknown (0).
854
+ */
855
+ function ke(e, t) {
856
+ return t > 0 && t >= e;
806
857
  }
807
858
  // src/services/transaction.ts
808
- var Ee = class {
859
+ var Ae = class {
809
860
  constructor(e, t, n) {
810
861
  this.MAX_INPUTS_OUTPUTS = 250, this.rostrumService = e, this.keyManager = t, this.walletDb = n;
811
862
  }
@@ -821,7 +872,7 @@ var Ee = class {
821
872
  };
822
873
  }
823
874
  async fetchVaultTransactions(e) {
824
- let t = await this.rostrumService.getTransactionsHistory(e, W), n = [];
875
+ let t = await this.rostrumService.getTransactionsHistory(e, U), n = [];
825
876
  for (let r of t) {
826
877
  let t = this.classifyTransaction(r.tx_hash, [e]);
827
878
  n.push(t);
@@ -848,17 +899,17 @@ var Ee = class {
848
899
  address: e.addresses[0],
849
900
  nexaAmount: e.value_satoshi.toString(),
850
901
  assetId: e.token_id_hex ?? "",
851
- assetAmount: A(e.groupQuantity)
902
+ assetAmount: M(e.groupQuantity)
852
903
  };
853
904
  t.includes(n.address) ? r.push(n) : i.push(n);
854
905
  }
855
906
  for (let e of n.vout) {
856
- if (D(e.scriptPubKey.addresses)) continue;
907
+ if (k(e.scriptPubKey.addresses)) continue;
857
908
  let n = {
858
909
  address: e.scriptPubKey.addresses[0],
859
910
  nexaAmount: e.value_satoshi.toString(),
860
911
  assetId: e.scriptPubKey.token_id_hex ?? "",
861
- assetAmount: A(e.scriptPubKey.groupQuantity)
912
+ assetAmount: M(e.scriptPubKey.groupQuantity)
862
913
  };
863
914
  t.includes(n.address) ? a.push(n) : o.push(n);
864
915
  }
@@ -869,7 +920,7 @@ var Ee = class {
869
920
  accountId: 0,
870
921
  txId: n.txid,
871
922
  txIdem: n.txidem,
872
- time: c ? n.time : E(),
923
+ time: c ? n.time : O(),
873
924
  height: c ? n.height : 0,
874
925
  type: s,
875
926
  fee: n.fee_satoshi.toString(),
@@ -894,20 +945,20 @@ var Ee = class {
894
945
  return this.finalizeTransaction(i, Array.from(a.values()));
895
946
  }
896
947
  prepareTransaction(n, r, i, a) {
897
- if (!T(n) && !T(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
948
+ if (!D(n) && !D(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
898
949
  if (i && BigInt(r) < 1n || !i && parseInt(r) < h.DUST_AMOUNT) throw Error("The amount is too low.");
899
950
  if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > h.MAX_MONEY) throw Error("The amount is too high.");
900
951
  let o = new g();
901
952
  if (a && o.addData(a), i) {
902
- if (!T(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
953
+ if (!D(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
903
954
  if (e.getOutputType(n) === 0) throw Error("Token must be sent to script template address");
904
955
  o.to(n, h.DUST_AMOUNT, i, BigInt(r));
905
956
  } else o.to(n, r);
906
957
  return o;
907
958
  }
908
959
  async populateNexaInputsAndChange(e, t, n, r) {
909
- let i = t.filter((e) => BigInt(e.balance.confirmed) + BigInt(e.balance.unconfirmed) > 0n);
910
- if (D(i)) throw Error("Not enough Nexa balance.");
960
+ let i = t.filter((e) => N(e.balance) > 0n);
961
+ if (k(i)) throw Error("Not enough Nexa balance.");
911
962
  let a = /* @__PURE__ */ new Map(), o = r.isConsolidate ? 0 : Number(e.transaction.outputs.find((e) => e.value > 0n).value);
912
963
  for (let t of i) {
913
964
  let i = await this.rostrumService.getNexaUtxos(t.address);
@@ -948,14 +999,14 @@ var Ee = class {
948
999
  }
949
1000
  let s = {
950
1001
  errorMsg: "Not enough Nexa balance.",
951
- amount: v.formatNEXA(e.transaction.outputs[0].value),
952
- fee: v.formatNEXA(e.transaction.estimateRequiredFee())
1002
+ amount: y.formatNEXA(e.transaction.outputs[0].value),
1003
+ fee: y.formatNEXA(e.transaction.estimateRequiredFee())
953
1004
  };
954
1005
  throw Error(JSON.stringify(s));
955
1006
  }
956
1007
  async populateTokenInputsAndChange(e, t, n, r, i) {
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.");
1008
+ let a = j(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
1009
+ if (k(o)) throw Error("Not enough token balance.");
959
1010
  let s = /* @__PURE__ */ new Map(), c = 0n;
960
1011
  for (let t of o) {
961
1012
  let a = await this.rostrumService.getTokenUtxos(t.address, r);
@@ -991,14 +1042,60 @@ var Ee = class {
991
1042
  return JSON.stringify(t, null, 2);
992
1043
  }
993
1044
  };
1045
+ // src/utils/amount.ts
1046
+ /** Cached `Intl.NumberFormat`s: creating one is slow (on Hermes especially), formatting with one is fast. */
1047
+ const X = /* @__PURE__ */ new Map();
1048
+ function Z(e, t) {
1049
+ let n = `${e}|${JSON.stringify(t)}`, r = X.get(n);
1050
+ return r || (r = new Intl.NumberFormat(e, t), X.set(n, r)), r;
1051
+ }
1052
+ /**
1053
+ * An amount in base units (token units, satoshis) for display, without trailing zeros:
1054
+ * `formatTokenAmount(123456789n, 2)` → `1,234,567.89`, `formatTokenAmount(100n, 2)` → `1`.
1055
+ *
1056
+ * Decimals beyond `maxDecimals` are cut off in bigint, so a balance never shows more than it holds
1057
+ * (`0.999999` → `0.99999`, not `1`). A non-zero amount that would show as 0 becomes `<0.00001`.
1058
+ */
1059
+ function Q(e, t, { maxDecimals: n = 5, locale: r = "en-US" } = {}) {
1060
+ let i = BigInt(e), a = Math.min(t, n), o = i / 10n ** BigInt(t - a), s = Z(r, { maximumFractionDigits: a });
1061
+ return o === 0n && i !== 0n ? `${i < 0n ? "-" : ""}<${s.format(10 ** -a)}` : s.format(Number(y.formatUnits(o, a)));
1062
+ }
1063
+ /**
1064
+ * A token amount with its ticker, e.g. `1,500.25 USDT`.
1065
+ * Tokens without a ticker (it's optional in the token's genesis) show the amount alone.
1066
+ */
1067
+ function je(e, t, n, r = {}) {
1068
+ let i = Q(e, t, r);
1069
+ return n ? `${i} ${n}` : i;
1070
+ }
1071
+ /** Satoshis as a NEXA amount: `1,234,567.5`. Negative amounts keep their minus sign. Always exact (see above). */
1072
+ function Me(e, t = {}) {
1073
+ return Q(e, v.NEXA, t);
1074
+ }
1075
+ /** Satoshis as a NEXA amount with the ticker: `1,234,567.5 NEXA` (`tNEXA` on testnet). */
1076
+ function Ne(e, t = {}) {
1077
+ return je(e, v.NEXA, T(), t);
1078
+ }
1079
+ /**
1080
+ * Fiat value of an amount in base units (satoshis, token units), e.g. `$1,234.56`.
1081
+ * A non-zero value that would round to zero shows as below the currency's smallest unit: `<$0.01`, `<¥1`.
1082
+ * Exact to the cent below ~$10 trillion.
1083
+ */
1084
+ function Pe(e, t, n, r, i = "en-US") {
1085
+ let a = Z(i, {
1086
+ style: "currency",
1087
+ currency: r
1088
+ }), o = Number(y.formatUnits(e, t)) * n, s = 10 ** -(a.resolvedOptions().maximumFractionDigits ?? 2);
1089
+ return o !== 0 && Math.abs(o) < s / 2 ? `${o < 0 ? "-" : ""}<${a.format(s)}` : a.format(o);
1090
+ }
994
1091
  // src/utils/seed.ts
995
- function De(e = 12) {
1092
+ function Fe(e = 12) {
996
1093
  return re(x, e === 24 ? 256 : 128);
997
1094
  }
998
- function Z(e) {
1095
+ function Ie(e) {
999
1096
  return ae(e, x);
1000
1097
  }
1001
- async function Q(e, t) {
1098
+ async function Le(e, t) {
1002
1099
  let n = await crypto.subtle.importKey("raw", new Uint8Array(e), "PBKDF2", !1, ["deriveKey"]);
1003
1100
  return crypto.subtle.deriveKey({
1004
1101
  name: "PBKDF2",
@@ -1010,8 +1107,8 @@ async function Q(e, t) {
1010
1107
  length: 256
1011
1108
  }, !1, ["encrypt", "decrypt"]);
1012
1109
  }
1013
- async function Oe(e, t) {
1014
- let r = n.utf8ToBuffer(t), i = n.getRandomBuffer(16), a = n.getRandomBuffer(12), o = n.utf8ToBuffer(e), s = await Q(r, i), c = await crypto.subtle.encrypt({
1110
+ async function Re(e, t) {
1111
+ let r = n.utf8ToBuffer(t), i = n.getRandomBuffer(16), a = n.getRandomBuffer(12), o = n.utf8ToBuffer(e), s = await Le(r, i), c = await crypto.subtle.encrypt({
1015
1112
  name: "AES-GCM",
1016
1113
  iv: new Uint8Array(a)
1017
1114
  }, s, new Uint8Array(o)), l = n.concat([
@@ -1021,18 +1118,18 @@ async function Oe(e, t) {
1021
1118
  ]);
1022
1119
  return n.bufferToBase64(l);
1023
1120
  }
1024
- async function ke(e, t) {
1025
- let r = n.utf8ToBuffer(t), i = n.base64ToBuffer(e), a = i.slice(0, 16), o = i.slice(16, 28), s = i.slice(28), c = await Q(r, a), l = await crypto.subtle.decrypt({
1121
+ async function ze(e, t) {
1122
+ let r = n.utf8ToBuffer(t), i = n.base64ToBuffer(e), a = i.slice(0, 16), o = i.slice(16, 28), s = i.slice(28), c = await Le(r, a), l = await crypto.subtle.decrypt({
1026
1123
  name: "AES-GCM",
1027
1124
  iv: o
1028
1125
  }, c, s);
1029
1126
  return n.bufferToUtf8(new Uint8Array(l));
1030
1127
  }
1031
- async function Ae(e, t) {
1128
+ async function Be(e, t) {
1032
1129
  try {
1033
1130
  if (e) {
1034
- let n = await ke(e, t);
1035
- if (n && Z(n)) return n;
1131
+ let n = await ze(e, t);
1132
+ if (n && Ie(n)) return n;
1036
1133
  }
1037
1134
  return !1;
1038
1135
  } catch {
@@ -1040,7 +1137,7 @@ async function Ae(e, t) {
1040
1137
  }
1041
1138
  }
1042
1139
  // src/services/session.ts
1043
- var je = class {
1140
+ var Ve = class {
1044
1141
  constructor(e, t) {
1045
1142
  this.walletDb = e, this.keyManager = t, this.providers = /* @__PURE__ */ new Map(), this.handlers = /* @__PURE__ */ new Map(), this.removeOnClose = !0;
1046
1143
  }
@@ -1186,7 +1283,7 @@ var je = class {
1186
1283
  };
1187
1284
  });
1188
1285
  }
1189
- }, Me = class {
1286
+ }, He = class {
1190
1287
  constructor(e, t, n) {
1191
1288
  this.rostrumService = e, this.keyManager = t, this.assetService = n;
1192
1289
  }
@@ -1232,7 +1329,7 @@ var je = class {
1232
1329
  address: e.address,
1233
1330
  nexaAmount: i.amount.toString(),
1234
1331
  assetId: n,
1235
- assetAmount: A(i.group_quantity) || i.amount.toString()
1332
+ assetAmount: M(i.group_quantity) || i.amount.toString()
1236
1333
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1237
1334
  }
1238
1335
  r.scriptSig.findPlaceholder() > 0 && e.inputsToSign.add(t);
@@ -1241,11 +1338,11 @@ var je = class {
1241
1338
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1242
1339
  let n = e.txDetails.tx.outputs[t].toObject();
1243
1340
  if (n.address !== e.address) continue;
1244
- let r = n.groupId ? k(n.groupId) : "NEXA", i = {
1341
+ let r = n.groupId ? j(n.groupId) : "NEXA", i = {
1245
1342
  address: n.address,
1246
1343
  nexaAmount: n.value.toString(),
1247
1344
  assetId: r,
1248
- assetAmount: A(n.groupAmount) || n.value.toString()
1345
+ assetAmount: M(n.groupAmount) || n.value.toString()
1249
1346
  };
1250
1347
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1251
1348
  }
@@ -1311,19 +1408,19 @@ var je = class {
1311
1408
  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);
1312
1409
  }
1313
1410
  }
1314
- }, $ = class {
1411
+ }, Ue = class {
1315
1412
  constructor(e, t) {
1316
1413
  this.rostrumService = e, this.keyManager = t;
1317
1414
  }
1318
1415
  async discoverWalletIndex(e, t) {
1319
1416
  let n = 0, r = -1, i = [];
1320
1417
  for (;;) {
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;
1418
+ let a = await Promise.all(Array.from({ length: z.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1419
+ if (a.some((e) => e)) r = n, i = a, n += z.GAP_LIMIT;
1323
1420
  else break;
1324
1421
  }
1325
1422
  if (r === -1) return -1;
1326
- for (let e = B.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1423
+ for (let e = z.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1327
1424
  return r;
1328
1425
  }
1329
1426
  async discoverVaults() {
@@ -1338,14 +1435,14 @@ var je = class {
1338
1435
  * Indexes are checked in parallel batches, stopping after VAULT_GAP_LIMIT consecutive indexes with no scripts.
1339
1436
  */
1340
1437
  async checkForVaults() {
1341
- let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(K()), r = 0;
1438
+ let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(G()), r = 0;
1342
1439
  for (let i = 0; r < 5; i += 5) {
1343
1440
  let a = await Promise.all(Array.from({ length: 5 }, (e, r) => {
1344
1441
  let a = this.keyManager.getKey({
1345
1442
  account: 1,
1346
1443
  type: 0,
1347
1444
  index: i + r
1348
- }), o = n.bufferToHex(J(a.publicKey));
1445
+ }), o = n.bufferToHex(q(a.publicKey));
1349
1446
  return this.rostrumService.listTemplateScripts(t, o);
1350
1447
  }));
1351
1448
  for (let t of a) t.length === 0 ? r++ : (r = 0, t.forEach((t) => e.add(t.scriptpubkey)));
@@ -1354,7 +1451,7 @@ var je = class {
1354
1451
  }
1355
1452
  parseVaultDetails(t) {
1356
1453
  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];
1357
- if (a == X(this.keyManager.getKey({
1454
+ if (a == Y(this.keyManager.getKey({
1358
1455
  account: 1,
1359
1456
  type: 0,
1360
1457
  index: c
@@ -1372,7 +1469,7 @@ var je = class {
1372
1469
  type: 1
1373
1470
  };
1374
1471
  }
1375
- }, Ne = class e {
1472
+ }, We = class e {
1376
1473
  static {
1377
1474
  this.DEBOUNCE_MS = 1e3;
1378
1475
  }
@@ -1390,7 +1487,7 @@ var je = class {
1390
1487
  address: n,
1391
1488
  result: t
1392
1489
  });
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();
1490
+ }, this.discoveryService = new Ue(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();
1394
1491
  }
1395
1492
  clear() {
1396
1493
  this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.stopUpdates(), this.notify({ type: "clear_wallet" });
@@ -1423,20 +1520,26 @@ var je = class {
1423
1520
  let t = this.accounts.get(e);
1424
1521
  return [{
1425
1522
  address: t.address,
1426
- keyPath: R(2, 0, t.id),
1523
+ keyPath: L(2, 0, t.id),
1427
1524
  balance: t.balance,
1428
1525
  tokensBalance: t.tokensBalance
1429
1526
  }];
1430
1527
  }
1431
1528
  return this.getMainAddresses().filter((e) => e.used).map((e) => ({
1432
1529
  address: e.address,
1433
- keyPath: R(0, e.space, e.idx),
1530
+ keyPath: L(0, e.space, e.idx),
1434
1531
  balance: e.balance,
1435
1532
  tokensBalance: e.tokensBalance
1436
1533
  }));
1437
1534
  }
1535
+ /**
1536
+ * Switches to another server (or reconnects to the current one without `params`): saves it, disconnects, then
1537
+ * connects with `connect()`, retrying until it does. Check the server first with `RostrumService.checkInstance()`.
1538
+ *
1539
+ * @returns resolves like `connect()`: once connected and synced, or when stopped by `disconnectRostrum()`.
1540
+ */
1438
1541
  async reloadRostrum(e) {
1439
- e && await this.rostrumService.setCurrentInstance(e), await this.disconnectRostrum(), await this.initRostrum(), this.startUpdates(), await this.subscribeAllAddresses();
1542
+ return e && await this.rostrumService.setCurrentInstance(e), await this.disconnectRostrum(), this.connect();
1440
1543
  }
1441
1544
  async initRostrum() {
1442
1545
  this.isConnected ||= (await this.rostrumService.connect(), await this.rostrumService.subscribeHeaders((e) => this.notify({
@@ -1493,7 +1596,7 @@ var je = class {
1493
1596
  n,
1494
1597
  r
1495
1598
  ]);
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();
1599
+ this.receiveAddresses = this.deriveAddresses(0, 0, i + z.GAP_LIMIT + 1), this.changeAddresses = this.deriveAddresses(1, 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();
1497
1600
  }
1498
1601
  async loadWallet() {
1499
1602
  this.receiveAddresses = await this.walletDb.getReceiveAddresses(), this.changeAddresses = await this.walletDb.getChangeAddresses();
@@ -1530,8 +1633,8 @@ var je = class {
1530
1633
  id: -1,
1531
1634
  name: "HD Wallet",
1532
1635
  address: this.getReceiveAddress(),
1533
- balance: j(e.map((e) => e.balance)),
1534
- tokensBalance: M(e.map((e) => e.tokensBalance)),
1636
+ balance: P(e.map((e) => e.balance)),
1637
+ tokensBalance: F(e.map((e) => e.tokensBalance)),
1535
1638
  sessions: {}
1536
1639
  }
1537
1640
  });
@@ -1666,7 +1769,7 @@ var je = class {
1666
1769
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1667
1770
  let n = Array.from(t.values());
1668
1771
  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));
1772
+ let r = this.getMainAddresses(), i = P(r.map((e) => e.balance)), a = F(r.map((e) => e.tokensBalance));
1670
1773
  this.notify({
1671
1774
  type: "account_balance_updated",
1672
1775
  accountId: -1,
@@ -1728,8 +1831,8 @@ var je = class {
1728
1831
  }
1729
1832
  async checkGapLimit(e) {
1730
1833
  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;
1834
+ if (r < z.GAP_LIMIT) {
1835
+ let i = z.GAP_LIMIT - r, a = t[t.length - 1].idx;
1733
1836
  console.log(`Deriving ${i} more ${n} addresses...`);
1734
1837
  let o = this.deriveAddresses(e, a + 1, i);
1735
1838
  e === 0 ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
@@ -1827,7 +1930,7 @@ var je = class {
1827
1930
  }
1828
1931
  async recoverTokens() {
1829
1932
  let e = [];
1830
- e.push(this.assetService.syncTokens(-1, M(this.getMainAddresses().map((e) => e.tokensBalance))));
1933
+ e.push(this.assetService.syncTokens(-1, F(this.getMainAddresses().map((e) => e.tokensBalance))));
1831
1934
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1832
1935
  await Promise.all(e);
1833
1936
  }
@@ -1840,7 +1943,11 @@ var je = class {
1840
1943
  isMainAddress(e) {
1841
1944
  return e.type == 0;
1842
1945
  }
1843
- }, Pe = class e {
1946
+ };
1947
+ // src/services/market.ts
1948
+ /** Key of NEXA in the market data (`market_data_updated`'s `data`). */
1949
+ const $ = "nexa";
1950
+ var Ge = class e {
1844
1951
  static {
1845
1952
  this.POLL_INTERVAL_MS = 12e4;
1846
1953
  }
@@ -1848,7 +1955,7 @@ var je = class {
1848
1955
  this.CURRENCY_SETTING = "market-currency";
1849
1956
  }
1850
1957
  static {
1851
- this.SUPPORTED_TOKENS = { nexacoin: "nexa" };
1958
+ this.SUPPORTED_TOKENS = { nexacoin: $ };
1852
1959
  }
1853
1960
  constructor(e) {
1854
1961
  this.currency = "usd", this.running = !1, this.walletDb = e;
@@ -1921,6 +2028,6 @@ var je = class {
1921
2028
  }), a;
1922
2029
  }
1923
2030
  };
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 };
2031
+ export { se as AccountType, Oe as AssetService, fe as BLOCK_TIME_MINUTES, S as CURRENCIES, ue as HD_WALLET_ID, z as KeyManager, ce as KeySpace, de as MAX_INT64, Ge as MarketService, $ as NEXA_MARKET_ID, we as RostrumService, Ve as SessionManager, le as SessionRequestType, Ae as TransactionService, He as TransactionTransformer, U as VAULT_FIRST_BLOCK, Ce as WalletCache, Se as WalletDB, We as WalletManager, N as balanceTotal, Pe as calculateFiatValue, _e as capitalizeFirstLetter, C as currencyCodes, O as currentTimestamp, Re as encryptMnemonic, he as estimateDateByFutureBlock, me as estimateMinutesToBlock, Me as formatNexaAmount, Ne as formatNexaAmountWithTicker, Q as formatTokenAmount, je as formatTokenAmountWithTicker, Fe as generateNewMnemonic, Y as generateVaultAddress, K as generateVaultConstraint, J as generateVaultVisibleArgs, A as getAddressBuffer, V as getAssetFileUrl, B as getAssetMetadataUrl, pe as getExplorerUrl, ye as getFileMediaType, be as getFileMimeType, T as getNexaTicker, q as getVaultConstraintHash, W as getVaultTemplate, G as getVaultTemplateHash, E as isGenesisHashValid, Ie as isMnemonicValid, k as isNullOrEmpty, w as isTestnet, D as isValidNexaAddress, ke as isVaultUnlocked, L as keyPathToString, Ee as parseTokenDataUrl, xe as sleep, R as stringToKeyPath, P as sumBalance, F as sumTokensBalance, M as tokenAmountToAssetAmount, ve as tokenHexToAddr, j as tokenIdToHex, Te as transformTokenIconUrl, ge as truncateStringMiddle, Be as validateAndDecryptMnemonic };
1925
2032
 
1926
2033
  //# sourceMappingURL=index.js.map