nexa-wallet-sdk 0.1.2

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.
Files changed (48) hide show
  1. package/.parcel-cache/3e09f086f3c4d605-AssetGraph +0 -0
  2. package/.parcel-cache/5eac57ec674cdae8-AssetGraph +0 -0
  3. package/.parcel-cache/data.mdb +0 -0
  4. package/.parcel-cache/e43547b6c9167b58-RequestGraph +0 -0
  5. package/.parcel-cache/ecfe15d74834bbfd-BundleGraph +0 -0
  6. package/.parcel-cache/lock.mdb +0 -0
  7. package/.parcel-cache/snapshot-e43547b6c9167b58.txt +2 -0
  8. package/README.md +445 -0
  9. package/dist/browser/index.js +2456 -0
  10. package/dist/browser/index.js.map +1 -0
  11. package/dist/index.d.ts +918 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +2915 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/index.mjs +2456 -0
  16. package/dist/index.mjs.map +1 -0
  17. package/package.json +90 -0
  18. package/spec.md +257 -0
  19. package/src/index.ts +93 -0
  20. package/src/models/rostrum.entities.ts +159 -0
  21. package/src/models/transaction.entities.ts +46 -0
  22. package/src/models/wallet.entities.ts +42 -0
  23. package/src/network/RostrumProvider.ts +137 -0
  24. package/src/types.ts +0 -0
  25. package/src/utils/CommonUtils.ts +123 -0
  26. package/src/utils/TXUtils.ts +445 -0
  27. package/src/utils/TokenUtils.ts +75 -0
  28. package/src/utils/ValidationUtils.ts +86 -0
  29. package/src/utils/WalletUtils.ts +522 -0
  30. package/src/utils/WatchOnlyTXUtils.ts +275 -0
  31. package/src/wallet/Wallet.ts +397 -0
  32. package/src/wallet/WatchOnlyWallet.ts +169 -0
  33. package/src/wallet/accounts/AccountStore.ts +173 -0
  34. package/src/wallet/accounts/interfaces/BaseAccountInterface.ts +56 -0
  35. package/src/wallet/accounts/models/DappAccount.ts +80 -0
  36. package/src/wallet/accounts/models/DefaultAccount.ts +96 -0
  37. package/src/wallet/accounts/models/VaultAccount.ts +81 -0
  38. package/src/wallet/transactions/WalletTransactionCreator.ts +145 -0
  39. package/src/wallet/transactions/WatchOnlyTransactionCreator.ts +189 -0
  40. package/src/wallet/transactions/interfaces/TransactionCreator.ts +438 -0
  41. package/tests/core/tx/transactioncreator.test.ts +455 -0
  42. package/tests/core/tx/wallettransactioncreator.test.ts +362 -0
  43. package/tests/core/tx/watchonlytransactioncreator.test.ts +258 -0
  44. package/tests/core/wallet/accountstore.test.ts +341 -0
  45. package/tests/core/wallet/wallet.test.ts +69 -0
  46. package/tests/core/watchonlywallet/watchonlywallet.test.ts +251 -0
  47. package/tests/index.test.ts +12 -0
  48. package/tsconfig.json +113 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2456 @@
