@otoplo/wallet-common 0.8.2 → 0.9.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,18 +1,186 @@
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
- import { generateMnemonic as re, mnemonicToSeedSync as ie, validateMnemonic as ae } from "@scure/bip39";
4
- import { wordlist as S } from "@scure/bip39/wordlists/english.js";
5
- import { DAppProvider as oe } from "wallet-comms-sdk";
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 te, UnitType as v, UnitUtils as y } from "libnexa-ts";
2
+ import { ConnectionStatus as ne, ElectrumClient as re, TransportScheme as b } from "@otoplo/electrum-client";
3
+ import { generateMnemonic as ie, mnemonicToSeedSync as ae, validateMnemonic as oe } from "@scure/bip39";
4
+ import { wordlist as x } from "@scure/bip39/wordlists/english.js";
5
+ import { DAppProvider as se } from "wallet-comms-sdk";
6
6
  // src/utils/enums.ts
7
- let se = /* @__PURE__ */ function(e) {
7
+ let ce = /* @__PURE__ */ function(e) {
8
8
  return e[e.MAIN = 0] = "MAIN", e[e.VAULT = 1] = "VAULT", e[e.DAPP = 2] = "DAPP", e;
9
- }({}), ce = /* @__PURE__ */ function(e) {
10
- return e[e.RECEIVE = 0] = "RECEIVE", e[e.CHANGE = 1] = "CHANGE", e;
11
9
  }({}), le = /* @__PURE__ */ function(e) {
10
+ return e[e.RECEIVE = 0] = "RECEIVE", e[e.CHANGE = 1] = "CHANGE", e;
11
+ }({}), ue = /* @__PURE__ */ function(e) {
12
12
  return e.SignMessage = "signMessage", e.AddToken = "addToken", e.SignTransaction = "signTransaction", e.SendTransaction = "sendTransaction", e;
13
13
  }({});
14
+ // src/persistence/wallet-db.ts
15
+ var de = class {
16
+ constructor(e) {
17
+ this.repository = e;
18
+ }
19
+ initSchema() {
20
+ return this.repository.initSchema();
21
+ }
22
+ clearData() {
23
+ return this.repository.clearData();
24
+ }
25
+ upsertTransaction(e) {
26
+ let t = {
27
+ ...e,
28
+ othersOutputs: JSON.stringify(e.othersOutputs),
29
+ myOutputs: JSON.stringify(e.myOutputs),
30
+ myInputs: JSON.stringify(e.myInputs)
31
+ };
32
+ return this.repository.upsertTransaction(t);
33
+ }
34
+ upsertAssetTransaction(e) {
35
+ return this.repository.upsertAssetTransaction(e);
36
+ }
37
+ async getTransactions(e, t) {
38
+ return (await this.repository.getTransactions(e, t)).map((e) => ({
39
+ ...e,
40
+ othersOutputs: JSON.parse(e.othersOutputs),
41
+ myOutputs: JSON.parse(e.myOutputs),
42
+ myInputs: JSON.parse(e.myInputs)
43
+ }));
44
+ }
45
+ async getPageTransactions(e, t, n, r) {
46
+ return (await this.repository.getPageTransactions(e, t, n, r)).map((e) => ({
47
+ ...e,
48
+ othersOutputs: JSON.parse(e.othersOutputs),
49
+ myOutputs: JSON.parse(e.myOutputs),
50
+ myInputs: JSON.parse(e.myInputs)
51
+ }));
52
+ }
53
+ countTransactions(e, t) {
54
+ return this.repository.countTransactions(e, t);
55
+ }
56
+ clearTransactions(e) {
57
+ return this.repository.clearTransactions(e);
58
+ }
59
+ getAssets(e, t) {
60
+ return this.repository.getAssets(e, t);
61
+ }
62
+ saveAsset(e) {
63
+ return this.repository.upsertAsset(e);
64
+ }
65
+ saveAssetMetadata(e) {
66
+ return this.repository.upsertAssetMetadata(e);
67
+ }
68
+ getAssetMetadata(e) {
69
+ return this.repository.getAssetMetadata(e);
70
+ }
71
+ getPageAssets(e, t, n, r) {
72
+ return this.repository.getPageAssets(e, t, n, r);
73
+ }
74
+ countAssets(e, t) {
75
+ return this.repository.countAssets(e, t);
76
+ }
77
+ async isAssetHeld(e) {
78
+ return await this.repository.countAssetsById(e) > 0;
79
+ }
80
+ /** Removes the asset from the account, and its metadata once no account holds it. */
81
+ async deleteAsset(e, t) {
82
+ await this.repository.deleteAsset(e, t), await this.isAssetHeld(t) || await this.repository.deleteAssetMetadata(t);
83
+ }
84
+ saveAccount(e) {
85
+ let t = {
86
+ id: e.id,
87
+ address: e.address,
88
+ name: e.name,
89
+ height: e.height,
90
+ hidden: e.hidden,
91
+ statusHash: e.statusHash,
92
+ balance: JSON.stringify(e.balance),
93
+ tokensBalance: JSON.stringify(e.tokensBalance)
94
+ };
95
+ return this.repository.upsertAccount(t);
96
+ }
97
+ async getAccounts() {
98
+ return (await this.repository.getAccounts()).map((e) => ({
99
+ ...e,
100
+ type: 2,
101
+ balance: JSON.parse(e.balance),
102
+ tokensBalance: JSON.parse(e.tokensBalance)
103
+ }));
104
+ }
105
+ countAccounts() {
106
+ return this.repository.countAccounts();
107
+ }
108
+ updateAccountName(e, t) {
109
+ return this.repository.updateAccountName(e, t);
110
+ }
111
+ saveSession(e) {
112
+ return this.repository.upsertSession(e);
113
+ }
114
+ getAccountSessions(e) {
115
+ return this.repository.getSessionsByAccount(e);
116
+ }
117
+ removeSession(e) {
118
+ return this.repository.deleteSession(e);
119
+ }
120
+ saveAddress(e) {
121
+ let t = {
122
+ address: e.address,
123
+ idx: e.idx,
124
+ space: e.space,
125
+ height: e.height,
126
+ statusHash: e.statusHash,
127
+ used: e.used,
128
+ balance: JSON.stringify(e.balance),
129
+ tokensBalance: JSON.stringify(e.tokensBalance)
130
+ };
131
+ return this.repository.upsertAddress(t);
132
+ }
133
+ async getReceiveAddresses() {
134
+ return (await this.repository.getReceiveAddresses()).map((e) => ({
135
+ ...e,
136
+ type: 0,
137
+ balance: JSON.parse(e.balance),
138
+ tokensBalance: JSON.parse(e.tokensBalance)
139
+ }));
140
+ }
141
+ async getChangeAddresses() {
142
+ return (await this.repository.getChangeAddresses()).map((e) => ({
143
+ ...e,
144
+ type: 0,
145
+ balance: JSON.parse(e.balance),
146
+ tokensBalance: JSON.parse(e.tokensBalance)
147
+ }));
148
+ }
149
+ countAddresses() {
150
+ return this.repository.countAddresses();
151
+ }
152
+ async getVaults() {
153
+ return (await this.repository.getVaults()).map((e) => ({
154
+ ...e,
155
+ type: 1,
156
+ balance: JSON.parse(e.balance),
157
+ tokensBalance: JSON.parse(e.tokensBalance)
158
+ }));
159
+ }
160
+ saveVault(e) {
161
+ let t = {
162
+ address: e.address,
163
+ idx: e.idx,
164
+ block: e.block,
165
+ height: e.height,
166
+ statusHash: e.statusHash,
167
+ balance: JSON.stringify(e.balance),
168
+ tokensBalance: JSON.stringify(e.tokensBalance)
169
+ };
170
+ return this.repository.upsertVault(t);
171
+ }
172
+ getSetting(e) {
173
+ return this.repository.getSetting(e);
174
+ }
175
+ saveSetting(e, t) {
176
+ return this.repository.saveSetting(e, t);
177
+ }
178
+ removeSetting(e) {
179
+ return this.repository.deleteSetting(e);
180
+ }
181
+ };
14
182
  // src/utils/common.ts
15
- const ue = -1, de = 9223372036854775807n, fe = 2, pe = {
183
+ const fe = -1, pe = 9223372036854775807n, me = 2, S = {
16
184
  usd: {
17
185
  symbol: "$",
18
186
  name: "US Dollar"
@@ -49,7 +217,7 @@ const ue = -1, de = 9223372036854775807n, fe = 2, pe = {
49
217
  symbol: "¥",
50
218
  name: "Japanese Yen"
51
219
  }
52
- }, C = Object.keys(pe);
220
+ }, C = Object.keys(S);
53
221
  function w() {
54
222
  return c.defaultNetwork == c.testnet;
55
223
  }
@@ -57,61 +225,61 @@ function w() {
57
225
  function T() {
58
226
  return w() ? "tNEXA" : "NEXA";
59
227
  }
60
- function E(e) {
228
+ function he(e) {
61
229
  return w() ? e == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52" : e == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
62
230
  }
63
- function D(n, r = t.PayToScriptTemplate) {
231
+ function E(n, r = t.PayToScriptTemplate) {
64
232
  return e.isValid(n, c.defaultNetwork, r);
65
233
  }
66
- function me() {
234
+ function ge() {
67
235
  return `https://${w() ? "testnet-" : ""}explorer.nexa.org`;
68
236
  }
69
- function O() {
237
+ function D() {
70
238
  return Math.floor(Date.now() / 1e3);
71
239
  }
72
240
  /** Estimated minutes until `future` block, from the block time. 0 once it's reached. */
73
- function k(e, t) {
241
+ function O(e, t) {
74
242
  return Math.max(t - e, 0) * 2;
75
243
  }
76
244
  /**
77
245
  * Estimated date of a future block, e.g. `Mar 14, 2027`.
78
246
  * `locale` and `options` go to `toLocaleDateString` — defaults to `en-US` like `calculateFiatValue`.
79
247
  */
80
- function he(e, t, n = "en-US", r = {
248
+ function _e(e, t, n = "en-US", r = {
81
249
  month: "short",
82
250
  day: "numeric",
83
251
  year: "numeric"
84
252
  }) {
85
- return new Date(Date.now() + k(e, t) * 6e4).toLocaleDateString(n, r);
253
+ return new Date(Date.now() + O(e, t) * 6e4).toLocaleDateString(n, r);
86
254
  }
87
- function A(e) {
255
+ function k(e) {
88
256
  return !e || e.length === 0;
89
257
  }
90
- function ge(e, t = 0) {
258
+ function ve(e, t = 0) {
91
259
  if (!e || e.length <= t) return e || "";
92
260
  let n = Math.floor((t - 3) / 2), r = e.slice(0, n), i = e.slice(e.length - n);
93
261
  return r + "..." + i;
94
262
  }
95
- function _e(e) {
263
+ function ye(e) {
96
264
  return e.length === 0 ? "" : e.charAt(0).toUpperCase() + e.substring(1);
97
265
  }
98
- function j(t) {
266
+ function A(t) {
99
267
  return i.isHexa(t) ? n.hexToBuffer(t) : e.fromString(t).data;
100
268
  }
101
- function M(e) {
102
- return i.isHexa(e) ? e : n.bufferToHex(j(e));
269
+ function j(e) {
270
+ return i.isHexa(e) ? e : n.bufferToHex(A(e));
103
271
  }
104
- function ve(n) {
105
- return i.isHexa(n) ? new e(j(n), c.defaultNetwork, t.GroupIdAddress).toString() : n;
272
+ function be(n) {
273
+ return i.isHexa(n) ? new e(A(n), c.defaultNetwork, t.GroupIdAddress).toString() : n;
106
274
  }
107
- function N(e) {
275
+ function M(e) {
108
276
  return e == null || e === "" ? "" : BigInt(e) <= 0n ? "0" : e.toString();
109
277
  }
110
278
  /** Confirmed plus unconfirmed, in base units. The unconfirmed part can be negative (spent, not yet confirmed). */
111
- function P(e) {
279
+ function N(e) {
112
280
  return BigInt(e.confirmed) + BigInt(e.unconfirmed);
113
281
  }
114
- function F(e) {
282
+ function P(e) {
115
283
  let t = BigInt(0), n = BigInt(0);
116
284
  return e.forEach((e) => {
117
285
  t += BigInt(e.confirmed), n += BigInt(e.unconfirmed);
@@ -120,7 +288,7 @@ function F(e) {
120
288
  unconfirmed: n.toString()
121
289
  };
122
290
  }
123
- function I(e) {
291
+ function F(e) {
124
292
  let t = {};
125
293
  return e.forEach((e) => {
126
294
  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 +297,7 @@ function I(e) {
129
297
  };
130
298
  }), t;
131
299
  }
132
- const L = {
300
+ const I = {
133
301
  ".gif": {
134
302
  media: "image",
135
303
  mime: "image/gif"
@@ -199,235 +367,37 @@ const L = {
199
367
  mime: "audio/mp4"
200
368
  }
201
369
  };
202
- function ye(e) {
370
+ function xe(e) {
203
371
  let t = e.lastIndexOf(".");
204
372
  if (t === -1) return "unknown";
205
373
  let n = e.slice(t).toLowerCase();
206
- return L[n]?.media ?? "unknown";
374
+ return I[n]?.media ?? "unknown";
207
375
  }
208
- function be(e) {
376
+ function Se(e) {
209
377
  let t = e.lastIndexOf(".");
210
378
  if (t === -1) return "application/octet-stream";
211
379
  let n = e.slice(t).toLowerCase();
212
- return L[n]?.mime ?? "application/octet-stream";
380
+ return I[n]?.mime ?? "application/octet-stream";
213
381
  }
214
- function xe(e) {
382
+ function Ce(e) {
215
383
  return new Promise((t) => setTimeout(t, e));
216
384
  }
217
- // src/persistence/wallet-db.ts
218
- var Se = class {
219
- constructor(e) {
220
- this.repository = e;
221
- }
222
- initSchema() {
223
- return this.repository.initSchema();
224
- }
225
- clearData() {
226
- return this.repository.clearData();
227
- }
228
- upsertTransaction(e) {
229
- let t = {
230
- ...e,
231
- othersOutputs: JSON.stringify(e.othersOutputs),
232
- myOutputs: JSON.stringify(e.myOutputs),
233
- myInputs: JSON.stringify(e.myInputs)
234
- };
235
- return this.repository.upsertTransaction(t);
236
- }
237
- upsertAssetTransaction(e) {
238
- return this.repository.upsertAssetTransaction(e);
239
- }
240
- async getTransactions(e, t) {
241
- return (await this.repository.getTransactions(e, t)).map((e) => ({
242
- ...e,
243
- othersOutputs: JSON.parse(e.othersOutputs),
244
- myOutputs: JSON.parse(e.myOutputs),
245
- myInputs: JSON.parse(e.myInputs)
246
- }));
247
- }
248
- async getPageTransactions(e, t, n, r) {
249
- return (await this.repository.getPageTransactions(e, t, n, r)).map((e) => ({
250
- ...e,
251
- othersOutputs: JSON.parse(e.othersOutputs),
252
- myOutputs: JSON.parse(e.myOutputs),
253
- myInputs: JSON.parse(e.myInputs)
254
- }));
255
- }
256
- countTransactions(e, t) {
257
- return this.repository.countTransactions(e, t);
258
- }
259
- clearTransactions(e) {
260
- return this.repository.clearTransactions(e);
261
- }
262
- async saveToken(e, t) {
263
- let n = {
264
- accountId: e,
265
- tokenIdHex: t.tokenIdHex,
266
- type: "token",
267
- addedTime: O()
268
- };
269
- await this.repository.upsertToken(t), await this.saveAsset(n);
270
- }
271
- getTokens(e, t, n) {
272
- return this.repository.getTokens(e, t, n);
273
- }
274
- getToken(e) {
275
- return this.repository.getToken(e);
276
- }
277
- async deleteToken(e, t) {
278
- await this.removeAsset(e, t), await this.repository.countAssetsById(t) == 0 && await this.repository.deleteToken(t);
279
- }
280
- async saveNft(e, t, n) {
281
- let r = {
282
- accountId: e,
283
- tokenIdHex: t.tokenIdHex,
284
- type: "nft",
285
- addedTime: n
286
- };
287
- await this.repository.upsertNft(t), await this.saveAsset(r);
288
- }
289
- getNfts(e, t, n) {
290
- return this.repository.getNfts(e, t, n);
291
- }
292
- getNft(e) {
293
- return this.repository.getNft(e);
294
- }
295
- async deleteNft(e, t) {
296
- await this.removeAsset(e, t), await this.repository.countAssetsById(t) == 0 && await this.repository.deleteNft(t);
297
- }
298
- countNfts(e) {
299
- return this.repository.countNfts(e);
300
- }
301
- getAssets(e, t) {
302
- return this.repository.getAssets(e, t);
303
- }
304
- saveAsset(e) {
305
- return this.repository.upsertAsset(e);
306
- }
307
- removeAsset(e, t) {
308
- return this.repository.deleteAsset(e, t);
309
- }
310
- saveAccount(e) {
311
- let t = {
312
- id: e.id,
313
- address: e.address,
314
- name: e.name,
315
- height: e.height,
316
- hidden: e.hidden,
317
- statusHash: e.statusHash,
318
- balance: JSON.stringify(e.balance),
319
- tokensBalance: JSON.stringify(e.tokensBalance)
320
- };
321
- return this.repository.upsertAccount(t);
322
- }
323
- async getAccounts() {
324
- return (await this.repository.getAccounts()).map((e) => ({
325
- ...e,
326
- type: 2,
327
- balance: JSON.parse(e.balance),
328
- tokensBalance: JSON.parse(e.tokensBalance)
329
- }));
330
- }
331
- countAccounts() {
332
- return this.repository.countAccounts();
333
- }
334
- updateAccountName(e, t) {
335
- return this.repository.updateAccountName(e, t);
336
- }
337
- saveSession(e) {
338
- return this.repository.upsertSession(e);
339
- }
340
- getAccountSessions(e) {
341
- return this.repository.getSessionsByAccount(e);
342
- }
343
- removeSession(e) {
344
- return this.repository.deleteSession(e);
345
- }
346
- saveAddress(e) {
347
- let t = {
348
- address: e.address,
349
- idx: e.idx,
350
- space: e.space,
351
- height: e.height,
352
- statusHash: e.statusHash,
353
- used: e.used,
354
- balance: JSON.stringify(e.balance),
355
- tokensBalance: JSON.stringify(e.tokensBalance)
356
- };
357
- return this.repository.upsertAddress(t);
358
- }
359
- async getReceiveAddresses() {
360
- return (await this.repository.getReceiveAddresses()).map((e) => ({
361
- ...e,
362
- type: 0,
363
- balance: JSON.parse(e.balance),
364
- tokensBalance: JSON.parse(e.tokensBalance)
365
- }));
366
- }
367
- async getChangeAddresses() {
368
- return (await this.repository.getChangeAddresses()).map((e) => ({
369
- ...e,
370
- type: 0,
371
- balance: JSON.parse(e.balance),
372
- tokensBalance: JSON.parse(e.tokensBalance)
373
- }));
374
- }
375
- countAddresses() {
376
- return this.repository.countAddresses();
377
- }
378
- async getVaults() {
379
- return (await this.repository.getVaults()).map((e) => ({
380
- ...e,
381
- type: 1,
382
- balance: JSON.parse(e.balance),
383
- tokensBalance: JSON.parse(e.tokensBalance)
384
- }));
385
- }
386
- saveVault(e) {
387
- let t = {
388
- address: e.address,
389
- idx: e.idx,
390
- block: e.block,
391
- height: e.height,
392
- statusHash: e.statusHash,
393
- balance: JSON.stringify(e.balance),
394
- tokensBalance: JSON.stringify(e.tokensBalance)
395
- };
396
- return this.repository.upsertVault(t);
397
- }
398
- getSetting(e) {
399
- return this.repository.getSetting(e);
400
- }
401
- saveSetting(e, t) {
402
- return this.repository.saveSetting(e, t);
403
- }
404
- removeSetting(e) {
405
- return this.repository.deleteSetting(e);
406
- }
407
- }, Ce = class {
408
- constructor(e) {
409
- this.tokens = /* @__PURE__ */ new Map(), this.nfts = /* @__PURE__ */ new Map(), this.walletDb = e;
385
+ // src/services/cache.ts
386
+ /** Asset metadata in memory, for every asset looked up while the wallet is unlocked. */
387
+ var we = class {
388
+ constructor() {
389
+ this.assets = /* @__PURE__ */ new Map();
410
390
  }
411
391
  clear() {
412
- this.tokens.clear(), this.nfts.clear();
413
- }
414
- async getToken(e) {
415
- if (e = M(e), this.tokens.has(e)) return this.tokens.get(e);
416
- let t = await this.walletDb.getToken(e);
417
- return t && this.tokens.set(e, t), t;
392
+ this.assets.clear();
418
393
  }
419
- async getNft(e) {
420
- if (e = M(e), this.nfts.has(e)) return this.nfts.get(e);
421
- let t = await this.walletDb.getNft(e);
422
- return t && this.nfts.set(e, t), t;
394
+ getAsset(e) {
395
+ return this.assets.get(j(e));
423
396
  }
424
- removeToken(e) {
425
- this.tokens.delete(M(e));
397
+ setAsset(e, t) {
398
+ this.assets.set(j(e), t);
426
399
  }
427
- removeNft(e) {
428
- this.nfts.delete(M(e));
429
- }
430
- }, we = class e {
400
+ }, Te = class e {
431
401
  constructor(e) {
432
402
  this.walletDb = e;
433
403
  }
@@ -438,7 +408,7 @@ var Se = class {
438
408
  this.updateCallback?.(e);
439
409
  }
440
410
  isConnected() {
441
- return this.client?.status === te.CONNECTED;
411
+ return this.client?.status === ne.CONNECTED;
442
412
  }
443
413
  getFeatures() {
444
414
  return this.execute("server.features");
@@ -533,7 +503,7 @@ var Se = class {
533
503
  }
534
504
  async connect(e) {
535
505
  try {
536
- await this.disconnect(), e ||= await this.getCurrentInstance(), this.params = e, this.client = new ne({
506
+ await this.disconnect(), e ||= await this.getCurrentInstance(), this.params = e, this.client = new re({
537
507
  application: "com.otoplo.wallet",
538
508
  version: "1.4.3",
539
509
  host: e.host,
@@ -568,7 +538,7 @@ var Se = class {
568
538
  async check() {
569
539
  try {
570
540
  let e = await this.getFeatures();
571
- if (!E(e.genesis_hash)) return { status: "wrong_network" };
541
+ if (!he(e.genesis_hash)) return { status: "wrong_network" };
572
542
  if (!e.script_index) return { status: "unsupported" };
573
543
  let t = await this.getLatency();
574
544
  return t ? {
@@ -626,17 +596,17 @@ var Se = class {
626
596
  }
627
597
  static getPredefinedInstances() {
628
598
  return w() ? [{
629
- scheme: x.WSS,
599
+ scheme: b.WSS,
630
600
  host: "testnet-electrum.nexa.org",
631
601
  port: 30004,
632
602
  label: "NexaOrg"
633
603
  }] : [{
634
- scheme: x.WSS,
604
+ scheme: b.WSS,
635
605
  host: "rostrum.otoplo.com",
636
606
  port: 443,
637
607
  label: "Otoplo"
638
608
  }, {
639
- scheme: x.WSS,
609
+ scheme: b.WSS,
640
610
  host: "electrum.nexa.org",
641
611
  port: 20004,
642
612
  label: "NexaOrg"
@@ -644,10 +614,10 @@ var Se = class {
644
614
  }
645
615
  };
646
616
  // src/utils/keypath.ts
647
- function R(e, t, n) {
617
+ function L(e, t, n) {
648
618
  return `${e}'/${t}/${n}`;
649
619
  }
650
- function z(e) {
620
+ function R(e) {
651
621
  let t = e.split("/");
652
622
  return {
653
623
  account: parseInt(t[0].replace("'", "")),
@@ -656,7 +626,7 @@ function z(e) {
656
626
  };
657
627
  }
658
628
  // src/services/key.ts
659
- var B = class {
629
+ var z = class {
660
630
  constructor() {
661
631
  this.accountKeys = /* @__PURE__ */ new Map(), this.walletKeys = /* @__PURE__ */ new Map();
662
632
  }
@@ -664,7 +634,7 @@ var B = class {
664
634
  this.GAP_LIMIT = 20;
665
635
  }
666
636
  init(e) {
667
- this.seed = typeof e == "string" ? ie(e) : e, this.reset();
637
+ this.seed = typeof e == "string" ? ae(e) : e, this.reset();
668
638
  }
669
639
  reset() {
670
640
  if (!this.seed) throw Error("KeysManager not initialized");
@@ -686,129 +656,141 @@ var B = class {
686
656
  }
687
657
  getKey(e) {
688
658
  if (!this.seed) throw Error("KeysManager not initialized");
689
- let t = typeof e == "string" ? e : R(e.account, e.type, e.index), n = this.walletKeys.get(t);
659
+ let t = typeof e == "string" ? e : L(e.account, e.type, e.index), n = this.walletKeys.get(t);
690
660
  if (!n) {
691
- let { account: r, type: i, index: a } = typeof e == "string" ? z(e) : e;
661
+ let { account: r, type: i, index: a } = typeof e == "string" ? R(e) : e;
692
662
  n = this.getAccountKey(r).deriveChild(i, !1).deriveChild(a, !1), this.walletKeys.set(t, n);
693
663
  }
694
664
  return n;
695
665
  }
696
666
  };
697
667
  // src/utils/asset.ts
698
- function Te(e, t) {
668
+ function Ee(e, t) {
699
669
  return e && typeof e == "string" ? e.startsWith("http") ? e.replace("http://", "https://") : e.startsWith("ipfs://") ? e : `${new URL(t).origin}${e}` : "";
700
670
  }
701
- function Ee(e) {
702
- return e ? De(e) : null;
671
+ function De(e) {
672
+ return e ? Oe(e) : null;
703
673
  }
704
- function De(e, t = "https://ipfs.nebula.markets/") {
674
+ function Oe(e, t = "https://ipfs.nebula.markets/") {
705
675
  return e?.startsWith("ipfs://") ? t + e.substring(7) : e;
706
676
  }
707
- function V(e) {
708
- return `${U()}/metadata/${e}`;
677
+ function B(e) {
678
+ return `${H()}/metadata/${e}`;
709
679
  }
710
- function H(e, t) {
711
- return `${U()}/assets/${e}/${t}`;
680
+ function V(e, t) {
681
+ return `${H()}/assets/${e}/${t}`;
712
682
  }
713
- function U() {
683
+ function H() {
714
684
  return `https://${w() ? "testapi" : "api"}.otoplo.com`;
715
685
  }
716
686
  // src/services/asset.ts
717
- var Oe = class {
687
+ /**
688
+ * Bump when stored metadata must be fetched again, e.g. the assets API response changed.
689
+ * Rows of an older version are refetched when next used, with no DB migration.
690
+ */
691
+ const ke = 1;
692
+ var Ae = class {
718
693
  constructor(e, t) {
719
694
  this.walletDb = e, this.walletCache = t;
720
695
  }
696
+ /**
697
+ * Metadata of any asset, held or not: memory, then DB, then API.
698
+ * Metadata of an older version is refetched, and kept if the fetch fails.
699
+ */
721
700
  async getAssetInfo(e) {
701
+ let t = j(e);
722
702
  try {
723
- let t = await this.walletCache.getToken(e);
724
- if (t) return {
725
- type: "token",
726
- parent: t.parent,
727
- token: t.token,
728
- tokenIdHex: t.tokenIdHex,
729
- data: {
730
- name: t.name,
731
- ticker: t.ticker,
732
- decimals: t.decimals,
733
- iconUrl: t.iconUrl
734
- }
735
- };
736
- let n = await this.walletCache.getNft(e);
737
- return n ? {
738
- type: "nft",
739
- parent: n.parent,
740
- token: n.token,
741
- tokenIdHex: n.tokenIdHex,
742
- data: {
743
- name: n.name,
744
- series: n.series,
745
- collection: n.collection,
746
- author: n.author,
747
- public: n.public,
748
- front: n.front,
749
- back: n.back,
750
- thumb: n.thumb
751
- }
752
- } : await this.getAssetMetadata(e);
703
+ let e = this.walletCache.getAsset(t) ?? await this.loadFromDb(t);
704
+ return e?.version === 1 ? e.info : await this.fetchMetadata(t) ?? e?.info;
753
705
  } catch (e) {
754
706
  console.error(e);
755
707
  return;
756
708
  }
757
709
  }
710
+ /**
711
+ * One page of the account's assets, straight from the DB.
712
+ * Rows of an older version are returned as they are and refetched in the background,
713
+ * so the next load shows the new metadata.
714
+ */
715
+ async getAssets(e, t, n, r) {
716
+ return (await this.walletDb.getPageAssets(e, t, n, r)).map((e) => {
717
+ let t = e.tokenIdHex, n = U(e.data);
718
+ return n && !this.walletCache.getAsset(t) && this.walletCache.setAsset(t, {
719
+ info: n,
720
+ version: e.version
721
+ }), n && e.version === 1 || this.fetchMetadata(t), {
722
+ tokenIdHex: t,
723
+ type: e.type,
724
+ addedTime: e.addedTime,
725
+ info: n
726
+ };
727
+ });
728
+ }
729
+ countAssets(e, t) {
730
+ return this.walletDb.countAssets(e, t);
731
+ }
758
732
  async handleNftReceive(e, t, n) {
759
733
  let r = await this.getAssetInfo(t);
760
- if (r && r.type == "nft") {
761
- let t = {
762
- token: r.token,
763
- tokenIdHex: r.tokenIdHex,
764
- parent: r.parent,
765
- ...r.data
766
- };
767
- await this.saveNft(e, t, n);
768
- }
734
+ r && r.type == "nft" && await this.saveAsset(e, r, n);
769
735
  }
770
736
  async syncTokens(e, t) {
771
737
  for (let n in t) {
772
738
  let r = t[n];
773
- if (r && P(r) > 0n) {
739
+ if (r && N(r) > 0n) {
774
740
  let t = await this.getAssetInfo(n);
775
- if (t && t.type == "token") {
776
- let n = {
777
- token: t.token,
778
- tokenIdHex: t.tokenIdHex,
779
- parent: t.parent,
780
- ...t.data
781
- };
782
- await this.saveToken(e, n);
783
- }
741
+ t && t.type == "token" && await this.saveAsset(e, t);
784
742
  }
785
743
  }
786
744
  }
787
745
  async syncNfts(e, t) {
788
746
  let n = Object.keys(t), r = await this.walletDb.getAssets(e, "nft"), i = r?.filter((e) => !n.includes(e.tokenIdHex)) ?? [];
789
- for (let t of i) await this.deleteNft(e, t.tokenIdHex);
747
+ for (let t of i) await this.deleteAsset(e, t.tokenIdHex);
790
748
  for (let [n, i] of Object.entries(t)) {
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()));
749
+ let t = i && N(i) > 0n, a = r?.some((e) => e.tokenIdHex == n);
750
+ !t && !a || t && a || (!t && a ? await this.deleteAsset(e, n) : await this.handleNftReceive(e, n, D()));
793
751
  }
794
752
  }
795
- async saveToken(e, t) {
796
- await this.walletDb.saveToken(e, t);
797
- }
798
- async deleteToken(e, t) {
799
- await this.walletDb.deleteToken(e, t), this.walletCache.removeToken(t);
800
- }
801
- async saveNft(e, t, n) {
802
- await this.walletDb.saveNft(e, t, n);
753
+ /** Adds the asset to the account and stores its metadata. */
754
+ async saveAsset(e, t, n = D()) {
755
+ let r = j(t.tokenIdHex), i = this.walletCache.getAsset(r)?.version ?? 1;
756
+ await this.walletDb.saveAssetMetadata(W(r, {
757
+ info: t,
758
+ version: i
759
+ })), await this.walletDb.saveAsset({
760
+ accountId: e,
761
+ tokenIdHex: r,
762
+ type: t.type,
763
+ addedTime: n
764
+ });
803
765
  }
804
- async deleteNft(e, t) {
805
- await this.walletDb.deleteNft(e, t), this.walletCache.removeNft(t);
766
+ /** Removes the asset from the account; its metadata too once no account holds it. */
767
+ deleteAsset(e, t) {
768
+ return this.walletDb.deleteAsset(e, j(t));
806
769
  }
807
770
  getAssetFile(e, t) {
808
- return this.performGet(H(e, t), "raw");
771
+ return this.performGet(V(e, t), "raw");
809
772
  }
810
- getAssetMetadata(e) {
811
- return this.performGet(V(e), "json");
773
+ async loadFromDb(e) {
774
+ let t = await this.walletDb.getAssetMetadata(e), n = t ? U(t.data) : void 0;
775
+ if (!t || !n) return;
776
+ let r = {
777
+ info: n,
778
+ version: t.version
779
+ };
780
+ return this.walletCache.setAsset(e, r), r;
781
+ }
782
+ /** Fetches from the API into memory, and into the DB if the asset is held. Never throws. */
783
+ async fetchMetadata(e) {
784
+ try {
785
+ let t = await this.performGet(B(e), "json"), n = {
786
+ info: t,
787
+ version: 1
788
+ };
789
+ return this.walletCache.setAsset(e, n), await this.walletDb.isAssetHeld(e) && await this.walletDb.saveAssetMetadata(W(e, n)), t;
790
+ } catch (e) {
791
+ console.error(e);
792
+ return;
793
+ }
812
794
  }
813
795
  async performGet(e, t) {
814
796
  try {
@@ -824,39 +806,54 @@ var Oe = class {
824
806
  }
825
807
  }
826
808
  };
809
+ function U(e) {
810
+ try {
811
+ return JSON.parse(e);
812
+ } catch {
813
+ return;
814
+ }
815
+ }
816
+ function W(e, t) {
817
+ return {
818
+ tokenIdHex: e,
819
+ name: t.info.data.name,
820
+ data: JSON.stringify(t.info),
821
+ version: t.version
822
+ };
823
+ }
827
824
  // src/utils/vault.ts
828
- const W = 274710;
829
- function G() {
825
+ const G = 274710;
826
+ function K() {
830
827
  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);
831
828
  }
832
- function K() {
833
- let e = G();
829
+ function q() {
830
+ let e = K();
834
831
  return o.sha256ripemd160(e.toBuffer());
835
832
  }
836
- function q(e) {
833
+ function J(e) {
837
834
  return f.empty().add(e.toBuffer());
838
835
  }
839
- function J(e) {
840
- let t = q(e);
836
+ function Y(e) {
837
+ let t = J(e);
841
838
  return o.sha256ripemd160(t.toBuffer());
842
839
  }
843
- function Y(e) {
840
+ function X(e) {
844
841
  return e.map((e) => e <= 16 ? m.smallInt(e) : p.encode(e));
845
842
  }
846
- function X(t, n) {
843
+ function Z(t, n) {
847
844
  if (n.length !== 2) return;
848
- let r = K(), i = J(t), a = Y(n);
845
+ let r = q(), i = Y(t), a = X(n);
849
846
  return e.fromScriptTemplate(r, i, a).toString();
850
847
  }
851
848
  /**
852
849
  * A vault is spendable once the chain reached its lock block: a transaction with that lock time
853
850
  * can go into the next block (`OP_CHECKLOCKTIMEVERIFY` in the template). `false` while the height is unknown (0).
854
851
  */
855
- function ke(e, t) {
852
+ function je(e, t) {
856
853
  return t > 0 && t >= e;
857
854
  }
858
855
  // src/services/transaction.ts
859
- var Ae = class {
856
+ var Me = class {
860
857
  constructor(e, t, n) {
861
858
  this.MAX_INPUTS_OUTPUTS = 250, this.rostrumService = e, this.keyManager = t, this.walletDb = n;
862
859
  }
@@ -872,7 +869,7 @@ var Ae = class {
872
869
  };
873
870
  }
874
871
  async fetchVaultTransactions(e) {
875
- let t = await this.rostrumService.getTransactionsHistory(e, W), n = [];
872
+ let t = await this.rostrumService.getTransactionsHistory(e, G), n = [];
876
873
  for (let r of t) {
877
874
  let t = this.classifyTransaction(r.tx_hash, [e]);
878
875
  n.push(t);
@@ -899,17 +896,17 @@ var Ae = class {
899
896
  address: e.addresses[0],
900
897
  nexaAmount: e.value_satoshi.toString(),
901
898
  assetId: e.token_id_hex ?? "",
902
- assetAmount: N(e.groupQuantity)
899
+ assetAmount: M(e.groupQuantity)
903
900
  };
904
901
  t.includes(n.address) ? r.push(n) : i.push(n);
905
902
  }
906
903
  for (let e of n.vout) {
907
- if (A(e.scriptPubKey.addresses)) continue;
904
+ if (k(e.scriptPubKey.addresses)) continue;
908
905
  let n = {
909
906
  address: e.scriptPubKey.addresses[0],
910
907
  nexaAmount: e.value_satoshi.toString(),
911
908
  assetId: e.scriptPubKey.token_id_hex ?? "",
912
- assetAmount: N(e.scriptPubKey.groupQuantity)
909
+ assetAmount: M(e.scriptPubKey.groupQuantity)
913
910
  };
914
911
  t.includes(n.address) ? a.push(n) : o.push(n);
915
912
  }
@@ -920,7 +917,7 @@ var Ae = class {
920
917
  accountId: 0,
921
918
  txId: n.txid,
922
919
  txIdem: n.txidem,
923
- time: c ? n.time : O(),
920
+ time: c ? n.time : D(),
924
921
  height: c ? n.height : 0,
925
922
  type: s,
926
923
  fee: n.fee_satoshi.toString(),
@@ -945,20 +942,20 @@ var Ae = class {
945
942
  return this.finalizeTransaction(i, Array.from(a.values()));
946
943
  }
947
944
  prepareTransaction(n, r, i, a) {
948
- if (!D(n) && !D(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
945
+ if (!E(n) && !E(n, t.PayToPublicKeyHash)) throw Error("Invalid Address.");
949
946
  if (i && BigInt(r) < 1n || !i && parseInt(r) < g.DUST_AMOUNT) throw Error("The amount is too low.");
950
947
  if (i && BigInt(r) > 9223372036854775807n || !i && parseInt(r) > g.MAX_MONEY) throw Error("The amount is too high.");
951
948
  let o = new _();
952
949
  if (a && o.addData(a), i) {
953
- if (!D(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
950
+ if (!E(i, t.GroupIdAddress)) throw Error("Invalid Token ID");
954
951
  if (e.getOutputType(n) === 0) throw Error("Token must be sent to script template address");
955
952
  o.to(n, g.DUST_AMOUNT, i, BigInt(r));
956
953
  } else o.to(n, r);
957
954
  return o;
958
955
  }
959
956
  async populateNexaInputsAndChange(e, t, n, r) {
960
- let i = t.filter((e) => P(e.balance) > 0n);
961
- if (A(i)) throw Error("Not enough Nexa balance.");
957
+ let i = t.filter((e) => N(e.balance) > 0n);
958
+ if (k(i)) throw Error("Not enough Nexa balance.");
962
959
  let a = /* @__PURE__ */ new Map(), o = r.isConsolidate ? 0 : Number(e.transaction.outputs.find((e) => e.value > 0n).value);
963
960
  for (let t of i) {
964
961
  let i = await this.rostrumService.getNexaUtxos(t.address);
@@ -999,14 +996,14 @@ var Ae = class {
999
996
  }
1000
997
  let s = {
1001
998
  errorMsg: "Not enough Nexa balance.",
1002
- amount: b.formatNEXA(e.transaction.outputs[0].value),
1003
- fee: b.formatNEXA(e.transaction.estimateRequiredFee())
999
+ amount: y.formatNEXA(e.transaction.outputs[0].value),
1000
+ fee: y.formatNEXA(e.transaction.estimateRequiredFee())
1004
1001
  };
1005
1002
  throw Error(JSON.stringify(s));
1006
1003
  }
1007
1004
  async populateTokenInputsAndChange(e, t, n, r, i) {
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.");
1005
+ let a = j(r), o = t.filter((e) => Object.keys(e.tokensBalance).includes(a));
1006
+ if (k(o)) throw Error("Not enough token balance.");
1010
1007
  let s = /* @__PURE__ */ new Map(), c = 0n;
1011
1008
  for (let t of o) {
1012
1009
  let a = await this.rostrumService.getTokenUtxos(t.address, r);
@@ -1044,10 +1041,10 @@ var Ae = class {
1044
1041
  };
1045
1042
  // src/utils/amount.ts
1046
1043
  /** 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;
1044
+ const Q = /* @__PURE__ */ new Map();
1045
+ function Ne(e, t) {
1046
+ let n = `${e}|${JSON.stringify(t)}`, r = Q.get(n);
1047
+ return r || (r = new Intl.NumberFormat(e, t), Q.set(n, r)), r;
1051
1048
  }
1052
1049
  /**
1053
1050
  * An amount in base units (token units, satoshis) for display, without trailing zeros:
@@ -1057,45 +1054,45 @@ function Q(e, t) {
1057
1054
  * (`0.999999` → `0.99999`, not `1`). A non-zero amount that would show as 0 becomes `<0.00001`.
1058
1055
  */
1059
1056
  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)));
1057
+ let i = BigInt(e), a = Math.min(t, n), o = i / 10n ** BigInt(t - a), s = Ne(r, { maximumFractionDigits: a });
1058
+ return o === 0n && i !== 0n ? `${i < 0n ? "-" : ""}<${s.format(10 ** -a)}` : s.format(Number(y.formatUnits(o, a)));
1062
1059
  }
1063
1060
  /**
1064
1061
  * A token amount with its ticker, e.g. `1,500.25 USDT`.
1065
1062
  * Tokens without a ticker (it's optional in the token's genesis) show the amount alone.
1066
1063
  */
1067
- function je(e, t, n, r = {}) {
1064
+ function Pe(e, t, n, r = {}) {
1068
1065
  let i = $(e, t, r);
1069
1066
  return n ? `${i} ${n}` : i;
1070
1067
  }
1071
1068
  /** 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);
1069
+ function Fe(e, t = {}) {
1070
+ return $(e, v.NEXA, t);
1074
1071
  }
1075
1072
  /** 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);
1073
+ function Ie(e, t = {}) {
1074
+ return Pe(e, v.NEXA, T(), t);
1078
1075
  }
1079
1076
  /**
1080
1077
  * Fiat value of an amount in base units (satoshis, token units), e.g. `$1,234.56`.
1081
1078
  * A non-zero value that would round to zero shows as below the currency's smallest unit: `<$0.01`, `<¥1`.
1082
1079
  * Exact to the cent below ~$10 trillion.
1083
1080
  */
1084
- function Pe(e, t, n, r, i = "en-US") {
1085
- let a = Q(i, {
1081
+ function Le(e, t, n, r, i = "en-US") {
1082
+ let a = Ne(i, {
1086
1083
  style: "currency",
1087
1084
  currency: r
1088
- }), o = Number(b.formatUnits(e, t)) * n, s = 10 ** -(a.resolvedOptions().maximumFractionDigits ?? 2);
1085
+ }), o = Number(y.formatUnits(e, t)) * n, s = 10 ** -(a.resolvedOptions().maximumFractionDigits ?? 2);
1089
1086
  return o !== 0 && Math.abs(o) < s / 2 ? `${o < 0 ? "-" : ""}<${a.format(s)}` : a.format(o);
1090
1087
  }
1091
1088
  // src/utils/seed.ts
1092
- function Fe(e = 12) {
1093
- return re(S, e === 24 ? 256 : 128);
1089
+ function Re(e = 12) {
1090
+ return ie(x, e === 24 ? 256 : 128);
1094
1091
  }
1095
- function Ie(e) {
1096
- return ae(e, S);
1092
+ function ze(e) {
1093
+ return oe(e, x);
1097
1094
  }
1098
- async function Le(e, t) {
1095
+ async function Be(e, t) {
1099
1096
  let n = await crypto.subtle.importKey("raw", new Uint8Array(e), "PBKDF2", !1, ["deriveKey"]);
1100
1097
  return crypto.subtle.deriveKey({
1101
1098
  name: "PBKDF2",
@@ -1107,8 +1104,8 @@ async function Le(e, t) {
1107
1104
  length: 256
1108
1105
  }, !1, ["encrypt", "decrypt"]);
1109
1106
  }
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({
1107
+ async function Ve(e, t) {
1108
+ let r = n.utf8ToBuffer(t), i = n.getRandomBuffer(16), a = n.getRandomBuffer(12), o = n.utf8ToBuffer(e), s = await Be(r, i), c = await crypto.subtle.encrypt({
1112
1109
  name: "AES-GCM",
1113
1110
  iv: new Uint8Array(a)
1114
1111
  }, s, new Uint8Array(o)), l = n.concat([
@@ -1118,18 +1115,18 @@ async function Re(e, t) {
1118
1115
  ]);
1119
1116
  return n.bufferToBase64(l);
1120
1117
  }
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({
1118
+ async function He(e, t) {
1119
+ 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 Be(r, a), l = await crypto.subtle.decrypt({
1123
1120
  name: "AES-GCM",
1124
1121
  iv: o
1125
1122
  }, c, s);
1126
1123
  return n.bufferToUtf8(new Uint8Array(l));
1127
1124
  }
1128
- async function Be(e, t) {
1125
+ async function Ue(e, t) {
1129
1126
  try {
1130
1127
  if (e) {
1131
- let n = await ze(e, t);
1132
- if (n && Ie(n)) return n;
1128
+ let n = await He(e, t);
1129
+ if (n && ze(n)) return n;
1133
1130
  }
1134
1131
  return !1;
1135
1132
  } catch {
@@ -1137,7 +1134,7 @@ async function Be(e, t) {
1137
1134
  }
1138
1135
  }
1139
1136
  // src/services/session.ts
1140
- var Ve = class {
1137
+ var We = class {
1141
1138
  constructor(e, t) {
1142
1139
  this.walletDb = e, this.keyManager = t, this.providers = /* @__PURE__ */ new Map(), this.handlers = /* @__PURE__ */ new Map(), this.removeOnClose = !0;
1143
1140
  }
@@ -1178,7 +1175,7 @@ var Ve = class {
1178
1175
  if (n?.has(e.sessionId)) return;
1179
1176
  let r;
1180
1177
  try {
1181
- r = new oe(e.uri);
1178
+ r = new se(e.uri);
1182
1179
  let n = r.getSessionInfo();
1183
1180
  await r.connect(3e3);
1184
1181
  let i = await r.getAppInfo(2e3);
@@ -1283,7 +1280,7 @@ var Ve = class {
1283
1280
  };
1284
1281
  });
1285
1282
  }
1286
- }, He = class {
1283
+ }, Ge = class {
1287
1284
  constructor(e, t, n) {
1288
1285
  this.rostrumService = e, this.keyManager = t, this.assetService = n;
1289
1286
  }
@@ -1327,7 +1324,7 @@ var Ve = class {
1327
1324
  address: e.address,
1328
1325
  nexaAmount: i.amount.toString(),
1329
1326
  assetId: n,
1330
- assetAmount: N(i.group_quantity) || i.amount.toString()
1327
+ assetAmount: M(i.group_quantity) || i.amount.toString()
1331
1328
  }), e.involvedAssets.add(n), r.scriptSig.isEmpty() && e.inputsToSign.add(t);
1332
1329
  }
1333
1330
  if (r.scriptSig.findPlaceholder() > 0) {
@@ -1349,11 +1346,11 @@ var Ve = class {
1349
1346
  for (let t = 0; t < e.txDetails.tx.outputs.length; t++) {
1350
1347
  let n = e.txDetails.tx.outputs[t].toObject();
1351
1348
  if (n.address !== e.address) continue;
1352
- let r = n.groupId ? M(n.groupId) : "NEXA", i = {
1349
+ let r = n.groupId ? j(n.groupId) : "NEXA", i = {
1353
1350
  address: n.address,
1354
1351
  nexaAmount: n.value.toString(),
1355
1352
  assetId: r,
1356
- assetAmount: N(n.groupAmount) || n.value.toString()
1353
+ assetAmount: M(n.groupAmount) || n.value.toString()
1357
1354
  };
1358
1355
  e.involvedAssets.add(r), e.myOutputs.set(t, i);
1359
1356
  }
@@ -1363,12 +1360,12 @@ var Ve = class {
1363
1360
  for (let t of e.inputsToSign) {
1364
1361
  let n = e.txDetails.tx.inputs[t], r = this.validateAndGetSubscript(n);
1365
1362
  if (n.scriptSig.isEmpty()) {
1366
- let i = v.sign(e.txDetails.tx, t, h.ALL, r, e.privateKey).toTxFormat(), a = f.empty().add(e.privateKey.publicKey.toBuffer());
1363
+ let i = te.sign(e.txDetails.tx, t, h.ALL, r, e.privateKey).toTxFormat(), a = f.empty().add(e.privateKey.publicKey.toBuffer());
1367
1364
  n.scriptSig = ee.buildScriptTemplateIn(void 0, a, f.empty().add(i));
1368
1365
  } else {
1369
1366
  let i = n.scriptSig.findPlaceholder(), a = n.scriptSig.chunks[i].buf.subarray(64), o = h.fromBuffer(a);
1370
1367
  this.validateSigHashType(o, t), this.validateOutputsCoverage(e, o);
1371
- let s = v.sign(e.txDetails.tx, t, o, r, e.privateKey).toTxFormat(a);
1368
+ let s = te.sign(e.txDetails.tx, t, o, r, e.privateKey).toTxFormat(a);
1372
1369
  n.scriptSig.replaceChunk(i, f.empty().add(s));
1373
1370
  }
1374
1371
  }
@@ -1422,19 +1419,19 @@ var Ve = class {
1422
1419
  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);
1423
1420
  }
1424
1421
  }
1425
- }, Ue = class {
1422
+ }, Ke = class {
1426
1423
  constructor(e, t) {
1427
1424
  this.rostrumService = e, this.keyManager = t;
1428
1425
  }
1429
1426
  async discoverWalletIndex(e, t) {
1430
1427
  let n = 0, r = -1, i = [];
1431
1428
  for (;;) {
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;
1429
+ let a = await Promise.all(Array.from({ length: z.GAP_LIMIT }, (r, i) => this.rostrumService.isAddressUsed(this.keyManager.deriveAddress(e, t, n + i))));
1430
+ if (a.some((e) => e)) r = n, i = a, n += z.GAP_LIMIT;
1434
1431
  else break;
1435
1432
  }
1436
1433
  if (r === -1) return -1;
1437
- for (let e = B.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1434
+ for (let e = z.GAP_LIMIT - 1; e >= 0; e--) if (i[e]) return r + e;
1438
1435
  return r;
1439
1436
  }
1440
1437
  async discoverVaults() {
@@ -1449,14 +1446,14 @@ var Ve = class {
1449
1446
  * Indexes are checked in parallel batches, stopping after VAULT_GAP_LIMIT consecutive indexes with no scripts.
1450
1447
  */
1451
1448
  async checkForVaults() {
1452
- let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(K()), r = 0;
1449
+ let e = /* @__PURE__ */ new Set(), t = n.bufferToHex(q()), r = 0;
1453
1450
  for (let i = 0; r < 5; i += 5) {
1454
1451
  let a = await Promise.all(Array.from({ length: 5 }, (e, r) => {
1455
1452
  let a = this.keyManager.getKey({
1456
1453
  account: 1,
1457
1454
  type: 0,
1458
1455
  index: i + r
1459
- }), o = n.bufferToHex(J(a.publicKey));
1456
+ }), o = n.bufferToHex(Y(a.publicKey));
1460
1457
  return this.rostrumService.listTemplateScripts(t, o);
1461
1458
  }));
1462
1459
  for (let t of a) t.length === 0 ? r++ : (r = 0, t.forEach((t) => e.add(t.scriptpubkey)));
@@ -1465,7 +1462,7 @@ var Ve = class {
1465
1462
  }
1466
1463
  parseVaultDetails(t) {
1467
1464
  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({
1465
+ if (a == Z(this.keyManager.getKey({
1469
1466
  account: 1,
1470
1467
  type: 0,
1471
1468
  index: c
@@ -1483,7 +1480,7 @@ var Ve = class {
1483
1480
  type: 1
1484
1481
  };
1485
1482
  }
1486
- }, We = class e {
1483
+ }, qe = class e {
1487
1484
  static {
1488
1485
  this.DEBOUNCE_MS = 1e3;
1489
1486
  }
@@ -1501,7 +1498,7 @@ var Ve = class {
1501
1498
  address: n,
1502
1499
  result: t
1503
1500
  });
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();
1501
+ }, this.discoveryService = new Ke(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();
1505
1502
  }
1506
1503
  clear() {
1507
1504
  this.accounts.clear(), this.accountsAddressToId.clear(), this.receiveAddresses = [], this.changeAddresses = [], this.vaults.clear(), this.stopUpdates(), this.notify({ type: "clear_wallet" });
@@ -1534,14 +1531,14 @@ var Ve = class {
1534
1531
  let t = this.accounts.get(e);
1535
1532
  return [{
1536
1533
  address: t.address,
1537
- keyPath: R(2, 0, t.id),
1534
+ keyPath: L(2, 0, t.id),
1538
1535
  balance: t.balance,
1539
1536
  tokensBalance: t.tokensBalance
1540
1537
  }];
1541
1538
  }
1542
1539
  return this.getMainAddresses().filter((e) => e.used).map((e) => ({
1543
1540
  address: e.address,
1544
- keyPath: R(0, e.space, e.idx),
1541
+ keyPath: L(0, e.space, e.idx),
1545
1542
  balance: e.balance,
1546
1543
  tokensBalance: e.tokensBalance
1547
1544
  }));
@@ -1613,7 +1610,7 @@ var Ve = class {
1613
1610
  n,
1614
1611
  r
1615
1612
  ]);
1616
- 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();
1613
+ 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();
1617
1614
  }
1618
1615
  async loadWallet() {
1619
1616
  this.receiveAddresses = await this.walletDb.getReceiveAddresses(), this.changeAddresses = await this.walletDb.getChangeAddresses();
@@ -1650,8 +1647,8 @@ var Ve = class {
1650
1647
  id: -1,
1651
1648
  name: "HD Wallet",
1652
1649
  address: this.getReceiveAddress(),
1653
- balance: F(e.map((e) => e.balance)),
1654
- tokensBalance: I(e.map((e) => e.tokensBalance)),
1650
+ balance: P(e.map((e) => e.balance)),
1651
+ tokensBalance: F(e.map((e) => e.tokensBalance)),
1655
1652
  hasActivity: this.hasActivity(-1),
1656
1653
  sessions: {}
1657
1654
  }
@@ -1788,7 +1785,7 @@ var Ve = class {
1788
1785
  for (let { txs: n } of e) for (let e of n) t.set(e.tx_hash, e);
1789
1786
  let n = Array.from(t.values());
1790
1787
  await this.checkGapLimit(0), await this.checkGapLimit(1);
1791
- let r = this.getMainAddresses(), i = F(r.map((e) => e.balance)), a = I(r.map((e) => e.tokensBalance));
1788
+ let r = this.getMainAddresses(), i = P(r.map((e) => e.balance)), a = F(r.map((e) => e.tokensBalance));
1792
1789
  this.notify({
1793
1790
  type: "account_balance_updated",
1794
1791
  accountId: -1,
@@ -1852,8 +1849,8 @@ var Ve = class {
1852
1849
  }
1853
1850
  async checkGapLimit(e) {
1854
1851
  let t = e === 0 ? this.receiveAddresses : this.changeAddresses, n = e === 0 ? "Receive" : "Change", r = t.filter((e) => !e.used).length;
1855
- if (r < B.GAP_LIMIT) {
1856
- let i = B.GAP_LIMIT - r, a = t[t.length - 1].idx;
1852
+ if (r < z.GAP_LIMIT) {
1853
+ let i = z.GAP_LIMIT - r, a = t[t.length - 1].idx;
1857
1854
  console.log(`Deriving ${i} more ${n} addresses...`);
1858
1855
  let o = this.deriveAddresses(e, a + 1, i);
1859
1856
  e === 0 ? this.receiveAddresses.push(...o) : this.changeAddresses.push(...o), await this.saveAddresses(o), await this.subscribeAddresses(o);
@@ -1952,7 +1949,7 @@ var Ve = class {
1952
1949
  }
1953
1950
  async recoverTokens() {
1954
1951
  let e = [];
1955
- e.push(this.assetService.syncTokens(-1, I(this.getMainAddresses().map((e) => e.tokensBalance))));
1952
+ e.push(this.assetService.syncTokens(-1, F(this.getMainAddresses().map((e) => e.tokensBalance))));
1956
1953
  for (let t of this.accounts.values()) e.push(this.assetService.syncTokens(t.id, t.tokensBalance));
1957
1954
  await Promise.all(e);
1958
1955
  }
@@ -1968,8 +1965,8 @@ var Ve = class {
1968
1965
  };
1969
1966
  // src/services/market.ts
1970
1967
  /** Key of NEXA in the market data (`market_data_updated`'s `data`). */
1971
- const Ge = "nexa";
1972
- var Ke = class e {
1968
+ const Je = "nexa";
1969
+ var Ye = class e {
1973
1970
  static {
1974
1971
  this.POLL_INTERVAL_MS = 12e4;
1975
1972
  }
@@ -1977,7 +1974,7 @@ var Ke = class e {
1977
1974
  this.CURRENCY_SETTING = "market-currency";
1978
1975
  }
1979
1976
  static {
1980
- this.SUPPORTED_TOKENS = { nexacoin: Ge };
1977
+ this.SUPPORTED_TOKENS = { nexacoin: Je };
1981
1978
  }
1982
1979
  constructor(e) {
1983
1980
  this.currency = "usd", this.running = !1, this.walletDb = e;
@@ -2050,6 +2047,6 @@ var Ke = class e {
2050
2047
  }), a;
2051
2048
  }
2052
2049
  };
2053
- 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 };
2050
+ export { ke as ASSET_METADATA_VERSION, ce as AccountType, Ae as AssetService, me as BLOCK_TIME_MINUTES, S as CURRENCIES, fe as HD_WALLET_ID, z as KeyManager, le as KeySpace, pe as MAX_INT64, Ye as MarketService, Je as NEXA_MARKET_ID, Te as RostrumService, We as SessionManager, ue as SessionRequestType, Me as TransactionService, Ge as TransactionTransformer, G as VAULT_FIRST_BLOCK, we as WalletCache, de as WalletDB, qe as WalletManager, N as balanceTotal, Le as calculateFiatValue, ye as capitalizeFirstLetter, C as currencyCodes, D as currentTimestamp, Ve as encryptMnemonic, _e as estimateDateByFutureBlock, O as estimateMinutesToBlock, Fe as formatNexaAmount, Ie as formatNexaAmountWithTicker, $ as formatTokenAmount, Pe as formatTokenAmountWithTicker, Re as generateNewMnemonic, Z as generateVaultAddress, J as generateVaultConstraint, X as generateVaultVisibleArgs, A as getAddressBuffer, V as getAssetFileUrl, B as getAssetMetadataUrl, ge as getExplorerUrl, xe as getFileMediaType, Se as getFileMimeType, T as getNexaTicker, Y as getVaultConstraintHash, K as getVaultTemplate, q as getVaultTemplateHash, he as isGenesisHashValid, ze as isMnemonicValid, k as isNullOrEmpty, w as isTestnet, E as isValidNexaAddress, je as isVaultUnlocked, L as keyPathToString, De as parseTokenDataUrl, Ce as sleep, R as stringToKeyPath, P as sumBalance, F as sumTokensBalance, M as tokenAmountToAssetAmount, be as tokenHexToAddr, j as tokenIdToHex, Ee as transformTokenIconUrl, ve as truncateStringMiddle, Ue as validateAndDecryptMnemonic };
2054
2051
 
2055
2052
  //# sourceMappingURL=index.js.map