@otoplo/wallet-common 0.7.0 → 0.8.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.
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
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";
3
- import { ConnectionStatus as te, ElectrumClient as ne, TransportScheme as b } from "@otoplo/electrum-client";
1
+ import { Address as e, AddressType as t, BufferUtils as n, BufferWriter as r, CommonUtils as i, HDPrivateKey as a, Hash as o, InputSighashType as s, Networks as c, Opcode as l, Output as u, OutputSighashType as d, Script as f, ScriptFactory as ee, ScriptNum as p, ScriptOpcode as m, SighashType as h, Transaction as g, TransactionBuilder as _, TxSigner as v, UnitType as y, UnitUtils as b } from "libnexa-ts";
2
+ import { ConnectionStatus as te, ElectrumClient as ne, TransportScheme as x } from "@otoplo/electrum-client";
4
3
  import { generateMnemonic as re, mnemonicToSeedSync as ie, validateMnemonic as ae } from "@scure/bip39";
5
- import { wordlist as x } from "@scure/bip39/wordlists/english.js";
4
+ import { wordlist as S } from "@scure/bip39/wordlists/english.js";
6
5
  import { DAppProvider as oe } from "wallet-comms-sdk";
7
6
  // src/utils/enums.ts
8
7
  let se = /* @__PURE__ */ function(e) {
@@ -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, pe = {
17
16
  usd: {
18
17
  symbol: "$",
19
18
  name: "US Dollar"
@@ -50,46 +49,69 @@ const ue = -1, de = 9223372036854775807n, S = {
50
49
  symbol: "¥",
51
50
  name: "Japanese Yen"
52
51
  }
53
- }, C = Object.keys(S);
52
+ }, C = Object.keys(pe);
54
53
  function w() {
55
- return s.defaultNetwork == s.testnet;
54
+ return c.defaultNetwork == c.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) {
61
- return e.isValid(n, s.defaultNetwork, r);
63
+ function D(n, r = t.PayToScriptTemplate) {
64
+ return e.isValid(n, c.defaultNetwork, r);
62
65
  }
63
- function fe() {
66
+ function me() {
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 k(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() + k(e, t) * 6e4).toLocaleDateString(n, r);
86
+ }
87
+ function A(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 j(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 M(e) {
102
+ return i.isHexa(e) ? e : n.bufferToHex(j(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(j(n), c.defaultNetwork, t.GroupIdAddress).toString() : n;
88
106
  }
89
- function j(e) {
107
+ function N(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 P(e) {
112
+ return BigInt(e.confirmed) + BigInt(e.unconfirmed);
113
+ }
114
+ function F(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 I(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 L = {
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 L[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 L[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 = M(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 = M(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(M(e));
414
426
  }
415
427
  removeNft(e) {
416
- this.nfts.delete(A(e));
428
+ this.nfts.delete(M(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 ? {
@@ -614,17 +626,17 @@ var ve = class {
614
626
  }
615
627
  static getPredefinedInstances() {
616
628
  return w() ? [{
617
- scheme: b.WSS,
629
+ scheme: x.WSS,
618
630
  host: "testnet-electrum.nexa.org",
619
631
  port: 30004,
620
632
  label: "NexaOrg"
621
633
  }] : [{
622
- scheme: b.WSS,
634
+ scheme: x.WSS,
623
635
  host: "rostrum.otoplo.com",
624
636
  port: 443,
625
637
  label: "Otoplo"
626
638
  }, {
627
- scheme: b.WSS,
639
+ scheme: x.WSS,
628
640
  host: "electrum.nexa.org",
629
641
  port: 20004,
630
642
  label: "NexaOrg"
@@ -683,13 +695,13 @@ var B = class {
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
707
  function V(e) {
@@ -702,7 +714,7 @@ function U() {
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 && P(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 = M(n), a = i && P(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) {
@@ -815,33 +827,36 @@ var we = class {
815
827
  // src/utils/vault.ts
816
828
  const W = 274710;
817
829
  function G() {
818
- 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);
830
+ return f.empty().add(l.OP_FROMALTSTACK).add(l.OP_DROP).add(l.OP_FROMALTSTACK).add(l.OP_CHECKLOCKTIMEVERIFY).add(l.OP_DROP).add(l.OP_FROMALTSTACK).add(l.OP_CHECKSIGVERIFY);
819
831
  }
820
832
  function K() {
821
833
  let e = G();
822
834
  return o.sha256ripemd160(e.toBuffer());
823
835
  }
824
836
  function q(e) {
825
- return d.empty().add(e.toBuffer());
837
+ return f.empty().add(e.toBuffer());
826
838
  }
827
839
  function J(e) {
828
840
  let t = q(e);
829
841
  return o.sha256ripemd160(t.toBuffer());
830
842
  }
831
843
  function Y(e) {
832
- return e.map((e) => e <= 16 ? p.smallInt(e) : f.encode(e));
844
+ return e.map((e) => e <= 16 ? m.smallInt(e) : p.encode(e));
833
845
  }
834
846
  function X(t, n) {
835
847
  if (n.length !== 2) return;
836
848
  let r = K(), i = J(t), a = Y(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
  }
@@ -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: N(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 (A(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: N(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(),
@@ -926,24 +941,24 @@ var Ee = class {
926
941
  let r = {
927
942
  isConsolidate: !0,
928
943
  templateData: n
929
- }, i = new g(), a = await this.populateNexaInputsAndChange(i, e, t, r);
944
+ }, i = new _(), a = await this.populateNexaInputsAndChange(i, e, t, r);
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.");
934
- if (i && BigInt(r) < 1n || !i && parseInt(r) < h.DUST_AMOUNT) throw Error("The amount is too low.");
935
- if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > h.MAX_MONEY) throw Error("The amount is too high.");
936
- let o = new g();
948
+ if (!D(n) && !D(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
949
+ if (i && BigInt(r) < 1n || !i && parseInt(r) < g.DUST_AMOUNT) throw Error("The amount is too low.");
950
+ if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > g.MAX_MONEY) throw Error("The amount is too high.");
951
+ let o = new _();
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
- o.to(n, h.DUST_AMOUNT, i, BigInt(r));
955
+ o.to(n, g.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) => P(e.balance) > 0n);
961
+ if (A(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: b.formatNEXA(e.transaction.outputs[0].value),
1003
+ fee: b.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 = M(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
1009
+ if (A(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);
@@ -1009,7 +1024,7 @@ var Ee = class {
1009
1024
  if (c > 9223372036854775807n) throw Error("Token inputs exceeded max amount. Consider sending in small chunks");
1010
1025
  if (e.transaction.inputs.length > this.MAX_INPUTS_OUTPUTS) throw Error("Too many inputs. Consider consolidating transactions or reduce the send amount.");
1011
1026
  if (c == i) return s;
1012
- if (c > i) return e.to(n, h.DUST_AMOUNT, r, c - i), s;
1027
+ if (c > i) return e.to(n, g.DUST_AMOUNT, r, c - i), s;
1013
1028
  }
1014
1029
  }
1015
1030
  throw Error("Not enough token balance");
@@ -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 Z = /* @__PURE__ */ new Map();
1048
+ function Q(e, t) {
1049
+ let n = `${e}|${JSON.stringify(t)}`, r = Z.get(n);
1050
+ return r || (r = new Intl.NumberFormat(e, t), Z.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 $(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 = Q(r, { maximumFractionDigits: a });
1061
+ return o === 0n && i !== 0n ? `${i < 0n ? "-" : ""}<${s.format(10 ** -a)}` : s.format(Number(b.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 = $(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 $(e, y.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, y.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 = Q(i, {
1086
+ style: "currency",
1087
+ currency: r
1088
+ }), o = Number(b.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) {
1032
- return re(x, e === 24 ? 256 : 128);
1092
+ function Fe(e = 12) {
1093
+ return re(S, e === 24 ? 256 : 128);
1033
1094
  }
1034
- function Z(e) {
1035
- return ae(e, x);
1095
+ function Ie(e) {
1096
+ return ae(e, S);
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
  }
@@ -1212,7 +1273,7 @@ var je = class {
1212
1273
  address: e.address,
1213
1274
  pubkey: this.keyManager.getKey(t).publicKey.toString(),
1214
1275
  blockchain: "nexa",
1215
- network: s.defaultNetwork.name,
1276
+ network: c.defaultNetwork.name,
1216
1277
  capabilities: {
1217
1278
  addToken: !0,
1218
1279
  sendTransaction: !0,
@@ -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
  }
@@ -1236,16 +1297,14 @@ var je = class {
1236
1297
  address: t.address,
1237
1298
  privateKey: this.keyManager.getKey(t.keyPath).privateKey,
1238
1299
  txDetails: {
1239
- tx: new h(e),
1300
+ tx: new g(e),
1240
1301
  send: [],
1241
1302
  receive: []
1242
1303
  },
1243
1304
  myInputs: /* @__PURE__ */ new Map(),
1244
1305
  myOutputs: /* @__PURE__ */ new Map(),
1245
1306
  involvedAssets: /* @__PURE__ */ new Set(),
1246
- inputsToSign: /* @__PURE__ */ new Set(),
1247
- coveredOutputs: /* @__PURE__ */ new Set(),
1248
- allMyOutputsCovered: !1
1307
+ inputsToSign: /* @__PURE__ */ new Set()
1249
1308
  };
1250
1309
  } catch {
1251
1310
  throw Error("Invalid transaction format.");
@@ -1262,26 +1321,39 @@ var je = class {
1262
1321
  async processInput(e, t) {
1263
1322
  let r = e.txDetails.tx.inputs[t], i = await this.rostrumService.getUtxo(n.bufferToHex(r.outpoint));
1264
1323
  if (i.status == "spent") throw Error("Input UTXO is already spent.");
1265
- if (r.output = new l(i.amount, i.scriptpubkey), r.output.address == e.address) {
1324
+ if (r.output = new u(i.amount, i.scriptpubkey), r.output.address == e.address) {
1266
1325
  let n = i.token_id_hex || "NEXA";
1267
1326
  e.myInputs.set(t, {
1268
1327
  address: e.address,
1269
1328
  nexaAmount: i.amount.toString(),
1270
1329
  assetId: n,
1271
- assetAmount: j(i.group_quantity) || i.amount.toString()
1330
+ assetAmount: N(i.group_quantity) || i.amount.toString()
1272
1331
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1273
1332
  }
1274
- r.scriptSig.findPlaceholder() > 0 && e.inputsToSign.add(t);
1333
+ if (r.scriptSig.findPlaceholder() > 0) {
1334
+ if (r.output.address != e.address && !this.isMyContractInput(e, r)) throw Error("Transaction requests a signature for an input this wallet does not control.");
1335
+ e.inputsToSign.add(t);
1336
+ }
1337
+ }
1338
+ /**
1339
+ * A script template input that this wallet may sign: its visible args contain the wallet's public key
1340
+ * (e.g. withdrawing or closing a contract offer posted by this wallet).
1341
+ */
1342
+ isMyContractInput(e, t) {
1343
+ let r = t.output.scriptPubKey;
1344
+ if (!r.isScriptTemplateOut()) return !1;
1345
+ let i = e.privateKey.publicKey.toBuffer();
1346
+ return r.getVisibleArgs().chunks.some((e) => e.buf != null && n.equals(e.buf, i));
1275
1347
  }
1276
1348
  processOutputs(e) {
1277
1349
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1278
1350
  let n = e.txDetails.tx.outputs[t].toObject();
1279
1351
  if (n.address !== e.address) continue;
1280
- let r = n.groupId ? A(n.groupId) : "NEXA", i = {
1352
+ let r = n.groupId ? M(n.groupId) : "NEXA", i = {
1281
1353
  address: n.address,
1282
1354
  nexaAmount: n.value.toString(),
1283
1355
  assetId: r,
1284
- assetAmount: j(n.groupAmount) || n.value.toString()
1356
+ assetAmount: N(n.groupAmount) || n.value.toString()
1285
1357
  };
1286
1358
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1287
1359
  }
@@ -1291,46 +1363,49 @@ var je = class {
1291
1363
  for (let t of e.inputsToSign) {
1292
1364
  let n = e.txDetails.tx.inputs[t], r = this.validateAndGetSubscript(n);
1293
1365
  if (n.scriptSig.isEmpty()) {
1294
- e.allMyOutputsCovered = !0;
1295
- let i = _.sign(e.txDetails.tx, t, m.ALL, r, e.privateKey).toTxFormat(), a = d.empty().add(e.privateKey.publicKey.toBuffer());
1296
- n.scriptSig = ee.buildScriptTemplateIn(void 0, a, d.empty().add(i));
1366
+ let i = v.sign(e.txDetails.tx, t, h.ALL, r, e.privateKey).toTxFormat(), a = f.empty().add(e.privateKey.publicKey.toBuffer());
1367
+ n.scriptSig = ee.buildScriptTemplateIn(void 0, a, f.empty().add(i));
1297
1368
  } else {
1298
- let i = n.scriptSig.findPlaceholder(), a = n.scriptSig.chunks[i].buf.subarray(64), o = m.fromBuffer(a);
1299
- this.processSignatureCoverage(e, o);
1300
- let s = _.sign(e.txDetails.tx, t, o, r, e.privateKey).toTxFormat(a);
1301
- n.scriptSig.replaceChunk(i, d.empty().add(s));
1369
+ let i = n.scriptSig.findPlaceholder(), a = n.scriptSig.chunks[i].buf.subarray(64), o = h.fromBuffer(a);
1370
+ this.validateSigHashType(o, t), this.validateOutputsCoverage(e, o);
1371
+ let s = v.sign(e.txDetails.tx, t, o, r, e.privateKey).toTxFormat(a);
1372
+ n.scriptSig.replaceChunk(i, f.empty().add(s));
1302
1373
  }
1303
1374
  }
1304
- if (!e.allMyOutputsCovered) throw Error("Some of interested outputs are not covered by signatures.");
1305
1375
  }
1306
1376
  validateAndGetSubscript(e) {
1307
1377
  if (e.output.scriptPubKey.isPublicKeyTemplateOut()) {
1308
- if (e.scriptSig.isEmpty() || e.scriptSig.isPublicKeyTemplateIn()) return d.empty().add(c.OP_FROMALTSTACK).add(c.OP_CHECKSIGVERIFY);
1378
+ if (e.scriptSig.isEmpty() || e.scriptSig.isPublicKeyTemplateIn()) return f.empty().add(l.OP_FROMALTSTACK).add(l.OP_CHECKSIGVERIFY);
1309
1379
  throw Error("Invalid input script type.");
1310
1380
  }
1311
1381
  if (e.output.scriptPubKey.isScriptTemplateOut()) {
1312
1382
  if (!e.scriptSig.isScriptTemplateIn()) throw Error("Unsupported input script type.");
1313
1383
  let t = e.output.scriptPubKey.getTemplateHash(), r = e.scriptSig.chunks[0].buf;
1314
- if (n.equals(t, o.sha256ripemd160(r)) || n.equals(t, o.sha256sha256(r))) return d.fromBuffer(r);
1384
+ if (n.equals(t, o.sha256ripemd160(r)) || n.equals(t, o.sha256sha256(r))) return f.fromBuffer(r);
1315
1385
  throw Error("Invalid input script template.");
1316
1386
  }
1317
1387
  throw Error("Unsupported prevout script type.");
1318
1388
  }
1319
- processSignatureCoverage(e, t) {
1320
- if (!e.allMyOutputsCovered) {
1321
- if (t.outType == u.TWO) e.coveredOutputs.add(t.outData[0]), e.coveredOutputs.add(t.outData[1]), this.checkSignatureCoverage(e);
1322
- else if (t.outType == u.FIRSTN) {
1323
- let n = t.outData[0];
1324
- for (let t = 0; t < n; t++) e.coveredOutputs.add(t);
1325
- this.checkSignatureCoverage(e);
1326
- } else e.allMyOutputsCovered = !0;
1389
+ /**
1390
+ * The signature must commit to the input it signs, otherwise it is not bound to any outpoint
1391
+ * and can be replayed on any other coin locked by the same key and subscript.
1392
+ * Only output sighash types that we know how to check coverage for are accepted.
1393
+ */
1394
+ validateSigHashType(e, t) {
1395
+ if (!(e.inType == s.ALL || e.inType == s.THISIN || e.inType == s.FIRSTN && e.inData[0] > t)) throw Error("Signature type does not cover the input being signed.");
1396
+ switch (e.outType) {
1397
+ case d.ALL:
1398
+ case d.FIRSTN:
1399
+ case d.TWO: break;
1400
+ default: throw Error("Unsupported signature type.");
1327
1401
  }
1328
1402
  }
1329
- checkSignatureCoverage(e) {
1330
- if (!e.allMyOutputsCovered) {
1331
- for (let t of e.myOutputs.keys()) if (!e.coveredOutputs.has(t)) return;
1332
- e.allMyOutputsCovered = !0;
1333
- }
1403
+ /**
1404
+ * Each signature must commit to every output paid to this wallet.
1405
+ * Coverage is checked per signature, never pooled across signatures.
1406
+ */
1407
+ validateOutputsCoverage(e, t) {
1408
+ for (let n of e.myOutputs.keys()) if (!(t.outType == d.ALL || t.outType == d.FIRSTN && n < t.outData[0] || t.outType == d.TWO && t.outData.includes(n))) throw Error("Signature does not cover your outputs.");
1334
1409
  }
1335
1410
  async processAssetMovements(e) {
1336
1411
  let t = Array.from(e.myInputs.values()), n = Array.from(e.myOutputs.values()), r = [];
@@ -1347,7 +1422,7 @@ var je = class {
1347
1422
  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
1423
  }
1349
1424
  }
1350
- }, $ = class {
1425
+ }, Ue = class {
1351
1426
  constructor(e, t) {
1352
1427
  this.rostrumService = e, this.keyManager = t;
1353
1428
  }
@@ -1389,7 +1464,7 @@ var je = class {
1389
1464
  return e;
1390
1465
  }
1391
1466
  parseVaultDetails(t) {
1392
- 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];
1467
+ let n = f.fromHex(t), i = new r().writeVarLengthBuf(n.toBuffer()).toBuffer(), a = new e(i).toString(), o = n.getVisibleArgs(), s = Number(p.decode(o.chunks[0].buf)), c = m.isSmallIntOp(o.chunks[1].opcodenum) ? m.decodeOP_N(o.chunks[1].opcodenum) : Number(p.decode(o.chunks[1].buf)), l = [s, c];
1393
1468
  if (a == X(this.keyManager.getKey({
1394
1469
  account: 1,
1395
1470
  type: 0,
@@ -1408,7 +1483,7 @@ var je = class {
1408
1483
  type: 1
1409
1484
  };
1410
1485
  }
1411
- }, Ne = class e {
1486
+ }, We = class e {
1412
1487
  static {
1413
1488
  this.DEBOUNCE_MS = 1e3;
1414
1489
  }
@@ -1426,7 +1501,7 @@ var je = class {
1426
1501
  address: n,
1427
1502
  result: t
1428
1503
  });
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();
1504
+ }, 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
1505
  }
1431
1506
  clear() {
1432
1507
  this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.stopUpdates(), this.notify({ type: "clear_wallet" });
@@ -1572,8 +1647,8 @@ var je = class {
1572
1647
  id: -1,
1573
1648
  name: "HD Wallet",
1574
1649
  address: this.getReceiveAddress(),
1575
- balance: M(e.map((e) => e.balance)),
1576
- tokensBalance: N(e.map((e) => e.tokensBalance)),
1650
+ balance: F(e.map((e) => e.balance)),
1651
+ tokensBalance: I(e.map((e) => e.tokensBalance)),
1577
1652
  sessions: {}
1578
1653
  }
1579
1654
  });
@@ -1708,7 +1783,7 @@ var je = class {
1708
1783
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1709
1784
  let n = Array.from(t.values());
1710
1785
  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));
1786
+ let r = this.getMainAddresses(), i = F(r.map((e) => e.balance)), a = I(r.map((e) => e.tokensBalance));
1712
1787
  this.notify({
1713
1788
  type: "account_balance_updated",
1714
1789
  accountId: -1,
@@ -1869,7 +1944,7 @@ var je = class {
1869
1944
  }
1870
1945
  async recoverTokens() {
1871
1946
  let e = [];
1872
- e.push(this.assetService.syncTokens(-1, N(this.getMainAddresses().map((e) => e.tokensBalance))));
1947
+ e.push(this.assetService.syncTokens(-1, I(this.getMainAddresses().map((e) => e.tokensBalance))));
1873
1948
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1874
1949
  await Promise.all(e);
1875
1950
  }
@@ -1882,7 +1957,11 @@ var je = class {
1882
1957
  isMainAddress(e) {
1883
1958
  return e.type == 0;
1884
1959
  }
1885
- }, Pe = class e {
1960
+ };
1961
+ // src/services/market.ts
1962
+ /** Key of NEXA in the market data (`market_data_updated`'s `data`). */
1963
+ const Ge = "nexa";
1964
+ var Ke = class e {
1886
1965
  static {
1887
1966
  this.POLL_INTERVAL_MS = 12e4;
1888
1967
  }
@@ -1890,7 +1969,7 @@ var je = class {
1890
1969
  this.CURRENCY_SETTING = "market-currency";
1891
1970
  }
1892
1971
  static {
1893
- this.SUPPORTED_TOKENS = { nexacoin: "nexa" };
1972
+ this.SUPPORTED_TOKENS = { nexacoin: Ge };
1894
1973
  }
1895
1974
  constructor(e) {
1896
1975
  this.currency = "usd", this.running = !1, this.walletDb = e;
@@ -1963,6 +2042,6 @@ var je = class {
1963
2042
  }), a;
1964
2043
  }
1965
2044
  };
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 };
2045
+ export { se as AccountType, Oe as AssetService, fe as BLOCK_TIME_MINUTES, pe as CURRENCIES, ue as HD_WALLET_ID, B as KeyManager, ce as KeySpace, de as MAX_INT64, Ke as MarketService, Ge as NEXA_MARKET_ID, we as RostrumService, Ve as SessionManager, le as SessionRequestType, Ae as TransactionService, He as TransactionTransformer, W as VAULT_FIRST_BLOCK, Ce as WalletCache, Se as WalletDB, We as WalletManager, P as balanceTotal, Pe as calculateFiatValue, _e as capitalizeFirstLetter, C as currencyCodes, O as currentTimestamp, Re as encryptMnemonic, he as estimateDateByFutureBlock, k as estimateMinutesToBlock, Me as formatNexaAmount, Ne as formatNexaAmountWithTicker, $ as formatTokenAmount, je as formatTokenAmountWithTicker, Fe as generateNewMnemonic, X as generateVaultAddress, q as generateVaultConstraint, Y as generateVaultVisibleArgs, j as getAddressBuffer, H as getAssetFileUrl, V as getAssetMetadataUrl, me as getExplorerUrl, ye as getFileMediaType, be as getFileMimeType, T as getNexaTicker, J as getVaultConstraintHash, G as getVaultTemplate, K as getVaultTemplateHash, E as isGenesisHashValid, Ie as isMnemonicValid, A as isNullOrEmpty, w as isTestnet, D as isValidNexaAddress, ke as isVaultUnlocked, R as keyPathToString, Ee as parseTokenDataUrl, xe as sleep, z as stringToKeyPath, F as sumBalance, I as sumTokensBalance, N as tokenAmountToAssetAmount, ve as tokenHexToAddr, M as tokenIdToHex, Te as transformTokenIconUrl, ge as truncateStringMiddle, Be as validateAndDecryptMnemonic };
1967
2046
 
1968
2047
  //# sourceMappingURL=index.js.map