1
+ import {Networks as $633cp$Networks, HDPrivateKey as $633cp$HDPrivateKey, TransactionBuilder as $633cp$TransactionBuilder, Message as $633cp$Message, AddressType as $633cp$AddressType, Address as $633cp$Address, CommonUtils as $633cp$CommonUtils, UnitUtils as $633cp$UnitUtils, Transaction as $633cp$Transaction, GroupToken as $633cp$GroupToken, ScriptFactory as $633cp$ScriptFactory, Script as $633cp$Script, Output as $633cp$Output} from "libnexa-ts";
2
+ import {generateMnemonic as $633cp$generateMnemonic, wordlists as $633cp$wordlists, mnemonicToSeedSync as $633cp$mnemonicToSeedSync} from "bip39";
3
+ import {isNil as $633cp$isNil, isString as $633cp$isString, isBuffer as $633cp$isBuffer, parseInt as $633cp$parseInt, isArray as $633cp$isArray, isObject as $633cp$isObject} from "lodash-es";
4
+ import {ElectrumClient as $633cp$ElectrumClient} from "@vgrunner/electrum-cash";
5
+ import $633cp$jsbigdecimal from "js-big-decimal";
6
+
7
+
8
+ var $parcel$global = globalThis;
9
+ // @ts-ignore
10
+ var $bbe36848c5b6746e$exports = {};
11
+ $bbe36848c5b6746e$exports = JSON.parse("{\"name\":\"@nexa/wallet-sdk-ts\",\"version\":\"0.1.0\",\"main\":\"dist/index.js\",\"module\":\"dist/index.mjs\",\"types\":\"dist/index.d.ts\",\"source\":\"src/index.ts\",\"scripts\":{\"build\":\"parcel build\",\"dev\":\"parcel watch\",\"test\":\"vitest run\",\"clean\":\"rm -rf dist .parcel-cache\"},\"repository\":{\"type\":\"git\",\"url\":\"git+ssh://git@gitlab.com/nexa/wallet-sdk-ts.git\"},\"keywords\":[\"nexa\",\"wallet\",\"web3\",\"crypto\",\"dapp\",\"walletcomms\",\"walletsdk\"],\"contributors\":[{\"name\":\"Dolaned\"},{\"name\":\"Griffith\"},{\"name\":\"Vgrunner\"},{\"name\":\"myendy\"}],\"author\":\"Dolaned\",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://gitlab.com/nexa/wallet-sdk-ts/issues\"},\"homepage\":\"https://gitlab.com/nexa/wallet-sdk-ts#readme\",\"description\":\"Wallet SDK for the Nexa blockchain\",\"devDependencies\":{\"@parcel/packager-ts\":\"^2.15.4\",\"@parcel/transformer-typescript-types\":\"^2.15.4\",\"@types/lodash-es\":\"^4.17.12\",\"@types/node\":\"^22.13.1\",\"parcel\":\"^2.15.4\",\"typescript\":\"^5.8.3\",\"vitest\":\"^3.0.8\"},\"targets\":{\"main\":{\"context\":\"node\",\"outputFormat\":\"commonjs\",\"distDir\":\"dist\",\"isLibrary\":true,\"includeNodeModules\":[\"lodash-es\"]},\"module\":{\"context\":\"node\",\"outputFormat\":\"esmodule\",\"distDir\":\"dist\",\"isLibrary\":true},\"browser\":{\"context\":\"browser\",\"outputFormat\":\"esmodule\",\"distDir\":\"dist\",\"isLibrary\":true}},\"dependencies\":{\"@vgrunner/electrum-cash\":\"^2.0.12\",\"bip39\":\"^3.1.0\",\"js-big-decimal\":\"^2.2.0\",\"libnexa-ts\":\"^1.0.5\",\"lodash-es\":\"^4.17.21\"},\"directories\":{\"test\":\"tests\"}}");
12
+
13
+
14
+
15
+
16
+
17
+ const $a0b58ced4ea5a401$export$1f6f962b0b96558 = {
18
+ WS: 'ws',
19
+ WSS: 'wss'
20
+ };
21
+
22
+
23
+ class $30c92dd8e96ca60d$export$ba81aefc89aef50c {
24
+ constructor(){}
25
+ async getVersion() {
26
+ return await this.execute('server.version');
27
+ }
28
+ async getBlockTip() {
29
+ return await this.execute('blockchain.headers.tip');
30
+ }
31
+ async getBalance(address) {
32
+ return await this.execute('blockchain.address.get_balance', address, 'exclude_tokens');
33
+ }
34
+ async getTransactionsHistory(address) {
35
+ return await this.execute('blockchain.address.get_history', address);
36
+ }
37
+ async getFirstUse(address) {
38
+ return await this.execute('blockchain.address.get_first_use', address);
39
+ }
40
+ async getTransaction(id, verbose = true) {
41
+ return await this.execute('blockchain.transaction.get', id, verbose);
42
+ }
43
+ async getUtxo(outpoint) {
44
+ return await this.execute('blockchain.utxo.get', outpoint);
45
+ }
46
+ async getNexaUtxos(address) {
47
+ return await this.execute('blockchain.address.listunspent', address, 'exclude_tokens');
48
+ }
49
+ async getTokenUtxos(address, token) {
50
+ let listunspent = await this.execute('token.address.listunspent', address, null, token);
51
+ return listunspent.unspent;
52
+ }
53
+ async getTokensBalance(address, token) {
54
+ if (token) return await this.execute('token.address.get_balance', address, null, token);
55
+ return await this.execute('token.address.get_balance', address);
56
+ }
57
+ async getTokenGenesis(token) {
58
+ return await this.execute('token.genesis.info', token);
59
+ }
60
+ async subscribeToAddresses(addresses, callback) {
61
+ for (const addr of addresses)await this.client?.subscribe(callback, 'blockchain.address.subscribe', addr);
62
+ }
63
+ async broadcast(txHex) {
64
+ return await this.execute('blockchain.transaction.broadcast', txHex);
65
+ }
66
+ async getLatency() {
67
+ try {
68
+ let start = Date.now();
69
+ let res = await this.getBlockTip();
70
+ if (res) return Date.now() - start;
71
+ return 0;
72
+ } catch {
73
+ return 0;
74
+ }
75
+ }
76
+ async connect(params) {
77
+ try {
78
+ if (!params) params = {
79
+ host: 'aus.electrum.nexa.onethirtyseven.dev',
80
+ port: 30004,
81
+ scheme: (0, $a0b58ced4ea5a401$export$1f6f962b0b96558).WSS
82
+ };
83
+ this.client = new (0, $633cp$ElectrumClient)("com.otoplo.wallet", "1.4.3", params.host, params.port, params.scheme, 30000, 10000, true);
84
+ await this.client.connect();
85
+ } catch (e) {
86
+ if (e instanceof Error) console.info(e.message);
87
+ else console.error(e);
88
+ throw e;
89
+ }
90
+ }
91
+ async disconnect(force) {
92
+ try {
93
+ return await this.client.disconnect(force);
94
+ } catch (e) {
95
+ console.log(e);
96
+ return false;
97
+ }
98
+ }
99
+ async execute(method, ...parameters) {
100
+ var res = await this.client.request(method, ...parameters);
101
+ if (res instanceof Error) throw res;
102
+ return res;
103
+ }
104
+ }
105
+ const $30c92dd8e96ca60d$export$eaa49f0478d81b9d = new $30c92dd8e96ca60d$export$ba81aefc89aef50c();
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ class $51649cc8d0caebe5$export$c54c8796e94a37a0 {
114
+ get transactions() {
115
+ return this._transactions;
116
+ }
117
+ set transactions(value) {
118
+ this._transactions = value;
119
+ }
120
+ constructor(_bip44Account){
121
+ this._tokenBalances = {};
122
+ this._transactions = new Map();
123
+ this._bip44Account = _bip44Account;
124
+ this._balance = {
125
+ confirmed: 0,
126
+ unconfirmed: 0
127
+ };
128
+ this._tokenBalances = {};
129
+ }
130
+ get balance() {
131
+ return this._balance;
132
+ }
133
+ set balance(value) {
134
+ this._balance = value;
135
+ }
136
+ get tokenBalances() {
137
+ return this._tokenBalances;
138
+ }
139
+ set tokenBalances(value) {
140
+ this._tokenBalances = value;
141
+ }
142
+ }
143
+
144
+
145
+
146
+ class $5ef3d149a7ae4b51$export$2e2bcd8739ae039 extends (0, $51649cc8d0caebe5$export$c54c8796e94a37a0) {
147
+ constructor(bip44Account, accountIndex, addressKey){
148
+ super(bip44Account);
149
+ this._accountIndex = accountIndex;
150
+ this._accountKey = addressKey;
151
+ }
152
+ // this is used in AccountStore.ts to get the key to be used in the map for this account
153
+ getAccountStoreKey() {
154
+ return String(this._bip44Account + '.' + this._accountIndex);
155
+ }
156
+ getAccountType() {
157
+ return (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).DAPP_ACCOUNT;
158
+ }
159
+ getNewAddress() {
160
+ return this._accountKey.address;
161
+ }
162
+ getNewChangeAddress() {
163
+ return this._accountKey.address;
164
+ }
165
+ get accountIndexes() {
166
+ return {
167
+ rIndex: this._accountIndex,
168
+ cIndex: 0
169
+ };
170
+ }
171
+ get accountKeys() {
172
+ return {
173
+ receiveKeys: [
174
+ this._accountKey
175
+ ],
176
+ changeKeys: [
177
+ this._accountKey
178
+ ]
179
+ };
180
+ }
181
+ async loadBalances() {
182
+ let balances = await (0, $f10b40ff0fa7ccfb$export$9e38d26dbd7c33f4)([
183
+ this._accountKey
184
+ ]);
185
+ let tokenBalances = [
186
+ this._accountKey
187
+ ].map((k)=>k.tokensBalance);
188
+ super.balance = (0, $f10b40ff0fa7ccfb$export$a26005fb5b8d1e4a)(balances);
189
+ super.tokenBalances = (0, $f10b40ff0fa7ccfb$export$dec515296f176dbe)(tokenBalances);
190
+ }
191
+ getKeyFromAddress(address) {
192
+ return this._accountKey;
193
+ }
194
+ async getTransactions(fromHeight, address) {
195
+ let txPromises = [];
196
+ const transactions = await (0, $f10b40ff0fa7ccfb$export$a2ed4b531376a5a4)([
197
+ address ?? this._accountKey.address
198
+ ], fromHeight ?? 0);
199
+ for (let tx of transactions.txs.values()){
200
+ let t = await (0, $f10b40ff0fa7ccfb$export$9c6f4f51acbc89b9)(tx, [
201
+ address ?? this._accountKey.address
202
+ ]);
203
+ txPromises.push(t);
204
+ }
205
+ await Promise.all(txPromises);
206
+ for (let txEntity of txPromises)this.transactions.set(txEntity.txId, txEntity);
207
+ return this.transactions;
208
+ }
209
+ }
210
+
211
+
212
+
213
+
214
+ class $3213756e8a8eb72f$export$2e2bcd8739ae039 extends (0, $51649cc8d0caebe5$export$c54c8796e94a37a0) {
215
+ constructor(bip44Account, accountIndexes, accountKeys){
216
+ super(bip44Account);
217
+ if (accountIndexes.rIndex < 0) throw new Error(`Can not create nexa account with an rindex of ${accountIndexes.rIndex}. must be >= 0.`);
218
+ if (accountIndexes.cIndex < 0) throw new Error(`Can not create nexa account with an cindex of ${accountIndexes.cIndex}. must be >= 0.`);
219
+ this._accountIndexes = accountIndexes;
220
+ this._accountKeys = accountKeys;
221
+ }
222
+ // this is used in AccountStore.ts to get the key to be used in the map for this account
223
+ getAccountStoreKey() {
224
+ return String(this._bip44Account);
225
+ }
226
+ getAccountType() {
227
+ return (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).NEXA_ACCOUNT;
228
+ }
229
+ getNewAddress() {
230
+ return this._accountKeys.receiveKeys[this._accountKeys.receiveKeys.length - 1]?.address ?? '';
231
+ }
232
+ getNewChangeAddress() {
233
+ return this._accountKeys.changeKeys[this._accountKeys.changeKeys.length - 1]?.address ?? '';
234
+ }
235
+ get accountIndexes() {
236
+ return this._accountIndexes;
237
+ }
238
+ get accountKeys() {
239
+ return this._accountKeys;
240
+ }
241
+ async loadBalances() {
242
+ let balances = await (0, $f10b40ff0fa7ccfb$export$9e38d26dbd7c33f4)(this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys));
243
+ let tokenBalances = this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys).map((k)=>k.tokensBalance);
244
+ super.balance = (0, $f10b40ff0fa7ccfb$export$a26005fb5b8d1e4a)(balances);
245
+ super.tokenBalances = (0, $f10b40ff0fa7ccfb$export$dec515296f176dbe)(tokenBalances);
246
+ }
247
+ getKeyFromAddress(address) {
248
+ const allKeys = this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys);
249
+ const keyFound = allKeys.find((key)=>key.address === address);
250
+ return keyFound;
251
+ }
252
+ async getTransactions(fromHeight, address) {
253
+ let receiveAddresses = this.accountKeys.receiveKeys.map((ak)=>ak.address);
254
+ let changeAddresses = this.accountKeys.changeKeys.map((ak)=>ak.address);
255
+ let allAddresses = receiveAddresses.concat(changeAddresses);
256
+ let rTxs = (0, $f10b40ff0fa7ccfb$export$a2ed4b531376a5a4)(address != null ? [
257
+ address
258
+ ] : receiveAddresses, fromHeight ?? 0);
259
+ let cTxs = (0, $f10b40ff0fa7ccfb$export$a2ed4b531376a5a4)(address != null ? [
260
+ address
261
+ ] : receiveAddresses, fromHeight ?? 0);
262
+ let [rData, cData] = await Promise.all([
263
+ rTxs,
264
+ cTxs
265
+ ]);
266
+ let txHistory = rData.txs;
267
+ for (let tx of cData.txs.values())txHistory.set(tx.tx_hash, tx);
268
+ let txPromises = [];
269
+ for (let tx of txHistory.values()){
270
+ let t = await (0, $f10b40ff0fa7ccfb$export$9c6f4f51acbc89b9)(tx, allAddresses);
271
+ txPromises.push(t);
272
+ }
273
+ await Promise.all(txPromises);
274
+ for (let txEntity of txPromises)this.transactions.set(txEntity.txId, txEntity);
275
+ return this.transactions;
276
+ }
277
+ }
278
+
279
+
280
+
281
+
282
+ class $fcf0a0849682f4b5$export$2e2bcd8739ae039 extends (0, $51649cc8d0caebe5$export$c54c8796e94a37a0) {
283
+ constructor(bip44Account, accountIndex, addressKey){
284
+ super(bip44Account);
285
+ this._accountIndex = accountIndex;
286
+ this._accountKey = addressKey;
287
+ }
288
+ // this is used in AccountStore.ts to get the key to be used in the map for this account
289
+ getAccountStoreKey() {
290
+ return String(this._bip44Account + '.' + this._accountIndex);
291
+ }
292
+ getAccountType() {
293
+ return (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).VAULT_ACCOUNT;
294
+ }
295
+ getNewAddress() {
296
+ return this._accountKey.address;
297
+ }
298
+ getNewChangeAddress() {
299
+ return this._accountKey.address;
300
+ }
301
+ get accountIndexes() {
302
+ return {
303
+ rIndex: this._accountIndex,
304
+ cIndex: 0
305
+ };
306
+ }
307
+ get accountKeys() {
308
+ return {
309
+ receiveKeys: [
310
+ this._accountKey
311
+ ],
312
+ changeKeys: [
313
+ this._accountKey
314
+ ]
315
+ };
316
+ }
317
+ async loadBalances() {
318
+ let balances = await (0, $f10b40ff0fa7ccfb$export$9e38d26dbd7c33f4)([
319
+ this._accountKey
320
+ ]);
321
+ let tokenBalances = [
322
+ this._accountKey
323
+ ].map((k)=>k.tokensBalance);
324
+ super.balance = (0, $f10b40ff0fa7ccfb$export$a26005fb5b8d1e4a)(balances);
325
+ super.tokenBalances = (0, $f10b40ff0fa7ccfb$export$dec515296f176dbe)(tokenBalances);
326
+ }
327
+ getKeyFromAddress(address) {
328
+ return this._accountKey;
329
+ }
330
+ async getTransactions(fromHeight, address) {
331
+ let txPromises = [];
332
+ const transactions = await (0, $f10b40ff0fa7ccfb$export$a2ed4b531376a5a4)([
333
+ address ?? this._accountKey.address
334
+ ], fromHeight ?? 0);
335
+ for (let tx of transactions.txs.values()){
336
+ let t = await (0, $f10b40ff0fa7ccfb$export$9c6f4f51acbc89b9)(tx, [
337
+ address ?? this._accountKey.address
338
+ ]);
339
+ txPromises.push(t);
340
+ }
341
+ await Promise.all(txPromises);
342
+ for (let txEntity of txPromises)this.transactions.set(txEntity.txId, txEntity);
343
+ return this.transactions;
344
+ }
345
+ }
346
+
347
+
348
+
349
+
350
+ const $424cf91992355440$export$8ba128bc85947a2a = 9223372036854775807n;
351
+ function $424cf91992355440$export$78d0476e8d098ba7() {
352
+ return Math.floor(Date.now() / 1000);
353
+ }
354
+ function $424cf91992355440$export$c8733ae29fb53302(arg) {
355
+ return !arg || arg.length === 0;
356
+ }
357
+ function $424cf91992355440$export$78e516cc94be797b(amount, decimals) {
358
+ let val = new (0, $633cp$jsbigdecimal)(amount).divide(new (0, $633cp$jsbigdecimal)(Math.pow(10, decimals)), decimals).getPrettyValue();
359
+ if (val.match(/\./)) val = val.replace(/\.?0+$/, '');
360
+ return val;
361
+ }
362
+ function $424cf91992355440$export$9ad78026dec58d6(amount, decimals) {
363
+ return new (0, $633cp$jsbigdecimal)(amount).multiply(new (0, $633cp$jsbigdecimal)(Math.pow(10, decimals))).getValue();
364
+ }
365
+ function $424cf91992355440$export$23010fd5dda8dec1(address) {
366
+ if ((0, $633cp$CommonUtils).isHexa(address)) return Buffer.from(address, 'hex');
367
+ return (0, $633cp$Address).fromString(address).data;
368
+ }
369
+ function $424cf91992355440$export$254a5c7330bbfd41(token) {
370
+ if ((0, $633cp$CommonUtils).isHexa(token)) return token;
371
+ return $424cf91992355440$export$23010fd5dda8dec1(token).toString('hex');
372
+ }
373
+
374
+
375
+ var $f10b40ff0fa7ccfb$export$dcc1fb6ad5308e56 = /*#__PURE__*/ function(TxTokenType) {
376
+ TxTokenType[TxTokenType["NO_GROUP"] = 0] = "NO_GROUP";
377
+ TxTokenType[TxTokenType["CREATE"] = 1] = "CREATE";
378
+ TxTokenType[TxTokenType["MINT"] = 2] = "MINT";
379
+ TxTokenType[TxTokenType["MELT"] = 3] = "MELT";
380
+ TxTokenType[TxTokenType["RENEW"] = 4] = "RENEW";
381
+ TxTokenType[TxTokenType["TRANSFER"] = 5] = "TRANSFER";
382
+ return TxTokenType;
383
+ }({});
384
+ var $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7 = /*#__PURE__*/ function(AccountType) {
385
+ AccountType[AccountType["NEXA_ACCOUNT"] = 0] = "NEXA_ACCOUNT";
386
+ AccountType[AccountType["VAULT_ACCOUNT"] = 1] = "VAULT_ACCOUNT";
387
+ AccountType[AccountType["DAPP_ACCOUNT"] = 2] = "DAPP_ACCOUNT";
388
+ return AccountType;
389
+ }({});
390
+ function $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab(address, network, type = (0, $633cp$AddressType).PayToScriptTemplate) {
391
+ return (0, $633cp$Address).isValid(address, network, type);
392
+ }
393
+ function $f10b40ff0fa7ccfb$export$11f4ae2b4ff9633d(mnemonic, passphrase) {
394
+ const seed = $633cp$mnemonicToSeedSync(mnemonic, passphrase);
395
+ const masterKey = (0, $633cp$HDPrivateKey).fromSeed(seed);
396
+ return masterKey.deriveChild(44, true).deriveChild(29223, true);
397
+ }
398
+ function $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, account) {
399
+ return masterKey.deriveChild(account, true);
400
+ }
401
+ function $f10b40ff0fa7ccfb$export$d6e8eb22902c6b88(accountKey, fromRIndex, rIndex, fromCIndex, cIndex) {
402
+ if (fromRIndex < 0) throw new Error(`Can not generate keys with fromRIndex ${fromRIndex}. must be >= 0.`);
403
+ if (fromCIndex < 0) throw new Error(`Can not generate keys with fromCIndex ${fromCIndex}. must be >= 0.`);
404
+ let receive = accountKey.deriveChild(0, false);
405
+ let change = accountKey.deriveChild(1, false);
406
+ let rKeys = [], cKeys = [];
407
+ for(let index = fromRIndex; index < rIndex; index++){
408
+ let k = receive.deriveChild(index, false);
409
+ let addr = k.privateKey.toAddress().toString();
410
+ rKeys.push({
411
+ key: k,
412
+ address: addr,
413
+ balance: "0",
414
+ tokensBalance: {}
415
+ });
416
+ }
417
+ for(let index = fromCIndex; index < cIndex; index++){
418
+ let k = change.deriveChild(index, false);
419
+ let addr = k.privateKey.toAddress().toString();
420
+ cKeys.push({
421
+ key: k,
422
+ address: addr,
423
+ balance: "0",
424
+ tokensBalance: {}
425
+ });
426
+ }
427
+ return {
428
+ receiveKeys: rKeys,
429
+ changeKeys: cKeys
430
+ };
431
+ }
432
+ function $f10b40ff0fa7ccfb$export$1e0ce394ebe84ca9(accountKey, rIndex) {
433
+ let receive = accountKey.deriveChild(0, false);
434
+ let k = receive.deriveChild(rIndex, false);
435
+ let addr = k.privateKey.toAddress().toString();
436
+ return {
437
+ key: k,
438
+ address: addr,
439
+ balance: "0",
440
+ tokensBalance: {}
441
+ };
442
+ }
443
+ async function $f10b40ff0fa7ccfb$var$discoverUsedAccountIndexes(deriveKey) {
444
+ let lastUsed = -1, index = 0, toScan = 20;
445
+ while(toScan > 0){
446
+ toScan--;
447
+ let rAddr = deriveKey.deriveChild(index, false).privateKey.toAddress().toString();
448
+ let isUsed = await $f10b40ff0fa7ccfb$var$isAddressUsed(rAddr);
449
+ if (isUsed) {
450
+ lastUsed = index;
451
+ toScan = 20;
452
+ }
453
+ index++;
454
+ }
455
+ // return the last used index, returns -1 if no indexes are used
456
+ return lastUsed;
457
+ }
458
+ async function $f10b40ff0fa7ccfb$export$4aeb2c92e53ab137(accountKey) {
459
+ let receiveKey = accountKey.deriveChild(0, false);
460
+ let changeKey = accountKey.deriveChild(1, false);
461
+ let rIndexPromise = $f10b40ff0fa7ccfb$var$discoverUsedAccountIndexes(receiveKey);
462
+ let cIndexPromise = $f10b40ff0fa7ccfb$var$discoverUsedAccountIndexes(changeKey);
463
+ let [rIndex, cIndex] = await Promise.all([
464
+ rIndexPromise,
465
+ cIndexPromise
466
+ ]);
467
+ // get the index that is the last used nexa addr
468
+ let indexes = {
469
+ rIndex: rIndex,
470
+ cIndex: cIndex
471
+ };
472
+ return indexes;
473
+ }
474
+ async function $f10b40ff0fa7ccfb$export$f421913908d4303e(masterKey) {
475
+ let accounts = [];
476
+ let index = 0;
477
+ while(true){
478
+ const nexaAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, index);
479
+ const indexes = await $f10b40ff0fa7ccfb$export$4aeb2c92e53ab137(nexaAccountKey);
480
+ if (indexes.rIndex < 0 && indexes.cIndex < 0) break;
481
+ if (indexes.rIndex < 0) indexes.rIndex = 0;
482
+ if (indexes.cIndex < 0) indexes.cIndex = 0;
483
+ // make account after break check, otherwise we might push an empty account
484
+ const nexaAccount = new (0, $3213756e8a8eb72f$export$2e2bcd8739ae039)(index, indexes, $f10b40ff0fa7ccfb$export$d6e8eb22902c6b88(nexaAccountKey, indexes.rIndex + 1, indexes.rIndex + 20, indexes.cIndex + 1, indexes.cIndex + 20));
485
+ await nexaAccount.loadBalances();
486
+ accounts.push(nexaAccount);
487
+ if (index == 0) index = 100;
488
+ else index++;
489
+ }
490
+ if (accounts.length == 0) {
491
+ // default account was unused but we need to populate at least one account,
492
+ // make the default account here
493
+ let defaultNexaAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 0);
494
+ // get the last used indexes, -1 means unused
495
+ let defaultIndexes = {
496
+ rIndex: 0,
497
+ cIndex: 0
498
+ };
499
+ const defaultAccount = new (0, $3213756e8a8eb72f$export$2e2bcd8739ae039)(0, defaultIndexes, $f10b40ff0fa7ccfb$export$d6e8eb22902c6b88(defaultNexaAccountKey, defaultIndexes.rIndex, defaultIndexes.rIndex + 20, defaultIndexes.cIndex, defaultIndexes.cIndex + 20));
500
+ await defaultAccount.loadBalances();
501
+ accounts.push(defaultAccount);
502
+ }
503
+ return accounts;
504
+ }
505
+ async function $f10b40ff0fa7ccfb$var$findUsedVaultAccounts(masterKey) {
506
+ // all vaults are in bip44 account 1
507
+ let vaultAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 1);
508
+ // all vaults are in the external chain
509
+ let vaultChain = vaultAccountKey.deriveChild(0, false);
510
+ // get the index that is the last used vault
511
+ return await $f10b40ff0fa7ccfb$var$discoverUsedAccountIndexes(vaultChain);
512
+ }
513
+ async function $f10b40ff0fa7ccfb$export$eb24265dd203eccb(masterKey) {
514
+ let accounts = [];
515
+ // all vaults are in bip44 account 1
516
+ let vaultAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 1);
517
+ // find the next unused vault
518
+ let lastUsedVaultIndex = await $f10b40ff0fa7ccfb$var$findUsedVaultAccounts(masterKey);
519
+ // if all vaults unused, generate at least the first vault account
520
+ if (lastUsedVaultIndex < 0) lastUsedVaultIndex = 0;
521
+ // for each vault found, make the DefaultAccount for that vault
522
+ for(let index = 0; index <= lastUsedVaultIndex; index++){
523
+ const vaultAccount = new (0, $fcf0a0849682f4b5$export$2e2bcd8739ae039)(1, index, $f10b40ff0fa7ccfb$export$1e0ce394ebe84ca9(vaultAccountKey, index));
524
+ await vaultAccount.loadBalances();
525
+ accounts.push(vaultAccount);
526
+ }
527
+ return accounts;
528
+ }
529
+ async function $f10b40ff0fa7ccfb$var$findUsedDappAccounts(masterKey) {
530
+ // all dApp accounts are in bip44 account 2
531
+ let dappAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 2);
532
+ // all dApp accounts use the external chain
533
+ let dappChain = dappAccountKey.deriveChild(0, false);
534
+ // get the index that is the next unused dApp account
535
+ return await $f10b40ff0fa7ccfb$var$discoverUsedAccountIndexes(dappChain);
536
+ }
537
+ async function $f10b40ff0fa7ccfb$export$e3d879d0e09f52c3(masterKey) {
538
+ let accounts = [];
539
+ // all dApp accounts are in bip44 account 2
540
+ let dappAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 2);
541
+ // find the next unused dapp account
542
+ let lastUsedDappIndex = await $f10b40ff0fa7ccfb$var$findUsedDappAccounts(masterKey);
543
+ // if all dapp accounts unused, generate at least the first dapp account
544
+ if (lastUsedDappIndex < 0) lastUsedDappIndex = 0;
545
+ // for each dApp account found, make the DefaultAccount for that dApp account
546
+ // for each vault found, make the DefaultAccount for that vault
547
+ for(let index = 0; index <= lastUsedDappIndex; index++){
548
+ const dappAccount = new (0, $5ef3d149a7ae4b51$export$2e2bcd8739ae039)(2, index, $f10b40ff0fa7ccfb$export$1e0ce394ebe84ca9(dappAccountKey, index));
549
+ await dappAccount.loadBalances();
550
+ accounts.push(dappAccount);
551
+ }
552
+ return accounts;
553
+ }
554
+ async function $f10b40ff0fa7ccfb$export$4e4f91181d6bd31c(masterKey) {
555
+ let accounts = [];
556
+ // accounts 0, 100+
557
+ const nexaAccounts = await $f10b40ff0fa7ccfb$export$f421913908d4303e(masterKey);
558
+ // vaults in bip44 account 1
559
+ const vaultAccounts = await $f10b40ff0fa7ccfb$export$eb24265dd203eccb(masterKey);
560
+ // dApp accounts in bip44 account 2
561
+ const dappAccounts = await $f10b40ff0fa7ccfb$export$e3d879d0e09f52c3(masterKey);
562
+ // 3 - 99 are reserved and will go here when added
563
+ accounts = accounts.concat(nexaAccounts);
564
+ accounts = accounts.concat(vaultAccounts);
565
+ accounts = accounts.concat(dappAccounts);
566
+ return accounts;
567
+ }
568
+ async function $f10b40ff0fa7ccfb$var$isAddressUsed(address) {
569
+ try {
570
+ let firstUse = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getFirstUse(address);
571
+ return firstUse.tx_hash && firstUse.tx_hash !== "";
572
+ } catch (e) {
573
+ if (e instanceof Error && e.message.includes("not found")) return false;
574
+ throw e;
575
+ }
576
+ }
577
+ async function $f10b40ff0fa7ccfb$var$getKeyTokenBalance(key) {
578
+ let tokensBalance = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokensBalance(key.address);
579
+ let balance = {};
580
+ for(const cToken in tokensBalance.confirmed)if (tokensBalance.confirmed[cToken] != 0) balance[cToken] = {
581
+ confirmed: BigInt(tokensBalance.confirmed[cToken]).toString(),
582
+ unconfirmed: "0"
583
+ };
584
+ for(const uToken in tokensBalance.unconfirmed)if (tokensBalance.unconfirmed[uToken] != 0) {
585
+ if (balance[uToken]) balance[uToken].unconfirmed = BigInt(tokensBalance.unconfirmed[uToken]).toString();
586
+ else balance[uToken] = {
587
+ confirmed: "0",
588
+ unconfirmed: BigInt(tokensBalance.unconfirmed[uToken]).toString()
589
+ };
590
+ }
591
+ return balance;
592
+ }
593
+ async function $f10b40ff0fa7ccfb$var$getAndUpdateAddressKeyBalance(key) {
594
+ let balance = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getBalance(key.address);
595
+ key.balance = (BigInt(balance.confirmed) + BigInt(balance.unconfirmed)).toString();
596
+ key.tokensBalance = await $f10b40ff0fa7ccfb$var$getKeyTokenBalance(key);
597
+ return balance;
598
+ }
599
+ async function $f10b40ff0fa7ccfb$export$9e38d26dbd7c33f4(keys) {
600
+ let promises = [];
601
+ keys.forEach((key)=>{
602
+ let b = $f10b40ff0fa7ccfb$var$getAndUpdateAddressKeyBalance(key);
603
+ promises.push(b);
604
+ });
605
+ return await Promise.all(promises);
606
+ }
607
+ function $f10b40ff0fa7ccfb$export$a26005fb5b8d1e4a(balances) {
608
+ let confirmed = new (0, $633cp$jsbigdecimal)(0), unconfirmed = new (0, $633cp$jsbigdecimal)(0);
609
+ balances.forEach((b)=>{
610
+ confirmed = confirmed.add(new (0, $633cp$jsbigdecimal)(b.confirmed));
611
+ unconfirmed = unconfirmed.add(new (0, $633cp$jsbigdecimal)(b.unconfirmed));
612
+ });
613
+ return {
614
+ confirmed: confirmed.getValue(),
615
+ unconfirmed: unconfirmed.getValue()
616
+ };
617
+ }
618
+ function $f10b40ff0fa7ccfb$export$dec515296f176dbe(balances) {
619
+ let tokensBalance = {};
620
+ balances.forEach((b)=>{
621
+ for(const key in b)if (tokensBalance[key]) {
622
+ tokensBalance[key].confirmed = (BigInt(tokensBalance[key].confirmed) + BigInt(b[key].confirmed)).toString();
623
+ tokensBalance[key].unconfirmed = (BigInt(tokensBalance[key].unconfirmed) + BigInt(b[key].unconfirmed)).toString();
624
+ } else tokensBalance[key] = {
625
+ confirmed: b[key].confirmed,
626
+ unconfirmed: b[key].unconfirmed
627
+ };
628
+ });
629
+ return tokensBalance;
630
+ }
631
+ async function $f10b40ff0fa7ccfb$export$a2ed4b531376a5a4(addresses, fromHeight) {
632
+ let index = 0, i = 0, data = new Map(), maxHeight = fromHeight;
633
+ for (let address of addresses){
634
+ i++;
635
+ let txHistory = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTransactionsHistory(address);
636
+ if (txHistory && txHistory.length > 0) {
637
+ index = i;
638
+ for (let tx of txHistory)if (tx.height === 0 || tx.height > fromHeight) {
639
+ maxHeight = Math.max(maxHeight, tx.height);
640
+ data.set(tx.tx_hash, tx);
641
+ }
642
+ }
643
+ }
644
+ return {
645
+ index: index,
646
+ txs: data,
647
+ lastHeight: maxHeight
648
+ };
649
+ }
650
+ async function $f10b40ff0fa7ccfb$var$rescanAddressesHistory(addresses) {
651
+ let index = 0, i = 0, minHeight = Number.MAX_SAFE_INTEGER;
652
+ for (let address of addresses){
653
+ i++;
654
+ let txHistory = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTransactionsHistory(address);
655
+ if (!(0, $633cp$isNil)(txHistory)) {
656
+ index = i;
657
+ let heights = txHistory.filter((tx)=>tx.height > 0).map((h)=>h.height);
658
+ if (!(0, $633cp$isNil)(heights)) minHeight = Math.min(minHeight, ...heights);
659
+ }
660
+ }
661
+ return {
662
+ index: index > 0 ? index + 1 : 0,
663
+ height: minHeight == Number.MAX_SAFE_INTEGER ? 0 : minHeight
664
+ };
665
+ }
666
+ async function $f10b40ff0fa7ccfb$export$ef13479e8d3251d7(accountType, masterKey) {
667
+ if (accountType == 0) {
668
+ let defaultNexaAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, 0);
669
+ const defaultIndexes = await $f10b40ff0fa7ccfb$export$4aeb2c92e53ab137(defaultNexaAccountKey);
670
+ if (defaultIndexes.rIndex < 0 && defaultIndexes.cIndex < 0) return 0;
671
+ else // account 0 was not empty
672
+ for(let index = 100;; index++){
673
+ const nexaAccountKey = $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9(masterKey, index);
674
+ const indexes = await $f10b40ff0fa7ccfb$export$4aeb2c92e53ab137(nexaAccountKey);
675
+ if (indexes.rIndex < 0 && indexes.cIndex < 0) return index;
676
+ }
677
+ } else if (accountType == 1) {
678
+ // find the next unused vault
679
+ const lastUsedVault = await $f10b40ff0fa7ccfb$var$findUsedVaultAccounts(masterKey);
680
+ return lastUsedVault + 1;
681
+ } else if (accountType == 2) {
682
+ // find the next unused dapp account
683
+ const lastUsedDappAccount = await $f10b40ff0fa7ccfb$var$findUsedDappAccounts(masterKey);
684
+ return lastUsedDappAccount + 1;
685
+ } else throw new Error("Can not get next account index. Invalid accountType.");
686
+ }
687
+ async function $f10b40ff0fa7ccfb$export$9c6f4f51acbc89b9(txHistory, myAddresses) {
688
+ let t = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTransaction(txHistory.tx_hash);
689
+ let outputs = t.vout.filter((utxo)=>!(0, $633cp$isNil)(utxo.scriptPubKey.addresses));
690
+ let isOutgoing = t.vin.length > 0 && myAddresses.includes(t.vin[0].addresses[0]);
691
+ let isIncoming = !isOutgoing || outputs.every((utxo)=>myAddresses.includes(utxo.scriptPubKey.addresses[0]));
692
+ let isConfirmed = t.height > 0;
693
+ let txEntry = {};
694
+ txEntry.txId = t.txid;
695
+ txEntry.txIdem = t.txidem;
696
+ txEntry.height = isConfirmed ? t.height : 0;
697
+ txEntry.time = isConfirmed ? t.time : (0, $424cf91992355440$export$78d0476e8d098ba7)();
698
+ txEntry.fee = t.fee_satoshi;
699
+ if (isOutgoing && isIncoming) {
700
+ txEntry.state = 'both';
701
+ txEntry.value = "0";
702
+ txEntry.payTo = "Payment to yourself";
703
+ } else if (isIncoming) {
704
+ txEntry.state = 'incoming';
705
+ let utxos = outputs.filter((utxo)=>myAddresses.includes(utxo.scriptPubKey.addresses[0]));
706
+ let amount = new (0, $633cp$jsbigdecimal)(0);
707
+ utxos.forEach((utxo)=>{
708
+ amount = amount.add(new (0, $633cp$jsbigdecimal)(utxo.value_satoshi));
709
+ });
710
+ txEntry.value = amount.getValue();
711
+ txEntry.payTo = utxos[0].scriptPubKey.addresses[0];
712
+ } else if (isOutgoing) {
713
+ txEntry.state = 'outgoing';
714
+ let utxos = outputs.filter((utxo)=>!myAddresses.includes(utxo.scriptPubKey.addresses[0]));
715
+ let amount = new (0, $633cp$jsbigdecimal)(0);
716
+ utxos.forEach((utxo)=>{
717
+ amount = amount.add(new (0, $633cp$jsbigdecimal)(utxo.value_satoshi));
718
+ });
719
+ txEntry.value = amount.getValue();
720
+ txEntry.payTo = utxos[0].scriptPubKey.addresses[0];
721
+ }
722
+ let [txType, txGroup, tokenAmount, extraGroup] = $f10b40ff0fa7ccfb$var$classifyTokenTransaction(t.vin, outputs, txEntry.state, myAddresses);
723
+ txEntry.txGroupType = txType;
724
+ txEntry.token = txGroup;
725
+ txEntry.tokenAmount = tokenAmount;
726
+ txEntry.extraGroup = extraGroup;
727
+ return txEntry;
728
+ }
729
+ function $f10b40ff0fa7ccfb$var$classifyTokenTransaction(vin, vout, txState, myAddresses) {
730
+ let groupInputs = vin.filter((input)=>!(0, $424cf91992355440$export$c8733ae29fb53302)(input.group));
731
+ let groupOutputs = vout.filter((output)=>!(0, $424cf91992355440$export$c8733ae29fb53302)(output.scriptPubKey.group));
732
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(groupInputs) && (0, $424cf91992355440$export$c8733ae29fb53302)(groupOutputs)) return [
733
+ 0,
734
+ "none",
735
+ "0",
736
+ "none"
737
+ ];
738
+ let myGroupInputs = groupInputs.filter((input)=>myAddresses.includes(input.addresses[0]));
739
+ let myGroupOutputs = groupOutputs.filter((output)=>myAddresses.includes(output.scriptPubKey.addresses[0]));
740
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(myGroupInputs) && (0, $424cf91992355440$export$c8733ae29fb53302)(myGroupOutputs)) return [
741
+ 0,
742
+ "none",
743
+ "0",
744
+ "none"
745
+ ];
746
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(groupInputs)) {
747
+ let group = myGroupOutputs.find((output)=>BigInt(output.scriptPubKey.groupQuantity) < 0n)?.scriptPubKey.group ?? "none";
748
+ return [
749
+ 1,
750
+ group,
751
+ "0",
752
+ "none"
753
+ ];
754
+ }
755
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(groupOutputs)) {
756
+ if (txState === 'incoming') return [
757
+ 0,
758
+ "none",
759
+ "0",
760
+ "none"
761
+ ];
762
+ let inputs = myGroupInputs.filter((input)=>BigInt(input.groupQuantity) > 0n);
763
+ if (!(0, $424cf91992355440$export$c8733ae29fb53302)(inputs)) {
764
+ let amount = new (0, $633cp$jsbigdecimal)(0);
765
+ inputs.forEach((utxo)=>{
766
+ amount = amount.add(new (0, $633cp$jsbigdecimal)(utxo.groupQuantity));
767
+ });
768
+ let group = inputs[0].group;
769
+ let extraGroup = myGroupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && inputs[0].group != input.group)?.group ?? "none";
770
+ return [
771
+ 3,
772
+ group,
773
+ amount.getValue(),
774
+ extraGroup
775
+ ];
776
+ }
777
+ let group = myGroupInputs.find((input)=>BigInt(input.groupQuantity) < 0n)?.group ?? "none";
778
+ let extraGroup = myGroupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? "none";
779
+ return [
780
+ 3,
781
+ group,
782
+ "0",
783
+ extraGroup
784
+ ];
785
+ }
786
+ let tokenInputs = groupInputs.filter((input)=>BigInt(input.groupQuantity) > 0n);
787
+ let tokenOutputs = groupOutputs.filter((output)=>BigInt(output.scriptPubKey.groupQuantity) > 0n);
788
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(tokenInputs) && (0, $424cf91992355440$export$c8733ae29fb53302)(tokenOutputs)) {
789
+ let group = groupInputs.find((input)=>BigInt(input.groupQuantity) < 0n)?.group ?? "none";
790
+ let extraGroup = groupOutputs.find((output)=>BigInt(output.scriptPubKey.groupQuantity) < 0n && group != output.scriptPubKey.group)?.scriptPubKey.group ?? "none";
791
+ return [
792
+ 4,
793
+ extraGroup !== 'none' ? extraGroup : group,
794
+ "0",
795
+ extraGroup !== 'none' ? group : extraGroup
796
+ ];
797
+ }
798
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(tokenInputs)) {
799
+ let group = tokenOutputs[0].scriptPubKey.group;
800
+ let amount = new (0, $633cp$jsbigdecimal)(0);
801
+ tokenOutputs.forEach((utxo)=>{
802
+ amount = amount.add(new (0, $633cp$jsbigdecimal)(utxo.scriptPubKey.groupQuantity));
803
+ });
804
+ let extraGroup = groupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? "none";
805
+ return [
806
+ 2,
807
+ group,
808
+ amount.getValue(),
809
+ extraGroup
810
+ ];
811
+ }
812
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(tokenOutputs)) {
813
+ let group = tokenInputs[0].group;
814
+ let amount = new (0, $633cp$jsbigdecimal)(0);
815
+ tokenInputs.forEach((utxo)=>{
816
+ amount = amount.add(new (0, $633cp$jsbigdecimal)(utxo.groupQuantity));
817
+ });
818
+ let extraGroup = groupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? "none";
819
+ return [
820
+ 3,
821
+ group,
822
+ amount.getValue(),
823
+ extraGroup
824
+ ];
825
+ }
826
+ let outQuantitySum = tokenOutputs.map((output)=>BigInt(output.scriptPubKey.groupQuantity)).reduce((a, b)=>a + b, 0n);
827
+ let inQuantitySum = tokenInputs.map((input)=>BigInt(input.groupQuantity)).reduce((a, b)=>a + b, 0n);
828
+ if (outQuantitySum > inQuantitySum) {
829
+ let group = tokenOutputs[0].scriptPubKey.group;
830
+ let extraGroup = groupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? "none";
831
+ return [
832
+ 2,
833
+ group,
834
+ (outQuantitySum - inQuantitySum).toString(),
835
+ extraGroup
836
+ ];
837
+ }
838
+ if (inQuantitySum > outQuantitySum) {
839
+ let group = tokenInputs[0].group;
840
+ let extraGroup = groupInputs.find((input)=>BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? "none";
841
+ return [
842
+ 3,
843
+ group,
844
+ (inQuantitySum - outQuantitySum).toString(),
845
+ extraGroup
846
+ ];
847
+ }
848
+ let group = tokenOutputs[0].scriptPubKey.group;
849
+ let amount = "";
850
+ if (txState === 'incoming') amount = tokenOutputs.filter((output)=>myAddresses.includes(output.scriptPubKey.addresses[0])).map((output)=>BigInt(output.scriptPubKey.groupQuantity)).reduce((a, b)=>a + b, 0n).toString();
851
+ else if (txState === 'outgoing') amount = tokenOutputs.filter((output)=>!myAddresses.includes(output.scriptPubKey.addresses[0])).map((output)=>BigInt(output.scriptPubKey.groupQuantity)).reduce((a, b)=>a + b, 0n).toString();
852
+ else amount = "0";
853
+ return [
854
+ 5,
855
+ group,
856
+ amount,
857
+ "none"
858
+ ];
859
+ }
860
+
861
+
862
+
863
+
864
+
865
+
866
+
867
+
868
+
869
+ function $3091f185ded8655f$export$7f7cffd29bf2d96d(authFlags, permission) {
870
+ if (authFlags > 0) return false;
871
+ let flags = BigInt.asUintN(64, BigInt(authFlags));
872
+ switch(permission){
873
+ case 'authorise':
874
+ return (0, $633cp$GroupToken).allowsRenew(flags);
875
+ case 'mint':
876
+ return (0, $633cp$GroupToken).allowsMint(flags);
877
+ case 'melt':
878
+ return (0, $633cp$GroupToken).allowsMelt(flags);
879
+ case 'rescript':
880
+ return (0, $633cp$GroupToken).allowsRescript(flags);
881
+ case 'subgroup':
882
+ return (0, $633cp$GroupToken).allowsSubgroup(flags);
883
+ default:
884
+ return false;
885
+ }
886
+ }
887
+ function $3091f185ded8655f$export$636fb0b03b94ac81(authFlags, withSubgroup = true) {
888
+ if (authFlags > 0) return 0n;
889
+ let flags = BigInt.asUintN(64, BigInt(authFlags));
890
+ let newFlags = (0, $633cp$GroupToken).authFlags.AUTHORITY;
891
+ if ((0, $633cp$GroupToken).allowsRenew(flags)) newFlags |= (0, $633cp$GroupToken).authFlags.BATON;
892
+ if ((0, $633cp$GroupToken).allowsMint(flags)) newFlags |= (0, $633cp$GroupToken).authFlags.MINT;
893
+ if ((0, $633cp$GroupToken).allowsMelt(flags)) newFlags |= (0, $633cp$GroupToken).authFlags.MELT;
894
+ if ((0, $633cp$GroupToken).allowsRescript(flags)) newFlags |= (0, $633cp$GroupToken).authFlags.RESCRIPT;
895
+ if ((0, $633cp$GroupToken).allowsSubgroup(flags) && withSubgroup) newFlags |= (0, $633cp$GroupToken).authFlags.SUBGROUP;
896
+ return newFlags;
897
+ }
898
+ function $3091f185ded8655f$export$e240c810a53c3a0c(perms) {
899
+ let newFlags = (0, $633cp$GroupToken).authFlags.AUTHORITY;
900
+ for (let perm of perms)switch(perm){
901
+ case 'authorise':
902
+ newFlags |= (0, $633cp$GroupToken).authFlags.BATON;
903
+ break;
904
+ case 'mint':
905
+ newFlags |= (0, $633cp$GroupToken).authFlags.MINT;
906
+ break;
907
+ case 'melt':
908
+ newFlags |= (0, $633cp$GroupToken).authFlags.MELT;
909
+ break;
910
+ case 'rescript':
911
+ newFlags |= (0, $633cp$GroupToken).authFlags.RESCRIPT;
912
+ break;
913
+ case 'subgroup':
914
+ newFlags |= (0, $633cp$GroupToken).authFlags.SUBGROUP;
915
+ break;
916
+ }
917
+ return newFlags;
918
+ }
919
+
920
+
921
+ /** Maximum number of inputs/outputs allowed in a single transaction */ const $42a254343af658f0$var$MAX_INPUTS_OUTPUTS = 250;
922
+ async function $42a254343af658f0$export$afd979971a55acfc(txBuilder, keys, totalTxValue, options) {
923
+ let rKeys = keys.receiveKeys.filter((k)=>BigInt(k.balance) > 0n);
924
+ let cKeys = keys.changeKeys.filter((k)=>BigInt(k.balance) > 0n);
925
+ let allKeys = rKeys.concat(cKeys);
926
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(allKeys)) throw new Error("Not enough Nexa balance.");
927
+ let usedKeys = new Map();
928
+ let origAmount = options.isConsolidate ? 0 : Number(totalTxValue);
929
+ for (let key of allKeys){
930
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getNexaUtxos(key.address);
931
+ for (let utxo of utxos){
932
+ let input = {
933
+ outpoint: utxo.outpoint_hash,
934
+ address: key.address,
935
+ satoshis: utxo.value,
936
+ templateData: options.templateData
937
+ };
938
+ txBuilder.from(input);
939
+ if (!usedKeys.has(key.address)) usedKeys.set(key.address, key.key.privateKey);
940
+ if (options.isConsolidate) {
941
+ txBuilder.change(options.toChange ?? keys.receiveKeys[keys.receiveKeys.length - 1].address);
942
+ if (txBuilder.transaction.inputs.length > $42a254343af658f0$var$MAX_INPUTS_OUTPUTS) return Array.from(usedKeys.values());
943
+ } else {
944
+ let tx = txBuilder.transaction;
945
+ if (tx.inputs.length > $42a254343af658f0$var$MAX_INPUTS_OUTPUTS) throw new Error("Too many inputs. Consider consolidate transactions or reduce the send amount.");
946
+ let unspent = tx.getUnspentValue();
947
+ if (unspent < 0n) continue;
948
+ if (unspent == 0n && options.feeFromAmount) {
949
+ let txFee = tx.estimateRequiredFee();
950
+ tx.updateOutputAmount(0, origAmount - txFee);
951
+ return Array.from(usedKeys.values());
952
+ }
953
+ txBuilder.change(options.toChange ?? keys.changeKeys[keys.changeKeys.length - 1].address);
954
+ if (options.feeFromAmount) {
955
+ let hasChange = tx.getChangeOutput();
956
+ let txFee = tx.estimateRequiredFee();
957
+ tx.updateOutputAmount(0, origAmount - txFee);
958
+ // edge case where change added after update
959
+ if (!hasChange && tx.getChangeOutput()) {
960
+ txFee = tx.estimateRequiredFee();
961
+ tx.updateOutputAmount(0, origAmount - txFee);
962
+ }
963
+ }
964
+ // check again after change output manipulation
965
+ if (tx.getUnspentValue() < tx.estimateRequiredFee()) continue;
966
+ return Array.from(usedKeys.values());
967
+ }
968
+ }
969
+ }
970
+ if (options.isConsolidate) {
971
+ if (usedKeys.size > 0) return Array.from(usedKeys.values());
972
+ throw new Error("Not enough Nexa balance.");
973
+ }
974
+ let err = {
975
+ errorMsg: "Not enough Nexa balance.",
976
+ amount: (0, $633cp$UnitUtils).formatNEXA(txBuilder.transaction.outputs[0].value),
977
+ fee: (0, $633cp$UnitUtils).formatNEXA(txBuilder.transaction.estimateRequiredFee())
978
+ };
979
+ throw new Error(JSON.stringify(err));
980
+ }
981
+ async function $42a254343af658f0$export$931e37acdaa22dcf(txBuilder, keys, token, outTokenAmount) {
982
+ let tokenHex = (0, $424cf91992355440$export$254a5c7330bbfd41)(token);
983
+ let rKeys = keys.receiveKeys.filter((k)=>Object.keys(k.tokensBalance).includes(tokenHex));
984
+ let cKeys = keys.changeKeys.filter((k)=>Object.keys(k.tokensBalance).includes(tokenHex));
985
+ let allKeys = rKeys.concat(cKeys);
986
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(allKeys)) throw new Error("Not enough token balance.");
987
+ let usedKeys = new Map();
988
+ let inTokenAmount = 0n;
989
+ for (let key of allKeys){
990
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(key.address, token);
991
+ for (let utxo of utxos){
992
+ if (utxo.token_amount < 0) continue;
993
+ txBuilder.from({
994
+ outpoint: utxo.outpoint_hash,
995
+ address: key.address,
996
+ satoshis: utxo.value,
997
+ groupId: utxo.group,
998
+ groupAmount: BigInt(utxo.token_amount)
999
+ });
1000
+ inTokenAmount = inTokenAmount + BigInt(utxo.token_amount);
1001
+ if (!usedKeys.has(key.address)) usedKeys.set(key.address, key.key.privateKey);
1002
+ if (inTokenAmount > (0, $424cf91992355440$export$8ba128bc85947a2a)) throw new Error("Token inputs exceeded max amount. Consider sending in small chunks");
1003
+ if (txBuilder.transaction.inputs.length > $42a254343af658f0$var$MAX_INPUTS_OUTPUTS) throw new Error("Too many inputs. Consider consolidating transactions or reduce the send amount.");
1004
+ if (inTokenAmount == outTokenAmount) return Array.from(usedKeys.values());
1005
+ if (inTokenAmount > outTokenAmount) {
1006
+ // change
1007
+ txBuilder.to(keys.changeKeys[keys.changeKeys.length - 1].address, (0, $633cp$Transaction).DUST_AMOUNT, token, inTokenAmount - outTokenAmount);
1008
+ return Array.from(usedKeys.values());
1009
+ }
1010
+ }
1011
+ }
1012
+ throw new Error("Not enough token balance");
1013
+ }
1014
+ async function $42a254343af658f0$export$d7f2b844e1d59768(txBuilder, keys, opReturnData, network) {
1015
+ // TODO validate opreturn data
1016
+ const allKeys = keys.receiveKeys.concat(keys.changeKeys);
1017
+ let outpoint = '';
1018
+ let usedKeys = [];
1019
+ let signKey = undefined;
1020
+ for (let key of allKeys){
1021
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getNexaUtxos(key.address);
1022
+ for (let utxo of utxos){
1023
+ txBuilder.from({
1024
+ outpoint: utxo.outpoint_hash,
1025
+ address: key.address,
1026
+ satoshis: utxo.value
1027
+ });
1028
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(outpoint)) {
1029
+ outpoint = utxo.outpoint_hash;
1030
+ let id = (0, $633cp$GroupToken).findGroupId(Buffer.from(outpoint, 'hex'), Buffer.from(opReturnData, 'hex'), (0, $633cp$GroupToken).authFlags.ACTIVE_FLAG_BITS);
1031
+ const groupId = new (0, $633cp$Address)(id.hashBuffer, network, (0, $633cp$AddressType).GroupIdAddress).toString();
1032
+ txBuilder.to(keys.receiveKeys.at(-1).address, (0, $633cp$Transaction).DUST_AMOUNT, groupId, (0, $633cp$GroupToken).authFlags.ACTIVE_FLAG_BITS | id.nonce);
1033
+ signKey = key.key.privateKey;
1034
+ usedKeys.push(signKey);
1035
+ return usedKeys;
1036
+ }
1037
+ }
1038
+ }
1039
+ throw new Error("Not enough Nexa balance.");
1040
+ }
1041
+ async function $42a254343af658f0$export$48a48877d6df17e9(txBuilder, keys, outpoint) {
1042
+ let utxo = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getUtxo(outpoint);
1043
+ let address = utxo.addresses[0];
1044
+ txBuilder.from({
1045
+ outpoint: outpoint,
1046
+ address: address,
1047
+ satoshis: utxo.amount
1048
+ });
1049
+ let allKeys = keys.receiveKeys.concat(keys.changeKeys);
1050
+ let addrKey = allKeys.find((k)=>k.address === address);
1051
+ if (!addrKey) throw new Error('UTXO associated key not found in the wallet');
1052
+ return [
1053
+ addrKey.key.privateKey
1054
+ ];
1055
+ }
1056
+ async function $42a254343af658f0$export$1dfa5d829fc95097(txBuilder, keys, token, perm, subgroup = '', subgroupAddr = '') {
1057
+ let allKeys = keys.receiveKeys.concat(keys.changeKeys);
1058
+ for (let key of allKeys){
1059
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(key.address, token);
1060
+ for (let utxo of utxos){
1061
+ if (!(0, $3091f185ded8655f$export$7f7cffd29bf2d96d)(utxo.token_amount, perm)) continue;
1062
+ txBuilder.from({
1063
+ outpoint: utxo.outpoint_hash,
1064
+ address: key.address,
1065
+ satoshis: utxo.value
1066
+ });
1067
+ if (perm === 'subgroup') txBuilder.to(subgroupAddr, (0, $633cp$Transaction).DUST_AMOUNT, subgroup, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount, false));
1068
+ // if renew flag included, we don't want to burn it
1069
+ if ((0, $633cp$GroupToken).allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) txBuilder.to(keys.receiveKeys.at(-1).address, (0, $633cp$Transaction).DUST_AMOUNT, token, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount));
1070
+ return [
1071
+ key.key.privateKey
1072
+ ];
1073
+ }
1074
+ }
1075
+ throw new Error("The requested authority not found");
1076
+ }
1077
+ async function $42a254343af658f0$export$28a843ca046a6b3f(txBuilder, keys, token, perms, toAddr) {
1078
+ let allKeys = keys.receiveKeys.concat(keys.changeKeys);
1079
+ let usedKeys = [];
1080
+ let reqiredPerms = new Set(perms);
1081
+ reqiredPerms.add('authorise');
1082
+ for (let key of allKeys){
1083
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(key.address, token);
1084
+ for (let utxo of utxos){
1085
+ if (utxo.token_amount > 0) continue;
1086
+ let found = false;
1087
+ for (let perm of reqiredPerms)if ((0, $3091f185ded8655f$export$7f7cffd29bf2d96d)(utxo.token_amount, perm)) {
1088
+ reqiredPerms.delete(perm);
1089
+ found = true;
1090
+ }
1091
+ if (!found) continue;
1092
+ txBuilder.from({
1093
+ outpoint: utxo.outpoint_hash,
1094
+ address: key.address,
1095
+ satoshis: utxo.value
1096
+ });
1097
+ usedKeys.push(key.key.privateKey);
1098
+ // duplicate
1099
+ txBuilder.to(toAddr != null ? toAddr : keys.receiveKeys.at(-1).address, (0, $633cp$Transaction).DUST_AMOUNT, token, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount));
1100
+ if (reqiredPerms.size === 0) return usedKeys;
1101
+ }
1102
+ }
1103
+ throw new Error("The required authorities not found");
1104
+ }
1105
+
1106
+
1107
+
1108
+
1109
+
1110
+
1111
+ class $def4af748ddce85f$export$bba690fb5c12ba04 {
1112
+ /**
1113
+ * Creates a new TransactionCreator instance
1114
+ * @param tx Optional existing TransactionBuilder, hex string, or buffer
1115
+ */ constructor(tx){
1116
+ /** Array of async functions to execute when building the transaction */ this._builder = [];
1117
+ /** Total value of NEXA being sent in this transaction */ this._totalValue = BigInt(0);
1118
+ /** Network this transaction will be broadcast on */ this._network = (0, $633cp$Networks).mainnet;
1119
+ /** Transaction options for customizing behavior */ this._txOptions = {};
1120
+ if (tx instanceof (0, $633cp$TransactionBuilder)) this.transactionBuilder = tx;
1121
+ this.tokens = new Set();
1122
+ this.transactionBuilder = new (0, $633cp$TransactionBuilder)();
1123
+ }
1124
+ /**
1125
+ * Sets the network for this transaction
1126
+ * @param network Network name or Networkish object
1127
+ * @returns This instance for chaining
1128
+ */ onNetwork(network) {
1129
+ this.network = (0, $633cp$Networks).get(network);
1130
+ return this;
1131
+ }
1132
+ /** Gets transaction options */ get txOptions() {
1133
+ return this._txOptions;
1134
+ }
1135
+ /** Sets transaction options */ set txOptions(value) {
1136
+ this._txOptions = value;
1137
+ }
1138
+ /** Gets the network for this transaction */ get network() {
1139
+ return this._network;
1140
+ }
1141
+ /** Sets the network for this transaction */ set network(value) {
1142
+ this._network = value;
1143
+ }
1144
+ /** Gets the builder function array */ get builder() {
1145
+ return this._builder;
1146
+ }
1147
+ /** Sets the builder function array */ set builder(value) {
1148
+ this._builder = value;
1149
+ }
1150
+ /** Gets the underlying transaction builder */ get transactionBuilder() {
1151
+ return this._transactionBuilder;
1152
+ }
1153
+ /** Sets the underlying transaction builder */ set transactionBuilder(value) {
1154
+ this._transactionBuilder = value;
1155
+ }
1156
+ /** Gets the set of token actions */ get tokens() {
1157
+ return this._tokens;
1158
+ }
1159
+ /** Sets the set of token actions */ set tokens(value) {
1160
+ this._tokens = value;
1161
+ }
1162
+ /** Gets the total NEXA value being sent */ get totalValue() {
1163
+ return this._totalValue;
1164
+ }
1165
+ /** Sets the total NEXA value being sent */ set totalValue(value) {
1166
+ this._totalValue = value;
1167
+ }
1168
+ /**
1169
+ * Validates and creates a token action
1170
+ * @param toAddr Destination address
1171
+ * @param amount Amount to send
1172
+ * @param token Token ID
1173
+ * @param action Action type (mint, melt, send, etc.)
1174
+ * @throws Error if validation fails
1175
+ */ tokenAction(toAddr, amount, token, action) {
1176
+ // Validate destination address
1177
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
1178
+ // Validate amount ranges
1179
+ if (token && BigInt(amount) < 1n || !token && (0, $633cp$parseInt)(amount) < (0, $633cp$Transaction).DUST_AMOUNT) throw new Error("The amount is too low.");
1180
+ if (token && BigInt(amount) > (0, $424cf91992355440$export$8ba128bc85947a2a) || !token && (0, $633cp$parseInt)(amount) > (0, $633cp$Transaction).MAX_MONEY) throw new Error("The amount is too high.");
1181
+ // Validate token ID
1182
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(token, this.network, (0, $633cp$AddressType).GroupIdAddress)) throw new Error('Invalid Token ID');
1183
+ // Ensure tokens are sent to script template addresses
1184
+ if ((0, $633cp$Address).getOutputType(toAddr) === 0) throw new Error('Token must be sent to script template address');
1185
+ // Add output to transaction
1186
+ this.transactionBuilder.to(toAddr, (0, $633cp$Transaction).DUST_AMOUNT, token, BigInt(amount));
1187
+ // Record the token action
1188
+ this.tokens.add({
1189
+ token: token,
1190
+ amount: BigInt(amount),
1191
+ action: action
1192
+ });
1193
+ }
1194
+ /**
1195
+ * Configures transaction to consolidate UTXOs to a single address
1196
+ * @param toAddr Address to consolidate funds to
1197
+ * @returns This instance for chaining
1198
+ */ consolidate(toAddr) {
1199
+ this.builder.push(async ()=>{
1200
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
1201
+ this._txOptions.isConsolidate = true;
1202
+ this._txOptions.toChange = toAddr;
1203
+ });
1204
+ return this;
1205
+ }
1206
+ /**
1207
+ * Configures transaction to deduct fee from the send amount
1208
+ * @returns This instance for chaining
1209
+ */ feeFromAmount() {
1210
+ this.builder.push(async ()=>{
1211
+ this._txOptions.feeFromAmount = true;
1212
+ });
1213
+ return this;
1214
+ }
1215
+ /**
1216
+ * Adds a token send operation to the transaction
1217
+ * @param toAddr Destination address
1218
+ * @param amount Amount of tokens to send
1219
+ * @param token Token ID
1220
+ * @returns This instance for chaining
1221
+ */ sendToToken(toAddr, amount, token) {
1222
+ this.builder.push(async ()=>{
1223
+ this.tokenAction(toAddr, amount, token, 'send');
1224
+ });
1225
+ return this;
1226
+ }
1227
+ /**
1228
+ * Adds a NEXA send operation to the transaction
1229
+ * @param toAddr Destination address
1230
+ * @param amount Amount of NEXA to send
1231
+ * @returns This instance for chaining
1232
+ */ sendTo(toAddr, amount) {
1233
+ this.builder.push(async ()=>{
1234
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
1235
+ this.transactionBuilder.to(toAddr, amount);
1236
+ this.totalValue = BigInt(this.totalValue + amount);
1237
+ });
1238
+ return this;
1239
+ }
1240
+ /**
1241
+ * Adds a token authority renewal operation
1242
+ * @param token Token ID to renew authority for
1243
+ * @param perms Permissions to renew
1244
+ * @param toAddr
1245
+ * @returns This instance for chaining
1246
+ */ renewAuthority(token, perms, toAddr) {
1247
+ this.builder.push(async ()=>{
1248
+ if (toAddr != null) {
1249
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(toAddr, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
1250
+ }
1251
+ this.tokens.add({
1252
+ token: token,
1253
+ action: 'renew',
1254
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1255
+ parentToken: undefined,
1256
+ extraData: {
1257
+ perms: perms,
1258
+ address: toAddr
1259
+ }
1260
+ });
1261
+ });
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Adds a token authority deletion operation
1266
+ * @param token Token ID to delete authority for
1267
+ * @param outpoint Outpoint of the authority to delete
1268
+ * @returns This instance for chaining
1269
+ */ deleteAuthority(token, outpoint) {
1270
+ this.builder.push(async ()=>{
1271
+ this.tokens.add({
1272
+ token: token,
1273
+ action: 'delete',
1274
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1275
+ parentToken: undefined,
1276
+ extraData: {
1277
+ outpoint: outpoint
1278
+ }
1279
+ });
1280
+ });
1281
+ return this;
1282
+ }
1283
+ /**
1284
+ * Creates a legacy token (not implemented)
1285
+ * @returns This instance for chaining
1286
+ */ legacyToken(name, ticker, decimals, docUrl, docHash) {
1287
+ this.builder.push(async ()=>{
1288
+ const opReturn = (0, $633cp$ScriptFactory).buildTokenDescriptionLegacy(ticker, name, docUrl, docHash, decimals);
1289
+ this.transactionBuilder.addData(opReturn, true);
1290
+ this.tokens.add({
1291
+ action: 'group',
1292
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1293
+ extraData: {
1294
+ opReturnData: opReturn.toHex()
1295
+ }
1296
+ });
1297
+ });
1298
+ return this;
1299
+ }
1300
+ /**
1301
+ * Creates a legacy group (not implemented)
1302
+ * @returns This instance for chaining
1303
+ */ legacyGroup(name, ticker, docUrl, docHash) {
1304
+ this.builder.push(async ()=>{
1305
+ const opReturn = (0, $633cp$ScriptFactory).buildTokenDescriptionLegacy(ticker, name, docUrl, docHash);
1306
+ this.transactionBuilder.addData(opReturn, true);
1307
+ this.tokens.add({
1308
+ action: 'group',
1309
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1310
+ extraData: {
1311
+ opReturnData: opReturn.toHex()
1312
+ }
1313
+ });
1314
+ });
1315
+ return this;
1316
+ }
1317
+ /**
1318
+ * Creates a token with metadata
1319
+ * @param name Token name
1320
+ * @param ticker Token ticker symbol
1321
+ * @param decimals Number of decimal places
1322
+ * @param docUrl URL to token documentation
1323
+ * @param docHash Hash of token documentation
1324
+ * @returns This instance for chaining
1325
+ */ token(name, ticker, decimals, docUrl, docHash) {
1326
+ this.builder.push(async ()=>{
1327
+ const opReturn = (0, $633cp$ScriptFactory).buildTokenDescription(ticker, name, docUrl, docHash, decimals);
1328
+ this.transactionBuilder.addData(opReturn, true);
1329
+ this.tokens.add({
1330
+ action: 'group',
1331
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1332
+ extraData: {
1333
+ opReturnData: opReturn.toHex()
1334
+ }
1335
+ });
1336
+ });
1337
+ return this;
1338
+ }
1339
+ /**
1340
+ * Creates an NFT collection with metadata
1341
+ * @param name Collection name
1342
+ * @param ticker Collection ticker symbol
1343
+ * @param docUrl URL to collection documentation
1344
+ * @param docHash Hash of collection documentation
1345
+ * @returns This instance for chaining
1346
+ */ collection(name, ticker, docUrl, docHash) {
1347
+ this.builder.push(async ()=>{
1348
+ const opReturn = (0, $633cp$ScriptFactory).buildNFTCollectionDescription(ticker, name, docUrl, docHash);
1349
+ this.transactionBuilder.addData(opReturn, true);
1350
+ this.tokens.add({
1351
+ action: 'group',
1352
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1353
+ extraData: {
1354
+ opReturnData: opReturn.toHex()
1355
+ }
1356
+ });
1357
+ });
1358
+ return this;
1359
+ }
1360
+ /**
1361
+ * Creates an NFT within a collection
1362
+ * @param parent Parent collection token ID
1363
+ * @param zipUrl URL to NFT content ZIP file
1364
+ * @param zipHash Hash of NFT content ZIP file
1365
+ * @returns This instance for chaining
1366
+ */ nft(parent, zipUrl, zipHash) {
1367
+ this.builder.push(async ()=>{
1368
+ // add op_return for the nft
1369
+ let opReturn = (0, $633cp$ScriptFactory).buildNFTDescription(zipUrl, zipHash);
1370
+ this.transactionBuilder.addData(opReturn, true);
1371
+ // generate subgroup ID
1372
+ const subGroup = (0, $633cp$GroupToken).generateSubgroupId(parent, opReturn.toBuffer()).toString('hex');
1373
+ this.tokens.add({
1374
+ token: subGroup,
1375
+ parentToken: parent,
1376
+ amount: BigInt((0, $633cp$Transaction).DUST_AMOUNT),
1377
+ action: 'subgroup'
1378
+ });
1379
+ });
1380
+ return this;
1381
+ }
1382
+ /**
1383
+ * Adds an OP_RETURN output to the transaction
1384
+ * @param data Data to include in the OP_RETURN
1385
+ * @param isFullScript Whether the data is already a complete script
1386
+ * @returns This instance for chaining
1387
+ */ addOpReturn(data, isFullScript = false) {
1388
+ this.builder.push(async ()=>{
1389
+ let script = isFullScript ? new (0, $633cp$Script)(data) : (0, $633cp$ScriptFactory).buildDataOut(data);
1390
+ let output = new (0, $633cp$Output)(0, script);
1391
+ this.transactionBuilder.transaction.addOutput(output);
1392
+ });
1393
+ return this;
1394
+ }
1395
+ /**
1396
+ * Builds the transaction by executing all queued operations
1397
+ * @returns Promise resolving to the serialized transaction hex
1398
+ */ async build() {
1399
+ for (const task of this.builder)await task();
1400
+ return this.transactionBuilder.transaction.serialize({
1401
+ disableAll: true
1402
+ });
1403
+ }
1404
+ }
1405
+
1406
+
1407
+ class $d9127651ccaae19d$export$2e2bcd8739ae039 extends (0, $def4af748ddce85f$export$bba690fb5c12ba04) {
1408
+ constructor(fromAccount, tx){
1409
+ super(tx), this._keysToSign = [];
1410
+ this._account = fromAccount;
1411
+ this.validateAccount();
1412
+ }
1413
+ fromAccount(fromAccount) {
1414
+ this._account = fromAccount;
1415
+ return this;
1416
+ }
1417
+ parseTxHex(tx) {
1418
+ this.builder.push(async ()=>{
1419
+ const txBuilder = new (0, $633cp$TransactionBuilder)(tx);
1420
+ const newTxBuilder = new (0, $633cp$TransactionBuilder)();
1421
+ const oldInputs = txBuilder.transaction.inputs;
1422
+ for (const input of oldInputs){
1423
+ const utxo = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getUtxo(input.outpoint.toString('hex'));
1424
+ newTxBuilder.from({
1425
+ outpoint: utxo.tx_hash,
1426
+ amount: utxo.amount,
1427
+ scriptPubKey: utxo.scriptpubkey
1428
+ });
1429
+ const foundKey = this.findPrivateKeyFromAddress(utxo.addresses[0]);
1430
+ if (foundKey) this._keysToSign.push(foundKey.key.privateKey);
1431
+ }
1432
+ newTxBuilder.transaction.outputs = txBuilder.transaction.outputs;
1433
+ });
1434
+ return this;
1435
+ }
1436
+ parseTxBuffer(tx) {
1437
+ this.builder.push(async ()=>{
1438
+ this.transactionBuilder = new (0, $633cp$TransactionBuilder)(tx);
1439
+ });
1440
+ return this;
1441
+ }
1442
+ mint(token, amount) {
1443
+ this.builder.push(async ()=>{
1444
+ let toAddr = this._account.accountKeys.receiveKeys.at(-1).address;
1445
+ this.tokenAction(toAddr, amount, token, 'mint');
1446
+ });
1447
+ return this;
1448
+ }
1449
+ melt(token, amount) {
1450
+ this.builder.push(async ()=>{
1451
+ let toAddr = this._account.accountKeys.receiveKeys.at(-1).address;
1452
+ this.tokenAction(toAddr, amount, token, 'melt');
1453
+ });
1454
+ return this;
1455
+ }
1456
+ populate() {
1457
+ this.validateAccount();
1458
+ this.builder.push(async ()=>{
1459
+ let tK = [];
1460
+ let nK = [];
1461
+ if (this.tokens.size > 0) for (const tokenAction of this.tokens){
1462
+ if (tokenAction.action == 'mint' || tokenAction.action == 'melt') tK = tK.concat(await (0, $42a254343af658f0$export$1dfa5d829fc95097)(this.transactionBuilder, this._account.accountKeys, tokenAction.token, tokenAction.action));
1463
+ else if (tokenAction.action == 'group') tK = tK.concat(await (0, $42a254343af658f0$export$d7f2b844e1d59768)(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData?.opReturnData, this.network));
1464
+ else if (tokenAction.action == 'subgroup') tK = tK.concat(await (0, $42a254343af658f0$export$1dfa5d829fc95097)(this.transactionBuilder, this._account.accountKeys, tokenAction.parentToken, 'subgroup', tokenAction.token, this._account.accountKeys.receiveKeys.at(-1).address));
1465
+ else if (tokenAction.action == 'renew') tK = tK.concat(await (0, $42a254343af658f0$export$28a843ca046a6b3f)(this.transactionBuilder, this._account.accountKeys, tokenAction.token, tokenAction.extraData.perms, tokenAction.extraData.address));
1466
+ else if (tokenAction.action == 'delete') tK = tK.concat(await (0, $42a254343af658f0$export$48a48877d6df17e9)(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData.outpoint));
1467
+ else tK = tK.concat(await (0, $42a254343af658f0$export$931e37acdaa22dcf)(this.transactionBuilder, this._account.accountKeys, tokenAction.token, tokenAction.amount));
1468
+ this._keysToSign.concat(tK);
1469
+ }
1470
+ nK = nK.concat(await (0, $42a254343af658f0$export$afd979971a55acfc)(this.transactionBuilder, this._account.accountKeys, this.totalValue, this.txOptions));
1471
+ this._keysToSign = tK.concat(nK);
1472
+ });
1473
+ return this;
1474
+ }
1475
+ sign() {
1476
+ this.builder.push(async ()=>{
1477
+ const blockHeight = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getBlockTip();
1478
+ this.transactionBuilder.lockUntilBlockHeight(blockHeight.height).sign(this._keysToSign);
1479
+ });
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Validates that the account has the necessary keys before performing operations
1484
+ * @throws Error if account or keys are not properly initialized
1485
+ */ validateAccount() {
1486
+ if (!this._account) throw new Error('Account must be set before performing transactions');
1487
+ if (!this._account.accountKeys) throw new Error('Account keys are not initialized');
1488
+ if (!this._account.accountKeys.receiveKeys || this._account.accountKeys.receiveKeys.length === 0) throw new Error('No receive keys available in account');
1489
+ }
1490
+ findPrivateKeyFromAddress(addr) {
1491
+ const keys = this._account.accountKeys.receiveKeys.concat(this._account.accountKeys.changeKeys);
1492
+ return keys.find((key)=>key.address === addr);
1493
+ }
1494
+ }
1495
+
1496
+
1497
+
1498
+
1499
+
1500
+
1501
+ class $f956f86dd8b9f336$export$2e2bcd8739ae039 {
1502
+ /**
1503
+ * Creates a new AccountStore instance
1504
+ * Initializes an empty map to store accounts
1505
+ */ constructor(){
1506
+ this._accounts = new Map();
1507
+ }
1508
+ /**
1509
+ * Generates a unique store key for an account based on its type and index
1510
+ * @param accountType The type of account (DAPP, VAULT, or DEFAULT)
1511
+ * @param index The account index
1512
+ * @returns Unique string key for storing the account
1513
+ */ getAccountStoreKey(accountType, index) {
1514
+ switch(accountType){
1515
+ case (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).DAPP_ACCOUNT:
1516
+ // DApp accounts use format: "2.index"
1517
+ return String(accountType + '.' + index);
1518
+ case (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).VAULT_ACCOUNT:
1519
+ // Vault accounts use format: "1.index"
1520
+ return String(accountType + '.' + index);
1521
+ default:
1522
+ // Default accounts use just the index
1523
+ return String(index);
1524
+ }
1525
+ }
1526
+ /**
1527
+ * Creates a new account of the specified type
1528
+ * @param accountType Type of account to create (DAPP, VAULT, or DEFAULT)
1529
+ * @param masterKey Master HD private key for deriving account keys
1530
+ * @returns Promise resolving to the created account
1531
+ */ async createAccount(accountType, masterKey) {
1532
+ // Get the next available index for this account type
1533
+ const nextIndex = await (0, $f10b40ff0fa7ccfb$export$ef13479e8d3251d7)(accountType, masterKey);
1534
+ const accountStoreKey = this.getAccountStoreKey(accountType, nextIndex);
1535
+ // Check if account already exists
1536
+ const indexExists = this._accounts.get(String(accountStoreKey));
1537
+ if (indexExists) return indexExists;
1538
+ switch(accountType){
1539
+ case (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).DAPP_ACCOUNT:
1540
+ // Create DApp account (purpose 2)
1541
+ let dappAccountKey = (0, $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9)(masterKey, 2);
1542
+ const dAppAccount = new (0, $5ef3d149a7ae4b51$export$2e2bcd8739ae039)(2, nextIndex, (0, $f10b40ff0fa7ccfb$export$1e0ce394ebe84ca9)(dappAccountKey, nextIndex));
1543
+ await dAppAccount.loadBalances();
1544
+ this._accounts.set(dAppAccount.getAccountStoreKey(), dAppAccount);
1545
+ return dAppAccount;
1546
+ case (0, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7).VAULT_ACCOUNT:
1547
+ // Create Vault account (purpose 1)
1548
+ let vaultAccountKey = (0, $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9)(masterKey, 1);
1549
+ const vaultAccount = new (0, $fcf0a0849682f4b5$export$2e2bcd8739ae039)(1, nextIndex, (0, $f10b40ff0fa7ccfb$export$1e0ce394ebe84ca9)(vaultAccountKey, nextIndex));
1550
+ await vaultAccount.loadBalances();
1551
+ this._accounts.set(vaultAccount.getAccountStoreKey(), vaultAccount);
1552
+ return vaultAccount;
1553
+ default:
1554
+ // Create default NEXA account with receive and change addresses
1555
+ let nexaAccountKey = (0, $f10b40ff0fa7ccfb$export$b3a12d67e2f5f8c9)(masterKey, nextIndex);
1556
+ const nexaAccountIndexes = {
1557
+ rIndex: 0,
1558
+ cIndex: 0
1559
+ };
1560
+ const nexaAccount = new (0, $3213756e8a8eb72f$export$2e2bcd8739ae039)(nextIndex, nexaAccountIndexes, (0, $f10b40ff0fa7ccfb$export$d6e8eb22902c6b88)(nexaAccountKey, nexaAccountIndexes.rIndex + 1, nexaAccountIndexes.rIndex + 20, nexaAccountIndexes.cIndex + 1, nexaAccountIndexes.cIndex + 20));
1561
+ await nexaAccount.loadBalances();
1562
+ this._accounts.set(nexaAccount.getAccountStoreKey(), nexaAccount);
1563
+ return nexaAccount;
1564
+ }
1565
+ }
1566
+ /**
1567
+ * Finds the private key associated with a given address across all accounts
1568
+ * @param address The address to search for
1569
+ * @returns The AddressKey containing the private key, or null if not found
1570
+ */ findKeyForAddress(address) {
1571
+ // Search through all accounts
1572
+ for (const [_, account] of this._accounts.entries()){
1573
+ // Combine receive and change keys for this account
1574
+ const allKeys = account.accountKeys.receiveKeys.concat(account.accountKeys.changeKeys);
1575
+ // Check each key for a matching address
1576
+ for (const key of allKeys){
1577
+ if (key.address == address) return key;
1578
+ }
1579
+ }
1580
+ return null;
1581
+ }
1582
+ /**
1583
+ * Imports an existing account into the store
1584
+ * @param accountData The account data to import
1585
+ * @throws Error if an account with the same key already exists
1586
+ */ importAccount(accountData) {
1587
+ let index = accountData.getAccountStoreKey();
1588
+ if (this._accounts.get(index)) throw Error('Account already exists!');
1589
+ this._accounts.set(String(index), accountData);
1590
+ }
1591
+ /**
1592
+ * Exports account data by index
1593
+ * @param accountIndex The account index to export
1594
+ * @returns The account data
1595
+ * @throws Error if the account doesn't exist
1596
+ */ exportAccount(accountIndex) {
1597
+ if (!this._accounts.get(accountIndex)) throw Error('Cannot find account!');
1598
+ return this._accounts.get(accountIndex);
1599
+ }
1600
+ /**
1601
+ * Removes an account from the store
1602
+ * @param accountIndex The account index to remove
1603
+ * @throws Error if the account doesn't exist
1604
+ */ removeAccount(accountIndex) {
1605
+ if (!this._accounts.get(accountIndex)) throw Error('Cannot find account!');
1606
+ this._accounts.delete(accountIndex);
1607
+ }
1608
+ /**
1609
+ * Returns all accounts in the store
1610
+ * @returns Map of account store keys to BaseAccount objects
1611
+ */ listAccounts() {
1612
+ return this._accounts;
1613
+ }
1614
+ /**
1615
+ * Retrieves a specific account by its index
1616
+ * @param index The account index to retrieve
1617
+ * @returns The account if found, undefined otherwise
1618
+ */ getAccount(index) {
1619
+ return this._accounts.get(index);
1620
+ }
1621
+ }
1622
+
1623
+
1624
+
1625
+ class $8c756bc820fcaf73$export$2e2bcd8739ae039 {
1626
+ /**
1627
+ * Validate that a state condition is true
1628
+ *
1629
+ * @param condition - The condition to validate
1630
+ * @param message - Error message to throw if condition is false
1631
+ * @throws {Error} If condition is false
1632
+ *
1633
+ * @example
1634
+ * ```typescript
1635
+ * ValidationUtils.validateState(wallet.isInitialized, 'Wallet must be initialized');
1636
+ * ```
1637
+ */ static validateState(condition, message) {
1638
+ if (!condition) throw new Error(`Invalid State: ${message}`);
1639
+ }
1640
+ /**
1641
+ * Validate that an argument condition is true
1642
+ *
1643
+ * @param condition - The condition to validate
1644
+ * @param argumentName - Name of the argument being validated
1645
+ * @param message - Optional additional error message
1646
+ * @throws {Error} If condition is false
1647
+ *
1648
+ * @example
1649
+ * ```typescript
1650
+ * ValidationUtils.validateArgument(
1651
+ * typeof amount === 'number',
1652
+ * 'amount',
1653
+ * 'must be a number'
1654
+ * );
1655
+ * ```
1656
+ */ static validateArgument(condition, argumentName, message = "") {
1657
+ if (!condition) throw new Error(`Invalid Argument: ${argumentName}. ${message}`);
1658
+ }
1659
+ /**
1660
+ * Validate that an argument is of the expected type
1661
+ *
1662
+ * @param argument - The argument to validate
1663
+ * @param type - Expected type (string name or constructor function)
1664
+ * @param argumentName - Name of the argument being validated
1665
+ * @throws {TypeError} If argument is not of expected type
1666
+ *
1667
+ * @example
1668
+ * ```typescript
1669
+ * ValidationUtils.validateArgumentType(buffer, 'Buffer', 'data');
1670
+ * ValidationUtils.validateArgumentType(wallet, Wallet, 'wallet');
1671
+ * ValidationUtils.validateArgumentType(amount, 'number', 'amount');
1672
+ * ```
1673
+ */ static validateArgumentType(argument, type, argumentName) {
1674
+ argumentName = argumentName || '(unknown name)';
1675
+ if ((0, $633cp$isString)(type)) {
1676
+ if (type === 'Buffer') {
1677
+ if (!Buffer.isBuffer(argument)) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);
1678
+ } else if (typeof argument !== type) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);
1679
+ } else {
1680
+ if (!(argument instanceof type)) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);
1681
+ }
1682
+ }
1683
+ }
1684
+
1685
+
1686
+ class $f2814d31d49d257b$export$2e2bcd8739ae039 {
1687
+ /**
1688
+ * Creates a new Wallet instance
1689
+ *
1690
+ * @param data - Optional wallet data:
1691
+ * - undefined: Generate new random seed phrase
1692
+ * - string: Use as BIP39 seed phrase
1693
+ * - HDPrivateKey: Use as master key directly
1694
+ * @param network - Network name ('mainnet', 'testnet', 'regtest'). Defaults to 'mainnet'
1695
+ *
1696
+ * @example
1697
+ * ```typescript
1698
+ * // Create new wallet with random seed
1699
+ * const wallet = new Wallet();
1700
+ *
1701
+ * // Create from seed phrase
1702
+ * const wallet = new Wallet('abandon abandon abandon...');
1703
+ *
1704
+ * // Create from master key
1705
+ * const masterKey = HDPrivateKey.fromString('xprv...');
1706
+ * const wallet = new Wallet(masterKey);
1707
+ *
1708
+ * // Create on testnet
1709
+ * const wallet = new Wallet(undefined, 'testnet');
1710
+ * ```
1711
+ */ constructor(data, network){
1712
+ this._network = (0, $633cp$Networks).get(network) ?? (0, $633cp$Networks).mainnet;
1713
+ this._accountStore = new (0, $f956f86dd8b9f336$export$2e2bcd8739ae039)();
1714
+ if ((0, $633cp$isNil)(data)) {
1715
+ this.phrase = $633cp$generateMnemonic(128, undefined, $633cp$wordlists.english);
1716
+ const seed = $633cp$mnemonicToSeedSync(this.phrase, '');
1717
+ const masterKey = (0, $633cp$HDPrivateKey).fromSeed(seed, this._network ?? (0, $633cp$Networks).mainnet);
1718
+ this.masterKey = masterKey.deriveChild(44, true).deriveChild(29223, true);
1719
+ } else if (data instanceof (0, $633cp$HDPrivateKey)) this.masterKey = data;
1720
+ else if ((0, $633cp$isString)(data)) {
1721
+ this.phrase = data;
1722
+ const seed = $633cp$mnemonicToSeedSync(this.phrase, '');
1723
+ const masterKey = (0, $633cp$HDPrivateKey).fromSeed(seed, this._network ?? (0, $633cp$Networks).mainnet);
1724
+ this.masterKey = masterKey.deriveChild(44, true).deriveChild(29223, true);
1725
+ }
1726
+ }
1727
+ /**
1728
+ * Create a new wallet with a randomly generated seed phrase
1729
+ *
1730
+ * This is the recommended way to create a new wallet for first-time users.
1731
+ * The generated seed phrase should be securely stored by the user.
1732
+ *
1733
+ * @returns A new Wallet instance with a random 12-word seed phrase
1734
+ *
1735
+ * @example
1736
+ * ```typescript
1737
+ * const wallet = Wallet.create();
1738
+ * console.log(wallet.export().phrase); // Store this securely!
1739
+ * ```
1740
+ */ static create() {
1741
+ return new $f2814d31d49d257b$export$2e2bcd8739ae039();
1742
+ }
1743
+ /**
1744
+ * Create a wallet from an existing BIP39 seed phrase
1745
+ *
1746
+ * Use this method to restore a wallet from a previously generated seed phrase.
1747
+ * The seed phrase should be a valid BIP39 mnemonic.
1748
+ *
1749
+ * @param phrase - The BIP39 seed phrase (12 or 24 words)
1750
+ * @param network - Optional network name ('mainnet', 'testnet', 'regtest')
1751
+ * @returns A new Wallet instance restored from the seed phrase
1752
+ * @throws {Error} If the seed phrase is invalid or not provided
1753
+ *
1754
+ * @example
1755
+ * ```typescript
1756
+ * const wallet = Wallet.fromSeedPhrase(
1757
+ * 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
1758
+ * 'testnet'
1759
+ * );
1760
+ * ```
1761
+ */ static fromSeedPhrase(phrase, network) {
1762
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isString)(phrase), 'seedphrase must be provided');
1763
+ return new $f2814d31d49d257b$export$2e2bcd8739ae039(phrase, network);
1764
+ }
1765
+ /**
1766
+ * Create a wallet from an extended private key (xpriv)
1767
+ *
1768
+ * Use this method to create a wallet from a master private key in extended format.
1769
+ * This is useful for advanced users who want to use a specific key derivation.
1770
+ *
1771
+ * @param xpriv - The extended private key string (starts with 'xprv')
1772
+ * @param network - Optional network name ('mainnet', 'testnet', 'regtest')
1773
+ * @returns A new Wallet instance using the provided master key
1774
+ * @throws {Error} If the private key is invalid or not provided
1775
+ *
1776
+ * @example
1777
+ * ```typescript
1778
+ * const wallet = Wallet.fromXpriv(
1779
+ * 'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi'
1780
+ * );
1781
+ * ```
1782
+ */ static fromXpriv(xpriv, network) {
1783
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isString)(xpriv), 'private key must be provided');
1784
+ const masterKey = (0, $633cp$HDPrivateKey).fromString(xpriv);
1785
+ return new $f2814d31d49d257b$export$2e2bcd8739ae039(masterKey, network);
1786
+ }
1787
+ /**
1788
+ * Initialize the wallet by discovering accounts and loading balances
1789
+ *
1790
+ * This method performs account discovery using the BIP44 derivation path
1791
+ * and scans for existing accounts with transaction history or balances.
1792
+ * Must be called before using the wallet's accounts.
1793
+ *
1794
+ * @returns Promise that resolves when initialization is complete
1795
+ *
1796
+ * @example
1797
+ * ```typescript
1798
+ * const wallet = Wallet.fromSeedPhrase('your seed phrase');
1799
+ * await wallet.initialize();
1800
+ *
1801
+ * // Now you can access discovered accounts
1802
+ * const accounts = wallet.accountStore.listAccounts();
1803
+ * ```
1804
+ */ async initialize() {
1805
+ const walletAccounts = await (0, $f10b40ff0fa7ccfb$export$4e4f91181d6bd31c)(this.masterKey);
1806
+ for (const account of walletAccounts)this._accountStore.importAccount(account);
1807
+ }
1808
+ /**
1809
+ * Create a new transaction builder for this wallet
1810
+ *
1811
+ * @param fromAccount - The account to send the transaction from
1812
+ * @param x - Optional existing transaction data:
1813
+ * - TransactionBuilder: Use existing transaction builder
1814
+ * - string: Parse from hex string
1815
+ * - Buffer: Parse from binary buffer
1816
+ * - undefined: Create new empty transaction
1817
+ * @returns A new WalletTransactionCreator instance
1818
+ *
1819
+ * @example
1820
+ * ```typescript
1821
+ * const account = wallet.accountStore.getAccount(0);
1822
+ * const tx = wallet.newTransaction(account)
1823
+ * .to('nexa:address', 1000000) // 1 NEXA
1824
+ * .sign();
1825
+ *
1826
+ * // Or from existing transaction hex
1827
+ * const tx = wallet.newTransaction(account, 'raw_tx_hex')
1828
+ * .sign();
1829
+ * ```
1830
+ */ newTransaction(fromAccount, x) {
1831
+ let tx;
1832
+ if (x instanceof (0, $633cp$TransactionBuilder)) tx = new (0, $d9127651ccaae19d$export$2e2bcd8739ae039)(fromAccount, x);
1833
+ else if ((0, $633cp$isString)(x)) tx = new (0, $d9127651ccaae19d$export$2e2bcd8739ae039)(fromAccount).parseTxHex(x);
1834
+ else if ((0, $633cp$isBuffer)(x) && !(0, $633cp$isNil)(x)) tx = new (0, $d9127651ccaae19d$export$2e2bcd8739ae039)(fromAccount).parseTxBuffer(x);
1835
+ else tx = new (0, $d9127651ccaae19d$export$2e2bcd8739ae039)(fromAccount);
1836
+ return tx.onNetwork(this._network);
1837
+ }
1838
+ /**
1839
+ * Create a new account for this wallet
1840
+ *
1841
+ * @param accountType - The type of account to create:
1842
+ * - 'DefaultAccount': Standard account for general use
1843
+ * - 'VaultAccount': Secured account with additional protection
1844
+ * - 'DappAccount': Account optimized for dApp interactions
1845
+ * @returns Promise that resolves to the newly created account
1846
+ *
1847
+ * @example
1848
+ * ```typescript
1849
+ * const defaultAccount = await wallet.newAccount('DefaultAccount');
1850
+ * const vaultAccount = await wallet.newAccount('VaultAccount');
1851
+ * const dappAccount = await wallet.newAccount('DappAccount');
1852
+ * ```
1853
+ */ async newAccount(accountType) {
1854
+ return await this.accountStore.createAccount(accountType, this.masterKey);
1855
+ }
1856
+ /**
1857
+ * Broadcast a signed transaction to the Nexa network
1858
+ *
1859
+ * @param transaction - The signed transaction in hex format
1860
+ * @returns Promise that resolves to the transaction ID (txid)
1861
+ * @throws {Error} If the transaction is invalid or broadcast fails
1862
+ *
1863
+ * @example
1864
+ * ```typescript
1865
+ * const tx = wallet.newTransaction(account)
1866
+ * .to('nexa:address', 1000000)
1867
+ * .sign();
1868
+ *
1869
+ * const txId = await wallet.sendTransaction(tx.toHex());
1870
+ * console.log('Transaction sent:', txId);
1871
+ * ```
1872
+ */ async sendTransaction(transaction) {
1873
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isString)(transaction), 'transaction must be present and valid');
1874
+ return (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).broadcast(transaction);
1875
+ }
1876
+ /**
1877
+ * Sign a message using a specific address from this wallet
1878
+ *
1879
+ * The message is signed using the private key associated with the given address.
1880
+ * This can be used for authentication or to prove ownership of an address.
1881
+ *
1882
+ * @param message - The message to sign
1883
+ * @param addressToUse - The address whose private key should sign the message
1884
+ * @returns The signature as a base64-encoded string
1885
+ * @throws {Error} If the address is not owned by this wallet
1886
+ *
1887
+ * @example
1888
+ * ```typescript
1889
+ * const account = wallet.accountStore.getAccount(0);
1890
+ * const address = account.getReceiveAddress();
1891
+ * const signature = wallet.signMessage('Hello World', address);
1892
+ * ```
1893
+ */ signMessage(message, addressToUse) {
1894
+ let msg = new (0, $633cp$Message)(message);
1895
+ const addressKey = this.accountStore.findKeyForAddress(addressToUse);
1896
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isNil)(addressKey), "You dont own this private key");
1897
+ return msg.sign(addressKey?.key.privateKey);
1898
+ }
1899
+ /**
1900
+ * Verify a message signature against an address
1901
+ *
1902
+ * This method can verify signatures created by any address, not just addresses
1903
+ * owned by this wallet. It's useful for verifying messages from other parties.
1904
+ *
1905
+ * @param message - The original message that was signed
1906
+ * @param signature - The signature to verify (base64-encoded)
1907
+ * @param address - The address that supposedly signed the message
1908
+ * @returns true if the signature is valid, false otherwise
1909
+ * @throws {Error} If any parameters are missing or invalid
1910
+ *
1911
+ * @example
1912
+ * ```typescript
1913
+ * const isValid = wallet.verifyMessage(
1914
+ * 'Hello World',
1915
+ * 'signature_string',
1916
+ * 'nexa:address'
1917
+ * );
1918
+ * console.log('Signature valid:', isValid);
1919
+ * ```
1920
+ */ verifyMessage(message, signature, address) {
1921
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument(!(0, $633cp$isNil)(message), 'message is required');
1922
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument(!(0, $633cp$isNil)(signature), 'signature is required');
1923
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument(!(0, $633cp$isNil)(address), 'address is required ');
1924
+ let msg = new (0, $633cp$Message)(message);
1925
+ const addressKey = this.accountStore.findKeyForAddress(address);
1926
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isNil)(addressKey), "You dont own this private key");
1927
+ return msg.verify(address, signature);
1928
+ }
1929
+ /**
1930
+ * Export the wallet data for backup or storage
1931
+ *
1932
+ * Returns an object containing the wallet's seed phrase, master key, and accounts.
1933
+ * This data can be used to restore the wallet later. The seed phrase should be
1934
+ * stored securely as it provides full access to the wallet.
1935
+ *
1936
+ * @returns Object containing wallet data
1937
+ * @property {string} phrase - The BIP39 seed phrase (if available)
1938
+ * @property {HDPrivateKey} masterKey - The master private key
1939
+ * @property {BaseAccount[]} accounts - Array of discovered accounts
1940
+ *
1941
+ * @example
1942
+ * ```typescript
1943
+ * const walletData = wallet.export();
1944
+ *
1945
+ * // Store the seed phrase securely
1946
+ * const seedPhrase = walletData.phrase;
1947
+ *
1948
+ * // Later, restore the wallet
1949
+ * const restoredWallet = Wallet.fromSeedPhrase(seedPhrase);
1950
+ * ```
1951
+ */ export() {
1952
+ return {
1953
+ phrase: this.phrase,
1954
+ masterKey: this.masterKey,
1955
+ accounts: this._accountStore.listAccounts(),
1956
+ accountIndexes: this.accountStore.listAccounts().keys()
1957
+ };
1958
+ }
1959
+ /**
1960
+ * Get the account store for managing wallet accounts
1961
+ *
1962
+ * The account store provides methods to create, import, and manage accounts
1963
+ * within this wallet. Each account has its own set of addresses and keys.
1964
+ *
1965
+ * @returns The wallet's account store
1966
+ *
1967
+ * @example
1968
+ * ```typescript
1969
+ * const accountStore = wallet.accountStore;
1970
+ * const accounts = accountStore.listAccounts();
1971
+ * const firstAccount = accountStore.getAccount(0);
1972
+ * ```
1973
+ */ get accountStore() {
1974
+ return this._accountStore;
1975
+ }
1976
+ /**
1977
+ * Get the network this wallet is operating on
1978
+ *
1979
+ * @returns The network object (mainnet, testnet, or regtest)
1980
+ *
1981
+ * @example
1982
+ * ```typescript
1983
+ * const network = wallet.network;
1984
+ * console.log('Network:', network.name);
1985
+ * ```
1986
+ */ get network() {
1987
+ return this._network;
1988
+ }
1989
+ }
1990
+
1991
+
1992
+
1993
+
1994
+
1995
+
1996
+
1997
+
1998
+
1999
+ const $d99d0d987374a56c$var$MAX_INPUTS_OUTPUTS = 250;
2000
+ async function $d99d0d987374a56c$export$20e004915450ed44(txBuilder, addresses, totalTxValue, options) {
2001
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(addresses)) throw new Error("Not enough Nexa balance.");
2002
+ let usedAddresses = new Set();
2003
+ let origAmount = options.isConsolidate ? 0 : Number(totalTxValue);
2004
+ for (let item of addresses){
2005
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getNexaUtxos(item.address);
2006
+ for (let utxo of utxos){
2007
+ let input = {
2008
+ outpoint: utxo.outpoint_hash,
2009
+ address: item.address,
2010
+ satoshis: utxo.value,
2011
+ templateData: options.templateData
2012
+ };
2013
+ txBuilder.from(input);
2014
+ if (!usedAddresses.has(item.address)) usedAddresses.add(item.address);
2015
+ if (options.isConsolidate) {
2016
+ // need to handle change
2017
+ txBuilder.change(options.toChange ?? item.address);
2018
+ if (txBuilder.transaction.inputs.length > $d99d0d987374a56c$var$MAX_INPUTS_OUTPUTS) return Array.from(usedAddresses.values());
2019
+ } else {
2020
+ let tx = txBuilder.transaction;
2021
+ if (tx.inputs.length > $d99d0d987374a56c$var$MAX_INPUTS_OUTPUTS) throw new Error("Too many inputs. Consider consolidate transactions or reduce the send amount.");
2022
+ let unspent = tx.getUnspentValue();
2023
+ if (unspent < 0n) continue;
2024
+ if (unspent == 0n && options.feeFromAmount) {
2025
+ let txFee = tx.estimateRequiredFee();
2026
+ tx.updateOutputAmount(0, origAmount - txFee);
2027
+ return Array.from(usedAddresses.values());
2028
+ }
2029
+ txBuilder.change(options.toChange ?? item.address);
2030
+ if (options.feeFromAmount) {
2031
+ let hasChange = tx.getChangeOutput();
2032
+ let txFee = tx.estimateRequiredFee();
2033
+ tx.updateOutputAmount(0, origAmount - txFee);
2034
+ // edge case where change added after update
2035
+ if (!hasChange && tx.getChangeOutput()) {
2036
+ txFee = tx.estimateRequiredFee();
2037
+ tx.updateOutputAmount(0, origAmount - txFee);
2038
+ }
2039
+ }
2040
+ // check again after change output manipulation
2041
+ if (tx.getUnspentValue() < tx.estimateRequiredFee()) continue;
2042
+ return Array.from(usedAddresses.values());
2043
+ }
2044
+ }
2045
+ }
2046
+ if (options.isConsolidate) {
2047
+ if (usedAddresses.size > 0) return Array.from(usedAddresses.values());
2048
+ throw new Error("Not enough Nexa balance.");
2049
+ }
2050
+ let err = {
2051
+ errorMsg: "Not enough Nexa balance.",
2052
+ amount: (0, $633cp$UnitUtils).formatNEXA(Number(totalTxValue)),
2053
+ fee: (0, $633cp$UnitUtils).formatNEXA(txBuilder.transaction.estimateRequiredFee())
2054
+ };
2055
+ throw new Error(JSON.stringify(err));
2056
+ }
2057
+ async function $d99d0d987374a56c$export$49bc96b87058cba4(txBuilder, addresses, token, outTokenAmount) {
2058
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(addresses)) throw new Error("Not enough token balance.");
2059
+ let usedKeys = new Set();
2060
+ let inTokenAmount = 0n;
2061
+ for (let item of addresses){
2062
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(item.address, token);
2063
+ for (let utxo of utxos){
2064
+ if (utxo.token_amount < 0) continue;
2065
+ txBuilder.from({
2066
+ outpoint: utxo.outpoint_hash,
2067
+ address: item.address,
2068
+ satoshis: utxo.value,
2069
+ groupId: utxo.group,
2070
+ groupAmount: BigInt(utxo.token_amount)
2071
+ });
2072
+ inTokenAmount = inTokenAmount + BigInt(utxo.token_amount);
2073
+ if (!usedKeys.has(item.address)) usedKeys.add(item.address);
2074
+ if (inTokenAmount > (0, $424cf91992355440$export$8ba128bc85947a2a)) throw new Error("Token inputs exceeded max amount. Consider sending in small chunks");
2075
+ if (txBuilder.transaction.inputs.length > $d99d0d987374a56c$var$MAX_INPUTS_OUTPUTS) throw new Error("Too many inputs. Consider consolidating transactions or reduce the send amount.");
2076
+ if (inTokenAmount == outTokenAmount) return Array.from(usedKeys.values());
2077
+ if (inTokenAmount > outTokenAmount) {
2078
+ // change
2079
+ txBuilder.to(item.address, (0, $633cp$Transaction).DUST_AMOUNT, token, inTokenAmount - outTokenAmount);
2080
+ return Array.from(usedKeys.values());
2081
+ }
2082
+ }
2083
+ }
2084
+ throw new Error("Not enough token balance");
2085
+ }
2086
+ async function $d99d0d987374a56c$export$74e83de914f372c5(txBuilder, addresses, opReturnData, network) {
2087
+ let outpoint = '', idHex = '';
2088
+ let usedKeys = [];
2089
+ for (let item of addresses){
2090
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getNexaUtxos(item.address);
2091
+ for (let utxo of utxos){
2092
+ txBuilder.from({
2093
+ outpoint: utxo.outpoint_hash,
2094
+ address: item.address,
2095
+ satoshis: utxo.value
2096
+ });
2097
+ if ((0, $424cf91992355440$export$c8733ae29fb53302)(outpoint)) {
2098
+ outpoint = utxo.outpoint_hash;
2099
+ let id = (0, $633cp$GroupToken).findGroupId(Buffer.from(outpoint, 'hex'), Buffer.from(opReturnData, 'hex'), (0, $633cp$GroupToken).authFlags.ACTIVE_FLAG_BITS);
2100
+ const groupId = new (0, $633cp$Address)(id.hashBuffer, network, (0, $633cp$AddressType).GroupIdAddress).toString();
2101
+ txBuilder.to(item.address, (0, $633cp$Transaction).DUST_AMOUNT, groupId, (0, $633cp$GroupToken).authFlags.ACTIVE_FLAG_BITS | id.nonce);
2102
+ idHex = id.hashBuffer.toString('hex');
2103
+ usedKeys.push(item.address);
2104
+ return usedKeys;
2105
+ }
2106
+ }
2107
+ }
2108
+ throw new Error("Not enough Nexa balance.");
2109
+ }
2110
+ async function $d99d0d987374a56c$export$1eb54f2f084fd3c6(txBuilder, addresses, outpoint) {
2111
+ let utxo = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getUtxo(outpoint);
2112
+ let address = utxo.addresses[0];
2113
+ txBuilder.from({
2114
+ outpoint: outpoint,
2115
+ address: address,
2116
+ satoshis: utxo.amount
2117
+ });
2118
+ let addrKey = addresses.find((k)=>k.address === address);
2119
+ if (!addrKey) throw new Error('UTXO associated key not found in the wallet');
2120
+ return [
2121
+ addrKey.address
2122
+ ];
2123
+ }
2124
+ async function $d99d0d987374a56c$export$d7c9c386067a6463(txBuilder, addresses, token, perm, subgroup = '') {
2125
+ for (let item of addresses){
2126
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(item.address, token);
2127
+ for (let utxo of utxos){
2128
+ if (!(0, $3091f185ded8655f$export$7f7cffd29bf2d96d)(utxo.token_amount, perm)) continue;
2129
+ txBuilder.from({
2130
+ outpoint: utxo.outpoint_hash,
2131
+ address: item.address,
2132
+ satoshis: utxo.value
2133
+ });
2134
+ if (perm === 'subgroup') txBuilder.to(item.address, (0, $633cp$Transaction).DUST_AMOUNT, subgroup, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount, false));
2135
+ // if renew flag included, we don't want to burn it
2136
+ if ((0, $633cp$GroupToken).allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) txBuilder.to(item.address, (0, $633cp$Transaction).DUST_AMOUNT, token, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount));
2137
+ return [
2138
+ item.address
2139
+ ];
2140
+ }
2141
+ }
2142
+ throw new Error("The requested authority not found");
2143
+ }
2144
+ async function $d99d0d987374a56c$export$5c44e04d8c04c292(txBuilder, addresses, token, perms, toAddr) {
2145
+ let usedAddresses = [];
2146
+ let reqiredPerms = new Set(perms);
2147
+ reqiredPerms.add('authorise');
2148
+ for (let item of addresses){
2149
+ let utxos = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getTokenUtxos(item.address, token);
2150
+ for (let utxo of utxos){
2151
+ if (utxo.token_amount > 0) continue;
2152
+ let found = false;
2153
+ for (let perm of reqiredPerms)if ((0, $3091f185ded8655f$export$7f7cffd29bf2d96d)(utxo.token_amount, perm)) {
2154
+ reqiredPerms.delete(perm);
2155
+ found = true;
2156
+ }
2157
+ if (!found) continue;
2158
+ txBuilder.from({
2159
+ outpoint: utxo.outpoint_hash,
2160
+ address: item.address,
2161
+ satoshis: utxo.value
2162
+ });
2163
+ usedAddresses.push(item.address);
2164
+ // duplicate
2165
+ txBuilder.to(toAddr != null ? toAddr : item.address, (0, $633cp$Transaction).DUST_AMOUNT, token, (0, $3091f185ded8655f$export$636fb0b03b94ac81)(utxo.token_amount));
2166
+ if (reqiredPerms.size === 0) return usedAddresses;
2167
+ }
2168
+ }
2169
+ throw new Error("The required authorities not found");
2170
+ }
2171
+
2172
+
2173
+
2174
+
2175
+
2176
+ class $b43c09fc4c8f3049$export$2e2bcd8739ae039 extends (0, $def4af748ddce85f$export$bba690fb5c12ba04) {
2177
+ /**
2178
+ * Creates a new WatchOnlyTransactionCreator
2179
+ * @param tx Optional existing transaction builder or transaction data
2180
+ */ constructor(tx){
2181
+ super(tx), /** Addresses that need to be signed with (populated during transaction building) */ this._addressesToSignWith = [], /** Available addresses for input selection and change */ this._availableAddresses = [];
2182
+ }
2183
+ /**
2184
+ * Sets the source addresses for transaction inputs
2185
+ * @param address Single address string, array of addresses, or WatchOnlyAddress objects
2186
+ * @returns This instance for chaining
2187
+ */ from(address) {
2188
+ if ((0, $633cp$isString)(address)) {
2189
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(address, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(address, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
2190
+ // Single address string
2191
+ this._availableAddresses.push({
2192
+ address: address
2193
+ });
2194
+ } else if (Array.isArray(address)) // Array of addresses or WatchOnlyAddress objects
2195
+ address.forEach((addr)=>{
2196
+ if ((0, $633cp$isString)(addr)) {
2197
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(addr, this.network) && !(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(addr, this.network, (0, $633cp$AddressType).PayToPublicKeyHash)) throw new Error('Invalid Address.');
2198
+ // String address
2199
+ this._availableAddresses.push({
2200
+ address: addr
2201
+ });
2202
+ } else if (addr && typeof addr === 'object' && 'address' in addr) // WatchOnlyAddress object
2203
+ this._availableAddresses.push(addr);
2204
+ });
2205
+ else if (address.address != null) // Single WatchOnlyAddress object
2206
+ this._availableAddresses.push(address);
2207
+ return this;
2208
+ }
2209
+ /**
2210
+ * Adds a token minting operation to the transaction
2211
+ * @param token Token ID to mint
2212
+ * @param amount Amount to mint
2213
+ * @param toAddr Destination address for minted tokens
2214
+ * @returns This instance for chaining
2215
+ */ mint(token, amount, toAddr) {
2216
+ this.builder.push(async ()=>{
2217
+ this.tokenAction(toAddr, amount, token, 'mint');
2218
+ });
2219
+ return this;
2220
+ }
2221
+ /**
2222
+ * Adds a token melting operation to the transaction
2223
+ * @param token Token ID to melt
2224
+ * @param amount Amount to melt
2225
+ * @param toAddr Destination address for melted tokens
2226
+ * @returns This instance for chaining
2227
+ */ melt(token, amount, toAddr) {
2228
+ this.builder.push(async ()=>{
2229
+ this.tokenAction(toAddr, amount, token, 'melt');
2230
+ });
2231
+ return this;
2232
+ }
2233
+ /**
2234
+ * Populates the transaction with inputs and outputs based on the configured actions.
2235
+ * Handles different token operations (mint, melt, group creation, etc.) and
2236
+ * populates NEXA inputs for transaction fees.
2237
+ * @returns This instance for chaining
2238
+ */ populate() {
2239
+ this.builder.push(async ()=>{
2240
+ let tokenAddresses = [];
2241
+ let nexaAddresses = [];
2242
+ // Process token operations if any are configured
2243
+ if (this.tokens.size > 0) for (const tokenAction of this.tokens){
2244
+ if (tokenAction.action == 'mint' || tokenAction.action == 'melt') // Handle token minting/melting - requires authority
2245
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$d7c9c386067a6463)(this.transactionBuilder, this._availableAddresses, tokenAction.token, tokenAction.action));
2246
+ else if (tokenAction.action == 'group') // Handle group token creation
2247
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$74e83de914f372c5)(this.transactionBuilder, this._availableAddresses, tokenAction.token, this.network));
2248
+ else if (tokenAction.action == 'subgroup') // Handle subgroup token creation
2249
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$d7c9c386067a6463)(this.transactionBuilder, this._availableAddresses, tokenAction.parentToken, tokenAction.action, tokenAction.token));
2250
+ else if (tokenAction.action == 'renew') // Handle authority renewal
2251
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$5c44e04d8c04c292)(this.transactionBuilder, this._availableAddresses, tokenAction.token, tokenAction.extraData.perms, tokenAction.extraData?.address));
2252
+ else if (tokenAction.action == 'delete') // Handle authority deletion
2253
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$1eb54f2f084fd3c6)(this.transactionBuilder, this._availableAddresses, tokenAction.extraData.outpoint));
2254
+ else // Handle regular token transfers
2255
+ tokenAddresses = tokenAddresses.concat(await (0, $d99d0d987374a56c$export$49bc96b87058cba4)(this.transactionBuilder, this._availableAddresses, tokenAction.token, tokenAction.amount));
2256
+ // Accumulate addresses that need signing
2257
+ this._addressesToSignWith.concat(tokenAddresses);
2258
+ }
2259
+ // Populate NEXA inputs for transaction fees and change
2260
+ nexaAddresses = nexaAddresses.concat(await (0, $d99d0d987374a56c$export$20e004915450ed44)(this.transactionBuilder, this._availableAddresses, this.totalValue, this.txOptions));
2261
+ // Combine all addresses that need signing
2262
+ this._addressesToSignWith = tokenAddresses.concat(nexaAddresses);
2263
+ });
2264
+ return this;
2265
+ }
2266
+ /**
2267
+ * Parse transaction from buffer (not implemented for watch-only)
2268
+ * @param tx Transaction buffer
2269
+ * @returns This instance for chaining
2270
+ * @throws Error indicating method not implemented
2271
+ */ parseTxBuffer(tx) {
2272
+ this.builder.push(async ()=>{
2273
+ this.transactionBuilder = new (0, $633cp$TransactionBuilder)(tx);
2274
+ });
2275
+ return this;
2276
+ }
2277
+ /**
2278
+ * Parse transaction from hex string (not implemented for watch-only)
2279
+ * @param tx Transaction hex string
2280
+ * @returns This instance for chaining
2281
+ * @throws Error indicating method not implemented
2282
+ */ parseTxHex(tx) {
2283
+ this.builder.push(async ()=>{
2284
+ const txBuilder = new (0, $633cp$TransactionBuilder)(tx);
2285
+ const newTxBuilder = new (0, $633cp$TransactionBuilder)();
2286
+ const oldInputs = txBuilder.transaction.inputs;
2287
+ for (const input of oldInputs){
2288
+ const utxo = await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).getUtxo(input.outpoint.toString('hex'));
2289
+ newTxBuilder.from({
2290
+ outpoint: utxo.tx_hash,
2291
+ amount: utxo.amount,
2292
+ scriptPubKey: utxo.scriptpubkey
2293
+ });
2294
+ }
2295
+ newTxBuilder.transaction.outputs = txBuilder.transaction.outputs;
2296
+ this.transactionBuilder = newTxBuilder;
2297
+ });
2298
+ return this;
2299
+ }
2300
+ }
2301
+
2302
+
2303
+
2304
+
2305
+
2306
+
2307
+ class $426a9fb8db44c326$export$2e2bcd8739ae039 {
2308
+ /**
2309
+ * Creates a new WatchOnlyWallet instance
2310
+ * @param addressesToWatch Array of addresses to monitor
2311
+ * @param network Optional network name (defaults to mainnet)
2312
+ * @throws Error if validation fails
2313
+ */ constructor(addressesToWatch, network){
2314
+ // Validate network parameter
2315
+ if (network !== undefined && !(0, $633cp$isString)(network)) throw new Error('Network must be a string');
2316
+ if (network !== undefined && (0, $633cp$isString)(network)) {
2317
+ const n = (0, $633cp$Networks).get(network);
2318
+ if (n === undefined) throw new Error(`Invalid network: ${network}`);
2319
+ }
2320
+ this._network = (0, $633cp$Networks).get(network) ?? (0, $633cp$Networks).mainnet;
2321
+ // Validate addressesToWatch parameter
2322
+ this._addressesToWatch = this.validateAddressesToWatch(addressesToWatch);
2323
+ }
2324
+ /**
2325
+ * Validates the addresses to watch array
2326
+ * @param addressesToWatch Array of addresses to validate
2327
+ * @returns Validated array of WatchOnlyAddress objects
2328
+ * @throws Error if validation fails
2329
+ */ validateAddressesToWatch(addressesToWatch) {
2330
+ if (addressesToWatch === null || addressesToWatch === undefined) throw new Error('addresesToWatch is required');
2331
+ if (!(0, $633cp$isArray)(addressesToWatch)) throw new Error('addressesToWatch must be an array');
2332
+ // Check if array is not empty
2333
+ if (addressesToWatch.length === 0) throw new Error('addressesToWatch cannot be empty');
2334
+ // Validate each address object
2335
+ const validatedAddresses = [];
2336
+ for(let i = 0; i < addressesToWatch.length; i++){
2337
+ const addr = addressesToWatch[i];
2338
+ // Check if address is an object
2339
+ if (!(0, $633cp$isObject)(addr) || (0, $633cp$isArray)(addr)) throw new Error(`addressesToWatch[${i}] must be an object`);
2340
+ // Check if address property exists and is a string
2341
+ if (!addr.hasOwnProperty('address') || !(0, $633cp$isString)(addr.address)) throw new Error(`addressesToWatch[${i}].address must be a string`);
2342
+ // Check if address is not empty
2343
+ if (addr.address.trim() === '') throw new Error(`addressesToWatch[${i}].address cannot be empty`);
2344
+ // Validate address format
2345
+ if (!(0, $f10b40ff0fa7ccfb$export$8d986bd2866fe6ab)(addr.address, this._network)) throw new Error(`addressesToWatch[${i}].address is not a valid NEXA address: ${addr.address}`);
2346
+ // Validate optional xPub property
2347
+ if (addr.xPub !== undefined && !(0, $633cp$isObject)(addr.xPub)) throw new Error(`addressesToWatch[${i}].xPub must be a PublicKey object`);
2348
+ // Validate optional derivationPath property
2349
+ if (addr.derivationPath !== undefined && !(0, $633cp$isString)(addr.derivationPath)) throw new Error(`addressesToWatch[${i}].derivationPath must be a string`);
2350
+ // Check for duplicate addresses
2351
+ const isDuplicate = validatedAddresses.some((existingAddr)=>existingAddr.address === addr.address);
2352
+ if (isDuplicate) throw new Error(`Duplicate address found: ${addr.address}`);
2353
+ validatedAddresses.push({
2354
+ address: addr.address.trim(),
2355
+ xPub: addr.xPub,
2356
+ derivationPath: addr.derivationPath
2357
+ });
2358
+ }
2359
+ return validatedAddresses;
2360
+ }
2361
+ /**
2362
+ * Creates a new transaction creator for this watch-only wallet
2363
+ * @param x Optional transaction data - can be a TransactionBuilder, hex string, or Buffer
2364
+ * @returns WatchOnlyTransactionCreator configured with wallet's addresses and network
2365
+ */ newTransaction(x) {
2366
+ let tx;
2367
+ // Handle different input types for creating transactions
2368
+ if (x instanceof (0, $633cp$TransactionBuilder)) // Use existing TransactionBuilder instance
2369
+ tx = new (0, $b43c09fc4c8f3049$export$2e2bcd8739ae039)(x);
2370
+ else if ((0, $633cp$isString)(x)) // Parse transaction from hex string
2371
+ tx = new (0, $b43c09fc4c8f3049$export$2e2bcd8739ae039)().parseTxHex(x);
2372
+ else if ((0, $633cp$isBuffer)(x) && !(0, $633cp$isNil)(x)) // Parse transaction from buffer
2373
+ tx = new (0, $b43c09fc4c8f3049$export$2e2bcd8739ae039)().parseTxBuffer(x);
2374
+ else // Create new empty transaction
2375
+ tx = new (0, $b43c09fc4c8f3049$export$2e2bcd8739ae039)();
2376
+ // Configure transaction with wallet's addresses and network
2377
+ return tx.from(this._addressesToWatch).onNetwork(this._network);
2378
+ }
2379
+ /**
2380
+ * Broadcasts a signed transaction to the network
2381
+ * @param transaction Hex-encoded signed transaction
2382
+ * @returns Promise resolving to transaction ID
2383
+ * @throws Error if transaction is invalid or broadcast fails
2384
+ */ async sendTransaction(transaction) {
2385
+ (0, $8c756bc820fcaf73$export$2e2bcd8739ae039).validateArgument((0, $633cp$isString)(transaction), 'transaction must be present and valid');
2386
+ return (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).broadcast(transaction);
2387
+ }
2388
+ async subscribeToAddressNotifications(callback) {
2389
+ await (0, $30c92dd8e96ca60d$export$eaa49f0478d81b9d).subscribeToAddresses(this._addressesToWatch.map((addr)=>addr.address), callback);
2390
+ }
2391
+ /**
2392
+ * Gets the list of addresses being watched
2393
+ * @returns Array of watched addresses (copy to prevent mutation)
2394
+ */ getWatchedAddresses() {
2395
+ return [
2396
+ ...this._addressesToWatch
2397
+ ];
2398
+ }
2399
+ }
2400
+
2401
+
2402
+
2403
+
2404
+
2405
+
2406
+
2407
+
2408
+
2409
+
2410
+
2411
+ /**
2412
+ * Guards against multiple instances of the wallet SDK being loaded.
2413
+ * This prevents conflicts and ensures only one version is active at a time.
2414
+ * @param version - The version string to check
2415
+ * @throws {Error} When multiple instances are detected
2416
+ */ function $5cbb3ff6642afc2e$var$versionGuard(version) {
2417
+ if (version !== undefined) {
2418
+ let message = "More than one instance of Wallet SDKPlease make sure to require Wallet SDK and check that submodules do not also include their own Wallet SDK dependency.";
2419
+ throw new Error(message);
2420
+ }
2421
+ }
2422
+ $5cbb3ff6642afc2e$var$versionGuard($parcel$global._walletSdk_ver);
2423
+ $parcel$global._walletSdk_ver = `v${0, $bbe36848c5b6746e$exports.version}`;
2424
+ /**
2425
+ * Wallet SDK - A TypeScript SDK for the Nexa blockchain
2426
+ *
2427
+ * This SDK provides comprehensive wallet functionality including:
2428
+ * - Creating and managing wallets from seed phrases or private keys
2429
+ * - Account management with different account types
2430
+ * - Transaction building and signing
2431
+ * - Token operations and management
2432
+ * - Message signing and verification
2433
+ *
2434
+ * @example
2435
+ * ```typescript
2436
+ * import { Wallet } from 'wallet-sdk-ts';
2437
+ *
2438
+ * // Create a new wallet
2439
+ * const wallet = Wallet.create();
2440
+ *
2441
+ * // Or restore from seed phrase
2442
+ * const wallet = Wallet.fromSeedPhrase('your seed phrase here');
2443
+ *
2444
+ * // Initialize and discover accounts
2445
+ * await wallet.initialize();
2446
+ * ```
2447
+ */ const $5cbb3ff6642afc2e$var$walletSdk = {
2448
+ versionGuard: $5cbb3ff6642afc2e$var$versionGuard,
2449
+ version: `v${(0, $bbe36848c5b6746e$exports.version)}`,
2450
+ Wallet: $f2814d31d49d257b$export$2e2bcd8739ae039
2451
+ };
2452
+ var $5cbb3ff6642afc2e$export$2e2bcd8739ae039 = $5cbb3ff6642afc2e$var$walletSdk;
2453
+
2454
+
2455
+ export {$5cbb3ff6642afc2e$export$2e2bcd8739ae039 as default, $f2814d31d49d257b$export$2e2bcd8739ae039 as Wallet, $426a9fb8db44c326$export$2e2bcd8739ae039 as WatchOnlyWallet, $f10b40ff0fa7ccfb$export$b8ca5fa4899cbfc7 as AccountType, $f10b40ff0fa7ccfb$export$dcc1fb6ad5308e56 as TxTokenType, $51649cc8d0caebe5$export$c54c8796e94a37a0 as BaseAccount, $3213756e8a8eb72f$export$2e2bcd8739ae039 as DefaultAccount, $5ef3d149a7ae4b51$export$2e2bcd8739ae039 as DappAccount, $fcf0a0849682f4b5$export$2e2bcd8739ae039 as VaultAccount, $f956f86dd8b9f336$export$2e2bcd8739ae039 as AccountStore, $d9127651ccaae19d$export$2e2bcd8739ae039 as WalletTransactionCreator, $b43c09fc4c8f3049$export$2e2bcd8739ae039 as WatchOnlyTransactionCreator, $30c92dd8e96ca60d$export$eaa49f0478d81b9d as rostrumProvider};
2456
+ //# sourceMappingURL=index.mjs.map