mainnet-js 1.1.34-alpha.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/dist/index.html +1 -1
  2. package/dist/{mainnet-1.1.34-alpha.1.js → mainnet-2.0.0.js} +26 -338
  3. package/dist/module/db/SqlProvider.d.ts +2 -2
  4. package/dist/module/db/SqlProvider.d.ts.map +1 -1
  5. package/dist/module/db/SqlProvider.js +6 -24
  6. package/dist/module/db/SqlProvider.js.map +1 -1
  7. package/dist/module/index.d.ts +0 -3
  8. package/dist/module/index.d.ts.map +1 -1
  9. package/dist/module/index.js +3 -6
  10. package/dist/module/index.js.map +1 -1
  11. package/dist/module/transaction/Wif.d.ts +4 -8
  12. package/dist/module/transaction/Wif.d.ts.map +1 -1
  13. package/dist/module/transaction/Wif.js +6 -10
  14. package/dist/module/transaction/Wif.js.map +1 -1
  15. package/dist/module/util/deriveCashaddr.d.ts +1 -0
  16. package/dist/module/util/deriveCashaddr.d.ts.map +1 -1
  17. package/dist/module/util/deriveCashaddr.js +8 -1
  18. package/dist/module/util/deriveCashaddr.js.map +1 -1
  19. package/dist/module/wallet/Base.d.ts +1 -1
  20. package/dist/module/wallet/Base.js +1 -1
  21. package/dist/module/wallet/Bcmr.d.ts.map +1 -1
  22. package/dist/module/wallet/Bcmr.js +0 -1
  23. package/dist/module/wallet/Bcmr.js.map +1 -1
  24. package/dist/module/wallet/Util.d.ts +2 -2
  25. package/dist/module/wallet/Util.js +2 -2
  26. package/dist/module/wallet/Wif.d.ts +0 -28
  27. package/dist/module/wallet/Wif.d.ts.map +1 -1
  28. package/dist/module/wallet/Wif.js +2 -109
  29. package/dist/module/wallet/Wif.js.map +1 -1
  30. package/dist/module/wallet/createWallet.d.ts +0 -12
  31. package/dist/module/wallet/createWallet.d.ts.map +1 -1
  32. package/dist/module/wallet/createWallet.js +0 -43
  33. package/dist/module/wallet/createWallet.js.map +1 -1
  34. package/dist/module/wallet/interface.d.ts +0 -2
  35. package/dist/module/wallet/interface.d.ts.map +1 -1
  36. package/dist/module/webhook/Webhook.d.ts +1 -6
  37. package/dist/module/webhook/Webhook.d.ts.map +1 -1
  38. package/dist/module/webhook/Webhook.js +0 -4
  39. package/dist/module/webhook/Webhook.js.map +1 -1
  40. package/dist/module/webhook/index.d.ts +0 -1
  41. package/dist/module/webhook/index.d.ts.map +1 -1
  42. package/dist/module/webhook/index.js +0 -1
  43. package/dist/module/webhook/index.js.map +1 -1
  44. package/dist/module/webhook/interface.d.ts +0 -1
  45. package/dist/module/webhook/interface.d.ts.map +1 -1
  46. package/dist/tsconfig.tsbuildinfo +1 -1
  47. package/package.json +5 -10
  48. package/src/db/SqlProvider.test.ts +2 -18
  49. package/src/db/SqlProvider.ts +5 -26
  50. package/src/index.ts +3 -7
  51. package/src/transaction/Wif.ts +2 -19
  52. package/src/util/deriveCashaddr.test.ts +8 -0
  53. package/src/util/deriveCashaddr.ts +9 -0
  54. package/src/wallet/Base.ts +1 -1
  55. package/src/wallet/Bcmr.ts +0 -1
  56. package/src/wallet/Util.ts +2 -2
  57. package/src/wallet/Wif.test.ts +0 -23
  58. package/src/wallet/Wif.ts +2 -148
  59. package/src/wallet/createWallet.ts +0 -53
  60. package/src/wallet/interface.ts +0 -2
  61. package/src/webhook/Webhook.ts +4 -10
  62. package/src/webhook/index.ts +0 -1
  63. package/src/webhook/interface.ts +0 -1
  64. package/webpack.config.cjs +7 -7
  65. package/dist/module/slp/GsppProvider.d.ts +0 -55
  66. package/dist/module/slp/GsppProvider.d.ts.map +0 -1
  67. package/dist/module/slp/GsppProvider.js +0 -204
  68. package/dist/module/slp/GsppProvider.js.map +0 -1
  69. package/dist/module/slp/SlpDbProvider.d.ts +0 -52
  70. package/dist/module/slp/SlpDbProvider.d.ts.map +0 -1
  71. package/dist/module/slp/SlpDbProvider.js +0 -175
  72. package/dist/module/slp/SlpDbProvider.js.map +0 -1
  73. package/dist/module/slp/SlpDbTemplates.d.ts +0 -313
  74. package/dist/module/slp/SlpDbTemplates.d.ts.map +0 -1
  75. package/dist/module/slp/SlpDbTemplates.js +0 -375
  76. package/dist/module/slp/SlpDbTemplates.js.map +0 -1
  77. package/dist/module/slp/SlpLibAuth.d.ts +0 -210
  78. package/dist/module/slp/SlpLibAuth.d.ts.map +0 -1
  79. package/dist/module/slp/SlpLibAuth.js +0 -451
  80. package/dist/module/slp/SlpLibAuth.js.map +0 -1
  81. package/dist/module/slp/SlpProvider.d.ts +0 -24
  82. package/dist/module/slp/SlpProvider.d.ts.map +0 -1
  83. package/dist/module/slp/SlpProvider.js +0 -29
  84. package/dist/module/slp/SlpProvider.js.map +0 -1
  85. package/dist/module/slp/index.d.ts +0 -6
  86. package/dist/module/slp/index.d.ts.map +0 -1
  87. package/dist/module/slp/index.js +0 -5
  88. package/dist/module/slp/index.js.map +0 -1
  89. package/dist/module/slp/interface.d.ts +0 -114
  90. package/dist/module/slp/interface.d.ts.map +0 -1
  91. package/dist/module/slp/interface.js +0 -7
  92. package/dist/module/slp/interface.js.map +0 -1
  93. package/dist/module/util/bchaddr.d.ts +0 -2
  94. package/dist/module/util/bchaddr.d.ts.map +0 -1
  95. package/dist/module/util/bchaddr.js +0 -16
  96. package/dist/module/util/bchaddr.js.map +0 -1
  97. package/dist/module/wallet/Slp.d.ts +0 -431
  98. package/dist/module/wallet/Slp.d.ts.map +0 -1
  99. package/dist/module/wallet/Slp.js +0 -770
  100. package/dist/module/wallet/Slp.js.map +0 -1
  101. package/dist/module/webhook/WebhookSlp.d.ts +0 -15
  102. package/dist/module/webhook/WebhookSlp.d.ts.map +0 -1
  103. package/dist/module/webhook/WebhookSlp.js +0 -100
  104. package/dist/module/webhook/WebhookSlp.js.map +0 -1
  105. package/src/slp/GsppProvider.test.ts +0 -40
  106. package/src/slp/GsppProvider.ts +0 -329
  107. package/src/slp/SlpDbProvider.test.ts +0 -27
  108. package/src/slp/SlpDbProvider.ts +0 -291
  109. package/src/slp/SlpDbTemplates.ts +0 -400
  110. package/src/slp/SlpLibAuth.test.ts +0 -162
  111. package/src/slp/SlpLibAuth.ts +0 -532
  112. package/src/slp/SlpProvider.ts +0 -100
  113. package/src/slp/index.ts +0 -6
  114. package/src/slp/interface.ts +0 -128
  115. package/src/util/bchaddr.test.ts +0 -27
  116. package/src/util/bchaddr.ts +0 -27
  117. package/src/wallet/Slp.test.headless.js +0 -120
  118. package/src/wallet/Slp.test.ts +0 -1000
  119. package/src/wallet/Slp.ts +0 -1014
  120. package/src/webhook/WebhookSlp.test.ts +0 -288
  121. package/src/webhook/WebhookSlp.ts +0 -123
