@rsksmart/powpeg-sdk 1.1.0 → 1.2.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -301,6 +301,10 @@ var ApiService = class {
301
301
  const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
302
302
  return response.data;
303
303
  }
304
+ async getFeatures() {
305
+ const response = await this.api.get("/features").catch(this.handleError);
306
+ return response.data;
307
+ }
304
308
  };
305
309
 
306
310
  // src/sdk/powpeg.ts
@@ -425,12 +429,27 @@ var PowPegSDK = class {
425
429
  }
426
430
  return Buffer.from(output, "hex");
427
431
  }
432
+ /**
433
+ * Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
434
+ * @param {bigint} amount - Amount to peg in, in satoshis.
435
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
436
+ * @returns {Promise<number>} The estimated total fee in satoshis.
437
+ */
428
438
  async estimatePeginFee(amount, feeLevel = "fast") {
429
439
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
430
440
  const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
431
441
  const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
432
442
  return totalFee;
433
443
  }
444
+ /**
445
+ * Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
446
+ * encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
447
+ * Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction.
448
+ * @param {bigint} amount - Amount to peg in, in satoshis.
449
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
450
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
451
+ * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
452
+ */
434
453
  async createPegin(amount, recipientAddress, selectedUtxos) {
435
454
  const addresses = await this.getAddressesGroupedByUsage();
436
455
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
@@ -490,6 +509,14 @@ var PowPegSDK = class {
490
509
  const totalFee = baseFee + feePerInput * inputs.length;
491
510
  return { inputs, change: Math.abs(rest), totalFee };
492
511
  }
512
+ /**
513
+ * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
514
+ * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
515
+ * @param {Psbt} psbt - The peg-in PSBT to fund.
516
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
517
+ * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
518
+ * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
519
+ */
493
520
  async fundPegin(psbt, feeLevel = "fast", value) {
494
521
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
495
522
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
@@ -514,12 +541,30 @@ var PowPegSDK = class {
514
541
  });
515
542
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
516
543
  }
544
+ /**
545
+ * Convenience method that creates and funds a peg-in PSBT in one call.
546
+ * @param {bigint} amount - Amount to peg in, in satoshis.
547
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
548
+ * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
549
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
550
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
551
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
552
+ */
517
553
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
518
554
  this.bitcoinSigner = signer;
519
555
  this.validatePeginAmount(amount);
520
556
  const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
521
557
  return this.fundPegin(psbt, feeLevel);
522
558
  }
559
+ /**
560
+ * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
561
+ * without routing through the federation address (unlike {@link createPegin}).
562
+ * @param {bigint} amount - Amount to send, in satoshis.
563
+ * @param {string} recipientAddress - Bitcoin address to receive the payment.
564
+ * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
565
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
566
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
567
+ */
523
568
  async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
