@otoplo/wallet-common 0.8.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,7 +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 _, UnitType as v, UnitUtils as y } from "libnexa-ts";
2
- 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";
3
3
  import { generateMnemonic as re, mnemonicToSeedSync as ie, validateMnemonic as ae } from "@scure/bip39";
4
- import { wordlist as x } from "@scure/bip39/wordlists/english.js";
4
+ import { wordlist as S } from "@scure/bip39/wordlists/english.js";
5
5
  import { DAppProvider as oe } from "wallet-comms-sdk";
6
6
  // src/utils/enums.ts
7
7
  let se = /* @__PURE__ */ function(e) {
@@ -12,7 +12,7 @@ let se = /* @__PURE__ */ function(e) {
12
12
  return e.SignMessage = "signMessage", e.AddToken = "addToken", e.SignTransaction = "signTransaction", e.SendTransaction = "sendTransaction", e;
13
13
  }({});
14
14
  // src/utils/common.ts
15
- const ue = -1, de = 9223372036854775807n, fe = 2, S = {
15
+ const ue = -1, de = 9223372036854775807n, fe = 2, pe = {
16
16
  usd: {
17
17
  symbol: "$",
18
18
  name: "US Dollar"
@@ -49,9 +49,9 @@ const ue = -1, de = 9223372036854775807n, fe = 2, S = {
49
49
  symbol: "¥",
50
50
  name: "Japanese Yen"
51
51
  }
52
- }, C = Object.keys(S);
52
+ }, C = Object.keys(pe);
53
53
  function w() {
54
- return s.defaultNetwork == s.testnet;
54
+ return c.defaultNetwork == c.testnet;
55
55
  }
56
56
  /** `NEXA` on mainnet, `tNEXA` on testnet. */
57
57
  function T() {
@@ -61,16 +61,16 @@ function E(e) {
61
61
  return w() ? e == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52" : e == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
62
62
  }
63
63
  function D(n, r = t.PayToScriptTemplate) {
64
- return e.isValid(n, s.defaultNetwork, r);
64
+ return e.isValid(n, c.defaultNetwork, r);
65
65
  }
66
- function pe() {
66
+ function me() {
67
67
  return `https://${w() ? "testnet-" : ""}explorer.nexa.org`;
68
68
  }
69
69
  function O() {
70
70
  return Math.floor(Date.now() / 1e3);
71
71
  }
72
72
  /** Estimated minutes until `future` block, from the block time. 0 once it's reached. */
73
- function me(e, t) {
73
+ function k(e, t) {
74
74
  return Math.max(t - e, 0) * 2;
75
75
  }
76
76
  /**
@@ -82,9 +82,9 @@ function he(e, t, n = "en-US", r = {
82
82
  day: "numeric",
83
83
  year: "numeric"
84
84
  }) {
85
- return new Date(Date.now() + me(e, t) * 6e4).toLocaleDateString(n, r);
85
+ return new Date(Date.now() + k(e, t) * 6e4).toLocaleDateString(n, r);
86
86
  }
87
- function k(e) {
87
+ function A(e) {
88
88
  return !e || e.length === 0;
89
89
  }
90
90
  function ge(e, t = 0) {
@@ -95,23 +95,23 @@ function ge(e, t = 0) {
95
95
  function _e(e) {
96
96
  return e.length === 0 ? "" : e.charAt(0).toUpperCase() + e.substring(1);
97
97
  }
98
- function A(t) {
98
+ function j(t) {
99
99
  return i.isHexa(t) ? n.hexToBuffer(t) : e.fromString(t).data;
100
100
  }
101
- function j(e) {
102
- return i.isHexa(e) ? e : n.bufferToHex(A(e));
101
+ function M(e) {
102
+ return i.isHexa(e) ? e : n.bufferToHex(j(e));
103
103
  }
104
104
  function ve(n) {
105
- return i.isHexa(n) ? new e(A(n), s.defaultNetwork, t.GroupIdAddress).toString() : n;
105
+ return i.isHexa(n) ? new e(j(n), c.defaultNetwork, t.GroupIdAddress).toString() : n;
106
106
  }
107
- function M(e) {
107
+ function N(e) {
108
108
  return e == null || e === "" ? "" : BigInt(e) <= 0n ? "0" : e.toString();
109
109
  }
110
110
  /** Confirmed plus unconfirmed, in base units. The unconfirmed part can be negative (spent, not yet confirmed). */
111
- function N(e) {
111
+ function P(e) {
112
112
  return BigInt(e.confirmed) + BigInt(e.unconfirmed);
113
113
  }
114
- function P(e) {
114
+ function F(e) {
115
115
  let t = BigInt(0), n = BigInt(0);
116
116
  return e.forEach((e) => {
117
117
  t += BigInt(e.confirmed), n += BigInt(e.unconfirmed);
@@ -120,7 +120,7 @@ function P(e) {
120
120
  unconfirmed: n.toString()
121
121
  };
122
122
  }
123
- function F(e) {
123
+ function I(e) {
124
124
  let t = {};
125
125
  return e.forEach((e) => {
126
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] = {
@@ -129,7 +129,7 @@ function F(e) {
129
129
  };
130
130
  }), t;
131
131
  }
132
- const I = {
132
+ const L = {
133
133
  ".gif": {
134
134
  media: "image",
135
135
  mime: "image/gif"
@@ -203,13 +203,13 @@ function ye(e) {
203
203
  let t = e.lastIndexOf(".");
204
204
  if (t === -1) return "unknown";
205
205
  let n = e.slice(t).toLowerCase();
206
- return I[n]?.media ?? "unknown";
206
+ return L[n]?.media ?? "unknown";
207
207
  }
208
208
  function be(e) {
209
209
  let t = e.lastIndexOf(".");
210
210
  if (t === -1) return "application/octet-stream";
211
211
  let n = e.slice(t).toLowerCase();
212
- return I[n]?.mime ?? "application/octet-stream";
212
+ return L[n]?.mime ?? "application/octet-stream";
213
213
  }
214
214
  function xe(e) {
215
215
  return new Promise((t) => setTimeout(t, e));
@@ -412,20 +412,20 @@ var Se = class {
412
412
  this.tokens.clear(), this.nfts.clear();
413
413
  }
414
414
  async getToken(e) {
415
- if (e = j(e), this.tokens.has(e)) return this.tokens.get(e);
415
+ if (e = M(e), this.tokens.has(e)) return this.tokens.get(e);
416
416
  let t = await this.walletDb.getToken(e);
417
417
  return t && this.tokens.set(e, t), t;
418
418
  }
419
419
  async getNft(e) {
420
- if (e = j(e), this.nfts.has(e)) return this.nfts.get(e);
420
+ if (e = M(e), this.nfts.has(e)) return this.nfts.get(e);
421
421
  let t = await this.walletDb.getNft(e);
422
422
  return t && this.nfts.set(e, t), t;
423
423
  }
424
424
  removeToken(e) {
425
- this.tokens.delete(j(e));
425
+ this.tokens.delete(M(e));
426
426
  }
427
427
  removeNft(e) {
428
- this.nfts.delete(j(e));
428
+ this.nfts.delete(M(e));
429
429
  }
430
430
  }, we = class e {
431
431
  constructor(e) {
@@ -626,17 +626,17 @@ var Se = class {
626
626
  }
627
627
  static getPredefinedInstances() {
628
628
  return w() ? [{
629
- scheme: b.WSS,
629
+ scheme: x.WSS,
630
630
  host: "testnet-electrum.nexa.org",
631
631
  port: 30004,
632
632
  label: "NexaOrg"
633
633
  }] : [{
634
- scheme: b.WSS,
634
+ scheme: x.WSS,
635
635
  host: "rostrum.otoplo.com",
636
636
  port: 443,
637
637
  label: "Otoplo"
638
638
  }, {
639
- scheme: b.WSS,
639
+ scheme: x.WSS,
640
640
  host: "electrum.nexa.org",
641
641
  port: 20004,
642
642
  label: "NexaOrg"
@@ -644,10 +644,10 @@ var Se = class {
644
644
  }
645
645
  };
646
646
  // src/utils/keypath.ts
647
- function L(e, t, n) {
647
+ function R(e, t, n) {
648
648
  return `${e}'/${t}/${n}`;
649
649
  }
650
- function R(e) {
650
+ function z(e) {
651
651
  let t = e.split("/");
652
652
  return {
653
653
  account: parseInt(t[0].replace("'", "")),
@@ -656,7 +656,7 @@ function R(e) {
656
656
  };
657
657
  }
658
658
  // src/services/key.ts
659
- var z = class {
659
+ var B = class {
660
660
  constructor() {
661
661
  this.accountKeys = /* @__PURE__ */ new Map(), this.walletKeys = /* @__PURE__ */ new Map();
662
662
  }
@@ -686,9 +686,9 @@ var z = class {
686
686
  }
687
687
  getKey(e) {
688
688
  if (!this.seed) throw Error("KeysManager not initialized");
689
- let t = typeof e == "string" ? e : L(e.account, e.type, e.index), n = this.walletKeys.get(t);
689
+ let t = typeof e == "string" ? e : R(e.account, e.type, e.index), n = this.walletKeys.get(t);
690
690
  if (!n) {
691
- let { account: r, type: i, index: a } = typeof e == "string" ? R(e) : e;
691
+ let { account: r, type: i, index: a } = typeof e == "string" ? z(e) : e;
692
692
  n = this.getAccountKey(r).deriveChild(i, !1).deriveChild(a, !1), this.walletKeys.set(t, n);
693
693
  }
694
694
  return n;
@@ -704,13 +704,13 @@ function Ee(e) {
704
704
  function De(e, t = "https://ipfs.nebula.markets/") {
705
705
  return e?.startsWith("ipfs://") ? t + e.substring(7) : e;
706
706
  }
707
- function B(e) {
708
- return `${H()}/metadata/${e}`;
707
+ function V(e) {
708
+ return `${U()}/metadata/${e}`;
709
709
  }
710
- function V(e, t) {
711
- return `${H()}/assets/${e}/${t}`;
710
+ function H(e, t) {
711
+ return `${U()}/assets/${e}/${t}`;
712
712
  }
713
- function H() {
713
+ function U() {
714
714
  return `https://${w() ? "testapi" : "api"}.otoplo.com`;
715
715
  }
716
716
  // src/services/asset.ts
@@ -770,7 +770,7 @@ var Oe = class {
770
770
  async syncTokens(e, t) {
771
771
  for (let n in t) {
772
772
  let r = t[n];
773
- if (r && N(r) > 0n) {
773
+ if (r && P(r) > 0n) {
774
774
  let t = await this.getAssetInfo(n);
775
775
  if (t && t.type == "token") {
776
776
  let n = {
@@ -788,7 +788,7 @@ var Oe = class {
788
788
  let n = Object.keys(t), r = await this.walletDb.getAssets(e, "nft"), i = r?.filter((e) => !n.includes(e.tokenIdHex)) ?? [];
789
789
  for (let t of i) await this.deleteNft(e, t.tokenIdHex);
790
790
  for (let [n, i] of Object.entries(t)) {
791
- let t = j(n), a = i && N(i) > 0n, o = r?.some((e) => e.tokenIdHex == t);
791
+ let t = M(n), a = i && P(i) > 0n, o = r?.some((e) => e.tokenIdHex == t);
792
792
  !a && !o || a && o || (!a && o ? await this.deleteNft(e, t) : await this.handleNftReceive(e, t, O()));
793
793
  }
794
794
  }
@@ -805,10 +805,10 @@ var Oe = class {
805
805
  await this.walletDb.deleteNft(e, t), this.walletCache.removeNft(t);
806
806
  }
807
807
  getAssetFile(e, t) {
808
- return this.performGet(V(e, t), "raw");
808
+ return this.performGet(H(e, t), "raw");
809
809
  }
810
810
  getAssetMetadata(e) {
811
- return this.performGet(B(e), "json");
811
+ return this.performGet(V(e), "json");
812
812
  }
813
813
  async performGet(e, t) {
814
814
  try {
@@ -825,27 +825,27 @@ var Oe = class {
825
825
  }
826
826
  };
827
827
  // src/utils/vault.ts
828
- const U = 274710;
829
- function W() {
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);
831
- }
828
+ const W = 274710;
832
829
  function G() {
833
- let e = W();
834
- return o.sha256ripemd160(e.toBuffer());
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);
835
831
  }
836
- function K(e) {
837
- return d.empty().add(e.toBuffer());
832
+ function K() {
833
+ let e = G();
834
+ return o.sha256ripemd160(e.toBuffer());
838
835
  }
839
836
  function q(e) {
840
- let t = K(e);
841
- return o.sha256ripemd160(t.toBuffer());
837
+ return f.empty().add(e.toBuffer());
842
838
  }
843
839
  function J(e) {
844
- return e.map((e) => e <= 16 ? p.smallInt(e) : f.encode(e));
840
+ let t = q(e);
841
+ return o.sha256ripemd160(t.toBuffer());
842
+ }
843
+ function Y(e) {
844
+ return e.map((e) => e <= 16 ? m.smallInt(e) : p.encode(e));
845
845
  }
846
- function Y(t, n) {
846
+ function X(t, n) {
847
847
  if (n.length !== 2) return;
848
- let r = G(), i = q(t), a = J(n);
848
+ let r = K(), i = J(t), a = Y(n);
849
849
  return e.fromScriptTemplate(r, i, a).toString();
850
850
  }
851
851
  /**
@@ -872,7 +872,7 @@ var Ae = class {
872
872
  };
873
873
  }
874
874
  async fetchVaultTransactions(e) {
875
- let t = await this.rostrumService.getTransactionsHistory(e, U), n = [];
875
+ let t = await this.rostrumService.getTransactionsHistory(e, W), n = [];
876
876
  for (let r of t) {
877
877
  let t = this.classifyTransaction(r.tx_hash, [e]);
878
878
  n.push(t);
@@ -899,17 +899,17 @@ var Ae = class {
899
899
  address: e.addresses[0],
900
900
  nexaAmount: e.value_satoshi.toString(),
901
901
  assetId: e.token_id_hex ?? "",
902
- assetAmount: M(e.groupQuantity)
902
+ assetAmount: N(e.groupQuantity)
903
903
  };
904
904
  t.includes(n.address) ? r.push(n) : i.push(n);
905
905
  }
906
906
  for (let e of n.vout) {
907
- if (k(e.scriptPubKey.addresses)) continue;
907
+ if (A(e.scriptPubKey.addresses)) continue;
908
908
  let n = {
909
909
  address: e.scriptPubKey.addresses[0],
910
910
  nexaAmount: e.value_satoshi.toString(),
911
911
  assetId: e.scriptPubKey.token_id_hex ?? "",
912
- assetAmount: M(e.scriptPubKey.groupQuantity)
912
+ assetAmount: N(e.scriptPubKey.groupQuantity)
913
913
  };
914
914
  t.includes(n.address) ? a.push(n) : o.push(n);
915
915
  }
@@ -941,24 +941,24 @@ var Ae = class {
941
941
  let r = {
942
942
  isConsolidate: !0,
943
943
  templateData: n
944
- }, i = new g(), a = await this.populateNexaInputsAndChange(i, e, t, r);
944
+ }, i = new _(), a = await this.populateNexaInputsAndChange(i, e, t, r);
945
945
  return this.finalizeTransaction(i, Array.from(a.values()));
946
946
  }
947
947
  prepareTransaction(n, r, i, a) {
948
948
  if (!D(n) && !D(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
949
- if (i && BigInt(r) < 1n || !i && parseInt(r) < h.DUST_AMOUNT) throw Error("The amount is too low.");
950
- if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > h.MAX_MONEY) throw Error("The amount is too high.");
951
- let o = new g();
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 _();
952
952
  if (a && o.addData(a), i) {
953
953
  if (!D(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
954
954
  if (e.getOutputType(n) === 0) throw Error("Token must be sent to script template address");
955
- o.to(n, h.DUST_AMOUNT, i, BigInt(r));
955
+ o.to(n, g.DUST_AMOUNT, i, BigInt(r));
956
956
  } else o.to(n, r);
957
957
  return o;
958
958
  }
959
959
  async populateNexaInputsAndChange(e, t, n, r) {
960
- let i = t.filter((e) => N(e.balance) > 0n);
961
- if (k(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.");
962
962
  let a = /* @__PURE__ */ new Map(), o = r.isConsolidate ? 0 : Number(e.transaction.outputs.find((e) => e.value > 0n).value);
963
963
  for (let t of i) {
964
964
  let i = await this.rostrumService.getNexaUtxos(t.address);
@@ -999,14 +999,14 @@ var Ae = class {
999
999
  }
1000
1000
  let s = {
1001
1001
  errorMsg: "Not enough Nexa balance.",
1002
- amount: y.formatNEXA(e.transaction.outputs[0].value),
1003
- fee: y.formatNEXA(e.transaction.estimateRequiredFee())
1002
+ amount: b.formatNEXA(e.transaction.outputs[0].value),
1003
+ fee: b.formatNEXA(e.transaction.estimateRequiredFee())
1004
1004
  };
1005
1005
  throw Error(JSON.stringify(s));
1006
1006
  }
1007
1007
  async populateTokenInputsAndChange(e, t, n, r, i) {
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.");
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.");
1010
1010
  let s = /* @__PURE__ */ new Map(), c = 0n;
1011
1011
  for (let t of o) {
1012
1012
  let a = await this.rostrumService.getTokenUtxos(t.address, r);
@@ -1024,7 +1024,7 @@ var Ae = class {
1024
1024
  if (c > 9223372036854775807n) throw Error("Token inputs exceeded max amount. Consider sending in small chunks");
1025
1025
  if (e.transaction.inputs.length > this.MAX_INPUTS_OUTPUTS) throw Error("Too many inputs. Consider consolidating transactions or reduce the send amount.");
1026
1026
  if (c == i) return s;
1027
- 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;
1028
1028
  }
1029
1029
  }
1030
1030
  throw Error("Not enough token balance");
@@ -1044,10 +1044,10 @@ var Ae = class {
1044
1044
  };
1045
1045
  // src/utils/amount.ts
1046
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;
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
1051
  }
1052
1052
  /**
1053
1053
  * An amount in base units (token units, satoshis) for display, without trailing zeros:
@@ -1056,25 +1056,25 @@ function Z(e, t) {
1056
1056
  * Decimals beyond `maxDecimals` are cut off in bigint, so a balance never shows more than it holds
1057
1057
  * (`0.999999` → `0.99999`, not `1`). A non-zero amount that would show as 0 becomes `<0.00001`.
1058
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)));
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
1062
  }
1063
1063
  /**
1064
1064
  * A token amount with its ticker, e.g. `1,500.25 USDT`.
1065
1065
  * Tokens without a ticker (it's optional in the token's genesis) show the amount alone.
1066
1066
  */
1067
1067
  function je(e, t, n, r = {}) {
1068
- let i = Q(e, t, r);
1068
+ let i = $(e, t, r);
1069
1069
  return n ? `${i} ${n}` : i;
1070
1070
  }
1071
1071
  /** Satoshis as a NEXA amount: `1,234,567.5`. Negative amounts keep their minus sign. Always exact (see above). */
1072
1072
  function Me(e, t = {}) {
1073
- return Q(e, v.NEXA, t);
1073
+ return $(e, y.NEXA, t);
1074
1074
  }
1075
1075
  /** Satoshis as a NEXA amount with the ticker: `1,234,567.5 NEXA` (`tNEXA` on testnet). */
1076
1076
  function Ne(e, t = {}) {
1077
- return je(e, v.NEXA, T(), t);
1077
+ return je(e, y.NEXA, T(), t);
1078
1078
  }
1079
1079
  /**
1080
1080
  * Fiat value of an amount in base units (satoshis, token units), e.g. `$1,234.56`.
@@ -1082,18 +1082,18 @@ function Ne(e, t = {}) {
1082
1082
  * Exact to the cent below ~$10 trillion.
1083
1083
  */
1084
1084
  function Pe(e, t, n, r, i = "en-US") {
1085
- let a = Z(i, {
1085
+ let a = Q(i, {
1086
1086
  style: "currency",
1087
1087
  currency: r
1088
- }), o = Number(y.formatUnits(e, t)) * n, s = 10 ** -(a.resolvedOptions().maximumFractionDigits ?? 2);
1088
+ }), o = Number(b.formatUnits(e, t)) * n, s = 10 ** -(a.resolvedOptions().maximumFractionDigits ?? 2);
1089
1089
  return o !== 0 && Math.abs(o) < s / 2 ? `${o < 0 ? "-" : ""}<${a.format(s)}` : a.format(o);
1090
1090
  }
1091
1091
  // src/utils/seed.ts
1092
1092
  function Fe(e = 12) {
1093
- return re(x, e === 24 ? 256 : 128);
1093
+ return re(S, e === 24 ? 256 : 128);
1094
1094
  }
1095
1095
  function Ie(e) {
1096
- return ae(e, x);
1096
+ return ae(e, S);
1097
1097
  }
1098
1098
  async function Le(e, t) {
1099
1099
  let n = await crypto.subtle.importKey("raw", new Uint8Array(e), "PBKDF2", !1, ["deriveKey"]);
@@ -1273,7 +1273,7 @@ var Ve = class {
1273
1273
  address: e.address,
1274
1274
  pubkey: this.keyManager.getKey(t).publicKey.toString(),
1275
1275
  blockchain: "nexa",
1276
- network: s.defaultNetwork.name,
1276
+ network: c.defaultNetwork.name,
1277
1277
  capabilities: {
1278
1278
  addToken: !0,
1279
1279
  sendTransaction: !0,
@@ -1297,16 +1297,14 @@ var Ve = class {
1297
1297
  address: t.address,
1298
1298
  privateKey: this.keyManager.getKey(t.keyPath).privateKey,
1299
1299
  txDetails: {
1300
- tx: new h(e),
1300
+ tx: new g(e),
1301
1301
  send: [],
1302
1302
  receive: []
1303
1303
  },
1304
1304
  myInputs: /* @__PURE__ */ new Map(),
1305
1305
  myOutputs: /* @__PURE__ */ new Map(),
1306
1306
  involvedAssets: /* @__PURE__ */ new Set(),
1307
- inputsToSign: /* @__PURE__ */ new Set(),
1308
- coveredOutputs: /* @__PURE__ */ new Set(),
1309
- allMyOutputsCovered: !1
1307
+ inputsToSign: /* @__PURE__ */ new Set()
1310
1308
  };
1311
1309
  } catch {
1312
1310
  throw Error("Invalid transaction format.");
@@ -1323,26 +1321,39 @@ var Ve = class {
1323
1321
  async processInput(e, t) {
1324
1322
  let r = e.txDetails.tx.inputs[t], i = await this.rostrumService.getUtxo(n.bufferToHex(r.outpoint));
1325
1323
  if (i.status == "spent") throw Error("Input UTXO is already spent.");
1326
- 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) {
1327
1325
  let n = i.token_id_hex || "NEXA";
1328
1326
  e.myInputs.set(t, {
1329
1327
  address: e.address,
1330
1328
  nexaAmount: i.amount.toString(),
1331
1329
  assetId: n,
1332
- assetAmount: M(i.group_quantity) || i.amount.toString()
1330
+ assetAmount: N(i.group_quantity) || i.amount.toString()
1333
1331
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1334
1332
  }
1335
- 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));
1336
1347
  }
1337
1348
  processOutputs(e) {
1338
1349
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1339
1350
  let n = e.txDetails.tx.outputs[t].toObject();
1340
1351
  if (n.address !== e.address) continue;
1341
- let r = n.groupId ? j(n.groupId) : "NEXA", i = {
1352
+ let r = n.groupId ? M(n.groupId) : "NEXA", i = {
1342
1353
  address: n.address,
1343
1354
  nexaAmount: n.value.toString(),
1344
1355
  assetId: r,
1345
- assetAmount: M(n.groupAmount) || n.value.toString()
1356
+ assetAmount: N(n.groupAmount) || n.value.toString()
1346
1357
  };
1347
1358
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1348
1359
  }
@@ -1352,46 +1363,49 @@ var Ve = class {
1352
1363
  for (let t of e.inputsToSign) {
1353
1364
  let n = e.txDetails.tx.inputs[t], r = this.validateAndGetSubscript(n);
1354
1365
  if (n.scriptSig.isEmpty()) {
1355
- e.allMyOutputsCovered = !0;
1356
- let i = _.sign(e.txDetails.tx, t, m.ALL, r, e.privateKey).toTxFormat(), a = d.empty().add(e.privateKey.publicKey.toBuffer());
1357
- 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));
1358
1368
  } else {
1359
- let i = n.scriptSig.findPlaceholder(), a = n.scriptSig.chunks[i].buf.subarray(64), o = m.fromBuffer(a);
1360
- this.processSignatureCoverage(e, o);
1361
- let s = _.sign(e.txDetails.tx, t, o, r, e.privateKey).toTxFormat(a);
1362
- 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));
1363
1373
  }
1364
1374
  }
1365
- if (!e.allMyOutputsCovered) throw Error("Some of interested outputs are not covered by signatures.");
1366
1375
  }
1367
1376
  validateAndGetSubscript(e) {
1368
1377
  if (e.output.scriptPubKey.isPublicKeyTemplateOut()) {
1369
- 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);
1370
1379
  throw Error("Invalid input script type.");
1371
1380
  }
1372
1381
  if (e.output.scriptPubKey.isScriptTemplateOut()) {
1373
1382
  if (!e.scriptSig.isScriptTemplateIn()) throw Error("Unsupported input script type.");
1374
1383
  let t = e.output.scriptPubKey.getTemplateHash(), r = e.scriptSig.chunks[0].buf;
1375
- 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);
1376
1385
  throw Error("Invalid input script template.");
1377
1386
  }
1378
1387
  throw Error("Unsupported prevout script type.");
1379
1388
  }
1380
- processSignatureCoverage(e, t) {
1381
- if (!e.allMyOutputsCovered) {
1382
- if (t.outType == u.TWO) e.coveredOutputs.add(t.outData[0]), e.coveredOutputs.add(t.outData[1]), this.checkSignatureCoverage(e);
1383
- else if (t.outType == u.FIRSTN) {
1384
- let n = t.outData[0];
1385
- for (let t = 0; t < n; t++) e.coveredOutputs.add(t);
1386
- this.checkSignatureCoverage(e);
1387
- } 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.");
1388
1401
  }
1389
1402
  }
1390
- checkSignatureCoverage(e) {
1391
- if (!e.allMyOutputsCovered) {
1392
- for (let t of e.myOutputs.keys()) if (!e.coveredOutputs.has(t)) return;
1393
- e.allMyOutputsCovered = !0;
1394
- }
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.");
1395
1409
  }
1396
1410
  async processAssetMovements(e) {
1397
1411
  let t = Array.from(e.myInputs.values()), n = Array.from(e.myOutputs.values()), r = [];
@@ -1415,12 +1429,12 @@ var Ve = class {
1415
1429
  async discoverWalletIndex(e, t) {
1416
1430
  let n = 0, r = -1, i = [];
1417
1431
  for (;;) {
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;
1432
+ let a = await Promise.all(Array.from({ length: B.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1433
+ if (a.some((e) => e)) r = n, i = a, n += B.GAP_LIMIT;
1420
1434
  else break;
1421
1435
  }
1422
1436
  if (r === -1) return -1;
1423
- for (let e = z.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1437
+ for (let e = B.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1424
1438
  return r;
1425
1439
  }
1426
1440
  async discoverVaults() {
@@ -1435,14 +1449,14 @@ var Ve = class {
1435
1449
  * Indexes are checked in parallel batches, stopping after VAULT_GAP_LIMIT consecutive indexes with no scripts.
1436
1450
  */
1437
1451
  async checkForVaults() {
1438
- let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(G()), r = 0;
1452
+ let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(K()), r = 0;
1439
1453
  for (let i = 0; r < 5; i += 5) {
1440
1454
  let a = await Promise.all(Array.from({ length: 5 }, (e, r) => {
1441
1455
  let a = this.keyManager.getKey({
1442
1456
  account: 1,
1443
1457
  type: 0,
1444
1458
  index: i + r
1445
- }), o = n.bufferToHex(q(a.publicKey));
1459
+ }), o = n.bufferToHex(J(a.publicKey));
1446
1460
  return this.rostrumService.listTemplateScripts(t, o);
1447
1461
  }));
1448
1462
  for (let t of a) t.length === 0 ? r++ : (r = 0, t.forEach((t) => e.add(t.scriptpubkey)));
@@ -1450,8 +1464,8 @@ var Ve = class {
1450
1464
  return e;
1451
1465
  }
1452
1466
  parseVaultDetails(t) {
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];
1454
- if (a == Y(this.keyManager.getKey({
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];
1468
+ if (a == X(this.keyManager.getKey({
1455
1469
  account: 1,
1456
1470
  type: 0,
1457
1471
  index: c
@@ -1520,14 +1534,14 @@ var Ve = class {
1520
1534
  let t = this.accounts.get(e);
1521
1535
  return [{
1522
1536
  address: t.address,
1523
- keyPath: L(2, 0, t.id),
1537
+ keyPath: R(2, 0, t.id),
1524
1538
  balance: t.balance,
1525
1539
  tokensBalance: t.tokensBalance
1526
1540
  }];
1527
1541
  }
1528
1542
  return this.getMainAddresses().filter((e) => e.used).map((e) => ({
1529
1543
  address: e.address,
1530
- keyPath: L(0, e.space, e.idx),
1544
+ keyPath: R(0, e.space, e.idx),
1531
1545
  balance: e.balance,
1532
1546
  tokensBalance: e.tokensBalance
1533
1547
  }));
@@ -1596,7 +1610,7 @@ var Ve = class {
1596
1610
  n,
1597
1611
  r
1598
1612
  ]);
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();
1613
+ 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();
1600
1614
  }
1601
1615
  async loadWallet() {
1602
1616
  this.receiveAddresses = await this.walletDb.getReceiveAddresses(), this.changeAddresses = await this.walletDb.getChangeAddresses();
@@ -1633,8 +1647,8 @@ var Ve = class {
1633
1647
  id: -1,
1634
1648
  name: "HD Wallet",
1635
1649
  address: this.getReceiveAddress(),
1636
- balance: P(e.map((e) => e.balance)),
1637
- tokensBalance: F(e.map((e) => e.tokensBalance)),
1650
+ balance: F(e.map((e) => e.balance)),
1651
+ tokensBalance: I(e.map((e) => e.tokensBalance)),
1638
1652
  sessions: {}
1639
1653
  }
1640
1654
  });
@@ -1769,7 +1783,7 @@ var Ve = class {
1769
1783
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1770
1784
  let n = Array.from(t.values());
1771
1785
  await this.checkGapLimit(0), await this.checkGapLimit(1);
1772
- let r = this.getMainAddresses(), i = P(r.map((e) => e.balance)), a = F(r.map((e) => e.tokensBalance));
1786
+ let r = this.getMainAddresses(), i = F(r.map((e) => e.balance)), a = I(r.map((e) => e.tokensBalance));
1773
1787
  this.notify({
1774
1788
  type: "account_balance_updated",
1775
1789
  accountId: -1,
@@ -1831,8 +1845,8 @@ var Ve = class {
1831
1845
  }
1832
1846
  async checkGapLimit(e) {
1833
1847
  let t = e === 0 ? this.receiveAddresses : this.changeAddresses, n = e === 0 ? "Receive" : "Change", r = t.filter((e) => !e.used).length;
1834
- if (r < z.GAP_LIMIT) {
1835
- let i = z.GAP_LIMIT - r, a = t[t.length - 1].idx;
1848
+ if (r < B.GAP_LIMIT) {
1849
+ let i = B.GAP_LIMIT - r, a = t[t.length - 1].idx;
1836
1850
  console.log(`Deriving ${i} more ${n} addresses...`);
1837
1851
  let o = this.deriveAddresses(e, a + 1, i);
1838
1852
  e === 0 ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
@@ -1930,7 +1944,7 @@ var Ve = class {
1930
1944
  }
1931
1945
  async recoverTokens() {
1932
1946
  let e = [];
1933
- e.push(this.assetService.syncTokens(-1, F(this.getMainAddresses().map((e) => e.tokensBalance))));
1947
+ e.push(this.assetService.syncTokens(-1, I(this.getMainAddresses().map((e) => e.tokensBalance))));
1934
1948
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1935
1949
  await Promise.all(e);
1936
1950
  }
@@ -1946,8 +1960,8 @@ var Ve = class {
1946
1960
  };
1947
1961
  // src/services/market.ts
1948
1962
  /** Key of NEXA in the market data (`market_data_updated`'s `data`). */
1949
- const $ = "nexa";
1950
- var Ge = class e {
1963
+ const Ge = "nexa";
1964
+ var Ke = class e {
1951
1965
  static {
1952
1966
  this.POLL_INTERVAL_MS = 12e4;
1953
1967
  }
@@ -1955,7 +1969,7 @@ var Ge = class e {
1955
1969
  this.CURRENCY_SETTING = "market-currency";
1956
1970
  }
1957
1971
  static {
1958
- this.SUPPORTED_TOKENS = { nexacoin: $ };
1972
+ this.SUPPORTED_TOKENS = { nexacoin: Ge };
1959
1973
  }
1960
1974
  constructor(e) {
1961
1975
  this.currency = "usd", this.running = !1, this.walletDb = e;
@@ -2028,6 +2042,6 @@ var Ge = class e {
2028
2042
  }), a;
2029
2043
  }
2030
2044
  };
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 };
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 };
2032
2046
 
2033
2047
  //# sourceMappingURL=index.js.map