@atomicfinance/bitcoin-wallet-provider 3.5.3 → 3.6.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.
@@ -1 +0,0 @@
1
-
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @atomicfinance/bitcoin-wallet-provider
2
2
 
3
+ ## 3.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - cbf35c5: - **BREAKING CHANGE**: Migrated from `@node-lightning` packages to `@node-dlc` packages
8
+ - Updated all imports from `@node-lightning/*` to `@node-dlc/*`
9
+ - Update @node-dlc 0.24.0 and Node 18+
10
+ - Upgraded Node.js requirement to v18+
11
+ - Updated cfd-dlc-js to v0.0.51 and cfd-js to v0.3.13
12
+ - Removed unused dependencies: lerna, mocha-webpack
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies [cbf35c5]
17
+ - @atomicfinance/types@3.6.0
18
+ - @atomicfinance/bitcoin-utils@3.6.0
19
+ - @atomicfinance/provider@3.6.0
20
+
3
21
  ## 3.5.3
4
22
 
5
23
  ### Patch Changes
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@atomicfinance/bitcoin-wallet-provider",
3
3
  "umdName": "BitcoinWalletProvider",
4
- "version": "3.5.3",
4
+ "version": "3.6.0",
5
5
  "description": "Bitcoin Abstraction Layer Wallet Provider",
6
6
  "author": "Atomic Finance <info@atomic.finance>",
7
7
  "homepage": "",
@@ -15,10 +15,10 @@
15
15
  "lint:fix": "../../node_modules/.bin/eslint --fix --ignore-path ../../.eslintignore -c ../../.eslintrc.js ."
16
16
  },