524
569
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
525
570
  psbt.addOutput({
@@ -532,6 +577,13 @@ var PowPegSDK = class {
532
577
  async signPegin(psbt, inputs, transactions) {
533
578
  return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
534
579
  }
580
+ /**
581
+ * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
582
+ * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
583
+ * @param {Utxo[]} [inputs] - The PSBT's funding UTXOs (the `inputs` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
584
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs` (the `transactions` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
585
+ * @returns {Promise<string>} The broadcast transaction's ID.
586
+ */
535
587
  async signAndBroadcastPegin(psbt, inputs, transactions) {
536
588
  const signedTx = await this.signPegin(psbt, inputs, transactions);
537
589
  return this.bitcoinDataSource.broadcast(signedTx);
@@ -551,6 +603,12 @@ var PowPegSDK = class {
551
603
  value: amountBN.toString()
552
604
  };
553
605
  }
606
+ /**
607
+ * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
608
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
609
+ * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
610
+ * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
611
+ */
554
612
  async estimatePegoutFees(amount, fromAddress = import_bridges_core_sdk4.ethers.constants.AddressZero) {
555
613
  this.validateMinimumPegoutAmount(amount);
556
614
  const tx = this.createPegoutTransaction(amount, fromAddress);
@@ -565,6 +623,14 @@ var PowPegSDK = class {
565
623
  rootstockFee
566
624
  };
567
625
  }
626
+ /**
627
+ * Validates the requested amount and the sender's balance, then builds an unsigned peg-out
628
+ * transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
629
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
630
+ * @param {string} senderAccount - Rootstock address that will send the peg-out.
631
+ * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
632
+ * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
633
+ */
568
634
  async createPegout(amount, senderAccount) {
569
635
  const fees = await this.estimatePegoutFees(amount, senderAccount);
570
636
  const amountBN = import_bridges_core_sdk4.ethers.utils.parseUnits(amount, 18).toBigInt();
@@ -579,13 +645,39 @@ var PowPegSDK = class {
579
645
  bitcoinFee: fees.bitcoinFee
580
646
  };
581
647
  }
648
+ /**
649
+ * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
650
+ * and waits for it to be mined.
651
+ * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
652
+ * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
653
+ * @returns The mined transaction receipt, if the signer's provider is set.
654
+ */
582
655
  async signAndBroadcastPegout(tx, signer) {
583
656
  const { hash } = await signer.sendTransaction(tx);
584
657
  return signer.provider?.waitForTransaction(hash);
585
658
  }
659
+ /**
660
+ * Fetches the current status of a peg-in or peg-out transaction from the configured API.
661
+ * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
662
+ * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
663
+ * @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
664
+ */
586
665
  async getTransactionStatus(txHash, txType) {
587
666
  return this.api.getTransactionStatus(txHash, txType);
588
667
  }
668
+ /**
669
+ * Retrieves the feature flags from the 2WP API `/features` endpoint.
670
+ * @returns {Promise<Feature[]>} The feature flags as returned by the API.
671
+ */
672
+ async getFeatures() {
673
+ return this.api.getFeatures();
674
+ }
675
+ /**
676
+ * Returns the spendable UTXOs for the given Bitcoin address(es).
677
+ * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
678
+ * @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
679
+ * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
680
+ */
589
681
  async getAvailableUtxos(addresses) {
590
682
  const addressList = Array.isArray(addresses) ? addresses : [addresses];
591
683
  const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
@@ -598,6 +690,7 @@ var PowPegSDK = class {
598
690
 
599
691
  // src/bitcoin-signers/trezor/trezor.ts
600
692
  var import_connect_web = __toESM(require("@trezor/connect-web"));
693
+ var import_bridges_core_sdk5 = require("@rsksmart/bridges-core-sdk");
601
694
  var import_bitcoinjs_lib5 = require("bitcoinjs-lib");
602
695
  var TrezorSigner = class _TrezorSigner {
603
696
  constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
@@ -606,14 +699,25 @@ var TrezorSigner = class _TrezorSigner {
606
699
  }
607
700
  bitcoinTxVersion = 1;
608
701
  addresses = /* @__PURE__ */ new Map();
702
+ /**
703
+ * Initializes the Trezor connection and returns a ready-to-use signer.
704
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
705
+ * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
706
+ * @returns {Promise<TrezorSigner>} The initialized signer.
707
+ */
609
708
  static async init(network, initOptions) {
610
709
  await import_connect_web.default.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
611
710
  return new _TrezorSigner(network);
612
711
  }
712
+ /**
713
+ * Disposes the current Trezor connection and re-initializes it.
714
+ * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
715
+ */
613
716
  static async reinit() {
614
717
  import_connect_web.default.dispose();
615
718
  return _TrezorSigner.init();
616
719
  }
720
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
617
721
  set addressType(addressType) {
618
722
  this._addressType = addressType;
619
723
  }
@@ -641,9 +745,17 @@ var TrezorSigner = class _TrezorSigner {
641
745
  }
642
746
  return addresses;
643
747
  }
748
+ /**
749
+ * @param {number} bundleSize - Number of change addresses to derive.
750
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
751
+ */
644
752
  async getChangeAddresses(bundleSize) {
645
753
  return this.getAddresses(bundleSize, true);
646
754
  }
755
+ /**
756
+ * @param {number} bundleSize - Number of receive addresses to derive.
757
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
758
+ */
647
759
  async getNonChangeAddresses(bundleSize) {
648
760
  return this.getAddresses(bundleSize);
649
761
  }
@@ -687,7 +799,14 @@ var TrezorSigner = class _TrezorSigner {
687
799
  };
688
800
  });
689
801
  }
802
+ /**
803
+ * Signs the given PSBT's inputs/outputs on the Trezor device.
804
+ * @param {Psbt} psbt - The PSBT to sign.
805
+ * @param {Utxo[]} [utxos] - The PSBT's inputs, used to look up each input's derivation path and script type. Required — TrezorSigner cannot sign from the PSBT alone.
806
+ * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
807
+ */
690
808
  async signTransaction(psbt, utxos) {
809
+ (0, import_bridges_core_sdk5.assertTruthy)(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
691
810
  const inputs = this.getInputs(utxos);
692
811
  const outputs = this.getOutputs(psbt);
693
812
  const result = await import_connect_web.default.signTransaction({
@@ -706,6 +825,7 @@ var TrezorSigner = class _TrezorSigner {
706
825
  // src/bitcoin-signers/ledger/ledger.ts
707
826
  var import_hw_app_btc = __toESM(require("@ledgerhq/hw-app-btc"));
708
827
  var import_hw_transport_webusb = __toESM(require("@ledgerhq/hw-transport-webusb"));
828
+ var import_bridges_core_sdk6 = require("@rsksmart/bridges-core-sdk");
709
829
  var import_bitcoinjs_lib6 = require("bitcoinjs-lib");
710
830
 
711
831
  // src/bitcoin-signers/ledger/ledger-transport.ts
@@ -761,17 +881,27 @@ var LedgerSigner = class _LedgerSigner {
761
881
  }
762
882
  addresses = /* @__PURE__ */ new Map();
763
883
  transportService;
884
+ /**
885
+ * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
886
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
887
+ * @returns {Promise<LedgerSigner>} The initialized signer.
888
+ */
764
889
  static async init(network = "TEST") {
765
890
  const transport = await import_hw_transport_webusb.default.create();
766
891
  const connection = new import_hw_app_btc.default({ transport, currency: networks[network].currency });
767
892
  return new _LedgerSigner(connection, transport, network);
768
893
  }
894
+ /**
895
+ * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
896
+ * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
897
+ */
769
898
  async reinit() {
770
899
  return this.transportService.enqueue(async () => {
771
900
  await this.transport.close();
772
901
  return _LedgerSigner.init();
773
902
  });
774
903
  }
904
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
775
905
  set addressType(addressType) {
776
906
  this._addressType = addressType;
777
907
  }
@@ -809,9 +939,17 @@ var LedgerSigner = class _LedgerSigner {
809
939
  return addresses;
810
940
  });
811
941
  }
942
+ /**
943
+ * @param {number} bundleSize - Number of change addresses to derive.
944
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
945
+ */
812
946
  async getChangeAddresses(bundleSize) {
813
947
  return this.getAddresses(bundleSize, true);
814
948
  }
949
+ /**
950
+ * @param {number} bundleSize - Number of receive addresses to derive.
951
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
952
+ */
815
953
  async getNonChangeAddresses(bundleSize) {
816
954
  return this.getAddresses(bundleSize);
817
955
  }
@@ -834,7 +972,16 @@ var LedgerSigner = class _LedgerSigner {
834
972
  });
835
973
  return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
836
974
  }
975
+ /**
976
+ * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
977
+ * @param {Psbt} psbt - The PSBT to sign.
978
+ * @param {Utxo[]} [inputs] - The PSBT's inputs, used to look up each input's previously derived address path. Required — LedgerSigner cannot sign from the PSBT alone.
979
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
980
+ * @returns {Promise<string>} The signed, serialized transaction.
981
+ */
837
982
  async signTransaction(psbt, inputs, transactions) {
983
+ (0, import_bridges_core_sdk6.assertTruthy)(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
984
+ (0, import_bridges_core_sdk6.assertTruthy)(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
838
985
  return this.transportService.enqueue(async () => {
839
986
  const ledgerInputs = this.getInputs(inputs, transactions);
840
987
  const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
package/dist/index.mjs CHANGED
@@ -255,6 +255,10 @@ var ApiService = class {
255
255
  const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
256
256
  return response.data;
257
257
  }
258
+ async getFeatures() {
259
+ const response = await this.api.get("/features").catch(this.handleError);
260
+ return response.data;
261
+ }
258
262
  };
259
263
 
260
264
  // src/sdk/powpeg.ts
@@ -379,12 +383,27 @@ var PowPegSDK = class {
379
383
  }
380
384
  return Buffer.from(output, "hex");
381
385
  }
386
+ /**
387
+ * Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
388
+ * @param {bigint} amount - Amount to peg in, in satoshis.
389
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
390
+ * @returns {Promise<number>} The estimated total fee in satoshis.
391
+ */
382
392
  async estimatePeginFee(amount, feeLevel = "fast") {
383
393
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
384
394
  const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
385
395
  const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
386
396
  return totalFee;
387
397
  }
398
+ /**
399
+ * Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
400
+ * encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
401
+ * Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction.
402
+ * @param {bigint} amount - Amount to peg in, in satoshis.
403
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
404
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
405
+ * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
406
+ */
388
407
  async createPegin(amount, recipientAddress, selectedUtxos) {
389
408
  const addresses = await this.getAddressesGroupedByUsage();
390
409
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
@@ -444,6 +463,14 @@ var PowPegSDK = class {
444
463
  const totalFee = baseFee + feePerInput * inputs.length;
445
464
  return { inputs, change: Math.abs(rest), totalFee };
446
465
  }
466
+ /**
467
+ * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
468
+ * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
469
+ * @param {Psbt} psbt - The peg-in PSBT to fund.
470
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
471
+ * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
472
+ * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
473
+ */
447
474
  async fundPegin(psbt, feeLevel = "fast", value) {
448
475
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
449
476
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
@@ -468,12 +495,30 @@ var PowPegSDK = class {
468
495
  });
469
496
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
470
497
  }
498
+ /**
499
+ * Convenience method that creates and funds a peg-in PSBT in one call.
500
+ * @param {bigint} amount - Amount to peg in, in satoshis.
501
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
502
+ * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
503
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
504
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
505
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
506
+ */
471
507
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
472
508
  this.bitcoinSigner = signer;
473
509
  this.validatePeginAmount(amount);
474
510
  const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
475
511
  return this.fundPegin(psbt, feeLevel);
476
512
  }
513
+ /**
514
+ * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
515
+ * without routing through the federation address (unlike {@link createPegin}).
516
+ * @param {bigint} amount - Amount to send, in satoshis.
517
+ * @param {string} recipientAddress - Bitcoin address to receive the payment.
518
+ * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
519
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
520
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
521
+ */
477
522
  async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
478
523
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
479
524
  psbt.addOutput({
@@ -486,6 +531,13 @@ var PowPegSDK = class {
486
531
  async signPegin(psbt, inputs, transactions) {
487
532
  return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
488
533
  }
534
+ /**
535
+ * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
536
+ * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
537
+ * @param {Utxo[]} [inputs] - The PSBT's funding UTXOs (the `inputs` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
538
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs` (the `transactions` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
539
+ * @returns {Promise<string>} The broadcast transaction's ID.
540
+ */
489
541
  async signAndBroadcastPegin(psbt, inputs, transactions) {
490
542
  const signedTx = await this.signPegin(psbt, inputs, transactions);
491
543
  return this.bitcoinDataSource.broadcast(signedTx);
@@ -505,6 +557,12 @@ var PowPegSDK = class {
505
557
  value: amountBN.toString()
506
558
  };
507
559
  }
560
+ /**
561
+ * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
562
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
563
+ * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
564
+ * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
565
+ */
508
566
  async estimatePegoutFees(amount, fromAddress = ethers3.constants.AddressZero) {
509
567
  this.validateMinimumPegoutAmount(amount);
510
568
  const tx = this.createPegoutTransaction(amount, fromAddress);
@@ -519,6 +577,14 @@ var PowPegSDK = class {
519
577
  rootstockFee
520
578
  };
521
579
  }
580
+ /**
581
+ * Validates the requested amount and the sender's balance, then builds an unsigned peg-out
582
+ * transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
583
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
584
+ * @param {string} senderAccount - Rootstock address that will send the peg-out.
585
+ * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
586
+ * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
587
+ */
522
588
  async createPegout(amount, senderAccount) {
523
589
  const fees = await this.estimatePegoutFees(amount, senderAccount);
524
590
  const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
@@ -533,13 +599,39 @@ var PowPegSDK = class {
533
599
  bitcoinFee: fees.bitcoinFee
534
600
  };
535
601
  }
602
+ /**
603
+ * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
604
+ * and waits for it to be mined.
605
+ * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
606
+ * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
607
+ * @returns The mined transaction receipt, if the signer's provider is set.
608
+ */
536
609
  async signAndBroadcastPegout(tx, signer) {
537
610
  const { hash } = await signer.sendTransaction(tx);
538
611
  return signer.provider?.waitForTransaction(hash);
539
612
  }
613
+ /**
614
+ * Fetches the current status of a peg-in or peg-out transaction from the configured API.
615
+ * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
616
+ * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
617
+ * @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
618
+ */
540
619
  async getTransactionStatus(txHash, txType) {
541
620
  return this.api.getTransactionStatus(txHash, txType);
542
621
  }
622
+ /**
623
+ * Retrieves the feature flags from the 2WP API `/features` endpoint.
624
+ * @returns {Promise<Feature[]>} The feature flags as returned by the API.
625
+ */
626
+ async getFeatures() {
627
+ return this.api.getFeatures();
628
+ }
629
+ /**
630
+ * Returns the spendable UTXOs for the given Bitcoin address(es).
631
+ * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
632
+ * @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
633
+ * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
634
+ */
543
635
  async getAvailableUtxos(addresses) {
544
636
  const addressList = Array.isArray(addresses) ? addresses : [addresses];
545
637
  const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
@@ -552,6 +644,7 @@ var PowPegSDK = class {
552
644
 
553
645
  // src/bitcoin-signers/trezor/trezor.ts
554
646
  import TrezorConnect from "@trezor/connect-web";
647
+ import { assertTruthy as assertTruthy2 } from "@rsksmart/bridges-core-sdk";
555
648
  import "bitcoinjs-lib";
556
649
  var TrezorSigner = class _TrezorSigner {
557
650
  constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
@@ -560,14 +653,25 @@ var TrezorSigner = class _TrezorSigner {
560
653
  }
561
654
  bitcoinTxVersion = 1;
562
655
  addresses = /* @__PURE__ */ new Map();
656
+ /**
657
+ * Initializes the Trezor connection and returns a ready-to-use signer.
658
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
659
+ * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
660
+ * @returns {Promise<TrezorSigner>} The initialized signer.
661
+ */
563
662
  static async init(network, initOptions) {
564
663
  await TrezorConnect.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
565
664
  return new _TrezorSigner(network);
566
665
  }
666
+ /**
667
+ * Disposes the current Trezor connection and re-initializes it.
668
+ * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
669
+ */
567
670
  static async reinit() {
568
671
  TrezorConnect.dispose();
569
672
  return _TrezorSigner.init();
570
673
  }
674
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
571
675
  set addressType(addressType) {
572
676
  this._addressType = addressType;
573
677
  }
@@ -595,9 +699,17 @@ var TrezorSigner = class _TrezorSigner {
595
699
  }
596
700
  return addresses;
597
701
  }
702
+ /**
703
+ * @param {number} bundleSize - Number of change addresses to derive.
704
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
705
+ */
598
706
  async getChangeAddresses(bundleSize) {
599
707
  return this.getAddresses(bundleSize, true);
600
708
  }
709
+ /**
710
+ * @param {number} bundleSize - Number of receive addresses to derive.
711
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
712
+ */
601
713
  async getNonChangeAddresses(bundleSize) {
602
714
  return this.getAddresses(bundleSize);
603
715
  }
@@ -641,7 +753,14 @@ var TrezorSigner = class _TrezorSigner {
641
753
  };
642
754
  });
643
755
  }
756
+ /**
757
+ * Signs the given PSBT's inputs/outputs on the Trezor device.
758
+ * @param {Psbt} psbt - The PSBT to sign.
759
+ * @param {Utxo[]} [utxos] - The PSBT's inputs, used to look up each input's derivation path and script type. Required — TrezorSigner cannot sign from the PSBT alone.
760
+ * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
761
+ */
644
762
  async signTransaction(psbt, utxos) {
763
+ assertTruthy2(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
645
764
  const inputs = this.getInputs(utxos);
646
765
  const outputs = this.getOutputs(psbt);
647
766
  const result = await TrezorConnect.signTransaction({
@@ -660,6 +779,7 @@ var TrezorSigner = class _TrezorSigner {
660
779
  // src/bitcoin-signers/ledger/ledger.ts
661
780
  import Btc from "@ledgerhq/hw-app-btc";
662
781
  import TransportWebUSB from "@ledgerhq/hw-transport-webusb";
782
+ import { assertTruthy as assertTruthy3 } from "@rsksmart/bridges-core-sdk";
663
783
  import { Transaction as Transaction2 } from "bitcoinjs-lib";
664
784
 
665
785
  // src/bitcoin-signers/ledger/ledger-transport.ts
@@ -715,17 +835,27 @@ var LedgerSigner = class _LedgerSigner {
715
835
  }
716
836
  addresses = /* @__PURE__ */ new Map();
717
837
  transportService;
838
+ /**
839
+ * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
840
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
841
+ * @returns {Promise<LedgerSigner>} The initialized signer.
842
+ */
718
843
  static async init(network = "TEST") {
719
844
  const transport = await TransportWebUSB.create();
720
845
  const connection = new Btc({ transport, currency: networks[network].currency });
721
846
  return new _LedgerSigner(connection, transport, network);
722
847
  }
848
+ /**
849
+ * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
850
+ * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
851
+ */
723
852
  async reinit() {
724
853
  return this.transportService.enqueue(async () => {
725
854
  await this.transport.close();
726
855
  return _LedgerSigner.init();
727
856
  });
728
857
  }
858
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
729
859
  set addressType(addressType) {
730
860
  this._addressType = addressType;
731
861
  }
@@ -763,9 +893,17 @@ var LedgerSigner = class _LedgerSigner {
763
893
  return addresses;
764
894
  });
765
895
  }
896
+ /**
897
+ * @param {number} bundleSize - Number of change addresses to derive.
898
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
899
+ */
766
900
  async getChangeAddresses(bundleSize) {
767
901
  return this.getAddresses(bundleSize, true);
768
902
  }
903
+ /**
904
+ * @param {number} bundleSize - Number of receive addresses to derive.
905
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
906
+ */
769
907
  async getNonChangeAddresses(bundleSize) {
770
908
  return this.getAddresses(bundleSize);
771
909
  }
@@ -788,7 +926,16 @@ var LedgerSigner = class _LedgerSigner {
788
926
  });
789
927
  return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
790
928
  }
929
+ /**
930
+ * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
931
+ * @param {Psbt} psbt - The PSBT to sign.
932
+ * @param {Utxo[]} [inputs] - The PSBT's inputs, used to look up each input's previously derived address path. Required — LedgerSigner cannot sign from the PSBT alone.
933
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
934
+ * @returns {Promise<string>} The signed, serialized transaction.
935
+ */
791
936
  async signTransaction(psbt, inputs, transactions) {
937
+ assertTruthy3(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
938
+ assertTruthy3(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
792
939
  return this.transportService.enqueue(async () => {
793
940
  const ledgerInputs = this.getInputs(inputs, transactions);
794
941
  const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
package/docs/api.md ADDED
@@ -0,0 +1,51 @@
1
+ # API Reference
2
+
3
+ Public exports of the package's entry point (`src/index.ts`). Each description is the first line of that symbol's TSDoc comment — see the linked source file for the full contract.
4
+
5
+ ## SDK
6
+
7
+ | Export | Kind | Description |
8
+ |---|---|---|
9
+ | [`PowPegSDK`](../src/sdk/powpeg.ts) | class | SDK for creating, funding, signing and broadcasting native PowPeg peg-in (BTC -> RBTC) and peg-out (RBTC -> BTC) transactions. |
10
+
11
+ See [`PowPegSDK`](../src/sdk/powpeg.ts) for the full list of methods (`estimatePeginFee`, `createPegin`, `fundPegin`, `createAndFundPegin`, `createAndFundPsbt`, `signAndBroadcastPegin`, `estimatePegoutFees`, `createPegout`, `signAndBroadcastPegout`, `getTransactionStatus`, `getAvailableUtxos`) — each documented in place with its params and return type.
12
+
13
+ ## Bitcoin signers
14
+
15
+ See [`bitcoin-signers.md`](./bitcoin-signers.md) for the `BitcoinSigner` contract and the bundled implementations.
16
+
17
+ | Export | Kind | Description |
18
+ |---|---|---|
19
+ | [`TrezorSigner`](../src/bitcoin-signers/trezor/trezor.ts) | class | `BitcoinSigner` backed by a Trezor hardware wallet, connected via `@trezor/connect-web`. |
20
+ | [`LedgerSigner`](../src/bitcoin-signers/ledger/ledger.ts) | class | `BitcoinSigner` backed by a Ledger hardware wallet, connected over WebUSB. |
21
+
22
+ ## Types (`src/types.ts`)
23
+
24
+ | Export | Kind | Description |
25
+ |---|---|---|
26
+ | `FeeLevel` | type | Priority level used to look up a Bitcoin network fee rate. |
27
+ | `BitcoinSigner` | interface | Contract that a Bitcoin signing backend must implement so `PowPegSDK` can derive addresses and sign peg-in transactions with it. |
28
+ | `BitcoinDataSource` | interface | Contract for a Bitcoin data provider (fee rates, UTXOs, raw transactions, broadcasting). |
29
+ | `AddressWithDetails` | interface | A Bitcoin address together with its current balance and transaction count. |
30
+ | `Utxo` | interface | A spendable Bitcoin unspent transaction output. |
31
+ | `PegoutFeeEstimation` | interface | Estimated Bitcoin and Rootstock fees for a peg-out. |
32
+ | `TxType` | enum | Distinguishes a peg-in (BTC -> RBTC) from a peg-out (RBTC -> BTC) transaction. |
33
+ | `PegoutStatuses` | enum | Lifecycle status of a peg-out transaction, as reported by the 2WP API. |
34
+ | `PeginStatuses` | enum | Lifecycle status of a peg-in transaction, as reported by the 2WP API. |
35
+ | `RejectedPegoutReasons` | const | Maps the bridge's numeric rejection codes to a human-readable peg-out rejection reason. |
36
+ | `RejectedPegoutReason` | type | A human-readable reason a peg-out was rejected, as reported by the 2WP API. |
37
+ | `PeginTxDetails` | interface | Bitcoin and Rootstock-side details of a peg-in transaction. |
38
+ | `PegoutTxDetails` | interface | Details of a peg-out transaction, including its Bitcoin release once processed. |
39
+ | `PegoutStatusData` | interface | Status payload for a peg-out transaction, as returned by `PowPegSDK.getTransactionStatus`. |
40
+ | `PeginStatusData` | interface | Status payload for a peg-in transaction, as returned by `PowPegSDK.getTransactionStatus`. |
41
+ | `StatusData` | type | Discriminated union of the two possible `PowPegSDK.getTransactionStatus` payloads. |
42
+ | `UnsignedPegin` | interface | An unsigned, fee-funded peg-in PSBT ready to be signed, as returned by `PowPegSDK.createAndFundPegin`. |
43
+
44
+ ## Errors (`src/errors.ts`)
45
+
46
+ | Export | Kind | Description |
47
+ |---|---|---|
48
+ | `AmountBelowMinError` | class | Thrown when a requested peg-in or peg-out amount is below the protocol's minimum allowed amount. |
49
+ | `NotEnoughFundsError` | class | Thrown when the available UTXOs/balance can't cover the requested amount plus fees. |
50
+ | `APIError` | class | Thrown when the 2WP API responds with an error, a failed request, or an unexpected failure. |
51
+ | `InvalidAddressError` | class | Thrown when one or more Bitcoin addresses don't belong to the SDK's configured network. |