@otoplo/wallet-common 0.7.0 → 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 T(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 E(n, r = t.PayToScriptTemplate) {
63
+ function D(n, r = t.PayToScriptTemplate) {
61
64
  return e.isValid(n, s.defaultNetwork, r);
62
65
  }
63
- function fe() {
66
+ function pe() {
64
67
  return `https://${w() ? "testnet-" : ""}explorer.nexa.org`;
65
68
  }
66
- function D() {
69
+ function O() {
67
70
  return Math.floor(Date.now() / 1e3);
68
71
  }
69
- function O(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 pe(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 me(e) {
95
+ function _e(e) {
78
96
  return e.length === 0 ? "" : e.charAt(0).toUpperCase() + e.substring(1);
79
97
  }
80
- function k(t) {
98
+ function A(t) {
81
99
  return i.isHexa(t) ? n.hexToBuffer(t) : e.fromString(t).data;
82
100
  }
83
- function A(e) {
84
- return i.isHexa(e) ? e : n.bufferToHex(k(e));
101
+ function j(e) {
102
+ return i.isHexa(e) ? e : n.bufferToHex(A(e));
85
103
  }
86
- function he(n) {
87
- return i.isHexa(n) ? new e(k(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 j(e) {
107
+ function M(e) {
90
108
  return e == null || e === "" ? "" : BigInt(e) <= 0n ? "0" : e.toString();
91
109
  }
92
- function M(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 M(e) {
98
120
  unconfirmed: n.toString()
99
121
  };
100
122
  }
101
- function N(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 N(e) {
107
129
  };
108
130
  }), t;
109
131
  }
110
- const P = {
132
+ const I = {
111
133
  ".gif": {
112
134
  media: "image",
113
135
  mime: "image/gif"
@@ -177,33 +199,23 @@ const P = {
177
199
  mime: "audio/mp4"
178
200
  }
179
201
  };
180
- function ge(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 P[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 P[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: D()
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 = A(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 = A(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(A(e));
425
+ this.tokens.delete(j(e));
414
426
  }
415
427
  removeNft(e) {
416
- this.nfts.delete(A(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
  }
@@ -556,7 +568,7 @@ var ve = class {
556
568
  async check() {
557
569
  try {
558
570
  let e = await this.getFeatures();
559
- if (!T(e.genesis_hash)) return { status: "wrong_network" };
571
+ if (!E(e.genesis_hash)) return { status: "wrong_network" };
560
572
  if (!e.script_index) return { status: "unsupported" };
561
573
  let t = await this.getLatency();
562
574
  return t ? {
@@ -632,10 +644,10 @@ var ve = class {
632
644
  }
633
645
  };
634
646
  // src/utils/keypath.ts
635
- function R(e, t, n) {
647
+ function L(e, t, n) {
636
648
  return `${e}'/${t}/${n}`;
637
649
  }
638
- function z(e) {
650
+ function R(e) {
639
651
  let t = e.split("/");
640
652
  return {
641
653
  account: parseInt(t[0].replace("'", "")),
@@ -644,7 +656,7 @@ function z(e) {
644
656
  };
645
657
  }
646
658
  // src/services/key.ts
647
- var B = class {
659
+ var z = class {
648
660
  constructor() {
649
661
  this.accountKeys = /* @__PURE__ */ new Map(), this.walletKeys = /* @__PURE__ */ new Map();
650
662
  }
@@ -674,35 +686,35 @@ var B = class {
674
686
  }
675
687
  getKey(e) {
676
688
  if (!this.seed) throw Error("KeysManager not initialized");
677
- 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);
678
690
  if (!n) {
679
- 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;
680
692
  n = this.getAccountKey(r).deriveChild(i, !1).deriveChild(a, !1), this.walletKeys.set(t, n);
681
693
  }
682
694
  return n;
683
695
  }
684
696
  };
685
697
  // src/utils/asset.ts
686
- function xe(e, t) {
698
+ function Te(e, t) {
687
699
  return e && typeof e == "string" ? e.startsWith("http") ? e.replace("http://", "https://") : e.startsWith("ipfs://") ? e : `${new URL(t).origin}${e}` : "";
688
700
  }
689
- function Se(e) {
690
- return e ? Ce(e) : null;
701
+ function Ee(e) {
702
+ return e ? De(e) : null;
691
703
  }
692
- function Ce(e, t = "https://ipfs.nebula.markets/") {
704
+ function De(e, t = "https://ipfs.nebula.markets/") {
693
705
  return e?.startsWith("ipfs://") ? t + e.substring(7) : e;
694
706
  }
695
- function V(e) {
696
- return `${U()}/metadata/${e}`;
707
+ function B(e) {
708
+ return `${H()}/metadata/${e}`;
697
709
  }
698
- function H(e, t) {
699
- return `${U()}/assets/${e}/${t}`;
710
+ function V(e, t) {
711
+ return `${H()}/assets/${e}/${t}`;
700
712
  }
701
- function U() {
713
+ function H() {
702
714
  return `https://${w() ? "testapi" : "api"}.otoplo.com`;
703
715
  }
704
716
  // src/services/asset.ts
705
- var we = class {
717
+ var Oe = class {
706
718
  constructor(e, t) {
707
719
  this.walletDb = e, this.walletCache = t;
708
720
  }
@@ -758,7 +770,7 @@ var we = class {
758
770
  async syncTokens(e, t) {
759
771
  for (let n in t) {
760
772
  let r = t[n];
761
- if (r && BigInt(r.confirmed) + BigInt(r.unconfirmed) > 0n) {
773
+ if (r && N(r) > 0n) {
762
774
  let t = await this.getAssetInfo(n);
763
775
  if (t && t.type == "token") {
764
776
  let n = {
@@ -776,8 +788,8 @@ var we = class {
776
788
  let n = Object.keys(t), r = await this.walletDb.getAssets(e, "nft"), i = r?.filter((e) => !n.includes(e.tokenIdHex)) ?? [];
777
789
  for (let t of i) await this.deleteNft(e, t.tokenIdHex);
778
790
  for (let [n, i] of Object.entries(t)) {
779
- let t = A(n), a = i && BigInt(i.confirmed) + BigInt(i.unconfirmed) > 0n, o = r?.some((e) => e.tokenIdHex == t);
780
- !a && !o || a && o || (!a && o ? await this.deleteNft(e, t) : await this.handleNftReceive(e, t, D()));
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()));
781
793
  }
782
794
  }
783
795
  async saveToken(e, t) {
@@ -793,10 +805,10 @@ var we = class {
793
805
  await this.walletDb.deleteNft(e, t), this.walletCache.removeNft(t);
794
806
  }
795
807
  getAssetFile(e, t) {
796
- return this.performGet(H(e, t), "raw");
808
+ return this.performGet(V(e, t), "raw");
797
809
  }
798
810
  getAssetMetadata(e) {
799
- return this.performGet(V(e), "json");
811
+ return this.performGet(B(e), "json");
800
812
  }
801
813
  async performGet(e, t) {
802
814
  try {
@@ -813,35 +825,38 @@ var we = class {
813
825
  }
814
826
  };
815
827
  // src/utils/vault.ts
816
- const W = 274710;
817
- function G() {
828
+ const U = 274710;
829
+ function W() {
818
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);
819
831
  }
820
- function K() {
821
- let e = G();
832
+ function G() {
833
+ let e = W();
822
834
  return o.sha256ripemd160(e.toBuffer());
823
835
  }
824
- function q(e) {
836
+ function K(e) {
825
837
  return d.empty().add(e.toBuffer());
826
838
  }
827
- function J(e) {
828
- let t = q(e);
839
+ function q(e) {
840
+ let t = K(e);
829
841
  return o.sha256ripemd160(t.toBuffer());
830
842
  }
831
- function Y(e) {
843
+ function J(e) {
832
844
  return e.map((e) => e <= 16 ? p.smallInt(e) : f.encode(e));
833
845
  }
834
- function X(t, n) {
846
+ function Y(t, n) {
835
847
  if (n.length !== 2) return;
836
- let r = K(), i = J(t), a = Y(n);
848
+ let r = G(), i = q(t), a = J(n);
837
849
  return e.fromScriptTemplate(r, i, a).toString();
838
850
  }
839
- function Te(e, t) {
840
- let n = (t - e) * 2, r = /* @__PURE__ */ new Date();
841
- 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;
842
857
  }
843
858
  // src/services/transaction.ts
844
- var Ee = class {
859
+ var Ae = class {
845
860
  constructor(e, t, n) {
846
861
  this.MAX_INPUTS_OUTPUTS = 250, this.rostrumService = e, this.keyManager = t, this.walletDb = n;
847
862
  }
@@ -857,7 +872,7 @@ var Ee = class {
857
872
  };
858
873
  }
859
874
  async fetchVaultTransactions(e) {
860
- let t = await this.rostrumService.getTransactionsHistory(e, W), n = [];
875
+ let t = await this.rostrumService.getTransactionsHistory(e, U), n = [];
861
876
  for (let r of t) {
862
877
  let t = this.classifyTransaction(r.tx_hash, [e]);
863
878
  n.push(t);
@@ -884,17 +899,17 @@ var Ee = class {
884
899
  address: e.addresses[0],
885
900
  nexaAmount: e.value_satoshi.toString(),
886
901
  assetId: e.token_id_hex ?? "",
887
- assetAmount: j(e.groupQuantity)
902
+ assetAmount: M(e.groupQuantity)
888
903
  };
889
904
  t.includes(n.address) ? r.push(n) : i.push(n);
890
905
  }
891
906
  for (let e of n.vout) {
892
- if (O(e.scriptPubKey.addresses)) continue;
907
+ if (k(e.scriptPubKey.addresses)) continue;
893
908
  let n = {
894
909
  address: e.scriptPubKey.addresses[0],
895
910
  nexaAmount: e.value_satoshi.toString(),
896
911
  assetId: e.scriptPubKey.token_id_hex ?? "",
897
- assetAmount: j(e.scriptPubKey.groupQuantity)
912
+ assetAmount: M(e.scriptPubKey.groupQuantity)
898
913
  };
899
914
  t.includes(n.address) ? a.push(n) : o.push(n);
900
915
  }
@@ -905,7 +920,7 @@ var Ee = class {
905
920
  accountId: 0,
906
921
  txId: n.txid,
907
922
  txIdem: n.txidem,
908
- time: c ? n.time : D(),
923
+ time: c ? n.time : O(),
909
924
  height: c ? n.height : 0,
910
925
  type: s,
911
926
  fee: n.fee_satoshi.toString(),
@@ -930,20 +945,20 @@ var Ee = class {
930
945
  return this.finalizeTransaction(i, Array.from(a.values()));
931
946
  }
932
947
  prepareTransaction(n, r, i, a) {
933
- if (!E(n) && !E(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
948
+ if (!D(n) && !D(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
934
949
  if (i && BigInt(r) < 1n || !i && parseInt(r) < h.DUST_AMOUNT) throw Error("The amount is too low.");
935
950
  if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > h.MAX_MONEY) throw Error("The amount is too high.");
936
951
  let o = new g();
937
952
  if (a && o.addData(a), i) {
938
- if (!E(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
953
+ if (!D(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
939
954
  if (e.getOutputType(n) === 0) throw Error("Token must be sent to script template address");
940
955
  o.to(n, h.DUST_AMOUNT, i, BigInt(r));
941
956
  } else o.to(n, r);
942
957
  return o;
943
958
  }
944
959
  async populateNexaInputsAndChange(e, t, n, r) {
945
- let i = t.filter((e) => BigInt(e.balance.confirmed) + BigInt(e.balance.unconfirmed) > 0n);
946
- if (O(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.");
947
962
  let a = /* @__PURE__ */ new Map(), o = r.isConsolidate ? 0 : Number(e.transaction.outputs.find((e) => e.value > 0n).value);
948
963
  for (let t of i) {
949
964
  let i = await this.rostrumService.getNexaUtxos(t.address);
@@ -984,14 +999,14 @@ var Ee = class {
984
999
  }
985
1000
  let s = {
986
1001
  errorMsg: "Not enough Nexa balance.",
987
- amount: v.formatNEXA(e.transaction.outputs[0].value),
988
- fee: v.formatNEXA(e.transaction.estimateRequiredFee())
1002
+ amount: y.formatNEXA(e.transaction.outputs[0].value),
1003
+ fee: y.formatNEXA(e.transaction.estimateRequiredFee())
989
1004
  };
990
1005
  throw Error(JSON.stringify(s));
991
1006
  }
992
1007
  async populateTokenInputsAndChange(e, t, n, r, i) {
993
- let a = A(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
994
- if (O(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.");
995
1010
  let s = /* @__PURE__ */ new Map(), c = 0n;
996
1011
  for (let t of o) {
997
1012
  let a = await this.rostrumService.getTokenUtxos(t.address, r);
@@ -1027,14 +1042,60 @@ var Ee = class {
1027
1042
  return JSON.stringify(t, null, 2);
1028
1043
  }
1029
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
+ }
1030
1091
  // src/utils/seed.ts
1031
- function De(e = 12) {
1092
+ function Fe(e = 12) {
1032
1093
  return re(x, e === 24 ? 256 : 128);
1033
1094
  }
1034
- function Z(e) {
1095
+ function Ie(e) {
1035
1096
  return ae(e, x);
1036
1097
  }
1037
- async function Q(e, t) {
1098
+ async function Le(e, t) {
1038
1099
  let n = await crypto.subtle.importKey("raw", new Uint8Array(e), "PBKDF2", !1, ["deriveKey"]);
1039
1100
  return crypto.subtle.deriveKey({
1040
1101
  name: "PBKDF2",
@@ -1046,8 +1107,8 @@ async function Q(e, t) {
1046
1107
  length: 256
1047
1108
  }, !1, ["encrypt", "decrypt"]);
1048
1109
  }
1049
- async function Oe(e, t) {
1050
- 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({
1051
1112
  name: "AES-GCM",
1052
1113
  iv: new Uint8Array(a)
1053
1114
  }, s, new Uint8Array(o)), l = n.concat([
@@ -1057,18 +1118,18 @@ async function Oe(e, t) {
1057
1118
  ]);
1058
1119
  return n.bufferToBase64(l);
1059
1120
  }
1060
- async function ke(e, t) {
1061
- 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({
1062
1123
  name: "AES-GCM",
1063
1124
  iv: o
1064
1125
  }, c, s);
1065
1126
  return n.bufferToUtf8(new Uint8Array(l));
1066
1127
  }
1067
- async function Ae(e, t) {
1128
+ async function Be(e, t) {
1068
1129
  try {
1069
1130
  if (e) {
1070
- let n = await ke(e, t);
1071
- if (n && Z(n)) return n;
1131
+ let n = await ze(e, t);
1132
+ if (n && Ie(n)) return n;
1072
1133
  }
1073
1134
  return !1;
1074
1135
  } catch {
@@ -1076,7 +1137,7 @@ async function Ae(e, t) {
1076
1137
  }
1077
1138
  }
1078
1139
  // src/services/session.ts
1079
- var je = class {
1140
+ var Ve = class {
1080
1141
  constructor(e, t) {
1081
1142
  this.walletDb = e, this.keyManager = t, this.providers = /* @__PURE__ */ new Map(), this.handlers = /* @__PURE__ */ new Map(), this.removeOnClose = !0;
1082
1143
  }
@@ -1222,7 +1283,7 @@ var je = class {
1222
1283
  };
1223
1284
  });
1224
1285
  }
1225
- }, Me = class {
1286
+ }, He = class {
1226
1287
  constructor(e, t, n) {
1227
1288
  this.rostrumService = e, this.keyManager = t, this.assetService = n;
1228
1289
  }
@@ -1268,7 +1329,7 @@ var je = class {
1268
1329
  address: e.address,
1269
1330
  nexaAmount: i.amount.toString(),
1270
1331
  assetId: n,
1271
- assetAmount: j(i.group_quantity) || i.amount.toString()
1332
+ assetAmount: M(i.group_quantity) || i.amount.toString()
1272
1333
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1273
1334
  }
1274
1335
  r.scriptSig.findPlaceholder() > 0 && e.inputsToSign.add(t);
@@ -1277,11 +1338,11 @@ var je = class {
1277
1338
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1278
1339
  let n = e.txDetails.tx.outputs[t].toObject();
1279
1340
  if (n.address !== e.address) continue;
1280
- let r = n.groupId ? A(n.groupId) : "NEXA", i = {
1341
+ let r = n.groupId ? j(n.groupId) : "NEXA", i = {
1281
1342
  address: n.address,
1282
1343
  nexaAmount: n.value.toString(),
1283
1344
  assetId: r,
1284
- assetAmount: j(n.groupAmount) || n.value.toString()
1345
+ assetAmount: M(n.groupAmount) || n.value.toString()
1285
1346
  };
1286
1347
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1287
1348
  }
@@ -1347,19 +1408,19 @@ var je = class {
1347
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);
1348
1409
  }
1349
1410
  }
1350
- }, $ = class {
1411
+ }, Ue = class {
1351
1412
  constructor(e, t) {
1352
1413
  this.rostrumService = e, this.keyManager = t;
1353
1414
  }
1354
1415
  async discoverWalletIndex(e, t) {
1355
1416
  let n = 0, r = -1, i = [];
1356
1417
  for (;;) {
1357
- let a = await Promise.all(Array.from({ length: B.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1358
- 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;
1359
1420
  else break;
1360
1421
  }
1361
1422
  if (r === -1) return -1;
1362
- 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;
1363
1424
  return r;
1364
1425
  }
1365
1426
  async discoverVaults() {
@@ -1374,14 +1435,14 @@ var je = class {
1374
1435
  * Indexes are checked in parallel batches, stopping after VAULT_GAP_LIMIT consecutive indexes with no scripts.
1375
1436
  */
1376
1437
  async checkForVaults() {
1377
- let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(K()), r = 0;
1438
+ let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(G()), r = 0;
1378
1439
  for (let i = 0; r < 5; i += 5) {
1379
1440
  let a = await Promise.all(Array.from({ length: 5 }, (e, r) => {
1380
1441
  let a = this.keyManager.getKey({
1381
1442
  account: 1,
1382
1443
  type: 0,
1383
1444
  index: i + r
1384
- }), o = n.bufferToHex(J(a.publicKey));
1445
+ }), o = n.bufferToHex(q(a.publicKey));
1385
1446
  return this.rostrumService.listTemplateScripts(t, o);
1386
1447
  }));
1387
1448
  for (let t of a) t.length === 0 ? r++ : (r = 0, t.forEach((t) => e.add(t.scriptpubkey)));
@@ -1390,7 +1451,7 @@ var je = class {
1390
1451
  }
1391
1452
  parseVaultDetails(t) {
1392
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];
1393
- if (a == X(this.keyManager.getKey({
1454
+ if (a == Y(this.keyManager.getKey({
1394
1455
  account: 1,
1395
1456
  type: 0,
1396
1457
  index: c
@@ -1408,7 +1469,7 @@ var je = class {
1408
1469
  type: 1
1409
1470
  };
1410
1471
  }
1411
- }, Ne = class e {
1472
+ }, We = class e {
1412
1473
  static {
1413
1474
  this.DEBOUNCE_MS = 1e3;
1414
1475
  }
@@ -1426,7 +1487,7 @@ var je = class {
1426
1487
  address: n,
1427
1488
  result: t
1428
1489
  });
1429
- }, 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();
1430
1491
  }
1431
1492
  clear() {
1432
1493
  this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.stopUpdates(), this.notify({ type: "clear_wallet" });
@@ -1459,14 +1520,14 @@ var je = class {
1459
1520
  let t = this.accounts.get(e);
1460
1521
  return [{
1461
1522
  address: t.address,
1462
- keyPath: R(2, 0, t.id),
1523
+ keyPath: L(2, 0, t.id),
1463
1524
  balance: t.balance,
1464
1525
  tokensBalance: t.tokensBalance
1465
1526
  }];
1466
1527
  }
1467
1528
  return this.getMainAddresses().filter((e) => e.used).map((e) => ({
1468
1529
  address: e.address,
1469
- keyPath: R(0, e.space, e.idx),
1530
+ keyPath: L(0, e.space, e.idx),
1470
1531
  balance: e.balance,
1471
1532
  tokensBalance: e.tokensBalance
1472
1533
  }));
@@ -1535,7 +1596,7 @@ var je = class {
1535
1596
  n,
1536
1597
  r
1537
1598
  ]);
1538
- 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();
1539
1600
  }
1540
1601
  async loadWallet() {
1541
1602
  this.receiveAddresses = await this.walletDb.getReceiveAddresses(), this.changeAddresses = await this.walletDb.getChangeAddresses();
@@ -1572,8 +1633,8 @@ var je = class {
1572
1633
  id: -1,
1573
1634
  name: "HD Wallet",
1574
1635
  address: this.getReceiveAddress(),
1575
- balance: M(e.map((e) => e.balance)),
1576
- tokensBalance: N(e.map((e) => e.tokensBalance)),
1636
+ balance: P(e.map((e) => e.balance)),
1637
+ tokensBalance: F(e.map((e) => e.tokensBalance)),
1577
1638
  sessions: {}
1578
1639
  }
1579
1640
  });
@@ -1708,7 +1769,7 @@ var je = class {
1708
1769
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1709
1770
  let n = Array.from(t.values());
1710
1771
  await this.checkGapLimit(0), await this.checkGapLimit(1);
1711
- let r = this.getMainAddresses(), i = M(r.map((e) => e.balance)), a = N(r.map((e) => e.tokensBalance));
1772
+ let r = this.getMainAddresses(), i = P(r.map((e) => e.balance)), a = F(r.map((e) => e.tokensBalance));
1712
1773
  this.notify({
1713
1774
  type: "account_balance_updated",
1714
1775
  accountId: -1,
@@ -1770,8 +1831,8 @@ var je = class {
1770
1831
  }
1771
1832
  async checkGapLimit(e) {
1772
1833
  let t = e === 0 ? this.receiveAddresses : this.changeAddresses, n = e === 0 ? "Receive" : "Change", r = t.filter((e) => !e.used).length;
1773
- if (r < B.GAP_LIMIT) {
1774
- 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;
1775
1836
  console.log(`Deriving ${i} more ${n} addresses...`);
1776
1837
  let o = this.deriveAddresses(e, a + 1, i);
1777
1838
  e === 0 ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
@@ -1869,7 +1930,7 @@ var je = class {
1869
1930
  }
1870
1931
  async recoverTokens() {
1871
1932
  let e = [];
1872
- e.push(this.assetService.syncTokens(-1, N(this.getMainAddresses().map((e) => e.tokensBalance))));
1933
+ e.push(this.assetService.syncTokens(-1, F(this.getMainAddresses().map((e) => e.tokensBalance))));
1873
1934
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1874
1935
  await Promise.all(e);
1875
1936
  }
@@ -1882,7 +1943,11 @@ var je = class {
1882
1943
  isMainAddress(e) {
1883
1944
  return e.type == 0;
1884
1945
  }
1885
- }, 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 {
1886
1951
  static {
1887
1952
  this.POLL_INTERVAL_MS = 12e4;
1888
1953
  }
@@ -1890,7 +1955,7 @@ var je = class {
1890
1955
  this.CURRENCY_SETTING = "market-currency";
1891
1956
  }
1892
1957
  static {
1893
- this.SUPPORTED_TOKENS = { nexacoin: "nexa" };
1958
+ this.SUPPORTED_TOKENS = { nexacoin: $ };
1894
1959
  }
1895
1960
  constructor(e) {
1896
1961
  this.currency = "usd", this.running = !1, this.walletDb = e;
@@ -1963,6 +2028,6 @@ var je = class {
1963
2028
  }), a;
1964
2029
  }
1965
2030
  };
1966
- 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, me as capitalizeFirstLetter, C as currencyCodes, D as currentTimestamp, Oe as encryptMnemonic, Te as estimateDateByFutureBlock, De as generateNewMnemonic, X as generateVaultAddress, q as generateVaultConstraint, Y as generateVaultVisibleArgs, k as getAddressBuffer, H as getAssetFileUrl, V as getAssetMetadataUrl, fe as getExplorerUrl, ge as getFileMediaType, F as getFileMimeType, J as getVaultConstraintHash, G as getVaultTemplate, K as getVaultTemplateHash, T as isGenesisHashValid, Z as isMnemonicValid, O as isNullOrEmpty, w as isTestnet, E as isValidNexaAddress, R as keyPathToString, Se as parseTokenDataUrl, L as prettifyAmount, I as sleep, z as stringToKeyPath, M as sumBalance, N as sumTokensBalance, j as tokenAmountToAssetAmount, he as tokenHexToAddr, A as tokenIdToHex, xe as transformTokenIconUrl, pe 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 };
1967
2032
 
1968
2033
  //# sourceMappingURL=index.js.map