17
17
  "dependencies": {
18
- "@atomicfinance/bitcoin-utils": "^3.5.3",
19
- "@atomicfinance/provider": "^3.5.3",
20
- "@atomicfinance/types": "^3.5.3",
21
- "@node-dlc/core": "0.23.6",
18
+ "@atomicfinance/bitcoin-utils": "^3.6.0",
19
+ "@atomicfinance/provider": "^3.6.0",
20
+ "@atomicfinance/types": "^3.6.0",
21
+ "@node-dlc/core": "0.24.0",
22
22
  "bitcoin-networks": "^1.0.0",
23
23
  "bitcoinjs-lib": "5.2.0",
24
24
  "lodash": "^4.17.20",
@@ -1 +0,0 @@
1
-
@@ -1,596 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.AddressSearchType = void 0;
30
- const bitcoin_utils_1 = require("@atomicfinance/bitcoin-utils");
31
- const errors_1 = require("@atomicfinance/errors");
32
- const types_1 = require("@atomicfinance/types");
33
- const utils_1 = require("@atomicfinance/utils");
34
- const core_1 = require("@node-dlc/core");
35
- const bitcoin = __importStar(require("bitcoinjs-lib"));
36
- const memoizee_1 = __importDefault(require("memoizee"));
37
- const ADDRESS_GAP = 30;
38
- const NONCHANGE_ADDRESS = 0;
39
- const CHANGE_ADDRESS = 1;
40
- const NONCHANGE_OR_CHANGE_ADDRESS = 2;
41
- var AddressSearchType;
42
- (function (AddressSearchType) {
43
- AddressSearchType[AddressSearchType["EXTERNAL"] = 0] = "EXTERNAL";
44
- AddressSearchType[AddressSearchType["CHANGE"] = 1] = "CHANGE";
45
- AddressSearchType[AddressSearchType["EXTERNAL_OR_CHANGE"] = 2] = "EXTERNAL_OR_CHANGE";
46
- })(AddressSearchType = exports.AddressSearchType || (exports.AddressSearchType = {}));
47
- exports.default = (superclass) => {
48
- class BitcoinWalletProvider extends superclass {
49
- constructor(...args) {
50
- const options = args[0];
51
- const { network, baseDerivationPath, addressType = types_1.bitcoin.AddressType.BECH32, addressIndex = 0, changeAddressIndex = 0, } = options;
52
- const addressTypes = Object.values(types_1.bitcoin.AddressType);
53
- if (!addressTypes.includes(addressType)) {
54
- throw new Error(`addressType must be one of ${addressTypes.join(',')}`);
55
- }
56
- super(options);
57
- this._baseDerivationPath = baseDerivationPath;
58
- this._network = network;
59
- this._addressType = addressType;
60
- this._addressIndex = addressIndex;
61
- this._changeAddressIndex = changeAddressIndex;
62
- this._derivationCache = {};
63
- this._unusedAddressesBlacklist = {};
64
- this._maxAddressesToDerive = 5000;
65
- }
66
- getDerivationCache() {
67
- return this._derivationCache;
68
- }
69
- async setDerivationCache(derivationCache) {
70
- const address = await this.getDerivationPathAddress(Object.keys(derivationCache)[0]);
71
- if (derivationCache[address.derivationPath].address !== address.address) {
72
- throw new Error(`derivationCache at ${address.derivationPath} does not match`);
73
- }
74
- this._derivationCache = derivationCache;
75
- }
76
- sendOptionsToOutputs(transactions) {
77
- const targets = [];
78
- transactions.forEach((tx) => {
79
- if (tx.to && tx.value && tx.value.gt(0)) {
80
- targets.push({
81
- address: (0, utils_1.addressToString)(tx.to),
82
- value: tx.value.toNumber(),
83
- });
84
- }
85
- if (tx.data) {
86
- const scriptBuffer = bitcoin.script.compile([
87
- bitcoin.script.OPS.OP_RETURN,
88
- Buffer.from(tx.data, 'hex'),
89
- ]);
90
- targets.push({
91
- value: 0,
92
- script: scriptBuffer,
93
- });
94
- }
95
- });
96
- return targets;
97
- }
98
- async buildTransaction(output, feePerByte) {
99
- return this._buildTransaction([output], feePerByte);
100
- }
101
- async buildBatchTransaction(outputs) {
102
- return this._buildTransaction(outputs);
103
- }
104
- async _sendTransaction(transactions, feePerByte) {
105
- const { hex, fee } = await this._buildTransaction(transactions, feePerByte);
106
- await this.getMethod('sendRawTransaction')(hex);
107
- return (0, bitcoin_utils_1.normalizeTransactionObject)((0, bitcoin_utils_1.decodeRawTransaction)(hex, this._network), fee);
108
- }
109
- async sendTransaction(options) {
110
- return this._sendTransaction(this.sendOptionsToOutputs([options]), options.fee);
111
- }
112
- async sendBatchTransaction(transactions) {
113
- return this._sendTransaction(this.sendOptionsToOutputs(transactions));
114
- }
115
- async buildSweepTransaction(externalChangeAddress, feePerByte) {
116
- return this._buildSweepTransaction(externalChangeAddress, feePerByte);
117
- }
118
- async sendSweepTransaction(externalChangeAddress, feePerByte) {
119
- const { hex, fee } = await this._buildSweepTransaction((0, utils_1.addressToString)(externalChangeAddress), feePerByte);
120
- await this.getMethod('sendRawTransaction')(hex);
121
- return (0, bitcoin_utils_1.normalizeTransactionObject)((0, bitcoin_utils_1.decodeRawTransaction)(hex, this._network), fee);
122
- }
123
- getUnusedAddressesBlacklist() {
124
- return this._unusedAddressesBlacklist;
125
- }
126
- setUnusedAddressesBlacklist(unusedAddressesBlacklist) {
127
- this._unusedAddressesBlacklist = unusedAddressesBlacklist;
128
- }
129
- setMaxAddressesToDerive(maxAddressesToDerive) {
130
- this._maxAddressesToDerive = maxAddressesToDerive;
131
- }
132
- getMaxAddressesToDerive() {
133
- return this._maxAddressesToDerive;
134
- }
135
- async updateTransactionFee(tx, newFeePerByte) {
136
- const txHash = typeof tx === 'string' ? tx : tx.hash;
137
- const transaction = (await this.getMethod('getTransactionByHash')(txHash))._raw;
138
- const fixedInputs = [transaction.vin[0]]; // TODO: should this pick more than 1 input? RBF doesn't mandate it
139
- const lookupAddresses = transaction.vout.map((vout) => vout.scriptPubKey.addresses[0]);
140
- const changeAddress = await this.findAddress(lookupAddresses, true);
141
- const changeOutput = transaction.vout.find((vout) => vout.scriptPubKey.addresses[0] === changeAddress.address);
142
- let outputs = transaction.vout;
143
- if (changeOutput) {
144
- outputs = outputs.filter((vout) => vout.scriptPubKey.addresses[0] !==
145
- changeOutput.scriptPubKey.addresses[0]);
146
- }
147
- // TODO more checks?
148
- const transactions = outputs.map((output) => ({
149
- address: output.scriptPubKey.addresses[0],
150
- value: new types_1.BigNumber(output.value).times(1e8).toNumber(),
151
- }));
152
- const { hex, fee } = await this._buildTransaction(transactions, newFeePerByte, fixedInputs);
153
- await this.getMethod('sendRawTransaction')(hex);
154
- return (0, bitcoin_utils_1.normalizeTransactionObject)((0, bitcoin_utils_1.decodeRawTransaction)(hex, this._network), fee);
155
- }
156
- async getUnusedAddress(change = false, numAddressPerCall = 100) {
157
- const addressType = change ? CHANGE_ADDRESS : NONCHANGE_ADDRESS;
158
- const key = change ? 'change' : 'nonChange';
159
- const address = await this._getUsedUnusedAddresses(numAddressPerCall, addressType).then(({ unusedAddress }) => unusedAddress[key]);
160
- this._unusedAddressesBlacklist[address.address] = true;
161
- return address;
162
- }
163
- async _getUsedUnusedAddresses(numAddressPerCall = 100, addressType) {
164
- const usedAddresses = [];
165
- const addressCountMap = { change: 0, nonChange: 0 };
166
- const unusedAddressMap = { change: null, nonChange: null };
167
- let addrList;
168
- let addressIndex = this._addressIndex;
169
- let changeAddressIndex = this._changeAddressIndex;
170
- let changeAddresses = [];
171
- let nonChangeAddresses = [];
172
- /* eslint-disable no-unmodified-loop-condition */
173
- while ((addressType === NONCHANGE_OR_CHANGE_ADDRESS &&
174
- (addressCountMap.change < ADDRESS_GAP ||
175
- addressCountMap.nonChange < ADDRESS_GAP)) ||
176
- (addressType === NONCHANGE_ADDRESS &&
177
- addressCountMap.nonChange < ADDRESS_GAP) ||
178
- (addressType === CHANGE_ADDRESS && addressCountMap.change < ADDRESS_GAP)) {
179
- /* eslint-enable no-unmodified-loop-condition */
180
- addrList = [];
181
- if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
182
- addressType === CHANGE_ADDRESS) &&
183
- addressCountMap.change < ADDRESS_GAP) {
184
- // Scanning for change addr
185
- changeAddresses = await this.client.wallet.getAddresses(changeAddressIndex, numAddressPerCall, true);
186
- addrList = addrList.concat(changeAddresses);
187
- }
188
- else {
189
- changeAddresses = [];
190
- }
191
- if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
192
- addressType === NONCHANGE_ADDRESS) &&
193
- addressCountMap.nonChange < ADDRESS_GAP) {
194
- // Scanning for non change addr
195
- nonChangeAddresses = await this.getAddresses(addressIndex, numAddressPerCall, false);
196
- addrList = addrList.concat(nonChangeAddresses);
197
- }
198
- const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
199
- for (const address of addrList) {
200
- const isUsed = transactionCounts[address.address] > 0 ||
201
- this._unusedAddressesBlacklist[address.address];
202
- const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
203
- const key = isChangeAddress ? 'change' : 'nonChange';
204
- if (isUsed) {
205
- usedAddresses.push(address);
206
- addressCountMap[key] = 0;
207
- unusedAddressMap[key] = null;
208
- }
209
- else {
210
- addressCountMap[key]++;
211
- if (!unusedAddressMap[key]) {
212
- unusedAddressMap[key] = address;
213
- }
214
- }
215
- }
216
- addressIndex += numAddressPerCall;
217
- changeAddressIndex += numAddressPerCall;
218
- }
219
- let firstUnusedAddress;
220
- const indexNonChange = unusedAddressMap.nonChange
221
- ? unusedAddressMap.nonChange.index
222
- : Infinity;
223
- const indexChange = unusedAddressMap.change
224
- ? unusedAddressMap.change.index
225
- : Infinity;
226
- if (indexNonChange <= indexChange)
227
- firstUnusedAddress = unusedAddressMap.nonChange;
228
- else
229
- firstUnusedAddress = unusedAddressMap.change;
230
- return {
231
- usedAddresses,
232
- unusedAddress: unusedAddressMap,
233
- firstUnusedAddress,
234
- };
235
- }
236
- async getWalletAddress(address) {
237
- const foundAddress = await this.findAddress([address]);
238
- if (foundAddress)
239
- return foundAddress;
240
- throw new Error('Wallet does not contain address');
241
- }
242
- getAddressFromPublicKey(publicKey) {
243
- return this.getPaymentVariantFromPublicKey(publicKey).address;
244
- }
245
- getPaymentVariantFromPublicKey(publicKey) {
246
- if (this._addressType === types_1.bitcoin.AddressType.LEGACY) {
247
- return bitcoin.payments.p2pkh({
248
- pubkey: publicKey,
249
- network: this._network,
250
- });
251
- }
252
- else if (this._addressType === types_1.bitcoin.AddressType.P2SH_SEGWIT) {
253
- return bitcoin.payments.p2sh({
254
- redeem: bitcoin.payments.p2wpkh({
255
- pubkey: publicKey,
256
- network: this._network,
257
- }),
258
- network: this._network,
259
- });
260
- }
261
- else if (this._addressType === types_1.bitcoin.AddressType.BECH32) {
262
- return bitcoin.payments.p2wpkh({
263
- pubkey: publicKey,
264
- network: this._network,
265
- });
266
- }
267
- }
268
- async getDerivationPathAddress(path) {
269
- if (path in this._derivationCache) {
270
- return this._derivationCache[path];
271
- }
272
- const baseDerivationNode = await this.baseDerivationNode();
273
- const subPath = path.replace(this._baseDerivationPath + '/', '');
274
- const publicKey = baseDerivationNode.derivePath(subPath).publicKey;
275
- const address = this.getAddressFromPublicKey(publicKey);
276
- const addressObject = new types_1.Address({
277
- address,
278
- publicKey: publicKey.toString('hex'),
279
- derivationPath: path,
280
- });
281
- this._derivationCache[path] = addressObject;
282
- return addressObject;
283
- }
284
- /**
285
- * getAddresses is an optimized version of upstream CAL's getAddresses.
286
- * It removes the call to `asyncSetImmediate()`, speeding up the function by a factor of 6x.
287
- *
288
- * @param startingIndex
289
- * @param numAddresses
290
- * @param change
291
- * @returns {Promise<Address[]>}
292
- */
293
- async getAddresses(startingIndex = 0, numAddresses = 1, change = false) {
294
- if (numAddresses < 1) {
295
- throw new Error('You must return at least one address');
296
- }
297
- const addresses = [];
298
- const lastIndex = startingIndex + numAddresses;
299
- const changeVal = change ? '1' : '0';
300
- for (let currentIndex = startingIndex; currentIndex < lastIndex; currentIndex++) {
301
- const subPath = changeVal + '/' + currentIndex;
302
- const path = this._baseDerivationPath + '/' + subPath;
303
- const addressObject = await this.getDerivationPathAddress(path);
304
- addresses.push(addressObject);
305
- }
306
- return addresses;
307
- }
308
- /**
309
- * findAddress is an optimized version of upstream CAL's findAddress.
310
- *
311
- * It searches through both change and non-change addresses (if change arg is not provided) each iteration.
312
- *
313
- * This is in contrast to the original findAddress function which searches
314
- * through all non-change addresses before moving on to change addresses.
315
- *
316
- * @param addresses
317
- * @returns {Promise<Address>}
318
- */
319
- async findAddress(addresses, change = null) {
320
- const addressesPerCall = 20;
321
- let index = 0;
322
- while (index < this._maxAddressesToDerive) {
323
- const walletAddresses = [];
324
- if (change === null || change === false) {
325
- walletAddresses.push(...(await this.getAddresses(index, addressesPerCall, false)));
326
- }
327
- if (change === null || change === true) {
328
- walletAddresses.push(...(await this.getAddresses(index, addressesPerCall, true)));
329
- }
330
- const walletAddress = walletAddresses.find((walletAddr) => addresses.find((addr) => walletAddr.address === addr));
331
- if (walletAddress) {
332
- // Increment max addresses to derive by 100 if found within 100 addresses of maxAddressesToDerive
333
- this._maxAddressesToDerive = Math.max(this._maxAddressesToDerive, index + 100);
334
- return walletAddress;
335
- }
336
- index += addressesPerCall;
337
- }
338
- }
339
- async getUsedAddresses(numAddressPerCall = 100) {
340
- return this._getUsedUnusedAddresses(numAddressPerCall, AddressSearchType.EXTERNAL_OR_CHANGE).then(({ usedAddresses }) => usedAddresses);
341
- }
342
- async withCachedUtxos(func) {
343
- const originalGetMethod = this.getMethod;
344
- const memoizedGetFeePerByte = (0, memoizee_1.default)(this.getMethod('getFeePerByte'), {
345
- primitive: true,
346
- });
347
- const memoizedGetUnspentTransactions = (0, memoizee_1.default)(this.getMethod('getUnspentTransactions'), { primitive: true });
348
- const memoizedGetAddressTransactionCounts = (0, memoizee_1.default)(this.getMethod('getAddressTransactionCounts'), {
349
- primitive: true,
350
- });
351
- this.getMethod = (method, requestor = this) => {
352
- if (method === 'getFeePerByte')
353
- return memoizedGetFeePerByte;
354
- if (method === 'getUnspentTransactions')
355
- return memoizedGetUnspentTransactions;
356
- else if (method === 'getAddressTransactionCounts')
357
- return memoizedGetAddressTransactionCounts;
358
- else
359
- return originalGetMethod.bind(this)(method, requestor);
360
- };
361
- const result = await func.bind(this)();
362
- this.getMethod = originalGetMethod;
363
- return result;
364
- }
365
- async getTotalFee(opts, max) {
366
- const targets = this.sendOptionsToOutputs([opts]);
367
- if (!max) {
368
- const { fee } = await this.getInputsForAmount(targets, opts.fee);
369
- return fee;
370
- }
371
- else {
372
- const { fee } = await this.getInputsForAmount(targets.filter((t) => !t.value), opts.fee, [], 100, true);
373
- return fee;
374
- }
375
- }
376
- async getTotalFees(transactions, max) {
377
- const fees = await this.withCachedUtxos(async () => {
378
- const fees = {};
379
- for (const tx of transactions) {
380
- const fee = await this.getTotalFee(tx, max);
381
- fees[tx.fee] = new types_1.BigNumber(fee);
382
- }
383
- return fees;
384
- });
385
- return fees;
386
- }
387
- async getInputsForAmount(_targets, feePerByte, fixedInputs = [], numAddressPerCall = 100, sweep = false) {
388
- let addressIndex = 0;
389
- let changeAddresses = [];
390
- let externalAddresses = [];
391
- const addressCountMap = {
392
- change: 0,
393
- nonChange: 0,
394
- };
395
- const feePerBytePromise = this.getMethod('getFeePerByte')();
396
- let utxos = [];
397
- while (addressCountMap.change < ADDRESS_GAP ||
398
- addressCountMap.nonChange < ADDRESS_GAP) {
399
- let addrList = [];
400
- if (addressCountMap.change < ADDRESS_GAP) {
401
- // Scanning for change addr
402
- changeAddresses = await this.getAddresses(addressIndex, numAddressPerCall, true);
403
- addrList = addrList.concat(changeAddresses);
404
- }
405
- else {
406
- changeAddresses = [];
407
- }
408
- if (addressCountMap.nonChange < ADDRESS_GAP) {
409
- // Scanning for non change addr
410
- externalAddresses = await this.getAddresses(addressIndex, numAddressPerCall, false);
411
- addrList = addrList.concat(externalAddresses);
412
- }
413
- const fixedUtxos = [];
414
- if (fixedInputs.length > 0) {
415
- for (const input of fixedInputs) {
416
- const txHex = await this.getMethod('getRawTransactionByHash')(input.txid);
417
- const tx = (0, bitcoin_utils_1.decodeRawTransaction)(txHex, this._network);
418
- const value = new types_1.BigNumber(tx.vout[input.vout].value)
419
- .times(1e8)
420
- .toNumber();
421
- const address = tx.vout[input.vout].scriptPubKey.addresses[0];
422
- const walletAddress = await this.getWalletAddress(address);
423
- const utxo = {
424
- ...input,
425
- value,
426
- address,
427
- derivationPath: walletAddress.derivationPath,
428
- };
429
- fixedUtxos.push(utxo);
430
- }
431
- }
432
- if (!sweep || fixedUtxos.length === 0) {
433
- const _utxos = await this.getMethod('getUnspentTransactions')(addrList);
434
- utxos.push(..._utxos.map((utxo) => {
435
- const addr = addrList.find((a) => a.address === utxo.address);
436
- return {
437
- ...utxo,
438
- derivationPath: addr.derivationPath,
439
- };
440
- }));
441
- }
442
- else {
443
- utxos = fixedUtxos;
444
- }
445
- const utxoBalance = utxos.reduce((a, b) => a + (b.value || 0), 0);
446
- const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
447
- if (!feePerByte)
448
- feePerByte = await feePerBytePromise;
449
- const minRelayFee = await this.getMethod('getMinRelayFee')();
450
- if (feePerByte < minRelayFee) {
451
- throw new Error(`Fee supplied (${feePerByte} sat/b) too low. Minimum relay fee is ${minRelayFee} sat/b`);
452
- }
453
- let targets;
454
- if (sweep) {
455
- const outputBalance = _targets.reduce((a, b) => a + (b['value'] || 0), 0);
456
- const sweepOutputSize = 39;
457
- const paymentOutputSize = _targets.filter((t) => t.value && t.address).length * 39;
458
- const scriptOutputSize = _targets
459
- .filter((t) => !t.value && t.script)
460
- .reduce((size, t) => size + 39 + t.script.byteLength, 0);
461
- const outputSize = sweepOutputSize + paymentOutputSize + scriptOutputSize;
462
- const inputSize = utxos.length * 153;
463
- const sweepFee = feePerByte * (inputSize + outputSize);
464
- const amountToSend = new types_1.BigNumber(utxoBalance).minus(sweepFee);
465
- targets = _targets.map((target) => ({
466
- id: 'main',
467
- value: target.value,
468
- script: target.script,
469
- }));
470
- targets.push({
471
- id: 'main',
472
- value: amountToSend.minus(outputBalance).toNumber(),
473
- });
474
- }
475
- else {
476
- targets = _targets.map((target) => ({
477
- id: 'main',
478
- value: target.value,
479
- script: target.script,
480
- }));
481
- }
482
- const { inputs, outputs, change, fee } = (0, bitcoin_utils_1.selectCoins)(utxos, targets, Math.ceil(feePerByte), fixedUtxos);
483
- if (inputs && outputs) {
484
- return {
485
- inputs,
486
- change,
487
- outputs,
488
- fee,
489
- };
490
- }
491
- for (const address of addrList) {
492
- const isUsed = transactionCounts[address.address];
493
- const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
494
- const key = isChangeAddress ? 'change' : 'nonChange';
495
- if (isUsed) {
496
- addressCountMap[key] = 0;
497
- }
498
- else {
499
- addressCountMap[key]++;
500
- }
501
- }
502
- addressIndex += numAddressPerCall;
503
- }
504
- throw new errors_1.InsufficientBalanceError('Not enough balance');
505
- }
506
- async getInputsForDualFunding(collaterals, feePerByte, fixedInputs = [], numAddressPerCall = 100) {
507
- let addressIndex = 0;
508
- let changeAddresses = [];
509
- let externalAddresses = [];
510
- const addressCountMap = {
511
- change: 0,
512
- nonChange: 0,
513
- };
514
- const feePerBytePromise = this.getMethod('getFeePerByte')();
515
- let utxos = [];
516
- while (addressCountMap.change < ADDRESS_GAP ||
517
- addressCountMap.nonChange < ADDRESS_GAP) {
518
- let addrList = [];
519
- if (addressCountMap.change < ADDRESS_GAP) {
520
- // Scanning for change addr
521
- changeAddresses = await this.getAddresses(addressIndex, numAddressPerCall, true);
522
- addrList = addrList.concat(changeAddresses);
523
- }
524
- else {
525
- changeAddresses = [];
526
- }
527
- if (addressCountMap.nonChange < ADDRESS_GAP) {
528
- // Scanning for non change addr
529
- externalAddresses = await this.getAddresses(addressIndex, numAddressPerCall, false);
530
- addrList = addrList.concat(externalAddresses);
531
- }
532
- const fixedUtxos = [];
533
- if (fixedInputs.length > 0) {
534
- for (const input of fixedInputs) {
535
- const txHex = await this.getMethod('getRawTransactionByHash')(input.txid);
536
- const tx = (0, bitcoin_utils_1.decodeRawTransaction)(txHex, this._network);
537
- const value = new types_1.BigNumber(tx.vout[input.vout].value)
538
- .times(1e8)
539
- .toNumber();
540
- const address = tx.vout[input.vout].scriptPubKey.addresses[0];
541
- const walletAddress = await this.getWalletAddress(address);
542
- const utxo = {
543
- ...input,
544
- value,
545
- address,
546
- derivationPath: walletAddress.derivationPath,
547
- };
548
- fixedUtxos.push(utxo);
549
- }
550
- }
551
- if (fixedUtxos.length === 0) {
552
- const _utxos = await this.getMethod('getUnspentTransactions')(addrList);
553
- utxos.push(..._utxos.map((utxo) => {
554
- const addr = addrList.find((a) => a.address === utxo.address);
555
- return {
556
- ...utxo,
557
- derivationPath: addr.derivationPath,
558
- };
559
- }));
560
- }
561
- else {
562
- utxos = fixedUtxos;
563
- }
564
- const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
565
- if (!feePerByte)
566
- feePerByte = await feePerBytePromise;
567
- const minRelayFee = await this.getMethod('getMinRelayFee')();
568
- if (feePerByte < minRelayFee) {
569
- throw new Error(`Fee supplied (${feePerByte} sat/b) too low. Minimum relay fee is ${minRelayFee} sat/b`);
570
- }
571
- const { fee, inputs } = (0, core_1.dualFundingCoinSelect)(utxos, collaterals.map((c) => BigInt(c)), BigInt(feePerByte));
572
- if (inputs.length > 0) {
573
- return {
574
- inputs,
575
- fee,
576
- };
577
- }
578
- for (const address of addrList) {
579
- const isUsed = transactionCounts[address.address];
580
- const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
581
- const key = isChangeAddress ? 'change' : 'nonChange';
582
- if (isUsed) {
583
- addressCountMap[key] = 0;
584
- }
585
- else {
586
- addressCountMap[key]++;
587
- }
588
- }
589
- addressIndex += numAddressPerCall;
590
- }
591
- throw new errors_1.InsufficientBalanceError('Not enough balance for dual funding');
592
- }
593
- }
594
- return BitcoinWalletProvider;
595
- };
596
- //# sourceMappingURL=BitcoinWalletProvider.js.map
package/lib/index.js DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = void 0;
7
- var BitcoinWalletProvider_1 = require("./BitcoinWalletProvider");
8
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(BitcoinWalletProvider_1).default; } });
9
- //# sourceMappingURL=index.js.map