@xchainjs/xchain-bitcoin 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.d.ts CHANGED
@@ -3,17 +3,21 @@ import { AssetInfo, FeeRate } from '@xchainjs/xchain-client';
3
3
  import { Address } from '@xchainjs/xchain-util';
4
4
  import { Client as UTXOClient, PreparedTx, TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo';
5
5
  import * as Bitcoin from 'bitcoinjs-lib';
6
+ import { AddressFormat } from './types';
6
7
  export declare const defaultBTCParams: UtxoClientParams;
7
8
  /**
8
9
  * Custom Bitcoin client
9
10
  */
10
11
  declare abstract class Client extends UTXOClient {
12
+ protected addressFormat: AddressFormat;
11
13
  /**
12
14
  * Constructor
13
15
  * Initializes the client with network type and other parameters.
14
16
  * @param {UtxoClientParams} params
15
17
  */
16
- constructor(params?: UtxoClientParams);
18
+ constructor(params?: UtxoClientParams & {
19
+ addressFormat?: AddressFormat;
20
+ });
17
21
  /**
18
22
  * Get BTC asset info.
19
23
  * @returns {AssetInfo} BTC asset information.
@@ -1,11 +1,15 @@
1
1
  import { FeeRate, TxHash } from '@xchainjs/xchain-client';
2
2
  import { Address } from '@xchainjs/xchain-util';
3
- import { TxParams } from '@xchainjs/xchain-utxo';
3
+ import { TxParams, UtxoClientParams } from '@xchainjs/xchain-utxo';
4
4
  import { Client } from './client';
5
+ import { AddressFormat } from './types';
5
6
  /**
6
7
  * Custom Bitcoin client extended to support keystore functionality
7
8
  */
8
9
  declare class ClientKeystore extends Client {
10
+ constructor(params?: UtxoClientParams & {
11
+ addressFormat?: AddressFormat;
12
+ });
9
13
  /**
10
14
  * @deprecated This function eventually will be removed. Use getAddressAsync instead.
11
15
  * Get the address associated with the given index.
@@ -3,6 +3,7 @@ import { FeeRate, TxHash } from '@xchainjs/xchain-client';
3
3
  import { Address } from '@xchainjs/xchain-util';
4
4
  import { TxParams, UtxoClientParams } from '@xchainjs/xchain-utxo';
5
5
  import { Client } from './client';
6
+ import { AddressFormat } from './types';
6
7
  /**
7
8
  * Custom Ledger Bitcoin client
8
9
  */
@@ -11,6 +12,7 @@ declare class ClientLedger extends Client {
11
12
  private app;
12
13
  constructor(params: UtxoClientParams & {
13
14
  transport: any;
15
+ addressFormat?: AddressFormat;
14
16
  });
15
17
  getApp(): Promise<AppBtc>;
16
18
  getAddress(): string;
package/lib/const.d.ts CHANGED
@@ -29,3 +29,8 @@ export declare const SochainDataProviders: UtxoOnlineDataProviders;
29
29
  export declare const HaskoinDataProviders: UtxoOnlineDataProviders;
30
30
  export declare const BlockcypherDataProviders: UtxoOnlineDataProviders;
31
31
  export declare const BitgoProviders: UtxoOnlineDataProviders;
32
+ export declare const tapRootDerivationPaths: {
33
+ mainnet: string;
34
+ testnet: string;
35
+ stagenet: string;
36
+ };
package/lib/index.esm.js CHANGED
@@ -1,11 +1,20 @@
1
+ import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs';
1
2
  import { ExplorerProvider, Network, FeeOption, checkFeeBounds } from '@xchainjs/xchain-client';
2
3
  import { getSeed } from '@xchainjs/xchain-crypto';
4
+ import { BIP32Factory } from 'bip32';
3
5
  import * as Bitcoin from 'bitcoinjs-lib';
6
+ import { ECPairFactory } from 'ecpair';
4
7
  import { Client as Client$1 } from '@xchainjs/xchain-utxo';
5
8
  import { AssetType } from '@xchainjs/xchain-util';
6
9
  import { SochainProvider, SochainNetwork, HaskoinProvider, HaskoinNetwork, BlockcypherProvider, BlockcypherNetwork, BitgoProvider } from '@xchainjs/xchain-utxo-providers';
7
10
  import AppBtc from '@ledgerhq/hw-app-btc';
8
11
 
12
+ var AddressFormat;
13
+ (function (AddressFormat) {
14
+ AddressFormat[AddressFormat["P2WPKH"] = 0] = "P2WPKH";
15
+ AddressFormat[AddressFormat["P2TR"] = 1] = "P2TR";
16
+ })(AddressFormat || (AddressFormat = {}));
17
+
9
18
  /******************************************************************************
10
19
  Copyright (c) Microsoft Corporation.
11
20
 
@@ -215,6 +224,11 @@ const BitgoProviders = {
215
224
  [Network.Stagenet]: mainnetBitgoProvider,
216
225
  [Network.Mainnet]: mainnetBitgoProvider,
217
226
  };
227
+ const tapRootDerivationPaths = {
228
+ [Network.Mainnet]: `86'/0'/0'/0/`,
229
+ [Network.Testnet]: `86'/1'/0'/0/`,
230
+ [Network.Stagenet]: `86'/0'/0'/0/`,
231
+ };
218
232
 
219
233
  // Import statements for necessary modules and types
220
234
  // Constants defining the sizes of various components in a Bitcoin transaction
@@ -276,6 +290,12 @@ const getPrefix = (network) => {
276
290
  return 'tb1'; // Return the address prefix for Bitcoin testnet
277
291
  }
278
292
  };
293
+ /**
294
+ * Converts a public key to an X-only public key.
295
+ * @param pubKey The public key to convert.
296
+ * @returns The X-only public key.
297
+ */
298
+ const toXOnly = (pubKey) => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33));
279
299
 
280
300
  // Default parameters for the Bitcoin UTXO client
281
301
  const defaultBTCParams = {
@@ -302,7 +322,8 @@ class Client extends Client$1 {
302
322
  * Initializes the client with network type and other parameters.
303
323
  * @param {UtxoClientParams} params
304
324
  */
305
- constructor(params = defaultBTCParams) {
325
+ constructor(params = Object.assign(Object.assign({}, defaultBTCParams), { addressFormat: AddressFormat.P2WPKH })) {
326
+ var _a, _b, _c;
306
327
  super(BTCChain, {
307
328
  network: params.network,
308
329
  rootDerivationPaths: params.rootDerivationPaths,
@@ -311,6 +332,15 @@ class Client extends Client$1 {
311
332
  explorerProviders: params.explorerProviders,
312
333
  dataProviders: params.dataProviders,
313
334
  });
335
+ this.addressFormat = params.addressFormat || AddressFormat.P2WPKH;
336
+ if (this.addressFormat === AddressFormat.P2TR) {
337
+ if (!((_a = this.rootDerivationPaths) === null || _a === void 0 ? void 0 : _a.mainnet.startsWith(`86'`)) ||
338
+ !((_b = this.rootDerivationPaths) === null || _b === void 0 ? void 0 : _b.testnet.startsWith(`86'`)) ||
339
+ !((_c = this.rootDerivationPaths) === null || _c === void 0 ? void 0 : _c.stagenet.startsWith(`86'`))) {
340
+ throw Error(`Unsupported derivation paths for Taproot client. Use 86' paths`);
341
+ }
342
+ }
343
+ Bitcoin.initEccLib(ecc);
314
344
  }
315
345
  /**
316
346
  * Get BTC asset info.
@@ -409,17 +439,30 @@ class Client extends Client$1 {
409
439
  throw new Error('Insufficient Balance for transaction');
410
440
  // Initialize a new Bitcoin PSBT object.
411
441
  const psbt = new Bitcoin.Psbt({ network: btcNetwork(this.network) }); // Network-specific
412
- // Add inputs to the PSBT from the accumulated inputs.
413
- inputs.forEach((utxo) => psbt.addInput({
414
- hash: utxo.hash,
415
- index: utxo.index,
416
- witnessUtxo: utxo.witnessUtxo,
417
- }));
442
+ if (this.addressFormat === AddressFormat.P2WPKH) {
443
+ // Add inputs to the PSBT from the accumulated inputs.
444
+ inputs.forEach((utxo) => psbt.addInput({
445
+ hash: utxo.hash,
446
+ index: utxo.index,
447
+ witnessUtxo: utxo.witnessUtxo,
448
+ }));
449
+ }
450
+ else {
451
+ const { pubkey, output } = Bitcoin.payments.p2tr({
452
+ address: sender,
453
+ });
454
+ inputs.forEach((utxo) => psbt.addInput({
455
+ hash: utxo.hash,
456
+ index: utxo.index,
457
+ witnessUtxo: { value: utxo.value, script: output },
458
+ tapInternalKey: pubkey,
459
+ }));
460
+ }
418
461
  // Add outputs to the PSBT from the accumulated outputs.
419
462
  outputs.forEach((output) => {
420
463
  // If the output address is not specified, it's considered a change address and set to the sender's address.
421
464
  if (!output.address) {
422
- //an empty address means this is the change ddress
465
+ //an empty address means this is the change address
423
466
  output.address = sender;
424
467
  }
425
468
  // Add the output to the PSBT.
@@ -433,7 +476,6 @@ class Client extends Client$1 {
433
476
  }
434
477
  }
435
478
  });
436
- // Return the prepared transaction data including the PSBT, UTXOs, and inputs.
437
479
  return { psbt, utxos, inputs };
438
480
  });
439
481
  }
@@ -460,10 +502,14 @@ class Client extends Client$1 {
460
502
  }
461
503
  }
462
504
 
505
+ const ECPair = ECPairFactory(ecc);
463
506
  /**
464
507
  * Custom Bitcoin client extended to support keystore functionality
465
508
  */
466
509
  class ClientKeystore extends Client {
510
+ constructor(params = Object.assign(Object.assign({}, defaultBTCParams), { addressFormat: AddressFormat.P2WPKH })) {
511
+ super(params);
512
+ }
467
513
  /**
468
514
  * @deprecated This function eventually will be removed. Use getAddressAsync instead.
469
515
  * Get the address associated with the given index.
@@ -483,10 +529,19 @@ class ClientKeystore extends Client {
483
529
  const btcNetwork$1 = btcNetwork(this.network);
484
530
  const btcKeys = this.getBtcKeys(this.phrase, index);
485
531
  // Generate the address using the Bitcoinjs library
486
- const { address } = Bitcoin.payments.p2wpkh({
487
- pubkey: btcKeys.publicKey,
488
- network: btcNetwork$1,
489
- });
532
+ let address;
533
+ if (this.addressFormat === AddressFormat.P2WPKH) {
534
+ address = Bitcoin.payments.p2wpkh({
535
+ pubkey: btcKeys.publicKey,
536
+ network: btcNetwork$1,
537
+ }).address;
538
+ }
539
+ else {
540
+ address = Bitcoin.payments.p2tr({
541
+ internalPubkey: toXOnly(btcKeys.publicKey),
542
+ network: btcNetwork$1,
543
+ }).address;
544
+ }
490
545
  // Throw an error if the address is not defined
491
546
  if (!address) {
492
547
  throw new Error('Address not defined');
@@ -518,11 +573,12 @@ class ClientKeystore extends Client {
518
573
  getBtcKeys(phrase, index = 0) {
519
574
  const btcNetwork$1 = btcNetwork(this.network);
520
575
  const seed = getSeed(phrase);
521
- const master = Bitcoin.bip32.fromSeed(seed, btcNetwork$1).derivePath(this.getFullDerivationPath(index));
576
+ const bip32 = BIP32Factory(ecc);
577
+ const master = bip32.fromSeed(seed, btcNetwork$1).derivePath(this.getFullDerivationPath(index));
522
578
  if (!master.privateKey) {
523
579
  throw new Error('Could not get private key from phrase');
524
580
  }
525
- return Bitcoin.ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork$1 });
581
+ return ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork$1 });
526
582
  }
527
583
  /**
528
584
  * Transfer BTC.
@@ -539,14 +595,16 @@ class ClientKeystore extends Client {
539
595
  checkFeeBounds(this.feeBounds, feeRate);
540
596
  // Get the address index from the parameters or use the default value
541
597
  const fromAddressIndex = (params === null || params === void 0 ? void 0 : params.walletIndex) || 0;
542
- // Prepare the transaction
543
- const { rawUnsignedTx } = yield this.prepareTx(Object.assign(Object.assign({}, params), { sender: this.getAddress(fromAddressIndex), feeRate }));
544
598
  // Get the Bitcoin keys
545
599
  const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex);
600
+ // Prepare the transaction
601
+ const { rawUnsignedTx } = yield this.prepareTx(Object.assign(Object.assign({}, params), { sender: this.getAddress(fromAddressIndex), feeRate }));
546
602
  // Build the PSBT
547
603
  const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx);
548
604
  // Sign all inputs
549
- psbt.signAllInputs(btcKeys);
605
+ psbt.signAllInputs(this.addressFormat === AddressFormat.P2WPKH
606
+ ? btcKeys
607
+ : btcKeys.tweak(Bitcoin.crypto.taggedHash('TapTweak', toXOnly(btcKeys.publicKey))));
550
608
  // Finalize inputs
551
609
  psbt.finalizeAllInputs();
552
610
  // Extract the transaction hex
@@ -596,7 +654,7 @@ class ClientLedger extends Client {
596
654
  return __awaiter(this, void 0, void 0, function* () {
597
655
  const app = yield this.getApp();
598
656
  const result = yield app.getWalletPublicKey(this.getFullDerivationPath(index), {
599
- format: 'bech32',
657
+ format: this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32',
600
658
  verify,
601
659
  });
602
660
  return result.bitcoinAddress;
@@ -636,7 +694,7 @@ class ClientLedger extends Client {
636
694
  outputScriptHex,
637
695
  segwit: true,
638
696
  useTrustedInputForSegwit: true,
639
- additionals: ['bech32'],
697
+ additionals: [this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32'],
640
698
  });
641
699
  // Broadcast transaction
642
700
  const txHash = yield this.broadcastTx(txHex);
@@ -649,5 +707,5 @@ class ClientLedger extends Client {
649
707
  }
650
708
  }
651
709
 
652
- export { AssetBTC, BTCChain, BTC_DECIMAL, BTC_SATOSHI_SYMBOL, BTC_SYMBOL, BitgoProviders, BlockcypherDataProviders, ClientKeystore as Client, ClientLedger, HaskoinDataProviders, LOWER_FEE_BOUND, MIN_TX_FEE, SochainDataProviders, UPPER_FEE_BOUND, blockstreamExplorerProviders, defaultBTCParams, getPrefix, validateAddress };
710
+ export { AddressFormat, AssetBTC, BTCChain, BTC_DECIMAL, BTC_SATOSHI_SYMBOL, BTC_SYMBOL, BitgoProviders, BlockcypherDataProviders, ClientKeystore as Client, ClientLedger, HaskoinDataProviders, LOWER_FEE_BOUND, MIN_TX_FEE, SochainDataProviders, UPPER_FEE_BOUND, blockstreamExplorerProviders, defaultBTCParams, getPrefix, tapRootDerivationPaths, validateAddress };
653
711
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../../../node_modules/coinselect/utils.js","../../../node_modules/coinselect/accumulative.js","../src/const.ts","../src/utils.ts","../src/client.ts","../src/clientKeystore.ts","../src/clientLedger.ts"],"sourcesContent":["// baseline estimates, used to improve performance\nvar TX_EMPTY_SIZE = 4 + 1 + 1 + 4\nvar TX_INPUT_BASE = 32 + 4 + 1 + 4\nvar TX_INPUT_PUBKEYHASH = 107\nvar TX_OUTPUT_BASE = 8 + 1\nvar TX_OUTPUT_PUBKEYHASH = 25\n\nfunction inputBytes (input) {\n return TX_INPUT_BASE + (input.script ? input.script.length : TX_INPUT_PUBKEYHASH)\n}\n\nfunction outputBytes (output) {\n return TX_OUTPUT_BASE + (output.script ? output.script.length : TX_OUTPUT_PUBKEYHASH)\n}\n\nfunction dustThreshold (output, feeRate) {\n /* ... classify the output for input estimate */\n return inputBytes({}) * feeRate\n}\n\nfunction transactionBytes (inputs, outputs) {\n return TX_EMPTY_SIZE +\n inputs.reduce(function (a, x) { return a + inputBytes(x) }, 0) +\n outputs.reduce(function (a, x) { return a + outputBytes(x) }, 0)\n}\n\nfunction uintOrNaN (v) {\n if (typeof v !== 'number') return NaN\n if (!isFinite(v)) return NaN\n if (Math.floor(v) !== v) return NaN\n if (v < 0) return NaN\n return v\n}\n\nfunction sumForgiving (range) {\n return range.reduce(function (a, x) { return a + (isFinite(x.value) ? x.value : 0) }, 0)\n}\n\nfunction sumOrNaN (range) {\n return range.reduce(function (a, x) { return a + uintOrNaN(x.value) }, 0)\n}\n\nvar BLANK_OUTPUT = outputBytes({})\n\nfunction finalize (inputs, outputs, feeRate) {\n var bytesAccum = transactionBytes(inputs, outputs)\n var feeAfterExtraOutput = feeRate * (bytesAccum + BLANK_OUTPUT)\n var remainderAfterExtraOutput = sumOrNaN(inputs) - (sumOrNaN(outputs) + feeAfterExtraOutput)\n\n // is it worth a change output?\n if (remainderAfterExtraOutput > dustThreshold({}, feeRate)) {\n outputs = outputs.concat({ value: remainderAfterExtraOutput })\n }\n\n var fee = sumOrNaN(inputs) - sumOrNaN(outputs)\n if (!isFinite(fee)) return { fee: feeRate * bytesAccum }\n\n return {\n inputs: inputs,\n outputs: outputs,\n fee: fee\n }\n}\n\nmodule.exports = {\n dustThreshold: dustThreshold,\n finalize: finalize,\n inputBytes: inputBytes,\n outputBytes: outputBytes,\n sumOrNaN: sumOrNaN,\n sumForgiving: sumForgiving,\n transactionBytes: transactionBytes,\n uintOrNaN: uintOrNaN\n}\n","var utils = require('./utils')\n\n// add inputs until we reach or surpass the target value (or deplete)\n// worst-case: O(n)\nmodule.exports = function accumulative (utxos, outputs, feeRate) {\n if (!isFinite(utils.uintOrNaN(feeRate))) return {}\n var bytesAccum = utils.transactionBytes([], outputs)\n\n var inAccum = 0\n var inputs = []\n var outAccum = utils.sumOrNaN(outputs)\n\n for (var i = 0; i < utxos.length; ++i) {\n var utxo = utxos[i]\n var utxoBytes = utils.inputBytes(utxo)\n var utxoFee = feeRate * utxoBytes\n var utxoValue = utils.uintOrNaN(utxo.value)\n\n // skip detrimental input\n if (utxoFee > utxo.value) {\n if (i === utxos.length - 1) return { fee: feeRate * (bytesAccum + utxoBytes) }\n continue\n }\n\n bytesAccum += utxoBytes\n inAccum += utxoValue\n inputs.push(utxo)\n\n var fee = feeRate * bytesAccum\n\n // go again?\n if (inAccum < outAccum + fee) continue\n\n return utils.finalize(inputs, outputs, feeRate)\n }\n\n return { fee: feeRate * bytesAccum }\n}\n","import { ExplorerProvider, Network } from '@xchainjs/xchain-client'\nimport { Asset, AssetType } from '@xchainjs/xchain-util'\nimport {\n BitgoProvider,\n BlockcypherNetwork,\n BlockcypherProvider,\n HaskoinNetwork,\n HaskoinProvider,\n SochainNetwork,\n SochainProvider,\n UtxoOnlineDataProviders,\n} from '@xchainjs/xchain-utxo-providers'\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000\n\n// Decimal places for Bitcoin\nexport const BTC_DECIMAL = 8\n\n// Lower and upper bounds for fee rates\nexport const LOWER_FEE_BOUND = 1\nexport const UPPER_FEE_BOUND = 1_000\n\n// Symbols for Bitcoin\nexport const BTC_SYMBOL = '₿'\nexport const BTC_SATOSHI_SYMBOL = '⚡'\n\n/**\n * Chain identifier for Bitcoin mainnet\n */\nexport const BTCChain = 'BTC' as const\n\n/**\n * Base \"chain\" asset on bitcoin main net.\n */\nexport const AssetBTC: Asset = { chain: BTCChain, symbol: 'BTC', ticker: 'BTC', type: AssetType.NATIVE }\n\n// Explorer providers for Bitcoin\nconst BTC_MAINNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/',\n 'https://blockstream.info/address/%%ADDRESS%%',\n 'https://blockstream.info/tx/%%TX_ID%%',\n)\nconst BTC_TESTNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/testnet/',\n 'https://blockstream.info/testnet/address/%%ADDRESS%%',\n 'https://blockstream.info/testnet/tx/%%TX_ID%%',\n)\nexport const blockstreamExplorerProviders = {\n [Network.Testnet]: BTC_TESTNET_EXPLORER,\n [Network.Stagenet]: BTC_MAINNET_EXPLORER,\n [Network.Mainnet]: BTC_MAINNET_EXPLORER,\n}\n\n// Sochain data providers for Bitcoin\nconst testnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTCTEST,\n)\nconst mainnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTC,\n)\nexport const SochainDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetSochainProvider,\n [Network.Stagenet]: mainnetSochainProvider,\n [Network.Mainnet]: mainnetSochainProvider,\n}\n\n// Haskoin data providers for Bitcoin\nconst testnetHaskoinProvider = new HaskoinProvider(\n 'https://api.haskoin.com',\n BTCChain,\n AssetBTC,\n 8,\n HaskoinNetwork.BTCTEST,\n)\nconst mainnetHaskoinProvider = new HaskoinProvider('https://api.haskoin.com', BTCChain, AssetBTC, 8, HaskoinNetwork.BTC)\nexport const HaskoinDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetHaskoinProvider,\n [Network.Stagenet]: mainnetHaskoinProvider,\n [Network.Mainnet]: mainnetHaskoinProvider,\n}\n\n// Blockcypher data providers for Bitcoin\nconst testnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTCTEST,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nconst mainnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTC,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nexport const BlockcypherDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetBlockcypherProvider,\n [Network.Stagenet]: mainnetBlockcypherProvider,\n [Network.Mainnet]: mainnetBlockcypherProvider,\n}\n\n// Bitgo data providers for Bitcoin\nconst mainnetBitgoProvider = new BitgoProvider({\n baseUrl: 'https://app.bitgo.com',\n chain: BTCChain,\n})\nexport const BitgoProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: undefined,\n [Network.Stagenet]: mainnetBitgoProvider,\n [Network.Mainnet]: mainnetBitgoProvider,\n}\n","// Import statements for necessary modules and types\nimport { Network } from '@xchainjs/xchain-client' // Importing the Network type from xchain-client module\nimport { Address } from '@xchainjs/xchain-util' // Importing the Address type from xchain-util module\nimport { UTXO } from '@xchainjs/xchain-utxo' // Importing the UTXO type from xchain-utxo module\nimport * as Bitcoin from 'bitcoinjs-lib' // Importing the entire bitcoinjs-lib module and aliasing it as Bitcoin\n\n// Constants defining the sizes of various components in a Bitcoin transaction\nexport const TX_EMPTY_SIZE = 4 + 1 + 1 + 4 // Total size of an empty transaction\nexport const TX_INPUT_BASE = 32 + 4 + 1 + 4 // Size of a base input in a transaction\nexport const TX_INPUT_PUBKEYHASH = 107 // Size of an input with a public key hash\nexport const TX_OUTPUT_BASE = 8 + 1 // Size of a base output in a transaction\nexport const TX_OUTPUT_PUBKEYHASH = 25 // Size of an output with a public key hash\n\n/**\n * Function to calculate the size of an input in a transaction.\n * @param {UTXO} input - The UTXO (Unspent Transaction Output) for which to calculate the size.\n * @returns {number} The size of the input.\n */\nexport const inputBytes = (input: UTXO): number => {\n return TX_INPUT_BASE + (input.witnessUtxo?.script ? input.witnessUtxo?.script.length : TX_INPUT_PUBKEYHASH)\n}\n\n/**\n * Function to calculate the average value of an array of numbers.\n * @param {number[]} array - The array of numbers.\n * @returns {number} The average value of the array.\n */\nexport const arrayAverage = (array: number[]): number => {\n let sum = 0\n array.forEach((value) => (sum += value))\n return sum / array.length\n}\n\n/**\n * Function to get the Bitcoin network to be used with bitcoinjs.\n *\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {Bitcoin.Network} The Bitcoin network.\n */\nexport const btcNetwork = (network: Network): Bitcoin.Network => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return Bitcoin.networks.bitcoin // Return the Bitcoin mainnet or stagenet network\n case Network.Testnet:\n return Bitcoin.networks.testnet // Return the Bitcoin testnet network\n }\n}\n\n/**\n * Function to validate a Bitcoin address.\n * @param {Address} address - The Bitcoin address to validate.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\nexport const validateAddress = (address: Address, network: Network): boolean => {\n try {\n Bitcoin.address.toOutputScript(address, btcNetwork(network)) // Try to convert the address to an output script using the specified network\n return true // If successful, the address is valid\n } catch (error) {\n return false // If an error occurs, the address is invalid\n }\n}\n\n/**\n * Function to get the address prefix based on the network.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {string} The address prefix based on the network.\n */\nexport const getPrefix = (network: Network): string => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return 'bc1' // Return the address prefix for Bitcoin mainnet or stagenet\n case Network.Testnet:\n return 'tb1' // Return the address prefix for Bitcoin testnet\n }\n}\n","import { AssetInfo, FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { Client as UTXOClient, PreparedTx, TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport accumulative from 'coinselect/accumulative'\n\nimport {\n AssetBTC,\n BTCChain,\n BTC_DECIMAL,\n BitgoProviders,\n BlockcypherDataProviders,\n LOWER_FEE_BOUND,\n MIN_TX_FEE,\n UPPER_FEE_BOUND,\n blockstreamExplorerProviders,\n} from './const'\nimport * as Utils from './utils'\n// Default parameters for the Bitcoin UTXO client\nexport const defaultBTCParams: UtxoClientParams = {\n network: Network.Mainnet,\n phrase: '',\n explorerProviders: blockstreamExplorerProviders,\n dataProviders: [BitgoProviders, BlockcypherDataProviders],\n rootDerivationPaths: {\n [Network.Mainnet]: `84'/0'/0'/0/`, // Not BIP44 compliant but compatible with pre-HD wallets\n [Network.Testnet]: `84'/1'/0'/0/`,\n [Network.Stagenet]: `84'/0'/0'/0/`,\n },\n feeBounds: {\n lower: LOWER_FEE_BOUND,\n upper: UPPER_FEE_BOUND,\n },\n}\n/**\n * Custom Bitcoin client\n */\nabstract class Client extends UTXOClient {\n /**\n * Constructor\n * Initializes the client with network type and other parameters.\n * @param {UtxoClientParams} params\n */\n constructor(params = defaultBTCParams) {\n super(BTCChain, {\n network: params.network,\n rootDerivationPaths: params.rootDerivationPaths,\n phrase: params.phrase,\n feeBounds: params.feeBounds,\n explorerProviders: params.explorerProviders,\n dataProviders: params.dataProviders,\n })\n }\n\n /**\n * Get BTC asset info.\n * @returns {AssetInfo} BTC asset information.\n */\n getAssetInfo(): AssetInfo {\n const assetInfo: AssetInfo = {\n asset: AssetBTC,\n decimal: BTC_DECIMAL,\n }\n return assetInfo\n }\n\n /**\n * Validate the given Bitcoin address.\n * @param {string} address Bitcoin address to validate.\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\n validateAddress(address: string): boolean {\n return Utils.validateAddress(address, this.network)\n }\n\n /**\n * Compile memo into a buffer.\n * @param {string} memo Memo to compile.\n * @returns {Buffer} Compiled memo.\n */\n protected compileMemo(memo: string): Buffer {\n const data = Buffer.from(memo, 'utf8') // converts MEMO to buffer\n return Bitcoin.script.compile([Bitcoin.opcodes.OP_RETURN, data]) // Compile OP_RETURN script\n }\n\n /**\n * Get transaction fee from UTXOs.\n * @param {UTXO[]} inputs UTXOs to calculate fee from.\n * @param {FeeRate} feeRate Fee rate.\n * @param {Buffer | null} data Compiled memo (Optional).\n * @returns {number} Transaction fee.\n */\n protected getFeeFromUtxos(inputs: UTXO[], feeRate: FeeRate, data: Buffer | null = null): number {\n // Calculate input size based on inputs\n const inputSizeBasedOnInputs =\n inputs.length > 0\n ? inputs.reduce((a, x) => a + Utils.inputBytes(x), 0) + inputs.length // +1 byte for each input signature\n : 0\n // Calculate sum\n let sum =\n Utils.TX_EMPTY_SIZE +\n inputSizeBasedOnInputs +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH\n\n if (data) {\n sum += Utils.TX_OUTPUT_BASE + data.length\n }\n // Calculate fee\n const fee = sum * feeRate\n return fee > MIN_TX_FEE ? fee : MIN_TX_FEE\n }\n\n /**\n * Build a Bitcoin transaction.*\n * @param param0\n * @deprecated\n */\n async buildTx({\n amount,\n recipient,\n memo,\n feeRate,\n sender,\n spendPendingUTXO = true,\n }: TxParams & {\n feeRate: FeeRate\n sender: Address\n spendPendingUTXO?: boolean\n withTxHex?: boolean\n }): Promise<{ psbt: Bitcoin.Psbt; utxos: UTXO[]; inputs: UTXO[] }> {\n // Check memo length\n if (memo && memo.length > 80) {\n throw new Error('memo too long, must not be longer than 80 chars.')\n }\n // This section of the code is responsible for preparing a transaction by building a Bitcoin PSBT (Partially Signed Bitcoin Transaction).\n if (!this.validateAddress(recipient)) throw new Error('Invalid address')\n // Determine whether to only use confirmed UTXOs or include pending UTXOs based on the spendPendingUTXO flag.\n const confirmedOnly = !spendPendingUTXO\n // Scan UTXOs associated with the sender's address.\n const utxos = await this.scanUTXOs(sender, confirmedOnly)\n // Throw an error if there are no available UTXOs to cover the transaction.\n if (utxos.length === 0) throw new Error('Insufficient Balance for transaction')\n // Round up the fee rate to the nearest integer.\n const feeRateWhole = Math.ceil(feeRate)\n // Compile the memo into a Buffer if provided.\n const compiledMemo = memo ? this.compileMemo(memo) : null\n // Initialize an array to store the target outputs of the transaction.\n const targetOutputs = []\n\n // 1. Add the recipient address and amount to the target outputs.\n targetOutputs.push({\n address: recipient,\n value: amount.amount().toNumber(),\n })\n // 2. Add the compiled memo to the target outputs if it exists.\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 })\n }\n // Use the coinselect library to determine the inputs and outputs for the transaction.\n const { inputs, outputs } = accumulative(utxos, targetOutputs, feeRateWhole)\n // If no suitable inputs or outputs are found, throw an error indicating insufficient balance.\n if (!inputs || !outputs) throw new Error('Insufficient Balance for transaction')\n // Initialize a new Bitcoin PSBT object.\n const psbt = new Bitcoin.Psbt({ network: Utils.btcNetwork(this.network) }) // Network-specific\n\n // Add inputs to the PSBT from the accumulated inputs.\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: utxo.witnessUtxo,\n }),\n )\n\n // Add outputs to the PSBT from the accumulated outputs.\n outputs.forEach((output: Bitcoin.PsbtTxOutput) => {\n // If the output address is not specified, it's considered a change address and set to the sender's address.\n if (!output.address) {\n //an empty address means this is the change ddress\n output.address = sender\n }\n // Add the output to the PSBT.\n if (!output.script) {\n psbt.addOutput(output)\n } else {\n // If the output is a memo, add it to the PSBT to avoid dust error.\n if (compiledMemo) {\n psbt.addOutput({ script: compiledMemo, value: 0 })\n }\n }\n })\n // Return the prepared transaction data including the PSBT, UTXOs, and inputs.\n return { psbt, utxos, inputs }\n }\n\n /**\n * Prepare transfer.\n *\n * @param {TxParams&Address&FeeRate&boolean} params The transfer options.\n * @returns {PreparedTx} The raw unsigned transaction.\n */\n async prepareTx({\n sender,\n memo,\n amount,\n recipient,\n spendPendingUTXO = true,\n feeRate,\n }: TxParams & {\n sender: Address\n feeRate: FeeRate\n spendPendingUTXO?: boolean\n }): Promise<PreparedTx> {\n // Build the transaction using the provided parameters.\n const { psbt, utxos } = await this.buildTx({\n sender,\n recipient,\n amount,\n feeRate,\n memo,\n spendPendingUTXO,\n })\n // Return the raw unsigned transaction (PSBT) and associated UTXOs.\n return { rawUnsignedTx: psbt.toBase64(), utxos }\n }\n}\n\nexport { Client }\n","import { FeeOption, FeeRate, TxHash, checkFeeBounds } from '@xchainjs/xchain-client'\nimport { getSeed } from '@xchainjs/xchain-crypto'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client' // Importing the base Bitcoin client\nimport * as Utils from './utils' // Importing utility functions\n\n/**\n * Custom Bitcoin client extended to support keystore functionality\n */\nclass ClientKeystore extends Client {\n /**\n * @deprecated This function eventually will be removed. Use getAddressAsync instead.\n * Get the address associated with the given index.\n * @param {number} index The index of the address.\n * @returns {Address} The Bitcoin address.\n * @throws {\"index must be greater than zero\"} Thrown if the index is less than zero.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n * @throws {\"Address not defined\"} Thrown if failed to create the address from the phrase.\n */\n getAddress(index = 0): Address {\n // Check if the index is valid\n if (index < 0) {\n throw new Error('index must be greater than zero')\n }\n\n // Check if the phrase has been set\n if (this.phrase) {\n const btcNetwork = Utils.btcNetwork(this.network)\n const btcKeys = this.getBtcKeys(this.phrase, index)\n\n // Generate the address using the Bitcoinjs library\n const { address } = Bitcoin.payments.p2wpkh({\n pubkey: btcKeys.publicKey,\n network: btcNetwork,\n })\n\n // Throw an error if the address is not defined\n if (!address) {\n throw new Error('Address not defined')\n }\n\n return address\n }\n\n throw new Error('Phrase must be provided')\n }\n\n /**\n * Get the current address asynchronously.\n * @param {number} index The index of the address.\n * @returns {Promise<Address>} A promise that resolves to the Bitcoin address.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n */\n async getAddressAsync(index = 0): Promise<string> {\n return this.getAddress(index)\n }\n\n /**\n * @private\n * Get the Bitcoin keys derived from the given phrase.\n *\n * @param {string} phrase The phrase to be used for generating the keys.\n * @param {number} index The index of the address.\n * @returns {Bitcoin.ECPair.ECPairInterface} The Bitcoin key pair.\n * @throws {\"Could not get private key from phrase\"} Thrown if failed to create BTC keys from the given phrase.\n */\n private getBtcKeys(phrase: string, index = 0): Bitcoin.ECPair.ECPairInterface {\n const btcNetwork = Utils.btcNetwork(this.network)\n const seed = getSeed(phrase)\n const master = Bitcoin.bip32.fromSeed(seed, btcNetwork).derivePath(this.getFullDerivationPath(index))\n\n if (!master.privateKey) {\n throw new Error('Could not get private key from phrase')\n }\n\n return Bitcoin.ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork })\n }\n\n /**\n * Transfer BTC.\n *\n * @param {TxParams&FeeRate} params The transfer options including the fee rate.\n * @returns {Promise<TxHash|string>} A promise that resolves to the transaction hash or an error message.\n * @throws {\"memo too long\"} Thrown if the memo is longer than 80 characters.\n */\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n // Set the default fee rate to `fast`\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n\n // Check if the fee rate is within the fee bounds\n checkFeeBounds(this.feeBounds, feeRate)\n\n // Get the address index from the parameters or use the default value\n const fromAddressIndex = params?.walletIndex || 0\n\n // Prepare the transaction\n const { rawUnsignedTx } = await this.prepareTx({ ...params, sender: this.getAddress(fromAddressIndex), feeRate })\n\n // Get the Bitcoin keys\n const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex)\n\n // Build the PSBT\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n\n // Sign all inputs\n psbt.signAllInputs(btcKeys)\n\n // Finalize inputs\n psbt.finalizeAllInputs()\n\n // Extract the transaction hex\n const txHex = psbt.extractTransaction().toHex()\n\n // Extract the transaction hash\n const txHash = psbt.extractTransaction().getId()\n\n try {\n // Broadcast the transaction and return the transaction hash\n const txId = await this.roundRobinBroadcastTx(txHex)\n return txId\n } catch (err) {\n // If broadcasting fails, return an error message with a link to the explorer\n const error = `Server error, please check explorer for tx confirmation ${this.explorerProviders[\n this.network\n ].getExplorerTxUrl(txHash)}`\n return error\n }\n }\n}\n\nexport { ClientKeystore }\n","import AppBtc from '@ledgerhq/hw-app-btc'\nimport { Transaction } from '@ledgerhq/hw-app-btc/lib/types'\nimport { FeeOption, FeeRate, TxHash } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client'\n\n/**\n * Custom Ledger Bitcoin client\n */\nclass ClientLedger extends Client {\n // Reference to the Ledger transport object\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private transport: any // TODO: Parametrize\n private app: AppBtc | undefined\n\n // Constructor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(params: UtxoClientParams & { transport: any }) {\n super(params)\n this.transport = params.transport\n }\n\n // Get the Ledger BTC application instance\n public async getApp(): Promise<AppBtc> {\n if (this.app) {\n return this.app\n }\n this.app = new AppBtc({ transport: this.transport })\n return this.app\n }\n\n // Get the current address synchronously\n getAddress(): string {\n throw Error('Sync method not supported for Ledger')\n }\n\n // Get the current address asynchronously\n async getAddressAsync(index = 0, verify = false): Promise<Address> {\n const app = await this.getApp()\n const result = await app.getWalletPublicKey(this.getFullDerivationPath(index), {\n format: 'bech32',\n verify,\n })\n return result.bitcoinAddress\n }\n\n // Transfer BTC from Ledger\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n const app = await this.getApp()\n const fromAddressIndex = params?.walletIndex || 0\n // Get fee rate\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n // Get sender address\n const sender = await this.getAddressAsync(fromAddressIndex)\n // Prepare transaction\n const { rawUnsignedTx, utxos } = await this.prepareTx({ ...params, sender, feeRate })\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n // Prepare Ledger inputs\n const ledgerInputs: [Transaction, number, string | null, number | null][] = (utxos as UTXO[]).map(\n ({ txHex, hash, index }) => {\n if (!txHex) {\n throw Error(`Missing 'txHex' for UTXO (txHash ${hash})`)\n }\n const utxoTx = Bitcoin.Transaction.fromHex(txHex)\n const splittedTx = app.splitTransaction(txHex, utxoTx.hasWitnesses())\n return [splittedTx, index, null, null]\n },\n )\n\n // Prepare associated keysets\n const associatedKeysets = ledgerInputs.map(() => this.getFullDerivationPath(fromAddressIndex))\n // Serialize unsigned transaction\n const unsignedHex = psbt.data.globalMap.unsignedTx.toBuffer().toString('hex')\n const newTx = app.splitTransaction(unsignedHex, true)\n const outputScriptHex = app.serializeTransactionOutputs(newTx).toString('hex')\n // Create payment transaction\n const txHex = await app.createPaymentTransaction({\n inputs: ledgerInputs,\n associatedKeysets,\n outputScriptHex,\n segwit: true,\n useTrustedInputForSegwit: true,\n additionals: ['bech32'],\n })\n // Broadcast transaction\n const txHash = await this.broadcastTx(txHex)\n // Throw error if no transaction hash is received\n if (!txHash) {\n throw Error('No Tx hash')\n }\n\n return txHash\n }\n}\n\nexport { ClientLedger }\n"],"names":["TX_EMPTY_SIZE","TX_INPUT_BASE","TX_INPUT_PUBKEYHASH","TX_OUTPUT_BASE","TX_OUTPUT_PUBKEYHASH","inputBytes","utils","require$$0","UTXOClient","Utils.validateAddress","Utils.inputBytes","Utils.TX_EMPTY_SIZE","Utils.TX_OUTPUT_BASE","Utils.TX_OUTPUT_PUBKEYHASH","accumulative","Utils.btcNetwork","btcNetwork"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA,IAAIA,eAAa,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACjC,IAAIC,eAAa,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AAClC,IAAIC,qBAAmB,GAAG,IAAG;AAC7B,IAAIC,gBAAc,GAAG,CAAC,GAAG,EAAC;AAC1B,IAAIC,sBAAoB,GAAG,GAAE;AAC7B;AACA,SAASC,YAAU,EAAE,KAAK,EAAE;AAC5B,EAAE,OAAOJ,eAAa,IAAI,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,GAAGC,qBAAmB,CAAC;AACnF,CAAC;AACD;AACA,SAAS,WAAW,EAAE,MAAM,EAAE;AAC9B,EAAE,OAAOC,gBAAc,IAAI,MAAM,CAAC,MAAM,GAA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AC,CAAA;AACrD,YAAA,MAAM,eAAe,GAAG,GAAG,CAAC,2BAA2B,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;;AAE9E,YAAA,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,wBAAwB,CAAC;AAC/C,gBAAA,MAAM,EAAE,YAAY;gBACpB,iBAAiB;gBACjB,eAAe;AACf,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,wBAAwB,EAAE,IAAI;gBAC9B,WAAW,EAAE,CAAC,QAAQ,CAAC;AACxB,aAAA,CAAC,CAAA;;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;;YAE5C,IAAI,CAAC,MAAM,EAAE;AACX,gBAAA,MAAM,KAAK,CAAC,YAAY,CAAC,CAAA;AAC1B,aAAA;AAED,YAAA,OAAO,MAAM,CAAA;SACd,CAAA,CAAA;AAAA,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/types/client-types.ts","../../../node_modules/coinselect/utils.js","../../../node_modules/coinselect/accumulative.js","../src/const.ts","../src/utils.ts","../src/client.ts","../src/clientKeystore.ts","../src/clientLedger.ts"],"sourcesContent":["import { FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\n\nexport type NormalTxParams = { addressTo: Address; amount: number; feeRate: FeeRate }\nexport type VaultTxParams = NormalTxParams & { memo: string }\n\nexport type GetChangeParams = {\n valueOut: number\n sochainUrl: string\n network: Network\n address: Address\n}\n\nexport type ClientUrl = Record<Network, string>\n\nexport enum AddressFormat {\n P2WPKH,\n P2TR,\n}\n","// baseline estimates, used to improve performance\nvar TX_EMPTY_SIZE = 4 + 1 + 1 + 4\nvar TX_INPUT_BASE = 32 + 4 + 1 + 4\nvar TX_INPUT_PUBKEYHASH = 107\nvar TX_OUTPUT_BASE = 8 + 1\nvar TX_OUTPUT_PUBKEYHASH = 25\n\nfunction inputBytes (input) {\n return TX_INPUT_BASE + (input.script ? input.script.length : TX_INPUT_PUBKEYHASH)\n}\n\nfunction outputBytes (output) {\n return TX_OUTPUT_BASE + (output.script ? output.script.length : TX_OUTPUT_PUBKEYHASH)\n}\n\nfunction dustThreshold (output, feeRate) {\n /* ... classify the output for input estimate */\n return inputBytes({}) * feeRate\n}\n\nfunction transactionBytes (inputs, outputs) {\n return TX_EMPTY_SIZE +\n inputs.reduce(function (a, x) { return a + inputBytes(x) }, 0) +\n outputs.reduce(function (a, x) { return a + outputBytes(x) }, 0)\n}\n\nfunction uintOrNaN (v) {\n if (typeof v !== 'number') return NaN\n if (!isFinite(v)) return NaN\n if (Math.floor(v) !== v) return NaN\n if (v < 0) return NaN\n return v\n}\n\nfunction sumForgiving (range) {\n return range.reduce(function (a, x) { return a + (isFinite(x.value) ? x.value : 0) }, 0)\n}\n\nfunction sumOrNaN (range) {\n return range.reduce(function (a, x) { return a + uintOrNaN(x.value) }, 0)\n}\n\nvar BLANK_OUTPUT = outputBytes({})\n\nfunction finalize (inputs, outputs, feeRate) {\n var bytesAccum = transactionBytes(inputs, outputs)\n var feeAfterExtraOutput = feeRate * (bytesAccum + BLANK_OUTPUT)\n var remainderAfterExtraOutput = sumOrNaN(inputs) - (sumOrNaN(outputs) + feeAfterExtraOutput)\n\n // is it worth a change output?\n if (remainderAfterExtraOutput > dustThreshold({}, feeRate)) {\n outputs = outputs.concat({ value: remainderAfterExtraOutput })\n }\n\n var fee = sumOrNaN(inputs) - sumOrNaN(outputs)\n if (!isFinite(fee)) return { fee: feeRate * bytesAccum }\n\n return {\n inputs: inputs,\n outputs: outputs,\n fee: fee\n }\n}\n\nmodule.exports = {\n dustThreshold: dustThreshold,\n finalize: finalize,\n inputBytes: inputBytes,\n outputBytes: outputBytes,\n sumOrNaN: sumOrNaN,\n sumForgiving: sumForgiving,\n transactionBytes: transactionBytes,\n uintOrNaN: uintOrNaN\n}\n","var utils = require('./utils')\n\n// add inputs until we reach or surpass the target value (or deplete)\n// worst-case: O(n)\nmodule.exports = function accumulative (utxos, outputs, feeRate) {\n if (!isFinite(utils.uintOrNaN(feeRate))) return {}\n var bytesAccum = utils.transactionBytes([], outputs)\n\n var inAccum = 0\n var inputs = []\n var outAccum = utils.sumOrNaN(outputs)\n\n for (var i = 0; i < utxos.length; ++i) {\n var utxo = utxos[i]\n var utxoBytes = utils.inputBytes(utxo)\n var utxoFee = feeRate * utxoBytes\n var utxoValue = utils.uintOrNaN(utxo.value)\n\n // skip detrimental input\n if (utxoFee > utxo.value) {\n if (i === utxos.length - 1) return { fee: feeRate * (bytesAccum + utxoBytes) }\n continue\n }\n\n bytesAccum += utxoBytes\n inAccum += utxoValue\n inputs.push(utxo)\n\n var fee = feeRate * bytesAccum\n\n // go again?\n if (inAccum < outAccum + fee) continue\n\n return utils.finalize(inputs, outputs, feeRate)\n }\n\n return { fee: feeRate * bytesAccum }\n}\n","import { ExplorerProvider, Network } from '@xchainjs/xchain-client'\nimport { Asset, AssetType } from '@xchainjs/xchain-util'\nimport {\n BitgoProvider,\n BlockcypherNetwork,\n BlockcypherProvider,\n HaskoinNetwork,\n HaskoinProvider,\n SochainNetwork,\n SochainProvider,\n UtxoOnlineDataProviders,\n} from '@xchainjs/xchain-utxo-providers'\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000\n\n// Decimal places for Bitcoin\nexport const BTC_DECIMAL = 8\n\n// Lower and upper bounds for fee rates\nexport const LOWER_FEE_BOUND = 1\nexport const UPPER_FEE_BOUND = 1_000\n\n// Symbols for Bitcoin\nexport const BTC_SYMBOL = '₿'\nexport const BTC_SATOSHI_SYMBOL = '⚡'\n\n/**\n * Chain identifier for Bitcoin mainnet\n */\nexport const BTCChain = 'BTC' as const\n\n/**\n * Base \"chain\" asset on bitcoin main net.\n */\nexport const AssetBTC: Asset = { chain: BTCChain, symbol: 'BTC', ticker: 'BTC', type: AssetType.NATIVE }\n\n// Explorer providers for Bitcoin\nconst BTC_MAINNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/',\n 'https://blockstream.info/address/%%ADDRESS%%',\n 'https://blockstream.info/tx/%%TX_ID%%',\n)\nconst BTC_TESTNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/testnet/',\n 'https://blockstream.info/testnet/address/%%ADDRESS%%',\n 'https://blockstream.info/testnet/tx/%%TX_ID%%',\n)\nexport const blockstreamExplorerProviders = {\n [Network.Testnet]: BTC_TESTNET_EXPLORER,\n [Network.Stagenet]: BTC_MAINNET_EXPLORER,\n [Network.Mainnet]: BTC_MAINNET_EXPLORER,\n}\n\n// Sochain data providers for Bitcoin\nconst testnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTCTEST,\n)\nconst mainnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTC,\n)\nexport const SochainDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetSochainProvider,\n [Network.Stagenet]: mainnetSochainProvider,\n [Network.Mainnet]: mainnetSochainProvider,\n}\n\n// Haskoin data providers for Bitcoin\nconst testnetHaskoinProvider = new HaskoinProvider(\n 'https://api.haskoin.com',\n BTCChain,\n AssetBTC,\n 8,\n HaskoinNetwork.BTCTEST,\n)\nconst mainnetHaskoinProvider = new HaskoinProvider('https://api.haskoin.com', BTCChain, AssetBTC, 8, HaskoinNetwork.BTC)\nexport const HaskoinDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetHaskoinProvider,\n [Network.Stagenet]: mainnetHaskoinProvider,\n [Network.Mainnet]: mainnetHaskoinProvider,\n}\n\n// Blockcypher data providers for Bitcoin\nconst testnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTCTEST,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nconst mainnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTC,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nexport const BlockcypherDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetBlockcypherProvider,\n [Network.Stagenet]: mainnetBlockcypherProvider,\n [Network.Mainnet]: mainnetBlockcypherProvider,\n}\n\n// Bitgo data providers for Bitcoin\nconst mainnetBitgoProvider = new BitgoProvider({\n baseUrl: 'https://app.bitgo.com',\n chain: BTCChain,\n})\nexport const BitgoProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: undefined,\n [Network.Stagenet]: mainnetBitgoProvider,\n [Network.Mainnet]: mainnetBitgoProvider,\n}\n\nexport const tapRootDerivationPaths = {\n [Network.Mainnet]: `86'/0'/0'/0/`,\n [Network.Testnet]: `86'/1'/0'/0/`,\n [Network.Stagenet]: `86'/0'/0'/0/`,\n}\n","// Import statements for necessary modules and types\nimport { Network } from '@xchainjs/xchain-client' // Importing the Network type from xchain-client module\nimport { Address } from '@xchainjs/xchain-util' // Importing the Address type from xchain-util module\nimport { UTXO } from '@xchainjs/xchain-utxo' // Importing the UTXO type from xchain-utxo module\nimport * as Bitcoin from 'bitcoinjs-lib' // Importing the entire bitcoinjs-lib module and aliasing it as Bitcoin\n\n// Constants defining the sizes of various components in a Bitcoin transaction\nexport const TX_EMPTY_SIZE = 4 + 1 + 1 + 4 // Total size of an empty transaction\nexport const TX_INPUT_BASE = 32 + 4 + 1 + 4 // Size of a base input in a transaction\nexport const TX_INPUT_PUBKEYHASH = 107 // Size of an input with a public key hash\nexport const TX_OUTPUT_BASE = 8 + 1 // Size of a base output in a transaction\nexport const TX_OUTPUT_PUBKEYHASH = 25 // Size of an output with a public key hash\n\n/**\n * Function to calculate the size of an input in a transaction.\n * @param {UTXO} input - The UTXO (Unspent Transaction Output) for which to calculate the size.\n * @returns {number} The size of the input.\n */\nexport const inputBytes = (input: UTXO): number => {\n return TX_INPUT_BASE + (input.witnessUtxo?.script ? input.witnessUtxo?.script.length : TX_INPUT_PUBKEYHASH)\n}\n\n/**\n * Function to calculate the average value of an array of numbers.\n * @param {number[]} array - The array of numbers.\n * @returns {number} The average value of the array.\n */\nexport const arrayAverage = (array: number[]): number => {\n let sum = 0\n array.forEach((value) => (sum += value))\n return sum / array.length\n}\n\n/**\n * Function to get the Bitcoin network to be used with bitcoinjs.\n *\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {Bitcoin.Network} The Bitcoin network.\n */\nexport const btcNetwork = (network: Network): Bitcoin.Network => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return Bitcoin.networks.bitcoin // Return the Bitcoin mainnet or stagenet network\n case Network.Testnet:\n return Bitcoin.networks.testnet // Return the Bitcoin testnet network\n }\n}\n\n/**\n * Function to validate a Bitcoin address.\n * @param {Address} address - The Bitcoin address to validate.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\nexport const validateAddress = (address: Address, network: Network): boolean => {\n try {\n Bitcoin.address.toOutputScript(address, btcNetwork(network)) // Try to convert the address to an output script using the specified network\n return true // If successful, the address is valid\n } catch (error) {\n return false // If an error occurs, the address is invalid\n }\n}\n\n/**\n * Function to get the address prefix based on the network.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {string} The address prefix based on the network.\n */\nexport const getPrefix = (network: Network): string => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return 'bc1' // Return the address prefix for Bitcoin mainnet or stagenet\n case Network.Testnet:\n return 'tb1' // Return the address prefix for Bitcoin testnet\n }\n}\n\n/**\n * Converts a public key to an X-only public key.\n * @param pubKey The public key to convert.\n * @returns The X-only public key.\n */\nexport const toXOnly = (pubKey: Buffer): Buffer => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33))\n","import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs'\nimport { AssetInfo, FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { Client as UTXOClient, PreparedTx, TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport accumulative from 'coinselect/accumulative'\n\nimport {\n AssetBTC,\n BTCChain,\n BTC_DECIMAL,\n BitgoProviders,\n BlockcypherDataProviders,\n LOWER_FEE_BOUND,\n MIN_TX_FEE,\n UPPER_FEE_BOUND,\n blockstreamExplorerProviders,\n} from './const'\nimport { AddressFormat } from './types'\nimport * as Utils from './utils'\n\n// Default parameters for the Bitcoin UTXO client\nexport const defaultBTCParams: UtxoClientParams = {\n network: Network.Mainnet,\n phrase: '',\n explorerProviders: blockstreamExplorerProviders,\n dataProviders: [BitgoProviders, BlockcypherDataProviders],\n rootDerivationPaths: {\n [Network.Mainnet]: `84'/0'/0'/0/`, // Not BIP44 compliant but compatible with pre-HD wallets\n [Network.Testnet]: `84'/1'/0'/0/`,\n [Network.Stagenet]: `84'/0'/0'/0/`,\n },\n feeBounds: {\n lower: LOWER_FEE_BOUND,\n upper: UPPER_FEE_BOUND,\n },\n}\n/**\n * Custom Bitcoin client\n */\nabstract class Client extends UTXOClient {\n protected addressFormat: AddressFormat\n /**\n * Constructor\n * Initializes the client with network type and other parameters.\n * @param {UtxoClientParams} params\n */\n constructor(\n params: UtxoClientParams & { addressFormat?: AddressFormat } = {\n ...defaultBTCParams,\n addressFormat: AddressFormat.P2WPKH,\n },\n ) {\n super(BTCChain, {\n network: params.network,\n rootDerivationPaths: params.rootDerivationPaths,\n phrase: params.phrase,\n feeBounds: params.feeBounds,\n explorerProviders: params.explorerProviders,\n dataProviders: params.dataProviders,\n })\n this.addressFormat = params.addressFormat || AddressFormat.P2WPKH\n\n if (this.addressFormat === AddressFormat.P2TR) {\n if (\n !this.rootDerivationPaths?.mainnet.startsWith(`86'`) ||\n !this.rootDerivationPaths?.testnet.startsWith(`86'`) ||\n !this.rootDerivationPaths?.stagenet.startsWith(`86'`)\n ) {\n throw Error(`Unsupported derivation paths for Taproot client. Use 86' paths`)\n }\n }\n Bitcoin.initEccLib(ecc)\n }\n\n /**\n * Get BTC asset info.\n * @returns {AssetInfo} BTC asset information.\n */\n getAssetInfo(): AssetInfo {\n const assetInfo: AssetInfo = {\n asset: AssetBTC,\n decimal: BTC_DECIMAL,\n }\n return assetInfo\n }\n\n /**\n * Validate the given Bitcoin address.\n * @param {string} address Bitcoin address to validate.\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\n validateAddress(address: string): boolean {\n return Utils.validateAddress(address, this.network)\n }\n\n /**\n * Compile memo into a buffer.\n * @param {string} memo Memo to compile.\n * @returns {Buffer} Compiled memo.\n */\n protected compileMemo(memo: string): Buffer {\n const data = Buffer.from(memo, 'utf8') // converts MEMO to buffer\n return Bitcoin.script.compile([Bitcoin.opcodes.OP_RETURN, data]) // Compile OP_RETURN script\n }\n\n /**\n * Get transaction fee from UTXOs.\n * @param {UTXO[]} inputs UTXOs to calculate fee from.\n * @param {FeeRate} feeRate Fee rate.\n * @param {Buffer | null} data Compiled memo (Optional).\n * @returns {number} Transaction fee.\n */\n protected getFeeFromUtxos(inputs: UTXO[], feeRate: FeeRate, data: Buffer | null = null): number {\n // Calculate input size based on inputs\n const inputSizeBasedOnInputs =\n inputs.length > 0\n ? inputs.reduce((a, x) => a + Utils.inputBytes(x), 0) + inputs.length // +1 byte for each input signature\n : 0\n // Calculate sum\n let sum =\n Utils.TX_EMPTY_SIZE +\n inputSizeBasedOnInputs +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH\n\n if (data) {\n sum += Utils.TX_OUTPUT_BASE + data.length\n }\n // Calculate fee\n const fee = sum * feeRate\n return fee > MIN_TX_FEE ? fee : MIN_TX_FEE\n }\n\n /**\n * Build a Bitcoin transaction.*\n * @param param0\n * @deprecated\n */\n async buildTx({\n amount,\n recipient,\n memo,\n feeRate,\n sender,\n spendPendingUTXO = true,\n }: TxParams & {\n feeRate: FeeRate\n sender: Address\n spendPendingUTXO?: boolean\n withTxHex?: boolean\n }): Promise<{ psbt: Bitcoin.Psbt; utxos: UTXO[]; inputs: UTXO[] }> {\n // Check memo length\n if (memo && memo.length > 80) {\n throw new Error('memo too long, must not be longer than 80 chars.')\n }\n // This section of the code is responsible for preparing a transaction by building a Bitcoin PSBT (Partially Signed Bitcoin Transaction).\n if (!this.validateAddress(recipient)) throw new Error('Invalid address')\n // Determine whether to only use confirmed UTXOs or include pending UTXOs based on the spendPendingUTXO flag.\n const confirmedOnly = !spendPendingUTXO\n // Scan UTXOs associated with the sender's address.\n const utxos = await this.scanUTXOs(sender, confirmedOnly)\n // Throw an error if there are no available UTXOs to cover the transaction.\n if (utxos.length === 0) throw new Error('Insufficient Balance for transaction')\n // Round up the fee rate to the nearest integer.\n const feeRateWhole = Math.ceil(feeRate)\n // Compile the memo into a Buffer if provided.\n const compiledMemo = memo ? this.compileMemo(memo) : null\n // Initialize an array to store the target outputs of the transaction.\n const targetOutputs = []\n\n // 1. Add the recipient address and amount to the target outputs.\n targetOutputs.push({\n address: recipient,\n value: amount.amount().toNumber(),\n })\n // 2. Add the compiled memo to the target outputs if it exists.\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 })\n }\n // Use the coinselect library to determine the inputs and outputs for the transaction.\n const { inputs, outputs } = accumulative(utxos, targetOutputs, feeRateWhole)\n // If no suitable inputs or outputs are found, throw an error indicating insufficient balance.\n if (!inputs || !outputs) throw new Error('Insufficient Balance for transaction')\n // Initialize a new Bitcoin PSBT object.\n const psbt = new Bitcoin.Psbt({ network: Utils.btcNetwork(this.network) }) // Network-specific\n\n if (this.addressFormat === AddressFormat.P2WPKH) {\n // Add inputs to the PSBT from the accumulated inputs.\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: utxo.witnessUtxo,\n }),\n )\n } else {\n const { pubkey, output } = Bitcoin.payments.p2tr({\n address: sender,\n })\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: { value: utxo.value, script: output as Buffer },\n tapInternalKey: pubkey,\n }),\n )\n }\n // Add outputs to the PSBT from the accumulated outputs.\n outputs.forEach((output: Bitcoin.PsbtTxOutput) => {\n // If the output address is not specified, it's considered a change address and set to the sender's address.\n if (!output.address) {\n //an empty address means this is the change address\n output.address = sender\n }\n // Add the output to the PSBT.\n if (!output.script) {\n psbt.addOutput(output)\n } else {\n // If the output is a memo, add it to the PSBT to avoid dust error.\n if (compiledMemo) {\n psbt.addOutput({ script: compiledMemo, value: 0 })\n }\n }\n })\n\n return { psbt, utxos, inputs }\n }\n\n /**\n * Prepare transfer.\n *\n * @param {TxParams&Address&FeeRate&boolean} params The transfer options.\n * @returns {PreparedTx} The raw unsigned transaction.\n */\n async prepareTx({\n sender,\n memo,\n amount,\n recipient,\n spendPendingUTXO = true,\n feeRate,\n }: TxParams & {\n sender: Address\n feeRate: FeeRate\n spendPendingUTXO?: boolean\n }): Promise<PreparedTx> {\n // Build the transaction using the provided parameters.\n const { psbt, utxos } = await this.buildTx({\n sender,\n recipient,\n amount,\n feeRate,\n memo,\n spendPendingUTXO,\n })\n // Return the raw unsigned transaction (PSBT) and associated UTXOs.\n return { rawUnsignedTx: psbt.toBase64(), utxos }\n }\n}\n\nexport { Client }\n","import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs'\nimport { FeeOption, FeeRate, TxHash, checkFeeBounds } from '@xchainjs/xchain-client'\nimport { getSeed } from '@xchainjs/xchain-crypto'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport { BIP32Factory } from 'bip32'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport { ECPairFactory, ECPairInterface } from 'ecpair'\n\nimport { Client, defaultBTCParams } from './client' // Importing the base Bitcoin client\nimport { AddressFormat } from './types'\nimport * as Utils from './utils'\n\nconst ECPair = ECPairFactory(ecc)\n/**\n * Custom Bitcoin client extended to support keystore functionality\n */\nclass ClientKeystore extends Client {\n constructor(\n params: UtxoClientParams & { addressFormat?: AddressFormat } = {\n ...defaultBTCParams,\n addressFormat: AddressFormat.P2WPKH,\n },\n ) {\n super(params)\n }\n /**\n * @deprecated This function eventually will be removed. Use getAddressAsync instead.\n * Get the address associated with the given index.\n * @param {number} index The index of the address.\n * @returns {Address} The Bitcoin address.\n * @throws {\"index must be greater than zero\"} Thrown if the index is less than zero.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n * @throws {\"Address not defined\"} Thrown if failed to create the address from the phrase.\n */\n getAddress(index = 0): Address {\n // Check if the index is valid\n if (index < 0) {\n throw new Error('index must be greater than zero')\n }\n\n // Check if the phrase has been set\n if (this.phrase) {\n const btcNetwork = Utils.btcNetwork(this.network)\n const btcKeys = this.getBtcKeys(this.phrase, index)\n\n // Generate the address using the Bitcoinjs library\n\n let address: string | undefined\n if (this.addressFormat === AddressFormat.P2WPKH) {\n address = Bitcoin.payments.p2wpkh({\n pubkey: btcKeys.publicKey,\n network: btcNetwork,\n }).address\n } else {\n address = Bitcoin.payments.p2tr({\n internalPubkey: Utils.toXOnly(btcKeys.publicKey),\n network: btcNetwork,\n }).address\n }\n\n // Throw an error if the address is not defined\n if (!address) {\n throw new Error('Address not defined')\n }\n\n return address\n }\n\n throw new Error('Phrase must be provided')\n }\n\n /**\n * Get the current address asynchronously.\n * @param {number} index The index of the address.\n * @returns {Promise<Address>} A promise that resolves to the Bitcoin address.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n */\n async getAddressAsync(index = 0): Promise<string> {\n return this.getAddress(index)\n }\n\n /**\n * @private\n * Get the Bitcoin keys derived from the given phrase.\n *\n * @param {string} phrase The phrase to be used for generating the keys.\n * @param {number} index The index of the address.\n * @returns {Bitcoin.ECPair.ECPairInterface} The Bitcoin key pair.\n * @throws {\"Could not get private key from phrase\"} Thrown if failed to create BTC keys from the given phrase.\n */\n private getBtcKeys(phrase: string, index = 0): ECPairInterface {\n const btcNetwork = Utils.btcNetwork(this.network)\n const seed = getSeed(phrase)\n const bip32 = BIP32Factory(ecc)\n const master = bip32.fromSeed(seed, btcNetwork).derivePath(this.getFullDerivationPath(index))\n\n if (!master.privateKey) {\n throw new Error('Could not get private key from phrase')\n }\n\n return ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork })\n }\n\n /**\n * Transfer BTC.\n *\n * @param {TxParams&FeeRate} params The transfer options including the fee rate.\n * @returns {Promise<TxHash|string>} A promise that resolves to the transaction hash or an error message.\n * @throws {\"memo too long\"} Thrown if the memo is longer than 80 characters.\n */\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n // Set the default fee rate to `fast`\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n\n // Check if the fee rate is within the fee bounds\n checkFeeBounds(this.feeBounds, feeRate)\n\n // Get the address index from the parameters or use the default value\n const fromAddressIndex = params?.walletIndex || 0\n\n // Get the Bitcoin keys\n const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex)\n\n // Prepare the transaction\n const { rawUnsignedTx } = await this.prepareTx({\n ...params,\n sender: this.getAddress(fromAddressIndex),\n feeRate,\n })\n\n // Build the PSBT\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n\n // Sign all inputs\n psbt.signAllInputs(\n this.addressFormat === AddressFormat.P2WPKH\n ? btcKeys\n : btcKeys.tweak(Bitcoin.crypto.taggedHash('TapTweak', Utils.toXOnly(btcKeys.publicKey))),\n )\n\n // Finalize inputs\n psbt.finalizeAllInputs()\n\n // Extract the transaction hex\n const txHex = psbt.extractTransaction().toHex()\n\n // Extract the transaction hash\n const txHash = psbt.extractTransaction().getId()\n\n try {\n // Broadcast the transaction and return the transaction hash\n const txId = await this.roundRobinBroadcastTx(txHex)\n return txId\n } catch (err) {\n // If broadcasting fails, return an error message with a link to the explorer\n const error = `Server error, please check explorer for tx confirmation ${this.explorerProviders[\n this.network\n ].getExplorerTxUrl(txHash)}`\n return error\n }\n }\n}\n\nexport { ClientKeystore }\n","import AppBtc from '@ledgerhq/hw-app-btc'\nimport { Transaction } from '@ledgerhq/hw-app-btc/lib/types'\nimport { FeeOption, FeeRate, TxHash } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client'\nimport { AddressFormat } from './types'\n\n/**\n * Custom Ledger Bitcoin client\n */\nclass ClientLedger extends Client {\n // Reference to the Ledger transport object\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private transport: any // TODO: Parametrize\n private app: AppBtc | undefined\n\n // Constructor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(params: UtxoClientParams & { transport: any; addressFormat?: AddressFormat }) {\n super(params)\n this.transport = params.transport\n }\n\n // Get the Ledger BTC application instance\n public async getApp(): Promise<AppBtc> {\n if (this.app) {\n return this.app\n }\n this.app = new AppBtc({ transport: this.transport })\n return this.app\n }\n\n // Get the current address synchronously\n getAddress(): string {\n throw Error('Sync method not supported for Ledger')\n }\n\n // Get the current address asynchronously\n async getAddressAsync(index = 0, verify = false): Promise<Address> {\n const app = await this.getApp()\n const result = await app.getWalletPublicKey(this.getFullDerivationPath(index), {\n format: this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32',\n verify,\n })\n return result.bitcoinAddress\n }\n\n // Transfer BTC from Ledger\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n const app = await this.getApp()\n const fromAddressIndex = params?.walletIndex || 0\n // Get fee rate\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n // Get sender address\n const sender = await this.getAddressAsync(fromAddressIndex)\n // Prepare transaction\n const { rawUnsignedTx, utxos } = await this.prepareTx({ ...params, sender, feeRate })\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n // Prepare Ledger inputs\n const ledgerInputs: [Transaction, number, string | null, number | null][] = (utxos as UTXO[]).map(\n ({ txHex, hash, index }) => {\n if (!txHex) {\n throw Error(`Missing 'txHex' for UTXO (txHash ${hash})`)\n }\n const utxoTx = Bitcoin.Transaction.fromHex(txHex)\n const splittedTx = app.splitTransaction(txHex, utxoTx.hasWitnesses())\n return [splittedTx, index, null, null]\n },\n )\n\n // Prepare associated keysets\n const associatedKeysets = ledgerInputs.map(() => this.getFullDerivationPath(fromAddressIndex))\n // Serialize unsigned transaction\n const unsignedHex = psbt.data.globalMap.unsignedTx.toBuffer().toString('hex')\n const newTx = app.splitTransaction(unsignedHex, true)\n const outputScriptHex = app.serializeTransactionOutputs(newTx).toString('hex')\n // Create payment transaction\n const txHex = await app.createPaymentTransaction({\n inputs: ledgerInputs,\n associatedKeysets,\n outputScriptHex,\n segwit: true,\n useTrustedInputForSegwit: true,\n additionals: [this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32'],\n })\n // Broadcast transaction\n const txHash = await this.broadcastTx(txHex)\n // Throw error if no transaction hash is received\n if (!txHash) {\n throw Error('No Tx hash')\n }\n\n return txHash\n }\n}\n\nexport { ClientLedger }\n"],"names":["TX_EMPTY_SIZE","TX_INPUT_BASE","TX_INPUT_PUBKEYHASH","TX_OUTPUT_BASE","TX_OUTPUT_PUBKEYHASH","inputBytes","utils","require$$0","UTXOClient","Utils.validateAddress","Utils.inputBytes","Utils.TX_EMPTY_SIZE","Utils.TX_OUTPUT_BASE","Utils.TX_OUTPUT_PU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AC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;;AAE9E,YAAA,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,wBAAwB,CAAC;AAC/C,gBAAA,MAAM,EAAE,YAAY;gBACpB,iBAAiB;gBACjB,eAAe;AACf,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,wBAAwB,EAAE,IAAI;AAC9B,gBAAA,WAAW,EAAE,CAAC,IAAI,CAAC,aAAa,KAAK,aAAa,CAAC,IAAI,GAAG,SAAS,GAAG,QAAQ,CAAC;AAChF,aAAA,CAAC,CAAA;;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;;YAE5C,IAAI,CAAC,MAAM,EAAE;AACX,gBAAA,MAAM,KAAK,CAAC,YAAY,CAAC,CAAA;AAC1B,aAAA;AAED,YAAA,OAAO,MAAM,CAAA;SACd,CAAA,CAAA;AAAA,KAAA;AACF;;;;"}
package/lib/index.js CHANGED
@@ -2,9 +2,12 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var ecc = require('@bitcoin-js/tiny-secp256k1-asmjs');
5
6
  var xchainClient = require('@xchainjs/xchain-client');
6
7
  var xchainCrypto = require('@xchainjs/xchain-crypto');
8
+ var bip32 = require('bip32');
7
9
  var Bitcoin = require('bitcoinjs-lib');
10
+ var ecpair = require('ecpair');
8
11
  var xchainUtxo = require('@xchainjs/xchain-utxo');
9
12
  var xchainUtil = require('@xchainjs/xchain-util');
10
13
  var xchainUtxoProviders = require('@xchainjs/xchain-utxo-providers');
@@ -13,26 +16,33 @@ var AppBtc = require('@ledgerhq/hw-app-btc');
13
16
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
17
 
15
18
  function _interopNamespace(e) {
16
- if (e && e.__esModule) return e;
17
- var n = Object.create(null);
18
- if (e) {
19
- Object.keys(e).forEach(function (k) {
20
- if (k !== 'default') {
21
- var d = Object.getOwnPropertyDescriptor(e, k);
22
- Object.defineProperty(n, k, d.get ? d : {
23
- enumerable: true,
24
- get: function () { return e[k]; }
25
- });
26
- }
19
+ if (e && e.__esModule) return e;
20
+ var n = Object.create(null);
21
+ if (e) {
22
+ Object.keys(e).forEach(function (k) {
23
+ if (k !== 'default') {
24
+ var d = Object.getOwnPropertyDescriptor(e, k);
25
+ Object.defineProperty(n, k, d.get ? d : {
26
+ enumerable: true,
27
+ get: function () { return e[k]; }
27
28
  });
28
- }
29
- n["default"] = e;
30
- return Object.freeze(n);
29
+ }
30
+ });
31
+ }
32
+ n["default"] = e;
33
+ return Object.freeze(n);
31
34
  }
32
35
 
36
+ var ecc__namespace = /*#__PURE__*/_interopNamespace(ecc);
33
37
  var Bitcoin__namespace = /*#__PURE__*/_interopNamespace(Bitcoin);
34
38
  var AppBtc__default = /*#__PURE__*/_interopDefaultLegacy(AppBtc);
35
39
 
40
+ exports.AddressFormat = void 0;
41
+ (function (AddressFormat) {
42
+ AddressFormat[AddressFormat["P2WPKH"] = 0] = "P2WPKH";
43
+ AddressFormat[AddressFormat["P2TR"] = 1] = "P2TR";
44
+ })(exports.AddressFormat || (exports.AddressFormat = {}));
45
+
36
46
  /******************************************************************************
37
47
  Copyright (c) Microsoft Corporation.
38
48
 
@@ -242,6 +252,11 @@ const BitgoProviders = {
242
252
  [xchainClient.Network.Stagenet]: mainnetBitgoProvider,
243
253
  [xchainClient.Network.Mainnet]: mainnetBitgoProvider,
244
254
  };
255
+ const tapRootDerivationPaths = {
256
+ [xchainClient.Network.Mainnet]: `86'/0'/0'/0/`,
257
+ [xchainClient.Network.Testnet]: `86'/1'/0'/0/`,
258
+ [xchainClient.Network.Stagenet]: `86'/0'/0'/0/`,
259
+ };
245
260
 
246
261
  // Import statements for necessary modules and types
247
262
  // Constants defining the sizes of various components in a Bitcoin transaction
@@ -303,6 +318,12 @@ const getPrefix = (network) => {
303
318
  return 'tb1'; // Return the address prefix for Bitcoin testnet
304
319
  }
305
320
  };
321
+ /**
322
+ * Converts a public key to an X-only public key.
323
+ * @param pubKey The public key to convert.
324
+ * @returns The X-only public key.
325
+ */
326
+ const toXOnly = (pubKey) => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33));
306
327
 
307
328
  // Default parameters for the Bitcoin UTXO client
308
329
  const defaultBTCParams = {
@@ -329,7 +350,8 @@ class Client extends xchainUtxo.Client {
329
350
  * Initializes the client with network type and other parameters.
330
351
  * @param {UtxoClientParams} params
331
352
  */
332
- constructor(params = defaultBTCParams) {
353
+ constructor(params = Object.assign(Object.assign({}, defaultBTCParams), { addressFormat: exports.AddressFormat.P2WPKH })) {
354
+ var _a, _b, _c;
333
355
  super(BTCChain, {
334
356
  network: params.network,
335
357
  rootDerivationPaths: params.rootDerivationPaths,
@@ -338,6 +360,15 @@ class Client extends xchainUtxo.Client {
338
360
  explorerProviders: params.explorerProviders,
339
361
  dataProviders: params.dataProviders,
340
362
  });
363
+ this.addressFormat = params.addressFormat || exports.AddressFormat.P2WPKH;
364
+ if (this.addressFormat === exports.AddressFormat.P2TR) {
365
+ if (!((_a = this.rootDerivationPaths) === null || _a === void 0 ? void 0 : _a.mainnet.startsWith(`86'`)) ||
366
+ !((_b = this.rootDerivationPaths) === null || _b === void 0 ? void 0 : _b.testnet.startsWith(`86'`)) ||
367
+ !((_c = this.rootDerivationPaths) === null || _c === void 0 ? void 0 : _c.stagenet.startsWith(`86'`))) {
368
+ throw Error(`Unsupported derivation paths for Taproot client. Use 86' paths`);
369
+ }
370
+ }
371
+ Bitcoin__namespace.initEccLib(ecc__namespace);
341
372
  }
342
373
  /**
343
374
  * Get BTC asset info.
@@ -436,17 +467,30 @@ class Client extends xchainUtxo.Client {
436
467
  throw new Error('Insufficient Balance for transaction');
437
468
  // Initialize a new Bitcoin PSBT object.
438
469
  const psbt = new Bitcoin__namespace.Psbt({ network: btcNetwork(this.network) }); // Network-specific
439
- // Add inputs to the PSBT from the accumulated inputs.
440
- inputs.forEach((utxo) => psbt.addInput({
441
- hash: utxo.hash,
442
- index: utxo.index,
443
- witnessUtxo: utxo.witnessUtxo,
444
- }));
470
+ if (this.addressFormat === exports.AddressFormat.P2WPKH) {
471
+ // Add inputs to the PSBT from the accumulated inputs.
472
+ inputs.forEach((utxo) => psbt.addInput({
473
+ hash: utxo.hash,
474
+ index: utxo.index,
475
+ witnessUtxo: utxo.witnessUtxo,
476
+ }));
477
+ }
478
+ else {
479
+ const { pubkey, output } = Bitcoin__namespace.payments.p2tr({
480
+ address: sender,
481
+ });
482
+ inputs.forEach((utxo) => psbt.addInput({
483
+ hash: utxo.hash,
484
+ index: utxo.index,
485
+ witnessUtxo: { value: utxo.value, script: output },
486
+ tapInternalKey: pubkey,
487
+ }));
488
+ }
445
489
  // Add outputs to the PSBT from the accumulated outputs.
446
490
  outputs.forEach((output) => {
447
491
  // If the output address is not specified, it's considered a change address and set to the sender's address.
448
492
  if (!output.address) {
449
- //an empty address means this is the change ddress
493
+ //an empty address means this is the change address
450
494
  output.address = sender;
451
495
  }
452
496
  // Add the output to the PSBT.
@@ -460,7 +504,6 @@ class Client extends xchainUtxo.Client {
460
504
  }
461
505
  }
462
506
  });
463
- // Return the prepared transaction data including the PSBT, UTXOs, and inputs.
464
507
  return { psbt, utxos, inputs };
465
508
  });
466
509
  }
@@ -487,10 +530,14 @@ class Client extends xchainUtxo.Client {
487
530
  }
488
531
  }
489
532
 
533
+ const ECPair = ecpair.ECPairFactory(ecc__namespace);
490
534
  /**
491
535
  * Custom Bitcoin client extended to support keystore functionality
492
536
  */
493
537
  class ClientKeystore extends Client {
538
+ constructor(params = Object.assign(Object.assign({}, defaultBTCParams), { addressFormat: exports.AddressFormat.P2WPKH })) {
539
+ super(params);
540
+ }
494
541
  /**
495
542
  * @deprecated This function eventually will be removed. Use getAddressAsync instead.
496
543
  * Get the address associated with the given index.
@@ -510,10 +557,19 @@ class ClientKeystore extends Client {
510
557
  const btcNetwork$1 = btcNetwork(this.network);
511
558
  const btcKeys = this.getBtcKeys(this.phrase, index);
512
559
  // Generate the address using the Bitcoinjs library
513
- const { address } = Bitcoin__namespace.payments.p2wpkh({
514
- pubkey: btcKeys.publicKey,
515
- network: btcNetwork$1,
516
- });
560
+ let address;
561
+ if (this.addressFormat === exports.AddressFormat.P2WPKH) {
562
+ address = Bitcoin__namespace.payments.p2wpkh({
563
+ pubkey: btcKeys.publicKey,
564
+ network: btcNetwork$1,
565
+ }).address;
566
+ }
567
+ else {
568
+ address = Bitcoin__namespace.payments.p2tr({
569
+ internalPubkey: toXOnly(btcKeys.publicKey),
570
+ network: btcNetwork$1,
571
+ }).address;
572
+ }
517
573
  // Throw an error if the address is not defined
518
574
  if (!address) {
519
575
  throw new Error('Address not defined');
@@ -545,11 +601,12 @@ class ClientKeystore extends Client {
545
601
  getBtcKeys(phrase, index = 0) {
546
602
  const btcNetwork$1 = btcNetwork(this.network);
547
603
  const seed = xchainCrypto.getSeed(phrase);
548
- const master = Bitcoin__namespace.bip32.fromSeed(seed, btcNetwork$1).derivePath(this.getFullDerivationPath(index));
604
+ const bip32$1 = bip32.BIP32Factory(ecc__namespace);
605
+ const master = bip32$1.fromSeed(seed, btcNetwork$1).derivePath(this.getFullDerivationPath(index));
549
606
  if (!master.privateKey) {
550
607
  throw new Error('Could not get private key from phrase');
551
608
  }
552
- return Bitcoin__namespace.ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork$1 });
609
+ return ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork$1 });
553
610
  }
554
611
  /**
555
612
  * Transfer BTC.
@@ -566,14 +623,16 @@ class ClientKeystore extends Client {
566
623
  xchainClient.checkFeeBounds(this.feeBounds, feeRate);
567
624
  // Get the address index from the parameters or use the default value
568
625
  const fromAddressIndex = (params === null || params === void 0 ? void 0 : params.walletIndex) || 0;
569
- // Prepare the transaction
570
- const { rawUnsignedTx } = yield this.prepareTx(Object.assign(Object.assign({}, params), { sender: this.getAddress(fromAddressIndex), feeRate }));
571
626
  // Get the Bitcoin keys
572
627
  const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex);
628
+ // Prepare the transaction
629
+ const { rawUnsignedTx } = yield this.prepareTx(Object.assign(Object.assign({}, params), { sender: this.getAddress(fromAddressIndex), feeRate }));
573
630
  // Build the PSBT
574
631
  const psbt = Bitcoin__namespace.Psbt.fromBase64(rawUnsignedTx);
575
632
  // Sign all inputs
576
- psbt.signAllInputs(btcKeys);
633
+ psbt.signAllInputs(this.addressFormat === exports.AddressFormat.P2WPKH
634
+ ? btcKeys
635
+ : btcKeys.tweak(Bitcoin__namespace.crypto.taggedHash('TapTweak', toXOnly(btcKeys.publicKey))));
577
636
  // Finalize inputs
578
637
  psbt.finalizeAllInputs();
579
638
  // Extract the transaction hex
@@ -623,7 +682,7 @@ class ClientLedger extends Client {
623
682
  return __awaiter(this, void 0, void 0, function* () {
624
683
  const app = yield this.getApp();
625
684
  const result = yield app.getWalletPublicKey(this.getFullDerivationPath(index), {
626
- format: 'bech32',
685
+ format: this.addressFormat === exports.AddressFormat.P2TR ? 'bech32m' : 'bech32',
627
686
  verify,
628
687
  });
629
688
  return result.bitcoinAddress;
@@ -663,7 +722,7 @@ class ClientLedger extends Client {
663
722
  outputScriptHex,
664
723
  segwit: true,
665
724
  useTrustedInputForSegwit: true,
666
- additionals: ['bech32'],
725
+ additionals: [this.addressFormat === exports.AddressFormat.P2TR ? 'bech32m' : 'bech32'],
667
726
  });
668
727
  // Broadcast transaction
669
728
  const txHash = yield this.broadcastTx(txHex);
@@ -693,5 +752,6 @@ exports.UPPER_FEE_BOUND = UPPER_FEE_BOUND;
693
752
  exports.blockstreamExplorerProviders = blockstreamExplorerProviders;
694
753
  exports.defaultBTCParams = defaultBTCParams;
695
754
  exports.getPrefix = getPrefix;
755
+ exports.tapRootDerivationPaths = tapRootDerivationPaths;
696
756
  exports.validateAddress = validateAddress;
697
757
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../node_modules/coinselect/utils.js","../../../node_modules/coinselect/accumulative.js","../src/const.ts","../src/utils.ts","../src/client.ts","../src/clientKeystore.ts","../src/clientLedger.ts"],"sourcesContent":["// baseline estimates, used to improve performance\nvar TX_EMPTY_SIZE = 4 + 1 + 1 + 4\nvar TX_INPUT_BASE = 32 + 4 + 1 + 4\nvar TX_INPUT_PUBKEYHASH = 107\nvar TX_OUTPUT_BASE = 8 + 1\nvar TX_OUTPUT_PUBKEYHASH = 25\n\nfunction inputBytes (input) {\n return TX_INPUT_BASE + (input.script ? input.script.length : TX_INPUT_PUBKEYHASH)\n}\n\nfunction outputBytes (output) {\n return TX_OUTPUT_BASE + (output.script ? output.script.length : TX_OUTPUT_PUBKEYHASH)\n}\n\nfunction dustThreshold (output, feeRate) {\n /* ... classify the output for input estimate */\n return inputBytes({}) * feeRate\n}\n\nfunction transactionBytes (inputs, outputs) {\n return TX_EMPTY_SIZE +\n inputs.reduce(function (a, x) { return a + inputBytes(x) }, 0) +\n outputs.reduce(function (a, x) { return a + outputBytes(x) }, 0)\n}\n\nfunction uintOrNaN (v) {\n if (typeof v !== 'number') return NaN\n if (!isFinite(v)) return NaN\n if (Math.floor(v) !== v) return NaN\n if (v < 0) return NaN\n return v\n}\n\nfunction sumForgiving (range) {\n return range.reduce(function (a, x) { return a + (isFinite(x.value) ? x.value : 0) }, 0)\n}\n\nfunction sumOrNaN (range) {\n return range.reduce(function (a, x) { return a + uintOrNaN(x.value) }, 0)\n}\n\nvar BLANK_OUTPUT = outputBytes({})\n\nfunction finalize (inputs, outputs, feeRate) {\n var bytesAccum = transactionBytes(inputs, outputs)\n var feeAfterExtraOutput = feeRate * (bytesAccum + BLANK_OUTPUT)\n var remainderAfterExtraOutput = sumOrNaN(inputs) - (sumOrNaN(outputs) + feeAfterExtraOutput)\n\n // is it worth a change output?\n if (remainderAfterExtraOutput > dustThreshold({}, feeRate)) {\n outputs = outputs.concat({ value: remainderAfterExtraOutput })\n }\n\n var fee = sumOrNaN(inputs) - sumOrNaN(outputs)\n if (!isFinite(fee)) return { fee: feeRate * bytesAccum }\n\n return {\n inputs: inputs,\n outputs: outputs,\n fee: fee\n }\n}\n\nmodule.exports = {\n dustThreshold: dustThreshold,\n finalize: finalize,\n inputBytes: inputBytes,\n outputBytes: outputBytes,\n sumOrNaN: sumOrNaN,\n sumForgiving: sumForgiving,\n transactionBytes: transactionBytes,\n uintOrNaN: uintOrNaN\n}\n","var utils = require('./utils')\n\n// add inputs until we reach or surpass the target value (or deplete)\n// worst-case: O(n)\nmodule.exports = function accumulative (utxos, outputs, feeRate) {\n if (!isFinite(utils.uintOrNaN(feeRate))) return {}\n var bytesAccum = utils.transactionBytes([], outputs)\n\n var inAccum = 0\n var inputs = []\n var outAccum = utils.sumOrNaN(outputs)\n\n for (var i = 0; i < utxos.length; ++i) {\n var utxo = utxos[i]\n var utxoBytes = utils.inputBytes(utxo)\n var utxoFee = feeRate * utxoBytes\n var utxoValue = utils.uintOrNaN(utxo.value)\n\n // skip detrimental input\n if (utxoFee > utxo.value) {\n if (i === utxos.length - 1) return { fee: feeRate * (bytesAccum + utxoBytes) }\n continue\n }\n\n bytesAccum += utxoBytes\n inAccum += utxoValue\n inputs.push(utxo)\n\n var fee = feeRate * bytesAccum\n\n // go again?\n if (inAccum < outAccum + fee) continue\n\n return utils.finalize(inputs, outputs, feeRate)\n }\n\n return { fee: feeRate * bytesAccum }\n}\n","import { ExplorerProvider, Network } from '@xchainjs/xchain-client'\nimport { Asset, AssetType } from '@xchainjs/xchain-util'\nimport {\n BitgoProvider,\n BlockcypherNetwork,\n BlockcypherProvider,\n HaskoinNetwork,\n HaskoinProvider,\n SochainNetwork,\n SochainProvider,\n UtxoOnlineDataProviders,\n} from '@xchainjs/xchain-utxo-providers'\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000\n\n// Decimal places for Bitcoin\nexport const BTC_DECIMAL = 8\n\n// Lower and upper bounds for fee rates\nexport const LOWER_FEE_BOUND = 1\nexport const UPPER_FEE_BOUND = 1_000\n\n// Symbols for Bitcoin\nexport const BTC_SYMBOL = '₿'\nexport const BTC_SATOSHI_SYMBOL = '⚡'\n\n/**\n * Chain identifier for Bitcoin mainnet\n */\nexport const BTCChain = 'BTC' as const\n\n/**\n * Base \"chain\" asset on bitcoin main net.\n */\nexport const AssetBTC: Asset = { chain: BTCChain, symbol: 'BTC', ticker: 'BTC', type: AssetType.NATIVE }\n\n// Explorer providers for Bitcoin\nconst BTC_MAINNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/',\n 'https://blockstream.info/address/%%ADDRESS%%',\n 'https://blockstream.info/tx/%%TX_ID%%',\n)\nconst BTC_TESTNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/testnet/',\n 'https://blockstream.info/testnet/address/%%ADDRESS%%',\n 'https://blockstream.info/testnet/tx/%%TX_ID%%',\n)\nexport const blockstreamExplorerProviders = {\n [Network.Testnet]: BTC_TESTNET_EXPLORER,\n [Network.Stagenet]: BTC_MAINNET_EXPLORER,\n [Network.Mainnet]: BTC_MAINNET_EXPLORER,\n}\n\n// Sochain data providers for Bitcoin\nconst testnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTCTEST,\n)\nconst mainnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTC,\n)\nexport const SochainDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetSochainProvider,\n [Network.Stagenet]: mainnetSochainProvider,\n [Network.Mainnet]: mainnetSochainProvider,\n}\n\n// Haskoin data providers for Bitcoin\nconst testnetHaskoinProvider = new HaskoinProvider(\n 'https://api.haskoin.com',\n BTCChain,\n AssetBTC,\n 8,\n HaskoinNetwork.BTCTEST,\n)\nconst mainnetHaskoinProvider = new HaskoinProvider('https://api.haskoin.com', BTCChain, AssetBTC, 8, HaskoinNetwork.BTC)\nexport const HaskoinDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetHaskoinProvider,\n [Network.Stagenet]: mainnetHaskoinProvider,\n [Network.Mainnet]: mainnetHaskoinProvider,\n}\n\n// Blockcypher data providers for Bitcoin\nconst testnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTCTEST,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nconst mainnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTC,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nexport const BlockcypherDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetBlockcypherProvider,\n [Network.Stagenet]: mainnetBlockcypherProvider,\n [Network.Mainnet]: mainnetBlockcypherProvider,\n}\n\n// Bitgo data providers for Bitcoin\nconst mainnetBitgoProvider = new BitgoProvider({\n baseUrl: 'https://app.bitgo.com',\n chain: BTCChain,\n})\nexport const BitgoProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: undefined,\n [Network.Stagenet]: mainnetBitgoProvider,\n [Network.Mainnet]: mainnetBitgoProvider,\n}\n","// Import statements for necessary modules and types\nimport { Network } from '@xchainjs/xchain-client' // Importing the Network type from xchain-client module\nimport { Address } from '@xchainjs/xchain-util' // Importing the Address type from xchain-util module\nimport { UTXO } from '@xchainjs/xchain-utxo' // Importing the UTXO type from xchain-utxo module\nimport * as Bitcoin from 'bitcoinjs-lib' // Importing the entire bitcoinjs-lib module and aliasing it as Bitcoin\n\n// Constants defining the sizes of various components in a Bitcoin transaction\nexport const TX_EMPTY_SIZE = 4 + 1 + 1 + 4 // Total size of an empty transaction\nexport const TX_INPUT_BASE = 32 + 4 + 1 + 4 // Size of a base input in a transaction\nexport const TX_INPUT_PUBKEYHASH = 107 // Size of an input with a public key hash\nexport const TX_OUTPUT_BASE = 8 + 1 // Size of a base output in a transaction\nexport const TX_OUTPUT_PUBKEYHASH = 25 // Size of an output with a public key hash\n\n/**\n * Function to calculate the size of an input in a transaction.\n * @param {UTXO} input - The UTXO (Unspent Transaction Output) for which to calculate the size.\n * @returns {number} The size of the input.\n */\nexport const inputBytes = (input: UTXO): number => {\n return TX_INPUT_BASE + (input.witnessUtxo?.script ? input.witnessUtxo?.script.length : TX_INPUT_PUBKEYHASH)\n}\n\n/**\n * Function to calculate the average value of an array of numbers.\n * @param {number[]} array - The array of numbers.\n * @returns {number} The average value of the array.\n */\nexport const arrayAverage = (array: number[]): number => {\n let sum = 0\n array.forEach((value) => (sum += value))\n return sum / array.length\n}\n\n/**\n * Function to get the Bitcoin network to be used with bitcoinjs.\n *\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {Bitcoin.Network} The Bitcoin network.\n */\nexport const btcNetwork = (network: Network): Bitcoin.Network => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return Bitcoin.networks.bitcoin // Return the Bitcoin mainnet or stagenet network\n case Network.Testnet:\n return Bitcoin.networks.testnet // Return the Bitcoin testnet network\n }\n}\n\n/**\n * Function to validate a Bitcoin address.\n * @param {Address} address - The Bitcoin address to validate.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\nexport const validateAddress = (address: Address, network: Network): boolean => {\n try {\n Bitcoin.address.toOutputScript(address, btcNetwork(network)) // Try to convert the address to an output script using the specified network\n return true // If successful, the address is valid\n } catch (error) {\n return false // If an error occurs, the address is invalid\n }\n}\n\n/**\n * Function to get the address prefix based on the network.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {string} The address prefix based on the network.\n */\nexport const getPrefix = (network: Network): string => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return 'bc1' // Return the address prefix for Bitcoin mainnet or stagenet\n case Network.Testnet:\n return 'tb1' // Return the address prefix for Bitcoin testnet\n }\n}\n","import { AssetInfo, FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { Client as UTXOClient, PreparedTx, TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport accumulative from 'coinselect/accumulative'\n\nimport {\n AssetBTC,\n BTCChain,\n BTC_DECIMAL,\n BitgoProviders,\n BlockcypherDataProviders,\n LOWER_FEE_BOUND,\n MIN_TX_FEE,\n UPPER_FEE_BOUND,\n blockstreamExplorerProviders,\n} from './const'\nimport * as Utils from './utils'\n// Default parameters for the Bitcoin UTXO client\nexport const defaultBTCParams: UtxoClientParams = {\n network: Network.Mainnet,\n phrase: '',\n explorerProviders: blockstreamExplorerProviders,\n dataProviders: [BitgoProviders, BlockcypherDataProviders],\n rootDerivationPaths: {\n [Network.Mainnet]: `84'/0'/0'/0/`, // Not BIP44 compliant but compatible with pre-HD wallets\n [Network.Testnet]: `84'/1'/0'/0/`,\n [Network.Stagenet]: `84'/0'/0'/0/`,\n },\n feeBounds: {\n lower: LOWER_FEE_BOUND,\n upper: UPPER_FEE_BOUND,\n },\n}\n/**\n * Custom Bitcoin client\n */\nabstract class Client extends UTXOClient {\n /**\n * Constructor\n * Initializes the client with network type and other parameters.\n * @param {UtxoClientParams} params\n */\n constructor(params = defaultBTCParams) {\n super(BTCChain, {\n network: params.network,\n rootDerivationPaths: params.rootDerivationPaths,\n phrase: params.phrase,\n feeBounds: params.feeBounds,\n explorerProviders: params.explorerProviders,\n dataProviders: params.dataProviders,\n })\n }\n\n /**\n * Get BTC asset info.\n * @returns {AssetInfo} BTC asset information.\n */\n getAssetInfo(): AssetInfo {\n const assetInfo: AssetInfo = {\n asset: AssetBTC,\n decimal: BTC_DECIMAL,\n }\n return assetInfo\n }\n\n /**\n * Validate the given Bitcoin address.\n * @param {string} address Bitcoin address to validate.\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\n validateAddress(address: string): boolean {\n return Utils.validateAddress(address, this.network)\n }\n\n /**\n * Compile memo into a buffer.\n * @param {string} memo Memo to compile.\n * @returns {Buffer} Compiled memo.\n */\n protected compileMemo(memo: string): Buffer {\n const data = Buffer.from(memo, 'utf8') // converts MEMO to buffer\n return Bitcoin.script.compile([Bitcoin.opcodes.OP_RETURN, data]) // Compile OP_RETURN script\n }\n\n /**\n * Get transaction fee from UTXOs.\n * @param {UTXO[]} inputs UTXOs to calculate fee from.\n * @param {FeeRate} feeRate Fee rate.\n * @param {Buffer | null} data Compiled memo (Optional).\n * @returns {number} Transaction fee.\n */\n protected getFeeFromUtxos(inputs: UTXO[], feeRate: FeeRate, data: Buffer | null = null): number {\n // Calculate input size based on inputs\n const inputSizeBasedOnInputs =\n inputs.length > 0\n ? inputs.reduce((a, x) => a + Utils.inputBytes(x), 0) + inputs.length // +1 byte for each input signature\n : 0\n // Calculate sum\n let sum =\n Utils.TX_EMPTY_SIZE +\n inputSizeBasedOnInputs +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH\n\n if (data) {\n sum += Utils.TX_OUTPUT_BASE + data.length\n }\n // Calculate fee\n const fee = sum * feeRate\n return fee > MIN_TX_FEE ? fee : MIN_TX_FEE\n }\n\n /**\n * Build a Bitcoin transaction.*\n * @param param0\n * @deprecated\n */\n async buildTx({\n amount,\n recipient,\n memo,\n feeRate,\n sender,\n spendPendingUTXO = true,\n }: TxParams & {\n feeRate: FeeRate\n sender: Address\n spendPendingUTXO?: boolean\n withTxHex?: boolean\n }): Promise<{ psbt: Bitcoin.Psbt; utxos: UTXO[]; inputs: UTXO[] }> {\n // Check memo length\n if (memo && memo.length > 80) {\n throw new Error('memo too long, must not be longer than 80 chars.')\n }\n // This section of the code is responsible for preparing a transaction by building a Bitcoin PSBT (Partially Signed Bitcoin Transaction).\n if (!this.validateAddress(recipient)) throw new Error('Invalid address')\n // Determine whether to only use confirmed UTXOs or include pending UTXOs based on the spendPendingUTXO flag.\n const confirmedOnly = !spendPendingUTXO\n // Scan UTXOs associated with the sender's address.\n const utxos = await this.scanUTXOs(sender, confirmedOnly)\n // Throw an error if there are no available UTXOs to cover the transaction.\n if (utxos.length === 0) throw new Error('Insufficient Balance for transaction')\n // Round up the fee rate to the nearest integer.\n const feeRateWhole = Math.ceil(feeRate)\n // Compile the memo into a Buffer if provided.\n const compiledMemo = memo ? this.compileMemo(memo) : null\n // Initialize an array to store the target outputs of the transaction.\n const targetOutputs = []\n\n // 1. Add the recipient address and amount to the target outputs.\n targetOutputs.push({\n address: recipient,\n value: amount.amount().toNumber(),\n })\n // 2. Add the compiled memo to the target outputs if it exists.\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 })\n }\n // Use the coinselect library to determine the inputs and outputs for the transaction.\n const { inputs, outputs } = accumulative(utxos, targetOutputs, feeRateWhole)\n // If no suitable inputs or outputs are found, throw an error indicating insufficient balance.\n if (!inputs || !outputs) throw new Error('Insufficient Balance for transaction')\n // Initialize a new Bitcoin PSBT object.\n const psbt = new Bitcoin.Psbt({ network: Utils.btcNetwork(this.network) }) // Network-specific\n\n // Add inputs to the PSBT from the accumulated inputs.\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: utxo.witnessUtxo,\n }),\n )\n\n // Add outputs to the PSBT from the accumulated outputs.\n outputs.forEach((output: Bitcoin.PsbtTxOutput) => {\n // If the output address is not specified, it's considered a change address and set to the sender's address.\n if (!output.address) {\n //an empty address means this is the change ddress\n output.address = sender\n }\n // Add the output to the PSBT.\n if (!output.script) {\n psbt.addOutput(output)\n } else {\n // If the output is a memo, add it to the PSBT to avoid dust error.\n if (compiledMemo) {\n psbt.addOutput({ script: compiledMemo, value: 0 })\n }\n }\n })\n // Return the prepared transaction data including the PSBT, UTXOs, and inputs.\n return { psbt, utxos, inputs }\n }\n\n /**\n * Prepare transfer.\n *\n * @param {TxParams&Address&FeeRate&boolean} params The transfer options.\n * @returns {PreparedTx} The raw unsigned transaction.\n */\n async prepareTx({\n sender,\n memo,\n amount,\n recipient,\n spendPendingUTXO = true,\n feeRate,\n }: TxParams & {\n sender: Address\n feeRate: FeeRate\n spendPendingUTXO?: boolean\n }): Promise<PreparedTx> {\n // Build the transaction using the provided parameters.\n const { psbt, utxos } = await this.buildTx({\n sender,\n recipient,\n amount,\n feeRate,\n memo,\n spendPendingUTXO,\n })\n // Return the raw unsigned transaction (PSBT) and associated UTXOs.\n return { rawUnsignedTx: psbt.toBase64(), utxos }\n }\n}\n\nexport { Client }\n","import { FeeOption, FeeRate, TxHash, checkFeeBounds } from '@xchainjs/xchain-client'\nimport { getSeed } from '@xchainjs/xchain-crypto'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client' // Importing the base Bitcoin client\nimport * as Utils from './utils' // Importing utility functions\n\n/**\n * Custom Bitcoin client extended to support keystore functionality\n */\nclass ClientKeystore extends Client {\n /**\n * @deprecated This function eventually will be removed. Use getAddressAsync instead.\n * Get the address associated with the given index.\n * @param {number} index The index of the address.\n * @returns {Address} The Bitcoin address.\n * @throws {\"index must be greater than zero\"} Thrown if the index is less than zero.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n * @throws {\"Address not defined\"} Thrown if failed to create the address from the phrase.\n */\n getAddress(index = 0): Address {\n // Check if the index is valid\n if (index < 0) {\n throw new Error('index must be greater than zero')\n }\n\n // Check if the phrase has been set\n if (this.phrase) {\n const btcNetwork = Utils.btcNetwork(this.network)\n const btcKeys = this.getBtcKeys(this.phrase, index)\n\n // Generate the address using the Bitcoinjs library\n const { address } = Bitcoin.payments.p2wpkh({\n pubkey: btcKeys.publicKey,\n network: btcNetwork,\n })\n\n // Throw an error if the address is not defined\n if (!address) {\n throw new Error('Address not defined')\n }\n\n return address\n }\n\n throw new Error('Phrase must be provided')\n }\n\n /**\n * Get the current address asynchronously.\n * @param {number} index The index of the address.\n * @returns {Promise<Address>} A promise that resolves to the Bitcoin address.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n */\n async getAddressAsync(index = 0): Promise<string> {\n return this.getAddress(index)\n }\n\n /**\n * @private\n * Get the Bitcoin keys derived from the given phrase.\n *\n * @param {string} phrase The phrase to be used for generating the keys.\n * @param {number} index The index of the address.\n * @returns {Bitcoin.ECPair.ECPairInterface} The Bitcoin key pair.\n * @throws {\"Could not get private key from phrase\"} Thrown if failed to create BTC keys from the given phrase.\n */\n private getBtcKeys(phrase: string, index = 0): Bitcoin.ECPair.ECPairInterface {\n const btcNetwork = Utils.btcNetwork(this.network)\n const seed = getSeed(phrase)\n const master = Bitcoin.bip32.fromSeed(seed, btcNetwork).derivePath(this.getFullDerivationPath(index))\n\n if (!master.privateKey) {\n throw new Error('Could not get private key from phrase')\n }\n\n return Bitcoin.ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork })\n }\n\n /**\n * Transfer BTC.\n *\n * @param {TxParams&FeeRate} params The transfer options including the fee rate.\n * @returns {Promise<TxHash|string>} A promise that resolves to the transaction hash or an error message.\n * @throws {\"memo too long\"} Thrown if the memo is longer than 80 characters.\n */\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n // Set the default fee rate to `fast`\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n\n // Check if the fee rate is within the fee bounds\n checkFeeBounds(this.feeBounds, feeRate)\n\n // Get the address index from the parameters or use the default value\n const fromAddressIndex = params?.walletIndex || 0\n\n // Prepare the transaction\n const { rawUnsignedTx } = await this.prepareTx({ ...params, sender: this.getAddress(fromAddressIndex), feeRate })\n\n // Get the Bitcoin keys\n const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex)\n\n // Build the PSBT\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n\n // Sign all inputs\n psbt.signAllInputs(btcKeys)\n\n // Finalize inputs\n psbt.finalizeAllInputs()\n\n // Extract the transaction hex\n const txHex = psbt.extractTransaction().toHex()\n\n // Extract the transaction hash\n const txHash = psbt.extractTransaction().getId()\n\n try {\n // Broadcast the transaction and return the transaction hash\n const txId = await this.roundRobinBroadcastTx(txHex)\n return txId\n } catch (err) {\n // If broadcasting fails, return an error message with a link to the explorer\n const error = `Server error, please check explorer for tx confirmation ${this.explorerProviders[\n this.network\n ].getExplorerTxUrl(txHash)}`\n return error\n }\n }\n}\n\nexport { ClientKeystore }\n","import AppBtc from '@ledgerhq/hw-app-btc'\nimport { Transaction } from '@ledgerhq/hw-app-btc/lib/types'\nimport { FeeOption, FeeRate, TxHash } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client'\n\n/**\n * Custom Ledger Bitcoin client\n */\nclass ClientLedger extends Client {\n // Reference to the Ledger transport object\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private transport: any // TODO: Parametrize\n private app: AppBtc | undefined\n\n // Constructor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(params: UtxoClientParams & { transport: any }) {\n super(params)\n this.transport = params.transport\n }\n\n // Get the Ledger BTC application instance\n public async getApp(): Promise<AppBtc> {\n if (this.app) {\n return this.app\n }\n this.app = new AppBtc({ transport: this.transport })\n return this.app\n }\n\n // Get the current address synchronously\n getAddress(): string {\n throw Error('Sync method not supported for Ledger')\n }\n\n // Get the current address asynchronously\n async getAddressAsync(index = 0, verify = false): Promise<Address> {\n const app = await this.getApp()\n const result = await app.getWalletPublicKey(this.getFullDerivationPath(index), {\n format: 'bech32',\n verify,\n })\n return result.bitcoinAddress\n }\n\n // Transfer BTC from Ledger\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n const app = await this.getApp()\n const fromAddressIndex = params?.walletIndex || 0\n // Get fee rate\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n // Get sender address\n const sender = await this.getAddressAsync(fromAddressIndex)\n // Prepare transaction\n const { rawUnsignedTx, utxos } = await this.prepareTx({ ...params, sender, feeRate })\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n // Prepare Ledger inputs\n const ledgerInputs: [Transaction, number, string | null, number | null][] = (utxos as UTXO[]).map(\n ({ txHex, hash, index }) => {\n if (!txHex) {\n throw Error(`Missing 'txHex' for UTXO (txHash ${hash})`)\n }\n const utxoTx = Bitcoin.Transaction.fromHex(txHex)\n const splittedTx = app.splitTransaction(txHex, utxoTx.hasWitnesses())\n return [splittedTx, index, null, null]\n },\n )\n\n // Prepare associated keysets\n const associatedKeysets = ledgerInputs.map(() => this.getFullDerivationPath(fromAddressIndex))\n // Serialize unsigned transaction\n const unsignedHex = psbt.data.globalMap.unsignedTx.toBuffer().toString('hex')\n const newTx = app.splitTransaction(unsignedHex, true)\n const outputScriptHex = app.serializeTransactionOutputs(newTx).toString('hex')\n // Create payment transaction\n const txHex = await app.createPaymentTransaction({\n inputs: ledgerInputs,\n associatedKeysets,\n outputScriptHex,\n segwit: true,\n useTrustedInputForSegwit: true,\n additionals: ['bech32'],\n })\n // Broadcast transaction\n const txHash = await this.broadcastTx(txHex)\n // Throw error if no transaction hash is received\n if (!txHash) {\n throw Error('No Tx hash')\n }\n\n return txHash\n }\n}\n\nexport { ClientLedger }\n"],"names":["TX_EMPTY_SIZE","TX_INPUT_BASE","TX_INPUT_PUBKEYHASH","TX_OUTPUT_BASE","TX_OUTPUT_PUBKEYHASH","inputBytes","utils","require$$0","AssetType","ExplorerProvider","Network","SochainProvider","SochainNetwork","HaskoinProvider","HaskoinNetwork","BlockcypherProvider","BlockcypherNetwork","BitgoProvider","Bitcoin","UTXOClient","Utils.validateAddress","Utils.inputBytes","Utils.TX_EMPTY_SIZE","Utils.TX_OUTPUT_BASE","Utils.TX_OUTPUT_PUBKEYHASH","accumulative","Utils.btcNetwork","btcNetwork","getSeed","FeeOption","checkFeeBounds","AppBtc"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA,IAAIA,eAAa,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACjC,IAAIC,eAAa,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AAClC,IAAIC,qBAAmB,GAAG,IAAG;AAC7B,IAAIC,gBAAc,GAAG,CAAC,GAAG,EAAC;AAC1B,IAAIC,sBAAoB,GAAG,GAAE;AAC7B;AACA,SAASC,YAAU,EAAE,KAAK,EAAE;AAC5B,EAAE,OAAOJ,eAAa,IAAI,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,GAAGC,qBAAmB,CAAC;AACnF,CAAC;AACD;AACA,SAAS,WAAW,EAAE,MAAM,EAAE;AAC9B,EAAE,OAAOC,gBAAc,IAAI,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAGC,sBAAoB,CAAC;AACvF,CAAC;AACD;AACA,SAAS,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE;AACzC;AACA,EAAE,OAAOC,YAAU,CAAC,EAAE,CAAC,GAAG,OAAO;AACjC,CAAC;AACD;AACA,SAAS,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE;AAC5C,EAAE,OAAOL,eAAa;AACtB,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,GAAGK,YAAU,CAAC,CAAC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I;AACZ,gBAAA,wBAAwB,EAAE,IAAI;gBAC9B,WAAW,EAAE,CAAC,QAAQ,CAAC;AACxB,aAAA,CAAC,CAAA;;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;;YAE5C,IAAI,CAAC,MAAM,EAAE;AACX,gBAAA,MAAM,KAAK,CAAC,YAAY,CAAC,CAAA;AAC1B,aAAA;AAED,YAAA,OAAO,MAAM,CAAA;SACd,CAAA,CAAA;AAAA,KAAA;AACF;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/types/client-types.ts","../../../node_modules/coinselect/utils.js","../../../node_modules/coinselect/accumulative.js","../src/const.ts","../src/utils.ts","../src/client.ts","../src/clientKeystore.ts","../src/clientLedger.ts"],"sourcesContent":["import { FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\n\nexport type NormalTxParams = { addressTo: Address; amount: number; feeRate: FeeRate }\nexport type VaultTxParams = NormalTxParams & { memo: string }\n\nexport type GetChangeParams = {\n valueOut: number\n sochainUrl: string\n network: Network\n address: Address\n}\n\nexport type ClientUrl = Record<Network, string>\n\nexport enum AddressFormat {\n P2WPKH,\n P2TR,\n}\n","// baseline estimates, used to improve performance\nvar TX_EMPTY_SIZE = 4 + 1 + 1 + 4\nvar TX_INPUT_BASE = 32 + 4 + 1 + 4\nvar TX_INPUT_PUBKEYHASH = 107\nvar TX_OUTPUT_BASE = 8 + 1\nvar TX_OUTPUT_PUBKEYHASH = 25\n\nfunction inputBytes (input) {\n return TX_INPUT_BASE + (input.script ? input.script.length : TX_INPUT_PUBKEYHASH)\n}\n\nfunction outputBytes (output) {\n return TX_OUTPUT_BASE + (output.script ? output.script.length : TX_OUTPUT_PUBKEYHASH)\n}\n\nfunction dustThreshold (output, feeRate) {\n /* ... classify the output for input estimate */\n return inputBytes({}) * feeRate\n}\n\nfunction transactionBytes (inputs, outputs) {\n return TX_EMPTY_SIZE +\n inputs.reduce(function (a, x) { return a + inputBytes(x) }, 0) +\n outputs.reduce(function (a, x) { return a + outputBytes(x) }, 0)\n}\n\nfunction uintOrNaN (v) {\n if (typeof v !== 'number') return NaN\n if (!isFinite(v)) return NaN\n if (Math.floor(v) !== v) return NaN\n if (v < 0) return NaN\n return v\n}\n\nfunction sumForgiving (range) {\n return range.reduce(function (a, x) { return a + (isFinite(x.value) ? x.value : 0) }, 0)\n}\n\nfunction sumOrNaN (range) {\n return range.reduce(function (a, x) { return a + uintOrNaN(x.value) }, 0)\n}\n\nvar BLANK_OUTPUT = outputBytes({})\n\nfunction finalize (inputs, outputs, feeRate) {\n var bytesAccum = transactionBytes(inputs, outputs)\n var feeAfterExtraOutput = feeRate * (bytesAccum + BLANK_OUTPUT)\n var remainderAfterExtraOutput = sumOrNaN(inputs) - (sumOrNaN(outputs) + feeAfterExtraOutput)\n\n // is it worth a change output?\n if (remainderAfterExtraOutput > dustThreshold({}, feeRate)) {\n outputs = outputs.concat({ value: remainderAfterExtraOutput })\n }\n\n var fee = sumOrNaN(inputs) - sumOrNaN(outputs)\n if (!isFinite(fee)) return { fee: feeRate * bytesAccum }\n\n return {\n inputs: inputs,\n outputs: outputs,\n fee: fee\n }\n}\n\nmodule.exports = {\n dustThreshold: dustThreshold,\n finalize: finalize,\n inputBytes: inputBytes,\n outputBytes: outputBytes,\n sumOrNaN: sumOrNaN,\n sumForgiving: sumForgiving,\n transactionBytes: transactionBytes,\n uintOrNaN: uintOrNaN\n}\n","var utils = require('./utils')\n\n// add inputs until we reach or surpass the target value (or deplete)\n// worst-case: O(n)\nmodule.exports = function accumulative (utxos, outputs, feeRate) {\n if (!isFinite(utils.uintOrNaN(feeRate))) return {}\n var bytesAccum = utils.transactionBytes([], outputs)\n\n var inAccum = 0\n var inputs = []\n var outAccum = utils.sumOrNaN(outputs)\n\n for (var i = 0; i < utxos.length; ++i) {\n var utxo = utxos[i]\n var utxoBytes = utils.inputBytes(utxo)\n var utxoFee = feeRate * utxoBytes\n var utxoValue = utils.uintOrNaN(utxo.value)\n\n // skip detrimental input\n if (utxoFee > utxo.value) {\n if (i === utxos.length - 1) return { fee: feeRate * (bytesAccum + utxoBytes) }\n continue\n }\n\n bytesAccum += utxoBytes\n inAccum += utxoValue\n inputs.push(utxo)\n\n var fee = feeRate * bytesAccum\n\n // go again?\n if (inAccum < outAccum + fee) continue\n\n return utils.finalize(inputs, outputs, feeRate)\n }\n\n return { fee: feeRate * bytesAccum }\n}\n","import { ExplorerProvider, Network } from '@xchainjs/xchain-client'\nimport { Asset, AssetType } from '@xchainjs/xchain-util'\nimport {\n BitgoProvider,\n BlockcypherNetwork,\n BlockcypherProvider,\n HaskoinNetwork,\n HaskoinProvider,\n SochainNetwork,\n SochainProvider,\n UtxoOnlineDataProviders,\n} from '@xchainjs/xchain-utxo-providers'\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000\n\n// Decimal places for Bitcoin\nexport const BTC_DECIMAL = 8\n\n// Lower and upper bounds for fee rates\nexport const LOWER_FEE_BOUND = 1\nexport const UPPER_FEE_BOUND = 1_000\n\n// Symbols for Bitcoin\nexport const BTC_SYMBOL = '₿'\nexport const BTC_SATOSHI_SYMBOL = '⚡'\n\n/**\n * Chain identifier for Bitcoin mainnet\n */\nexport const BTCChain = 'BTC' as const\n\n/**\n * Base \"chain\" asset on bitcoin main net.\n */\nexport const AssetBTC: Asset = { chain: BTCChain, symbol: 'BTC', ticker: 'BTC', type: AssetType.NATIVE }\n\n// Explorer providers for Bitcoin\nconst BTC_MAINNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/',\n 'https://blockstream.info/address/%%ADDRESS%%',\n 'https://blockstream.info/tx/%%TX_ID%%',\n)\nconst BTC_TESTNET_EXPLORER = new ExplorerProvider(\n 'https://blockstream.info/testnet/',\n 'https://blockstream.info/testnet/address/%%ADDRESS%%',\n 'https://blockstream.info/testnet/tx/%%TX_ID%%',\n)\nexport const blockstreamExplorerProviders = {\n [Network.Testnet]: BTC_TESTNET_EXPLORER,\n [Network.Stagenet]: BTC_MAINNET_EXPLORER,\n [Network.Mainnet]: BTC_MAINNET_EXPLORER,\n}\n\n// Sochain data providers for Bitcoin\nconst testnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTCTEST,\n)\nconst mainnetSochainProvider = new SochainProvider(\n 'https://sochain.com/api/v3',\n process.env.SOCHAIN_API_KEY || '',\n BTCChain,\n AssetBTC,\n 8,\n SochainNetwork.BTC,\n)\nexport const SochainDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetSochainProvider,\n [Network.Stagenet]: mainnetSochainProvider,\n [Network.Mainnet]: mainnetSochainProvider,\n}\n\n// Haskoin data providers for Bitcoin\nconst testnetHaskoinProvider = new HaskoinProvider(\n 'https://api.haskoin.com',\n BTCChain,\n AssetBTC,\n 8,\n HaskoinNetwork.BTCTEST,\n)\nconst mainnetHaskoinProvider = new HaskoinProvider('https://api.haskoin.com', BTCChain, AssetBTC, 8, HaskoinNetwork.BTC)\nexport const HaskoinDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetHaskoinProvider,\n [Network.Stagenet]: mainnetHaskoinProvider,\n [Network.Mainnet]: mainnetHaskoinProvider,\n}\n\n// Blockcypher data providers for Bitcoin\nconst testnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTCTEST,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nconst mainnetBlockcypherProvider = new BlockcypherProvider(\n 'https://api.blockcypher.com/v1',\n BTCChain,\n AssetBTC,\n 8,\n BlockcypherNetwork.BTC,\n process.env.BLOCKCYPHER_API_KEY || '',\n)\nexport const BlockcypherDataProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: testnetBlockcypherProvider,\n [Network.Stagenet]: mainnetBlockcypherProvider,\n [Network.Mainnet]: mainnetBlockcypherProvider,\n}\n\n// Bitgo data providers for Bitcoin\nconst mainnetBitgoProvider = new BitgoProvider({\n baseUrl: 'https://app.bitgo.com',\n chain: BTCChain,\n})\nexport const BitgoProviders: UtxoOnlineDataProviders = {\n [Network.Testnet]: undefined,\n [Network.Stagenet]: mainnetBitgoProvider,\n [Network.Mainnet]: mainnetBitgoProvider,\n}\n\nexport const tapRootDerivationPaths = {\n [Network.Mainnet]: `86'/0'/0'/0/`,\n [Network.Testnet]: `86'/1'/0'/0/`,\n [Network.Stagenet]: `86'/0'/0'/0/`,\n}\n","// Import statements for necessary modules and types\nimport { Network } from '@xchainjs/xchain-client' // Importing the Network type from xchain-client module\nimport { Address } from '@xchainjs/xchain-util' // Importing the Address type from xchain-util module\nimport { UTXO } from '@xchainjs/xchain-utxo' // Importing the UTXO type from xchain-utxo module\nimport * as Bitcoin from 'bitcoinjs-lib' // Importing the entire bitcoinjs-lib module and aliasing it as Bitcoin\n\n// Constants defining the sizes of various components in a Bitcoin transaction\nexport const TX_EMPTY_SIZE = 4 + 1 + 1 + 4 // Total size of an empty transaction\nexport const TX_INPUT_BASE = 32 + 4 + 1 + 4 // Size of a base input in a transaction\nexport const TX_INPUT_PUBKEYHASH = 107 // Size of an input with a public key hash\nexport const TX_OUTPUT_BASE = 8 + 1 // Size of a base output in a transaction\nexport const TX_OUTPUT_PUBKEYHASH = 25 // Size of an output with a public key hash\n\n/**\n * Function to calculate the size of an input in a transaction.\n * @param {UTXO} input - The UTXO (Unspent Transaction Output) for which to calculate the size.\n * @returns {number} The size of the input.\n */\nexport const inputBytes = (input: UTXO): number => {\n return TX_INPUT_BASE + (input.witnessUtxo?.script ? input.witnessUtxo?.script.length : TX_INPUT_PUBKEYHASH)\n}\n\n/**\n * Function to calculate the average value of an array of numbers.\n * @param {number[]} array - The array of numbers.\n * @returns {number} The average value of the array.\n */\nexport const arrayAverage = (array: number[]): number => {\n let sum = 0\n array.forEach((value) => (sum += value))\n return sum / array.length\n}\n\n/**\n * Function to get the Bitcoin network to be used with bitcoinjs.\n *\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {Bitcoin.Network} The Bitcoin network.\n */\nexport const btcNetwork = (network: Network): Bitcoin.Network => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return Bitcoin.networks.bitcoin // Return the Bitcoin mainnet or stagenet network\n case Network.Testnet:\n return Bitcoin.networks.testnet // Return the Bitcoin testnet network\n }\n}\n\n/**\n * Function to validate a Bitcoin address.\n * @param {Address} address - The Bitcoin address to validate.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\nexport const validateAddress = (address: Address, network: Network): boolean => {\n try {\n Bitcoin.address.toOutputScript(address, btcNetwork(network)) // Try to convert the address to an output script using the specified network\n return true // If successful, the address is valid\n } catch (error) {\n return false // If an error occurs, the address is invalid\n }\n}\n\n/**\n * Function to get the address prefix based on the network.\n * @param {Network} network - The network type (Mainnet, Testnet, or Stagenet).\n * @returns {string} The address prefix based on the network.\n */\nexport const getPrefix = (network: Network): string => {\n switch (network) {\n case Network.Mainnet:\n case Network.Stagenet:\n return 'bc1' // Return the address prefix for Bitcoin mainnet or stagenet\n case Network.Testnet:\n return 'tb1' // Return the address prefix for Bitcoin testnet\n }\n}\n\n/**\n * Converts a public key to an X-only public key.\n * @param pubKey The public key to convert.\n * @returns The X-only public key.\n */\nexport const toXOnly = (pubKey: Buffer): Buffer => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33))\n","import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs'\nimport { AssetInfo, FeeRate, Network } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { Client as UTXOClient, PreparedTx, TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport accumulative from 'coinselect/accumulative'\n\nimport {\n AssetBTC,\n BTCChain,\n BTC_DECIMAL,\n BitgoProviders,\n BlockcypherDataProviders,\n LOWER_FEE_BOUND,\n MIN_TX_FEE,\n UPPER_FEE_BOUND,\n blockstreamExplorerProviders,\n} from './const'\nimport { AddressFormat } from './types'\nimport * as Utils from './utils'\n\n// Default parameters for the Bitcoin UTXO client\nexport const defaultBTCParams: UtxoClientParams = {\n network: Network.Mainnet,\n phrase: '',\n explorerProviders: blockstreamExplorerProviders,\n dataProviders: [BitgoProviders, BlockcypherDataProviders],\n rootDerivationPaths: {\n [Network.Mainnet]: `84'/0'/0'/0/`, // Not BIP44 compliant but compatible with pre-HD wallets\n [Network.Testnet]: `84'/1'/0'/0/`,\n [Network.Stagenet]: `84'/0'/0'/0/`,\n },\n feeBounds: {\n lower: LOWER_FEE_BOUND,\n upper: UPPER_FEE_BOUND,\n },\n}\n/**\n * Custom Bitcoin client\n */\nabstract class Client extends UTXOClient {\n protected addressFormat: AddressFormat\n /**\n * Constructor\n * Initializes the client with network type and other parameters.\n * @param {UtxoClientParams} params\n */\n constructor(\n params: UtxoClientParams & { addressFormat?: AddressFormat } = {\n ...defaultBTCParams,\n addressFormat: AddressFormat.P2WPKH,\n },\n ) {\n super(BTCChain, {\n network: params.network,\n rootDerivationPaths: params.rootDerivationPaths,\n phrase: params.phrase,\n feeBounds: params.feeBounds,\n explorerProviders: params.explorerProviders,\n dataProviders: params.dataProviders,\n })\n this.addressFormat = params.addressFormat || AddressFormat.P2WPKH\n\n if (this.addressFormat === AddressFormat.P2TR) {\n if (\n !this.rootDerivationPaths?.mainnet.startsWith(`86'`) ||\n !this.rootDerivationPaths?.testnet.startsWith(`86'`) ||\n !this.rootDerivationPaths?.stagenet.startsWith(`86'`)\n ) {\n throw Error(`Unsupported derivation paths for Taproot client. Use 86' paths`)\n }\n }\n Bitcoin.initEccLib(ecc)\n }\n\n /**\n * Get BTC asset info.\n * @returns {AssetInfo} BTC asset information.\n */\n getAssetInfo(): AssetInfo {\n const assetInfo: AssetInfo = {\n asset: AssetBTC,\n decimal: BTC_DECIMAL,\n }\n return assetInfo\n }\n\n /**\n * Validate the given Bitcoin address.\n * @param {string} address Bitcoin address to validate.\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\n validateAddress(address: string): boolean {\n return Utils.validateAddress(address, this.network)\n }\n\n /**\n * Compile memo into a buffer.\n * @param {string} memo Memo to compile.\n * @returns {Buffer} Compiled memo.\n */\n protected compileMemo(memo: string): Buffer {\n const data = Buffer.from(memo, 'utf8') // converts MEMO to buffer\n return Bitcoin.script.compile([Bitcoin.opcodes.OP_RETURN, data]) // Compile OP_RETURN script\n }\n\n /**\n * Get transaction fee from UTXOs.\n * @param {UTXO[]} inputs UTXOs to calculate fee from.\n * @param {FeeRate} feeRate Fee rate.\n * @param {Buffer | null} data Compiled memo (Optional).\n * @returns {number} Transaction fee.\n */\n protected getFeeFromUtxos(inputs: UTXO[], feeRate: FeeRate, data: Buffer | null = null): number {\n // Calculate input size based on inputs\n const inputSizeBasedOnInputs =\n inputs.length > 0\n ? inputs.reduce((a, x) => a + Utils.inputBytes(x), 0) + inputs.length // +1 byte for each input signature\n : 0\n // Calculate sum\n let sum =\n Utils.TX_EMPTY_SIZE +\n inputSizeBasedOnInputs +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH +\n Utils.TX_OUTPUT_BASE +\n Utils.TX_OUTPUT_PUBKEYHASH\n\n if (data) {\n sum += Utils.TX_OUTPUT_BASE + data.length\n }\n // Calculate fee\n const fee = sum * feeRate\n return fee > MIN_TX_FEE ? fee : MIN_TX_FEE\n }\n\n /**\n * Build a Bitcoin transaction.*\n * @param param0\n * @deprecated\n */\n async buildTx({\n amount,\n recipient,\n memo,\n feeRate,\n sender,\n spendPendingUTXO = true,\n }: TxParams & {\n feeRate: FeeRate\n sender: Address\n spendPendingUTXO?: boolean\n withTxHex?: boolean\n }): Promise<{ psbt: Bitcoin.Psbt; utxos: UTXO[]; inputs: UTXO[] }> {\n // Check memo length\n if (memo && memo.length > 80) {\n throw new Error('memo too long, must not be longer than 80 chars.')\n }\n // This section of the code is responsible for preparing a transaction by building a Bitcoin PSBT (Partially Signed Bitcoin Transaction).\n if (!this.validateAddress(recipient)) throw new Error('Invalid address')\n // Determine whether to only use confirmed UTXOs or include pending UTXOs based on the spendPendingUTXO flag.\n const confirmedOnly = !spendPendingUTXO\n // Scan UTXOs associated with the sender's address.\n const utxos = await this.scanUTXOs(sender, confirmedOnly)\n // Throw an error if there are no available UTXOs to cover the transaction.\n if (utxos.length === 0) throw new Error('Insufficient Balance for transaction')\n // Round up the fee rate to the nearest integer.\n const feeRateWhole = Math.ceil(feeRate)\n // Compile the memo into a Buffer if provided.\n const compiledMemo = memo ? this.compileMemo(memo) : null\n // Initialize an array to store the target outputs of the transaction.\n const targetOutputs = []\n\n // 1. Add the recipient address and amount to the target outputs.\n targetOutputs.push({\n address: recipient,\n value: amount.amount().toNumber(),\n })\n // 2. Add the compiled memo to the target outputs if it exists.\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 })\n }\n // Use the coinselect library to determine the inputs and outputs for the transaction.\n const { inputs, outputs } = accumulative(utxos, targetOutputs, feeRateWhole)\n // If no suitable inputs or outputs are found, throw an error indicating insufficient balance.\n if (!inputs || !outputs) throw new Error('Insufficient Balance for transaction')\n // Initialize a new Bitcoin PSBT object.\n const psbt = new Bitcoin.Psbt({ network: Utils.btcNetwork(this.network) }) // Network-specific\n\n if (this.addressFormat === AddressFormat.P2WPKH) {\n // Add inputs to the PSBT from the accumulated inputs.\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: utxo.witnessUtxo,\n }),\n )\n } else {\n const { pubkey, output } = Bitcoin.payments.p2tr({\n address: sender,\n })\n inputs.forEach((utxo: UTXO) =>\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n witnessUtxo: { value: utxo.value, script: output as Buffer },\n tapInternalKey: pubkey,\n }),\n )\n }\n // Add outputs to the PSBT from the accumulated outputs.\n outputs.forEach((output: Bitcoin.PsbtTxOutput) => {\n // If the output address is not specified, it's considered a change address and set to the sender's address.\n if (!output.address) {\n //an empty address means this is the change address\n output.address = sender\n }\n // Add the output to the PSBT.\n if (!output.script) {\n psbt.addOutput(output)\n } else {\n // If the output is a memo, add it to the PSBT to avoid dust error.\n if (compiledMemo) {\n psbt.addOutput({ script: compiledMemo, value: 0 })\n }\n }\n })\n\n return { psbt, utxos, inputs }\n }\n\n /**\n * Prepare transfer.\n *\n * @param {TxParams&Address&FeeRate&boolean} params The transfer options.\n * @returns {PreparedTx} The raw unsigned transaction.\n */\n async prepareTx({\n sender,\n memo,\n amount,\n recipient,\n spendPendingUTXO = true,\n feeRate,\n }: TxParams & {\n sender: Address\n feeRate: FeeRate\n spendPendingUTXO?: boolean\n }): Promise<PreparedTx> {\n // Build the transaction using the provided parameters.\n const { psbt, utxos } = await this.buildTx({\n sender,\n recipient,\n amount,\n feeRate,\n memo,\n spendPendingUTXO,\n })\n // Return the raw unsigned transaction (PSBT) and associated UTXOs.\n return { rawUnsignedTx: psbt.toBase64(), utxos }\n }\n}\n\nexport { Client }\n","import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs'\nimport { FeeOption, FeeRate, TxHash, checkFeeBounds } from '@xchainjs/xchain-client'\nimport { getSeed } from '@xchainjs/xchain-crypto'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport { BIP32Factory } from 'bip32'\nimport * as Bitcoin from 'bitcoinjs-lib'\nimport { ECPairFactory, ECPairInterface } from 'ecpair'\n\nimport { Client, defaultBTCParams } from './client' // Importing the base Bitcoin client\nimport { AddressFormat } from './types'\nimport * as Utils from './utils'\n\nconst ECPair = ECPairFactory(ecc)\n/**\n * Custom Bitcoin client extended to support keystore functionality\n */\nclass ClientKeystore extends Client {\n constructor(\n params: UtxoClientParams & { addressFormat?: AddressFormat } = {\n ...defaultBTCParams,\n addressFormat: AddressFormat.P2WPKH,\n },\n ) {\n super(params)\n }\n /**\n * @deprecated This function eventually will be removed. Use getAddressAsync instead.\n * Get the address associated with the given index.\n * @param {number} index The index of the address.\n * @returns {Address} The Bitcoin address.\n * @throws {\"index must be greater than zero\"} Thrown if the index is less than zero.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n * @throws {\"Address not defined\"} Thrown if failed to create the address from the phrase.\n */\n getAddress(index = 0): Address {\n // Check if the index is valid\n if (index < 0) {\n throw new Error('index must be greater than zero')\n }\n\n // Check if the phrase has been set\n if (this.phrase) {\n const btcNetwork = Utils.btcNetwork(this.network)\n const btcKeys = this.getBtcKeys(this.phrase, index)\n\n // Generate the address using the Bitcoinjs library\n\n let address: string | undefined\n if (this.addressFormat === AddressFormat.P2WPKH) {\n address = Bitcoin.payments.p2wpkh({\n pubkey: btcKeys.publicKey,\n network: btcNetwork,\n }).address\n } else {\n address = Bitcoin.payments.p2tr({\n internalPubkey: Utils.toXOnly(btcKeys.publicKey),\n network: btcNetwork,\n }).address\n }\n\n // Throw an error if the address is not defined\n if (!address) {\n throw new Error('Address not defined')\n }\n\n return address\n }\n\n throw new Error('Phrase must be provided')\n }\n\n /**\n * Get the current address asynchronously.\n * @param {number} index The index of the address.\n * @returns {Promise<Address>} A promise that resolves to the Bitcoin address.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n */\n async getAddressAsync(index = 0): Promise<string> {\n return this.getAddress(index)\n }\n\n /**\n * @private\n * Get the Bitcoin keys derived from the given phrase.\n *\n * @param {string} phrase The phrase to be used for generating the keys.\n * @param {number} index The index of the address.\n * @returns {Bitcoin.ECPair.ECPairInterface} The Bitcoin key pair.\n * @throws {\"Could not get private key from phrase\"} Thrown if failed to create BTC keys from the given phrase.\n */\n private getBtcKeys(phrase: string, index = 0): ECPairInterface {\n const btcNetwork = Utils.btcNetwork(this.network)\n const seed = getSeed(phrase)\n const bip32 = BIP32Factory(ecc)\n const master = bip32.fromSeed(seed, btcNetwork).derivePath(this.getFullDerivationPath(index))\n\n if (!master.privateKey) {\n throw new Error('Could not get private key from phrase')\n }\n\n return ECPair.fromPrivateKey(master.privateKey, { network: btcNetwork })\n }\n\n /**\n * Transfer BTC.\n *\n * @param {TxParams&FeeRate} params The transfer options including the fee rate.\n * @returns {Promise<TxHash|string>} A promise that resolves to the transaction hash or an error message.\n * @throws {\"memo too long\"} Thrown if the memo is longer than 80 characters.\n */\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n // Set the default fee rate to `fast`\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n\n // Check if the fee rate is within the fee bounds\n checkFeeBounds(this.feeBounds, feeRate)\n\n // Get the address index from the parameters or use the default value\n const fromAddressIndex = params?.walletIndex || 0\n\n // Get the Bitcoin keys\n const btcKeys = this.getBtcKeys(this.phrase, fromAddressIndex)\n\n // Prepare the transaction\n const { rawUnsignedTx } = await this.prepareTx({\n ...params,\n sender: this.getAddress(fromAddressIndex),\n feeRate,\n })\n\n // Build the PSBT\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n\n // Sign all inputs\n psbt.signAllInputs(\n this.addressFormat === AddressFormat.P2WPKH\n ? btcKeys\n : btcKeys.tweak(Bitcoin.crypto.taggedHash('TapTweak', Utils.toXOnly(btcKeys.publicKey))),\n )\n\n // Finalize inputs\n psbt.finalizeAllInputs()\n\n // Extract the transaction hex\n const txHex = psbt.extractTransaction().toHex()\n\n // Extract the transaction hash\n const txHash = psbt.extractTransaction().getId()\n\n try {\n // Broadcast the transaction and return the transaction hash\n const txId = await this.roundRobinBroadcastTx(txHex)\n return txId\n } catch (err) {\n // If broadcasting fails, return an error message with a link to the explorer\n const error = `Server error, please check explorer for tx confirmation ${this.explorerProviders[\n this.network\n ].getExplorerTxUrl(txHash)}`\n return error\n }\n }\n}\n\nexport { ClientKeystore }\n","import AppBtc from '@ledgerhq/hw-app-btc'\nimport { Transaction } from '@ledgerhq/hw-app-btc/lib/types'\nimport { FeeOption, FeeRate, TxHash } from '@xchainjs/xchain-client'\nimport { Address } from '@xchainjs/xchain-util'\nimport { TxParams, UTXO, UtxoClientParams } from '@xchainjs/xchain-utxo'\nimport * as Bitcoin from 'bitcoinjs-lib'\n\nimport { Client } from './client'\nimport { AddressFormat } from './types'\n\n/**\n * Custom Ledger Bitcoin client\n */\nclass ClientLedger extends Client {\n // Reference to the Ledger transport object\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private transport: any // TODO: Parametrize\n private app: AppBtc | undefined\n\n // Constructor\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(params: UtxoClientParams & { transport: any; addressFormat?: AddressFormat }) {\n super(params)\n this.transport = params.transport\n }\n\n // Get the Ledger BTC application instance\n public async getApp(): Promise<AppBtc> {\n if (this.app) {\n return this.app\n }\n this.app = new AppBtc({ transport: this.transport })\n return this.app\n }\n\n // Get the current address synchronously\n getAddress(): string {\n throw Error('Sync method not supported for Ledger')\n }\n\n // Get the current address asynchronously\n async getAddressAsync(index = 0, verify = false): Promise<Address> {\n const app = await this.getApp()\n const result = await app.getWalletPublicKey(this.getFullDerivationPath(index), {\n format: this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32',\n verify,\n })\n return result.bitcoinAddress\n }\n\n // Transfer BTC from Ledger\n async transfer(params: TxParams & { feeRate?: FeeRate }): Promise<TxHash> {\n const app = await this.getApp()\n const fromAddressIndex = params?.walletIndex || 0\n // Get fee rate\n const feeRate = params.feeRate || (await this.getFeeRates())[FeeOption.Fast]\n // Get sender address\n const sender = await this.getAddressAsync(fromAddressIndex)\n // Prepare transaction\n const { rawUnsignedTx, utxos } = await this.prepareTx({ ...params, sender, feeRate })\n const psbt = Bitcoin.Psbt.fromBase64(rawUnsignedTx)\n // Prepare Ledger inputs\n const ledgerInputs: [Transaction, number, string | null, number | null][] = (utxos as UTXO[]).map(\n ({ txHex, hash, index }) => {\n if (!txHex) {\n throw Error(`Missing 'txHex' for UTXO (txHash ${hash})`)\n }\n const utxoTx = Bitcoin.Transaction.fromHex(txHex)\n const splittedTx = app.splitTransaction(txHex, utxoTx.hasWitnesses())\n return [splittedTx, index, null, null]\n },\n )\n\n // Prepare associated keysets\n const associatedKeysets = ledgerInputs.map(() => this.getFullDerivationPath(fromAddressIndex))\n // Serialize unsigned transaction\n const unsignedHex = psbt.data.globalMap.unsignedTx.toBuffer().toString('hex')\n const newTx = app.splitTransaction(unsignedHex, true)\n const outputScriptHex = app.serializeTransactionOutputs(newTx).toString('hex')\n // Create payment transaction\n const txHex = await app.createPaymentTransaction({\n inputs: ledgerInputs,\n associatedKeysets,\n outputScriptHex,\n segwit: true,\n useTrustedInputForSegwit: true,\n additionals: [this.addressFormat === AddressFormat.P2TR ? 'bech32m' : 'bech32'],\n })\n // Broadcast transaction\n const txHash = await this.broadcastTx(txHex)\n // Throw error if no transaction hash is received\n if (!txHash) {\n throw Error('No Tx hash')\n }\n\n return txHash\n }\n}\n\nexport { ClientLedger }\n"],"names":["AddressFormat","TX_EMPTY_SIZE","TX_INPUT_BASE","TX_INPUT_PUBKEYHASH","TX_OUTPUT_BASE","TX_OUTPUT_PUBKEYHASH","inputBytes","utils","require$$0","AssetType","ExplorerProvider","Network","SochainProvider","SochainNetwork","HaskoinProvider","HaskoinNetwork","BlockcypherProvider","BlockcypherNetwork","BitgoProvider","Bitcoin","UTXOClient","ecc","Utils.validateAddress","Utils.inputBytes","Utils.TX_EMPTY_SIZE","Utils.TX_OUTPUT_BASE","Utils.TX_OUTPUT_PUBKEYHASH","accumulative","Utils.btcNetwork","ECPairFactory","btcNetwork","Utils.toXOnly","getSeed","bip32","BIP32Factory","FeeOption","checkFeeBounds","AppBtc"],"mappings":";;;;;;;;;;;;;;;;;;;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AAK,GAAG,GAAG,CAAC,gBAAgB,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;AACrD,YAAA,MAAM,eAAe,GAAG,GAAG,CAAC,2BAA2B,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;;AAE9E,YAAA,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,wBAAwB,CAAC;AAC/C,gBAAA,MAAM,EAAE,YAAY;gBACpB,iBAAiB;gBACjB,eAAe;AACf,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,wBAAwB,EAAE,IAAI;AAC9B,gBAAA,WAAW,EAAE,CAAC,IAAI,CAAC,aAAa,KAAKnB,qBAAa,CAAC,IAAI,GAAG,SAAS,GAAG,QAAQ,CAAC;AAChF,aAAA,CAAC,CAAA;;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;;YAE5C,IAAI,CAAC,MAAM,EAAE;AACX,gBAAA,MAAM,KAAK,CAAC,YAAY,CAAC,CAAA;AAC1B,aAAA;AAED,YAAA,OAAO,MAAM,CAAA;SACd,CAAA,CAAA;AAAA,KAAA;AACF;;;;;;;;;;;;;;;;;;;;;;"}
@@ -15,3 +15,7 @@ export type GetChangeParams = {
15
15
  address: Address;
16
16
  };
17
17
  export type ClientUrl = Record<Network, string>;
18
+ export declare enum AddressFormat {
19
+ P2WPKH = 0,
20
+ P2TR = 1
21
+ }
package/lib/utils.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import { Network } from '@xchainjs/xchain-client';
2
3
  import { Address } from '@xchainjs/xchain-util';
3
4
  import { UTXO } from '@xchainjs/xchain-utxo';
@@ -39,3 +40,9 @@ export declare const validateAddress: (address: Address, network: Network) => bo
39
40
  * @returns {string} The address prefix based on the network.
40
41
  */
41
42
  export declare const getPrefix: (network: Network) => string;
43
+ /**
44
+ * Converts a public key to an X-only public key.
45
+ * @param pubKey The public key to convert.
46
+ * @returns The X-only public key.
47
+ */
48
+ export declare const toXOnly: (pubKey: Buffer) => Buffer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xchainjs/xchain-bitcoin",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "Custom Bitcoin client and utilities used by XChainJS clients",
5
5
  "keywords": [
6
6
  "XChain",
@@ -33,15 +33,18 @@
33
33
  "postversion": "git push --follow-tags"
34
34
  },
35
35
  "dependencies": {
36
+ "@bitcoin-js/tiny-secp256k1-asmjs": "2.2.3",
36
37
  "@ledgerhq/hw-app-btc": "10.1.0",
37
- "@xchainjs/xchain-client": "1.0.3",
38
+ "@xchainjs/xchain-client": "1.0.4",
38
39
  "@xchainjs/xchain-crypto": "0.3.4",
39
- "@xchainjs/xchain-util": "1.0.2",
40
- "@xchainjs/xchain-utxo": "1.0.3",
41
- "@xchainjs/xchain-utxo-providers": "1.0.3",
42
- "bitcoinjs-lib": "5.2.0",
40
+ "@xchainjs/xchain-util": "1.0.3",
41
+ "@xchainjs/xchain-utxo": "1.0.4",
42
+ "@xchainjs/xchain-utxo-providers": "1.0.4",
43
+ "bip32": "4.0.0",
44
+ "bitcoinjs-lib": "6.1.6",
43
45
  "coininfo": "5.1.0",
44
- "coinselect": "3.1.12"
46
+ "coinselect": "3.1.12",
47
+ "ecpair": "2.1.0"
45
48
  },
46
49
  "devDependencies": {
47
50
  "@ledgerhq/hw-transport-node-hid": "6.28.6",