@@ -1,770 +0,0 @@
1
- import { Wallet, RegTestWallet, TestNetWallet, WifWallet, TestNetWifWallet, RegTestWifWallet, WatchWallet, TestNetWatchWallet, RegTestWatchWallet, } from "../wallet/Wif.js";
2
- import { SlpTokenType, } from "../slp/interface.js";
3
- import { SlpDbProvider } from "../slp/SlpDbProvider.js";
4
- import { qrAddress } from "../qr/Qr.js";
5
- import BigNumber from "bignumber.js";
6
- import { getRelayFeeCache } from "../network/getRelayFeeCache.js";
7
- import { buildEncodedTransaction, getFeeAmount, getSuitableUtxos, } from "../transaction/Wif.js";
8
- import { SlpGetGenesisOutputs, SlpGetMintOutputs, SlpGetSendOutputs, } from "../slp/SlpLibAuth.js";
9
- import { binToHex } from "@bitauth/libauth";
10
- import { toCashAddress, toSlpAddress } from "../util/bchaddr.js";
11
- import { GsppProvider } from "../slp/GsppProvider.js";
12
- import { delay } from "../util/delay.js";
13
- import { Util } from "./Util.js";
14
- import { FeePaidByEnum } from "./enum.js";
15
- import { getRuntimePlatform, RuntimePlatform, } from "../util/getRuntimePlatform.js";
16
- /**
17
- * Class to manage an slp enabled wallet.
18
- */
19
- export class Slp {
20
- /**
21
- * Initializes an Slp Wallet.
22
- *
23
- * @param wallet A non-slp wallet object
24
- */
25
- constructor(wallet) {
26
- // a loookup table of spent inputs to keep track of NFT parent token consumption. related to a bug in SLPDB
27
- this.spentParentUtxos = [];
28
- this.slpaddr = toSlpAddress(wallet.cashaddr);
29
- this.wallet = wallet;
30
- let provider = Slp.defaultProvider;
31
- if (getRuntimePlatform() === RuntimePlatform.node &&
32
- process.env.SLP_PROVIDER)
33
- provider = process.env.SLP_PROVIDER;
34
- if (provider === "gspp") {
35
- this.provider = new GsppProvider(this.wallet.network);
36
- }
37
- else {
38
- // provider === "slpdb"
39
- this.provider = new SlpDbProvider(this.wallet.network);
40
- }
41
- }
42
- static get walletType() {
43
- return Wallet;
44
- }
45
- /**
46
- * setProvider - sets the provider to fetch slp data from
47
- */
48
- setProvider(provider) {
49
- return (this.provider = provider);
50
- }
51
- /**
52
- * getDepositAddress - get the slp deposit address
53
- *
54
- * a high-level function,
55
- *
56
- * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpDepositAddress|/wallet/slp/deposit_address} for REST endpoint
57
- *
58
- * @returns The the slp address as a string
59
- */
60
- getDepositAddress() {
61
- return this.slpaddr;
62
- }
63
- /**
64
- * getDepositQr - get an slp address qrcode, encoded for display on the web
65
- *
66
- * a high-level function
67
- *
68
- * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpDepositQr|/wallet/slp/deposit_qr} for REST endpoint
69
- *
70
- * @returns The qrcode for the slp address
71
- */
72
- getDepositQr() {
73
- const result = qrAddress(this.slpaddr);
74
- result.alt = "A Bitcoin Cash Simple Ledger Protocol QR Code";
75
- return result;
76
- }
77
- /**
78
- * getTokenInfo - get data associated with a token
79
- *
80
- * a high-level function
81
- *
82
- * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpTokenInfo|/wallet/slp/token_info} for REST endpoint
83
- *
84
- * @param tokenId The tokenId to request information about
85
- *
86
- * @returns Promise to the slp token info or undefined.
87
- */
88
- getTokenInfo(tokenId) {
89
- return this.provider.SlpTokenInfo(tokenId);
90
- }
91
- /**
92
- * getSlpOutpoints - get a list of SLP unspent outpoints
93
- *
94
- * an intermediate function contributing to the output of wallet.getUtxos() and /wallet/utxos for slp enabled wallets
95
- *
96
- * @param slpaddr The slpaddr to request slp unspent outpoints for
97
- *
98
- * @returns Promise to a list of slp unspent outpoints
99
- */
100
- async getSlpOutpoints() {
101
- return this.provider.SlpOutpoints(this.slpaddr);
102
- }
103
- /**
104
- * getSlpUtxos - get a list of SLP unspent outputs
105
- *
106
- * @returns Promise to a list of slp unspent outputs
107
- */
108
- async getSlpUtxos() {
109
- return this.provider.SlpUtxos(this.slpaddr);
110
- }
111
- /**
112
- * getFormattedSlpUtxos - get a list of unspent outputs
113
- *
114
- * an intermediate function
115
- *
116
- * @returns Promise to a list of slp formatted unspent outputs
117
- */
118
- async getFormattedSlpUtxos() {
119
- const utxos = await this.getSlpUtxos();
120
- return utxos.map((val) => {
121
- let utxo = {};
122
- utxo.ticker = val.ticker;
123
- utxo.tokenId = val.tokenId;
124
- utxo.value = val.value.toString();
125
- utxo.satoshis = val.satoshis;
126
- utxo.decimals = val.decimals;
127
- utxo.txId = val.txid;
128
- utxo.index = val.vout;
129
- utxo.utxoId = utxo.txId + ":" + utxo.index;
130
- utxo.type = val.type;
131
- return utxo;
132
- });
133
- }
134
- /**
135
- * getBatonUtxos - get a list of baton unspent outputs
136
- *
137
- * an intermediate function
138
- *
139
- * @param tokenId The id of the slp token
140
- *
141
- * @returns Promise to a list of slp unspent outputs
142
- */
143
- async getBatonUtxos(tokenId) {
144
- return this.provider.SlpBatonUtxos(this.slpaddr, tokenId);
145
- }
146
- /**
147
- * getHistory - get a transaction history for a particular address
148
- *
149
- * an intermediate function
150
- *
151
- * @param tokenId The id of the slp token
152
- *
153
- * @returns Promise to a list of transactions
154
- */
155
- async getHistory(tokenId) {
156
- return this.provider.SlpAddressTransactionHistory(this.slpaddr, tokenId);
157
- }
158
- /**
159
- * getLastTransaction - get a last SLP token transaction of a particular address
160
- *
161
- * @param {boolean} [confirmedOnly=false] When confirmedOnly is true, results will be limited to only transactions included in a block.
162
- *
163
- * @returns Promise to the transaction hex or error
164
- */
165
- async getLastTransaction(confirmedOnly = false) {
166
- let history = await this.getHistory();
167
- if (confirmedOnly) {
168
- history = history.filter((val) => val.height > 0);
169
- }
170
- const [lastTx] = history.slice(-1);
171
- return this.wallet.provider.getRawTransactionObject(lastTx.tx_hash);
172
- }
173
- /**
174
- * getBalance - get a token balance for a particular address
175
- *
176
- * a high-level function, see also /wallet/slp/balance REST endpoint
177
- *
178
- * @param tokenId The id of the slp token
179
- *
180
- * @returns Promise to an SlpTokenBalance
181
- */
182
- async getBalance(tokenId) {
183
- if (!tokenId) {
184
- throw new Error(`Invalid tokenId ${tokenId}`);
185
- }
186
- return this.provider.SlpTokenBalance(this.slpaddr, tokenId);
187
- }
188
- /**
189
- * getAllBalances - get all token balances for a particular address
190
- *
191
- * a high-level function, see also /wallet/slp/all_balances REST endpoint
192
- *
193
- * @returns Promise to an array of SlpTokenBalance
194
- */
195
- async getAllBalances() {
196
- return this.provider.SlpAllTokenBalances(this.slpaddr);
197
- }
198
- /**
199
- * watchBalance - set up a callback to be called upon wallet's slp balance change
200
- *
201
- * can be cancelled by calling the function returned from this one
202
- *
203
- * @param callback The callback function to be called each time the balance changes
204
- * @param tokenId Specific token id to watch
205
- *
206
- * @returns A function to cancel the watching
207
- */
208
- watchBalance(callback, tokenId) {
209
- return this.provider.SlpWatchBalance(callback, this.slpaddr, tokenId);
210
- }
211
- /**
212
- * waitForBalance - wait for address balance to be greater than or equal to the target value
213
- *
214
- * This call halts the program execution
215
- *
216
- * @param value Target balance value
217
- * @param tokenId Specific token id to watch
218
- *
219
- * @returns Actual token balance after reaching or surpassing the target value
220
- */
221
- async waitForBalance(value, tokenId) {
222
- return this.provider.SlpWaitForBalance(value, this.slpaddr, tokenId);
223
- }
224
- /**
225
- * watchBalance - set up a callback to be called upon wallet's slp transactions occurring
226
- *
227
- * can be cancelled by calling the function returned from this one
228
- *
229
- * @param callback The callback function to be called each time the balance changes
230
- * @param tokenId Specific token id to watch, optional
231
- *
232
- * @returns A function to cancel the watching
233
- */
234
- watchTransactions(callback, tokenId) {
235
- return this.provider.SlpWatchTransactions(callback, this.slpaddr, tokenId);
236
- }
237
- /**
238
- * waitForBalance - wait for the next SLP transaction to occur
239
- *
240
- * This call halts the program execution
241
- *
242
- * @param tokenId Specific token id to watch, optional
243
- *
244
- * @returns Transaction object
245
- */
246
- async waitForTransaction(tokenId) {
247
- return this.provider.SlpWaitForTransaction(this.slpaddr, tokenId);
248
- }
249
- /**
250
- * genesis - create a new Type1 SLP token
251
- *
252
- * @param options Token creation options @see SlpGenesisOptions
253
- *
254
- * @returns Token Id and new token balance
255
- */
256
- async genesis(options) {
257
- let result = await this._processGenesis(options);
258
- return {
259
- tokenId: result,
260
- balance: await this.getBalance(result),
261
- };
262
- }
263
- /**
264
- * nftParentGenesis - create a new NFT Parent token
265
- *
266
- * @param options Token creation options @see SlpGenesisOptions
267
- *
268
- * @returns Token Id and new token balance
269
- */
270
- async nftParentGenesis(options) {
271
- options.type = SlpTokenType.NftParent;
272
- let result = await this._processGenesis(options);
273
- return {
274
- tokenId: result,
275
- balance: await this.getBalance(result),
276
- };
277
- }
278
- /**
279
- * nftParentGenesis - create a new NFT Child token
280
- *
281
- * @param parentTokenId Parent token id, at least one is required and will be spent in the child genesis process
282
- * @param options Token creation options @see SlpGenesisOptions
283
- *
284
- * @returns Token Id and new token balance
285
- */
286
- async nftChildGenesis(options) {
287
- if (!options.parentTokenId) {
288
- throw new Error(`The 'parentTokenId' was not set or invalid ${options.parentTokenId}`);
289
- }
290
- let parentUtxos = await this.provider.SlpSpendableUtxos(this.slpaddr, options.parentTokenId);
291
- parentUtxos = parentUtxos.filter((val) => this.spentParentUtxos.indexOf(`${val.txid}:${val.vout}`) === -1);
292
- parentUtxos = parentUtxos.sort((a, b) => a.value.comparedTo(b.value));
293
- if (!parentUtxos.length) {
294
- throw new Error(`You do not own any NFT parent tokens with id ${options.parentTokenId}`);
295
- }
296
- if (parentUtxos[0].type !== SlpTokenType.NftParent) {
297
- throw new Error(`The 'parentTokenId' is not of type ${SlpTokenType.NftParent}`);
298
- }
299
- // we are about to spend exactly 1 NFT parent
300
- // if we do not have it, we have to make one by splitting
301
- if (parentUtxos[0].value.isGreaterThan(new BigNumber(1))) {
302
- await this.send([
303
- {
304
- slpaddr: this.slpaddr,
305
- tokenId: options.parentTokenId,
306
- value: new BigNumber(1),
307
- },
308
- ]);
309
- return await this.nftChildGenesis(options);
310
- }
311
- options.type = SlpTokenType.NftChild;
312
- options.endBaton = true;
313
- options.initialAmount = 1;
314
- options.decimals = 0;
315
- let result = await this._processGenesis(options, [parentUtxos[0]]);
316
- const tx = (await this.wallet.provider.getRawTransactionObject(result));
317
- tx.vin.forEach((val) => this.spentParentUtxos.push(`${val.txid}:${val.vout}`));
318
- return {
319
- tokenId: result,
320
- balance: await this.getBalance(result),
321
- };
322
- }
323
- /**
324
- * _processGenesis - prepare the genesis transaction with given parameters
325
- *
326
- * a private utility wrapper to pre-process transactions
327
- *
328
- * @param options genesis options to controll the process
329
- *
330
- * @returns the created tokenId (which is genesis transaction id) and token balance
331
- */
332
- async _processGenesis(options, ensureInputs = []) {
333
- options = this.substituteOptionals(options);
334
- let slpOutputsResult = await SlpGetGenesisOutputs(options);
335
- let fundingBchUtxos = await this.wallet
336
- .slpAware(true)
337
- .getAddressUtxos(this.wallet.cashaddr);
338
- fundingBchUtxos = [...ensureInputs, ...fundingBchUtxos];
339
- return this.processSlpTransaction(fundingBchUtxos, slpOutputsResult);
340
- }
341
- /**
342
- * sendMax - send the maximum spendable amount for a token to an slpaddr.
343
- *
344
- * a high-level function, see also /wallet/slp/send_max REST endpoint
345
- *
346
- * @param slpaddr destination SLP address
347
- * @param tokenId the id of the token to be spent
348
- *
349
- * @returns transaction id and token balance
350
- */
351
- async sendMax(slpaddr, tokenId) {
352
- const balance = await this.getBalance(tokenId);
353
- const requests = [balance].map((val) => ({
354
- slpaddr: slpaddr,
355
- value: val.value,
356
- ticker: val.ticker,
357
- tokenId: val.tokenId,
358
- }));
359
- return this.send(requests);
360
- }
361
- /**
362
- * explorerUrl Web url to a transaction on a block explorer
363
- *
364
- * @param txId transaction Id
365
- * @returns Url string
366
- */
367
- explorerUrl(txId) {
368
- const explorerUrlMap = {
369
- mainnet: "https://simpleledger.info/#tx/",
370
- testnet: "https://testnet.simpleledger.info/#tx/",
371
- regtest: "",
372
- };
373
- return explorerUrlMap[this.wallet.network] + txId;
374
- }
375
- /**
376
- * send - attempt to process a list of slp send requests.
377
- *
378
- * a high-level function, see also /wallet/slp/send REST endpoint
379
- *
380
- * @param [requests] list of send requests
381
- *
382
- * @returns transaction id and token balance
383
- */
384
- async send(requests) {
385
- let [actualTokenId, result] = await this._processSendRequests(requests);
386
- return {
387
- txId: result,
388
- balance: await this.getBalance(actualTokenId),
389
- explorerUrl: this.explorerUrl(result),
390
- };
391
- }
392
- /**
393
- * _processSendRequests - given a list of sendRequests, estimate fees, build the transaction and submit it.
394
- *
395
- * A private utility wrapper to pre-process transactions
396
- *
397
- * Unstable - behavior may change without notice.
398
- *
399
- * @param {SlpSendRequest[]} sendRequests
400
- */
401
- async _processSendRequests(sendRequests) {
402
- if (!sendRequests.length) {
403
- throw Error("Empty send requests");
404
- }
405
- if (sendRequests.length > 19) {
406
- throw Error("Too many send requests in one transaction");
407
- }
408
- const uniqueTokenIds = new Set(sendRequests.map((val) => val.tokenId));
409
- if (uniqueTokenIds.size > 1) {
410
- throw Error("You have two different token types with the same ticker. Pass tokenId parameter");
411
- }
412
- const tokenId = sendRequests[0].tokenId;
413
- if (!tokenId.match(/^[0-9a-fA-F]{64}$/)) {
414
- throw new Error("Invalid tokenId, must be 64 character long hexadecimal string");
415
- }
416
- const slpUtxos = await this.provider.SlpSpendableUtxos(this.slpaddr, tokenId);
417
- let slpOutputsResult = await SlpGetSendOutputs(this.slpaddr, slpUtxos, sendRequests);
418
- let fundingBchUtxos = await this.wallet
419
- .slpAware(true)
420
- .getAddressUtxos(this.wallet.cashaddr);
421
- let slpToBchUtxos = slpOutputsResult.FundingSlpUtxos.map((val) => val);
422
- fundingBchUtxos = [...slpToBchUtxos, ...fundingBchUtxos];
423
- const actualTokenId = slpUtxos[0].tokenId;
424
- return [
425
- actualTokenId,
426
- await this.processSlpTransaction(fundingBchUtxos, slpOutputsResult, actualTokenId),
427
- ];
428
- }
429
- /**
430
- * mint - create new tokens to increase the circulation supply.
431
- *
432
- * a high-level function, see also /wallet/slp/mint endpoint
433
- *
434
- * @param value amount to mint
435
- * @param tokenId the tokenId of the slp being minted
436
- * @param endBaton boolean indicating whether the token should continue to be "mintable"
437
- *
438
- * @returns transaction id and token balance
439
- */
440
- async mint(options) {
441
- let [actualTokenId, result] = await this._processMint(options);
442
- return {
443
- txId: result,
444
- balance: await this.getBalance(actualTokenId),
445
- };
446
- }
447
- /**
448
- * _processMint - given mint parameters, prepare the transaction
449
- *
450
- * a private utility wrapper to pre-process transactions
451
- *
452
- * @param value amount to mint
453
- * @param tokenId the tokenId of the slp being minted
454
- * @param endBaton boolean indicating whether the token should continue to be "mintable"
455
- *
456
- * @returns the tokenId and minting transaction id
457
- */
458
- async _processMint(options) {
459
- options = this.substituteOptionals(options);
460
- options.value = new BigNumber(options.value);
461
- if (options.value.isLessThanOrEqualTo(0) &&
462
- options.batonReceiverSlpAddr === this.slpaddr) {
463
- throw Error("Mint amount should be greater than zero");
464
- }
465
- const slpBatonUtxos = await this.getBatonUtxos(options.tokenId);
466
- if (!slpBatonUtxos.length) {
467
- throw Error(`You do not possess the minting baton for ${options.tokenId}`);
468
- }
469
- let slpOutputsResult = await SlpGetMintOutputs(options, slpBatonUtxos);
470
- let bchUtxos = await this.wallet
471
- .slpAware(true)
472
- .getAddressUtxos(this.wallet.cashaddr);
473
- let fundingBchUtxos = bchUtxos;
474
- let slpToBchUtxos = slpOutputsResult.FundingSlpUtxos.map((val) => val);
475
- fundingBchUtxos = [...slpToBchUtxos, ...fundingBchUtxos];
476
- return [
477
- options.tokenId,
478
- await this.processSlpTransaction(fundingBchUtxos, slpOutputsResult, options.tokenId),
479
- ];
480
- }
481
- /**
482
- * processSlpTransaction - process the prepared SLP transaction and submit it to the network
483
- *
484
- * @param fundingBchUtxos ensure these BCH utxos to be spent in the process
485
- * @param slpOutputsResult prepared SLP outputs to be added to transaction
486
- *
487
- * @returns the tokenId and minting transaction id
488
- */
489
- async processSlpTransaction(fundingBchUtxos, slpOutputsResult, tokenId) {
490
- if (!this.wallet.privateKey) {
491
- throw new Error(`Wallet ${this.wallet.name} is missing either a network or private key`);
492
- }
493
- if (!fundingBchUtxos.length) {
494
- throw new Error("No bch available to fund this transaction");
495
- }
496
- const bestHeight = await this.wallet.provider.getBlockHeight();
497
- const relayFeePerByteInSatoshi = await getRelayFeeCache(this.wallet.provider);
498
- const feeEstimate = await getFeeAmount({
499
- utxos: fundingBchUtxos,
500
- sendRequests: slpOutputsResult.BchSendRequests,
501
- privateKey: this.wallet.privateKey,
502
- sourceAddress: this.wallet.cashaddr,
503
- relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,
504
- slpOutputs: slpOutputsResult.SlpOutputs,
505
- feePaidBy: FeePaidByEnum.change,
506
- });
507
- const bchSpendAmount = slpOutputsResult.BchSendRequests.map((val) => val.value).reduce((a, b) => a + b, 0);
508
- let fundingUtxos = await getSuitableUtxos(fundingBchUtxos, BigInt(bchSpendAmount) + BigInt(feeEstimate), bestHeight, FeePaidByEnum.change, slpOutputsResult.BchSendRequests);
509
- if (fundingUtxos.length === 0) {
510
- throw Error("The available inputs couldn't satisfy the request with fees");
511
- }
512
- const fee = await getFeeAmount({
513
- utxos: fundingUtxos,
514
- sendRequests: slpOutputsResult.BchSendRequests,
515
- privateKey: this.wallet.privateKey,
516
- sourceAddress: this.wallet.cashaddr,
517
- relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,
518
- slpOutputs: slpOutputsResult.SlpOutputs,
519
- feePaidBy: FeePaidByEnum.change,
520
- });
521
- const { encodedTransaction } = await buildEncodedTransaction({
522
- inputs: fundingUtxos,
523
- outputs: slpOutputsResult.BchSendRequests,
524
- signingKey: this.wallet.privateKey,
525
- sourceAddress: this.wallet.cashaddr,
526
- fee,
527
- discardChange: false,
528
- slpOutputs: slpOutputsResult.SlpOutputs,
529
- });
530
- return this._submitTransaction(encodedTransaction, tokenId);
531
- }
532
- /**
533
- * _submitTransaction - transform binary transaction to hex and submit it to the network provider
534
- *
535
- * a private utility wrapper submit raw transactions
536
- *
537
- * @param transaction raw transaction
538
- *
539
- * @returns the transaction id of the broadcasted transaction
540
- */
541
- async _submitTransaction(transaction, tokenId) {
542
- let rawTransaction = binToHex(transaction);
543
- const slpPromise = new Promise(async (resolve) => {
544
- const txHash = await Util.getTransactionHash(rawTransaction);
545
- const cancelWatchFn = this.provider.SlpWatchTransactions(async (tx) => {
546
- if (tx.tx_hash === txHash) {
547
- cancelWatchFn();
548
- resolve(txHash);
549
- }
550
- }, undefined, tokenId || txHash);
551
- });
552
- const bchPromise = this.wallet.provider.sendRawTransaction(rawTransaction, true);
553
- const [_, txHash] = await Promise.all([slpPromise, bchPromise]);
554
- // allow for indexer processing, delay value is a bit arbitrary
555
- await delay(100);
556
- return txHash;
557
- }
558
- /**
559
- * substituteOptionals - substitute optional fields with default values
560
- *
561
- * will ensure that baton and token receiver are intialized as SLP address of this wallet if absent
562
- * will ensure that baton will not be ended if endBaton is undefined
563
- * a private utility wrapper substitute optionals
564
- *
565
- * @param options genesis or mint options to substitute values int
566
- *
567
- * @returns options with relevant values substituted/initialized
568
- */
569
- substituteOptionals(options) {
570
- if (!options.batonReceiverSlpAddr) {
571
- options.batonReceiverSlpAddr = this.slpaddr;
572
- }
573
- if (!options.tokenReceiverSlpAddr) {
574
- options.tokenReceiverSlpAddr = this.slpaddr;
575
- }
576
- if (options.endBaton === undefined) {
577
- options.endBaton = false;
578
- }
579
- return options;
580
- }
581
- //#region Convenience methods to initialize Slp aware BCH wallet.
582
- /**
583
- * fromId - create an SLP aware wallet from encoded walletId string
584
- *
585
- * @param walletId walletId options to steer the creation process
586
- *
587
- * @returns wallet instantiated accordingly to the walletId rules
588
- */
589
- static async fromId(walletId) {
590
- const wallet = await this.walletType.fromId(walletId);
591
- wallet._slpAware = true;
592
- return wallet;
593
- }
594
- /**
595
- * named - create an SLP aware named wallet
596
- *
597
- * @param name user friendly wallet alias
598
- * @param dbName name under which the wallet will be stored in the database
599
- * @param force force recreate wallet in the database if a record already exist
600
- *
601
- * @returns instantiated wallet
602
- */
603
- static async named(name, dbName, force) {
604
- const wallet = await this.walletType.named(name, dbName, force);
605
- wallet.derivationPath = "m/44'/245'/0'/0/0";
606
- wallet._slpAware = true;
607
- return wallet;
608
- }
609
- /**
610
- * fromSeed - create an SLP aware wallet using the seed phrase and derivation path
611
- *
612
- * unless specified the derivation path m/44'/245'/0'/0/0 will be userd
613
- * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets
614
- *
615
- * @param seed BIP39 12 word seed phrase
616
- * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy
617
- *
618
- * @returns instantiated wallet
619
- */
620
- static async fromSeed(seed, derivationPath = "m/44'/245'/0'/0/0") {
621
- const wallet = await this.walletType.fromSeed(seed, derivationPath);
622
- wallet._slpAware = true;
623
- return wallet;
624
- }
625
- /**
626
- * newRandom - create an SLP aware random wallet
627
- *
628
- * if `name` parameter is specified, the wallet will also be persisted to DB
629
- *
630
- * @param name user friendly wallet alias
631
- * @param dbName name under which the wallet will be stored in the database
632
- *
633
- * @returns instantiated wallet
634
- */
635
- static async newRandom(name = "", dbName) {
636
- const wallet = await this.walletType.newRandom(name, dbName);
637
- wallet.derivationPath = "m/44'/245'/0'/0/0";
638
- wallet._slpAware = true;
639
- return wallet;
640
- }
641
- /**
642
- * fromWIF - create an SLP aware wallet using the private key supplied in `Wallet Import Format`
643
- *
644
- * @param wif WIF encoded private key string
645
- *
646
- * @returns instantiated wallet
647
- */
648
- static async fromWIF(wif) {
649
- const wallet = await this.walletType.fromWIF(wif);
650
- wallet.derivationPath = "m/44'/245'/0'/0/0";
651
- wallet._slpAware = true;
652
- return wallet;
653
- }
654
- /**
655
- * watchOnly - create an SLP aware watch-only wallet
656
- *
657
- * such kind of wallet does not have a private key and is unable to spend any funds
658
- * however it still allows to use many utility functions such as getting and watching balance, etc.
659
- *
660
- * @param address cashaddress or slpaddress of a wallet
661
- *
662
- * @returns instantiated wallet
663
- */
664
- static async watchOnly(address) {
665
- const wallet = await this.walletType.watchOnly(toCashAddress(address));
666
- wallet.derivationPath = "m/44'/245'/0'/0/0";
667
- wallet._slpAware = true;
668
- return wallet;
669
- }
670
- /**
671
- * fromCashaddr - create an SLP aware watch-only wallet in the network derived from the address
672
- *
673
- * such kind of wallet does not have a private key and is unable to spend any funds
674
- * however it still allows to use many utility functions such as getting and watching balance, etc.
675
- *
676
- * @param address cashaddress of a wallet
677
- *
678
- * @returns instantiated wallet
679
- */
680
- static async fromCashaddr(address) {
681
- const wallet = await this.walletType.fromCashaddr(address);
682
- wallet.derivationPath = "m/44'/245'/0'/0/0";
683
- wallet._slpAware = true;
684
- return wallet;
685
- }
686
- /**
687
- * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address
688
- *
689
- * such kind of wallet does not have a private key and is unable to spend any funds
690
- * however it still allows to use many utility functions such as getting and watching balance, etc.
691
- *
692
- * @param address slpaddress of a wallet
693
- *
694
- * @returns instantiated wallet
695
- */
696
- static async fromSlpaddr(address) {
697
- const wallet = await this.walletType.fromSlpaddr(address);
698
- wallet.derivationPath = "m/44'/245'/0'/0/0";
699
- wallet._slpAware = true;
700
- return wallet;
701
- }
702
- }
703
- Slp.defaultProvider = "slpdb";
704
- //#region Specific wallet classes
705
- /**
706
- * Class to manage an slp enabled testnet wallet.
707
- */
708
- export class TestNetSlp extends Slp {
709
- static get walletType() {
710
- return TestNetWallet;
711
- }
712
- }
713
- /**
714
- * Class to manage an slp enabled regtest wallet.
715
- */
716
- export class RegTestSlp extends Slp {
717
- static get walletType() {
718
- return RegTestWallet;
719
- }
720
- }
721
- /**
722
- * Class to manage a bitcoin cash wif wallet.
723
- */
724
- export class WifSlp extends Slp {
725
- static get walletType() {
726
- return WifWallet;
727
- }
728
- }
729
- /**
730
- * Class to manage a testnet wif wallet.
731
- */
732
- export class TestNetWifSlp extends Slp {
733
- static get walletType() {
734
- return TestNetWifWallet;
735
- }
736
- }
737
- /**
738
- * Class to manage a regtest wif wallet.
739
- */
740
- export class RegTestWifSlp extends Slp {
741
- static get walletType() {
742
- return RegTestWifWallet;
743
- }
744
- }
745
- /**
746
- * Class to manage a bitcoin cash watch wallet.
747
- */
748
- export class WatchSlp extends Slp {
749
- static get walletType() {
750
- return WatchWallet;
751
- }
752
- }
753
- /**
754
- * Class to manage a testnet watch wallet.
755
- */
756
- export class TestNetWatchSlp extends Slp {
757
- static get walletType() {
758
- return TestNetWatchWallet;
759
- }
760
- }
761
- /**
762
- * Class to manage a regtest watch wallet.
763
- */
764
- export class RegTestWatchSlp extends Slp {
765
- static get walletType() {
766
- return RegTestWatchWallet;
767
- }
768
- }
769
- //#endregion
770
- //# sourceMappingURL=Slp.js.map