@rsksmart/powpeg-sdk 1.2.0-beta.2 → 1.2.0-beta.3

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.mjs CHANGED
@@ -176,6 +176,12 @@ var APIError = class extends Error {
176
176
  this.data = data;
177
177
  }
178
178
  };
179
+ var FederationAddressError = class extends Error {
180
+ constructor(message) {
181
+ super(message);
182
+ this.name = "FederationAddressError";
183
+ }
184
+ };
179
185
  var InvalidAddressError = class extends Error {
180
186
  invalidAddresses;
181
187
  constructor(invalidAddresses, message) {
@@ -193,6 +199,7 @@ var ApiService = class {
193
199
  MAIN: "https://api.2wp.rootstock.io",
194
200
  TEST: "https://api.2wp.testnet.rootstock.io"
195
201
  };
202
+ maxFeeRateSatPerByte = 1e3;
196
203
  feeLevelBlocks = {
197
204
  slow: 5,
198
205
  average: 3,
@@ -221,8 +228,19 @@ var ApiService = class {
221
228
  async getFeeRate(level) {
222
229
  const blocks = this.feeLevelBlocks[level];
223
230
  const response = await this.api.get(`/estimate-fee/${blocks}`).catch(this.handleError);
224
- const rate = ethers2.utils.parseUnits(response.data.amount, 8).div(1e3).toNumber();
225
- return rate;
231
+ let satoshisPerKb;
232
+ try {
233
+ satoshisPerKb = ethers2.utils.parseUnits(String(response.data.amount), 8);
234
+ } catch {
235
+ throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
236
+ }
237
+ if (satoshisPerKb.lte(0)) {
238
+ throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
239
+ }
240
+ if (satoshisPerKb.gt(this.maxFeeRateSatPerByte * 1e3)) {
241
+ throw new APIError(`Fee rate out of bounds: ${response.data.amount}`);
242
+ }
243
+ return satoshisPerKb.add(999).div(1e3).toNumber();
226
244
  }
227
245
  async getTxHex(txId) {
228
246
  const response = await this.api.get(`/tx?tx=${txId}`).catch(this.handleError);
@@ -231,8 +249,8 @@ var ApiService = class {
231
249
  async getOutputs(address2) {
232
250
  const response = await this.api.post("/utxo", { addressList: [address2] }).catch(this.handleError);
233
251
  const { data: utxos } = response.data;
234
- return utxos.map(({ address: address3, txid, vout, satoshis }) => ({
235
- address: address3,
252
+ return utxos.map(({ txid, vout, satoshis }) => ({
253
+ address: address2,
236
254
  txid,
237
255
  amount: BigInt(satoshis),
238
256
  vout
@@ -242,7 +260,7 @@ var ApiService = class {
242
260
  const response = await this.api.post("/addresses-info", { addressList: [address2] }).catch(this.handleError);
243
261
  const [details] = response.data.addressesInfo;
244
262
  return {
245
- address: details.address,
263
+ address: address2,
246
264
  balance: details.balance,
247
265
  txCount: details.txs
248
266
  };
@@ -255,6 +273,14 @@ var ApiService = class {
255
273
  const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
256
274
  return response.data;
257
275
  }
276
+ async getPeginConfiguration() {
277
+ const response = await this.api.get("/pegin-configuration").catch(this.handleError);
278
+ return response.data;
279
+ }
280
+ async getFeatures() {
281
+ const response = await this.api.get("/features").catch(this.handleError);
282
+ return response.data;
283
+ }
258
284
  };
259
285
 
260
286
  // src/sdk/powpeg.ts
@@ -286,8 +312,7 @@ var PowPegSDK = class {
286
312
  pegInOutputs = 3;
287
313
  powpegRsktHeader = "52534b5401";
288
314
  burnDustMaxValue = 3e4;
289
- utxos = [];
290
- changeAddress;
315
+ funding = /* @__PURE__ */ new WeakMap();
291
316
  minPeginAmount = 500000n;
292
317
  peginFeeEstimationInputs = 2;
293
318
  minPegoutAmount = "0.004";
@@ -312,7 +337,18 @@ var PowPegSDK = class {
312
337
  async getUtxos(addresses) {
313
338
  const rawAddresses = addresses.map((address2) => typeof address2 === "string" ? address2 : address2.address);
314
339
  const utxoLists = await Promise.all(rawAddresses.map((address2) => this.bitcoinDataSource.getOutputs(address2)));
315
- return utxoLists.flat();
340
+ const allUtxos = utxoLists.flat();
341
+ const seen = /* @__PURE__ */ new Set();
342
+ const uniqueUtxos = allUtxos.filter((utxo) => {
343
+ const key = `${utxo.txid}:${utxo.vout}`;
344
+ if (seen.has(key)) {
345
+ console.warn(`[PowPegSDK] Duplicate UTXO detected and skipped: ${key}`);
346
+ return false;
347
+ }
348
+ seen.add(key);
349
+ return true;
350
+ });
351
+ return uniqueUtxos;
316
352
  }
317
353
  async getAddressesWithDetails(addresses) {
318
354
  return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
@@ -353,8 +389,31 @@ var PowPegSDK = class {
353
389
  change: this.groupAddressesByUsage(changeDetails)
354
390
  };
355
391
  }
392
+ validateRskRecipient(recipientAddress) {
393
+ const trimmed = recipientAddress.trim();
394
+ if (!/^(0x)?[0-9a-fA-F]{40}$/.test(trimmed)) {
395
+ throw new InvalidAddressError([recipientAddress], `Invalid Rootstock recipient: ${recipientAddress}`);
396
+ }
397
+ return trimmed.toLowerCase();
398
+ }
399
+ async getVerifiedFederationAddress() {
400
+ const [bridgeAddress, peginConfiguration] = await Promise.all([
401
+ this.bridge.getFederationAddress().catch((error) => {
402
+ const reason = error instanceof Error ? error.message : String(error);
403
+ throw new FederationAddressError(`Could not retrieve the federation address from the Bridge contract: ${reason}`);
404
+ }),
405
+ this.api.getPeginConfiguration().catch((error) => {
406
+ const reason = error instanceof Error ? error.message : String(error);
407
+ throw new FederationAddressError(`Could not retrieve the pegin configuration: ${reason}`);
408
+ })
409
+ ]);
410
+ if (peginConfiguration.federationAddress !== bridgeAddress) {
411
+ throw new FederationAddressError("Federation address mismatch between the Bridge contract and the pegin configuration.");
412
+ }
413
+ return bridgeAddress;
414
+ }
356
415
  getRskOutput(recipientAddress, refundAddress) {
357
- let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
416
+ let output = `${this.powpegRsktHeader}${remove0x(this.validateRskRecipient(recipientAddress))}`;
358
417
  if (refundAddress) {
359
418
  const refundAddressType = getAddressType(refundAddress, this.network);
360
419
  const prefixes = {
@@ -368,12 +427,33 @@ var PowPegSDK = class {
368
427
  }
369
428
  return Buffer.from(output, "hex");
370
429
  }
371
- async estimatePeginFee(amount, feeLevel = "fast") {
430
+ /**
431
+ * Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
432
+ * @param {bigint} amount - Amount to peg in, in satoshis.
433
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
434
+ * @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
435
+ * same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
436
+ * @returns {Promise<number>} The estimated total fee in satoshis.
437
+ */
438
+ async estimatePeginFee(amount, feeLevel = "fast", utxos) {
372
439
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
440
+ if (utxos) {
441
+ const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
442
+ return totalFee2;
443
+ }
373
444
  const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
374
445
  const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
375
446
  return totalFee;
376
447
  }
448
+ /**
449
+ * Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
450
+ * encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
451
+ * Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction.
452
+ * @param {bigint} amount - Amount to peg in, in satoshis.
453
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
454
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
455
+ * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
456
+ */
377
457
  async createPegin(amount, recipientAddress, selectedUtxos) {
378
458
  const addresses = await this.getAddressesGroupedByUsage();
379
459
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
@@ -385,31 +465,36 @@ var PowPegSDK = class {
385
465
  value: 0
386
466
  });
387
467
  }
388
- const bridgeAddress = await this.bridge.getFederationAddress();
468
+ const bridgeAddress = await this.getVerifiedFederationAddress();
389
469
  psbt.addOutput({
390
470
  address: bridgeAddress,
391
471
  value: Number(amount)
392
472
  });
473
+ let utxos;
393
474
  if (selectedUtxos) {
394
- this.utxos = selectedUtxos;
475
+ utxos = [...selectedUtxos];
395
476
  } else {
396
477
  const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
397
478
  const { withBalance } = this.groupAddressesByBalance(usedAddresses);
398
- this.utxos = await this.getUtxos(withBalance);
479
+ utxos = await this.getUtxos(withBalance);
399
480
  }
400
- this.changeAddress = addresses.change.unused[0]?.address;
481
+ this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
401
482
  return psbt;
402
483
  }
403
484
  selectInputs(amount, utxos, baseFee, feePerInput) {
404
485
  const inputs = [];
405
486
  let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
406
- utxos.sort((a, b) => a.amount < b.amount ? -1 : a.amount > b.amount ? 1 : 0);
407
- utxos.forEach((utxo) => {
408
- if (remainingSatoshisToBePaid > 0) {
409
- inputs.push(utxo);
410
- remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
487
+ const candidates = [...utxos].sort((a, b) => Number(b.amount - a.amount));
488
+ for (const utxo of candidates) {
489
+ if (remainingSatoshisToBePaid <= 0) {
490
+ break;
411
491
  }
412
- });
492
+ if (BigInt(utxo.amount) <= BigInt(feePerInput)) {
493
+ continue;
494
+ }
495
+ inputs.push(utxo);
496
+ remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
497
+ }
413
498
  return { inputs, rest: Number(remainingSatoshisToBePaid) };
414
499
  }
415
500
  validatePeginAmount(amount) {
@@ -433,13 +518,25 @@ var PowPegSDK = class {
433
518
  const totalFee = baseFee + feePerInput * inputs.length;
434
519
  return { inputs, change: Math.abs(rest), totalFee };
435
520
  }
521
+ /**
522
+ * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
523
+ * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
524
+ * @param {Psbt} psbt - The peg-in PSBT to fund.
525
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
526
+ * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
527
+ * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
528
+ */
436
529
  async fundPegin(psbt, feeLevel = "fast", value) {
530
+ const funding = this.funding.get(psbt);
531
+ assertTruthy(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
437
532
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
438
533
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
439
- const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, this.utxos, feeRate);
534
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
440
535
  if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
441
536
  psbt.addOutput({
442
- address: this.changeAddress ?? inputs[0].address,
537
+ // Fall back to the first funding input's address when every derived
538
+ // change address has already been used.
539
+ address: funding.changeAddress ?? inputs[0].address,
443
540
  value: change
444
541
  });
445
542
  }
@@ -457,24 +554,49 @@ var PowPegSDK = class {
457
554
  });
458
555
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
459
556
  }
557
+ /**
558
+ * Convenience method that creates and funds a peg-in PSBT in one call.
559
+ * @param {bigint} amount - Amount to peg in, in satoshis.
560
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
561
+ * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
562
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
563
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
564
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
565
+ */
460
566
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
461
567
  this.bitcoinSigner = signer;
462
568
  this.validatePeginAmount(amount);
463
569
  const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
464
570
  return this.fundPegin(psbt, feeLevel);
465
571
  }
572
+ /**
573
+ * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
574
+ * without routing through the federation address (unlike {@link createPegin}).
575
+ * @param {bigint} amount - Amount to send, in satoshis.
576
+ * @param {string} recipientAddress - Bitcoin address to receive the payment.
577
+ * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
578
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
579
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
580
+ */
466
581
  async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
467
582
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
468
583
  psbt.addOutput({
469
584
  address: recipientAddress,
470
585
  value: Number(amount)
471
586
  });
472
- this.utxos = utxos;
587
+ this.funding.set(psbt, { utxos: [...utxos] });
473
588
  return this.fundPegin(psbt, feeLevel, amount);
474
589
  }
475
590
  async signPegin(psbt, inputs, transactions) {
476
591
  return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
477
592
  }
593
+ /**
594
+ * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
595
+ * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
596
+ * @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.
597
+ * @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.
598
+ * @returns {Promise<string>} The broadcast transaction's ID.
599
+ */
478
600
  async signAndBroadcastPegin(psbt, inputs, transactions) {
479
601
  const signedTx = await this.signPegin(psbt, inputs, transactions);
480
602
  return this.bitcoinDataSource.broadcast(signedTx);
@@ -494,6 +616,12 @@ var PowPegSDK = class {
494
616
  value: amountBN.toString()
495
617
  };
496
618
  }
619
+ /**
620
+ * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
621
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
622
+ * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
623
+ * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
624
+ */
497
625
  async estimatePegoutFees(amount, fromAddress = ethers3.constants.AddressZero) {
498
626
  this.validateMinimumPegoutAmount(amount);
499
627
  const tx = this.createPegoutTransaction(amount, fromAddress);
@@ -508,6 +636,14 @@ var PowPegSDK = class {
508
636
  rootstockFee
509
637
  };
510
638
  }
639
+ /**
640
+ * Validates the requested amount and the sender's balance, then builds an unsigned peg-out
641
+ * transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
642
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
643
+ * @param {string} senderAccount - Rootstock address that will send the peg-out.
644
+ * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
645
+ * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
646
+ */
511
647
  async createPegout(amount, senderAccount) {
512
648
  const fees = await this.estimatePegoutFees(amount, senderAccount);
513
649
  const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
@@ -522,13 +658,39 @@ var PowPegSDK = class {
522
658
  bitcoinFee: fees.bitcoinFee
523
659
  };
524
660
  }
661
+ /**
662
+ * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
663
+ * and waits for it to be mined.
664
+ * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
665
+ * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
666
+ * @returns The mined transaction receipt, if the signer's provider is set.
667
+ */
525
668
  async signAndBroadcastPegout(tx, signer) {
526
669
  const { hash } = await signer.sendTransaction(tx);
527
670
  return signer.provider?.waitForTransaction(hash);
528
671
  }
672
+ /**
673
+ * Fetches the current status of a peg-in or peg-out transaction from the configured API.
674
+ * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
675
+ * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
676
+ * @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
677
+ */
529
678
  async getTransactionStatus(txHash, txType) {
530
679
  return this.api.getTransactionStatus(txHash, txType);
531
680
  }
681
+ /**
682
+ * Retrieves the feature flags from the 2WP API `/features` endpoint.
683
+ * @returns {Promise<Feature[]>} The feature flags as returned by the API.
684
+ */
685
+ async getFeatures() {
686
+ return this.api.getFeatures();
687
+ }
688
+ /**
689
+ * Returns the spendable UTXOs for the given Bitcoin address(es).
690
+ * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
691
+ * @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
692
+ * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
693
+ */
532
694
  async getAvailableUtxos(addresses) {
533
695
  const addressList = Array.isArray(addresses) ? addresses : [addresses];
534
696
  const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
@@ -541,6 +703,7 @@ var PowPegSDK = class {
541
703
 
542
704
  // src/bitcoin-signers/trezor/trezor.ts
543
705
  import TrezorConnect from "@trezor/connect-web";
706
+ import { assertTruthy as assertTruthy2 } from "@rsksmart/bridges-core-sdk";
544
707
  import "bitcoinjs-lib";
545
708
  var TrezorSigner = class _TrezorSigner {
546
709
  constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
@@ -549,14 +712,25 @@ var TrezorSigner = class _TrezorSigner {
549
712
  }
550
713
  bitcoinTxVersion = 1;
551
714
  addresses = /* @__PURE__ */ new Map();
715
+ /**
716
+ * Initializes the Trezor connection and returns a ready-to-use signer.
717
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
718
+ * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
719
+ * @returns {Promise<TrezorSigner>} The initialized signer.
720
+ */
552
721
  static async init(network, initOptions) {
553
722
  await TrezorConnect.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
554
723
  return new _TrezorSigner(network);
555
724
  }
725
+ /**
726
+ * Disposes the current Trezor connection and re-initializes it.
727
+ * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
728
+ */
556
729
  static async reinit() {
557
730
  TrezorConnect.dispose();
558
731
  return _TrezorSigner.init();
559
732
  }
733
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
560
734
  set addressType(addressType) {
561
735
  this._addressType = addressType;
562
736
  }
@@ -584,9 +758,17 @@ var TrezorSigner = class _TrezorSigner {
584
758
  }
585
759
  return addresses;
586
760
  }
761
+ /**
762
+ * @param {number} bundleSize - Number of change addresses to derive.
763
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
764
+ */
587
765
  async getChangeAddresses(bundleSize) {
588
766
  return this.getAddresses(bundleSize, true);
589
767
  }
768
+ /**
769
+ * @param {number} bundleSize - Number of receive addresses to derive.
770
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
771
+ */
590
772
  async getNonChangeAddresses(bundleSize) {
591
773
  return this.getAddresses(bundleSize);
592
774
  }
@@ -614,8 +796,23 @@ var TrezorSigner = class _TrezorSigner {
614
796
  };
615
797
  });
616
798
  }
799
+ getOutputScriptType(address2) {
800
+ const addressType = getAddressType(address2, this.network);
801
+ switch (addressType) {
802
+ case "SEGWIT":
803
+ return "PAYTOP2SHWITNESS";
804
+ case "NATIVE SEGWIT":
805
+ return "PAYTOWITNESS";
806
+ default:
807
+ return "PAYTOADDRESS";
808
+ }
809
+ }
810
+ isChangePath(path) {
811
+ return path.length === 5 && path[3] === 1;
812
+ }
617
813
  getOutputs(psbt) {
618
- return psbt.txOutputs.map((output) => {
814
+ const lastIndex = psbt.txOutputs.length - 1;
815
+ return psbt.txOutputs.map((output, index) => {
619
816
  if (output.value === 0 && !output.address) {
620
817
  return {
621
818
  amount: output.value,
@@ -623,6 +820,14 @@ var TrezorSigner = class _TrezorSigner {
623
820
  script_type: "PAYTOOPRETURN"
624
821
  };
625
822
  }
823
+ const path = output.address ? this.addresses.get(output.address) : void 0;
824
+ if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
825
+ return {
826
+ address_n: path,
827
+ script_type: this.getOutputScriptType(output.address),
828
+ amount: output.value
829
+ };
830
+ }
626
831
  return {
627
832
  address: output.address ?? "",
628
833
  script_type: "PAYTOADDRESS",
@@ -630,7 +835,14 @@ var TrezorSigner = class _TrezorSigner {
630
835
  };
631
836
  });
632
837
  }
838
+ /**
839
+ * Signs the given PSBT's inputs/outputs on the Trezor device.
840
+ * @param {Psbt} psbt - The PSBT to sign.
841
+ * @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.
842
+ * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
843
+ */
633
844
  async signTransaction(psbt, utxos) {
845
+ assertTruthy2(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
634
846
  const inputs = this.getInputs(utxos);
635
847
  const outputs = this.getOutputs(psbt);
636
848
  const result = await TrezorConnect.signTransaction({
@@ -649,6 +861,7 @@ var TrezorSigner = class _TrezorSigner {
649
861
  // src/bitcoin-signers/ledger/ledger.ts
650
862
  import Btc from "@ledgerhq/hw-app-btc";
651
863
  import TransportWebUSB from "@ledgerhq/hw-transport-webusb";
864
+ import { assertTruthy as assertTruthy3 } from "@rsksmart/bridges-core-sdk";
652
865
  import { Transaction as Transaction2 } from "bitcoinjs-lib";
653
866
 
654
867
  // src/bitcoin-signers/ledger/ledger-transport.ts
@@ -704,17 +917,27 @@ var LedgerSigner = class _LedgerSigner {
704
917
  }
705
918
  addresses = /* @__PURE__ */ new Map();
706
919
  transportService;
920
+ /**
921
+ * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
922
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
923
+ * @returns {Promise<LedgerSigner>} The initialized signer.
924
+ */
707
925
  static async init(network = "TEST") {
708
926
  const transport = await TransportWebUSB.create();
709
927
  const connection = new Btc({ transport, currency: networks[network].currency });
710
928
  return new _LedgerSigner(connection, transport, network);
711
929
  }
930
+ /**
931
+ * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
932
+ * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
933
+ */
712
934
  async reinit() {
713
935
  return this.transportService.enqueue(async () => {
714
936
  await this.transport.close();
715
937
  return _LedgerSigner.init();
716
938
  });
717
939
  }
940
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
718
941
  set addressType(addressType) {
719
942
  this._addressType = addressType;
720
943
  }
@@ -752,9 +975,17 @@ var LedgerSigner = class _LedgerSigner {
752
975
  return addresses;
753
976
  });
754
977
  }
978
+ /**
979
+ * @param {number} bundleSize - Number of change addresses to derive.
980
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
981
+ */
755
982
  async getChangeAddresses(bundleSize) {
756
983
  return this.getAddresses(bundleSize, true);
757
984
  }
985
+ /**
986
+ * @param {number} bundleSize - Number of receive addresses to derive.
987
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
988
+ */
758
989
  async getNonChangeAddresses(bundleSize) {
759
990
  return this.getAddresses(bundleSize);
760
991
  }
@@ -766,6 +997,21 @@ var LedgerSigner = class _LedgerSigner {
766
997
  return [deserializedTx, input.vout, void 0, void 0];
767
998
  });
768
999
  }
1000
+ isChangePath(path) {
1001
+ const segments = path.split("/");
1002
+ return segments.length === 6 && segments[4] === "1";
1003
+ }
1004
+ getChangePath(psbt) {
1005
+ if (psbt.txOutputs.length < 2) {
1006
+ return void 0;
1007
+ }
1008
+ const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
1009
+ if (!lastOutput.address) {
1010
+ return void 0;
1011
+ }
1012
+ const path = this.addresses.get(lastOutput.address);
1013
+ return path && this.isChangePath(path) ? path : void 0;
1014
+ }
769
1015
  getOutputScriptHex(psbt) {
770
1016
  const outputs = psbt.txOutputs.map((output) => {
771
1017
  const amount = Buffer.alloc(8);
@@ -777,15 +1023,28 @@ var LedgerSigner = class _LedgerSigner {
777
1023
  });
778
1024
  return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
779
1025
  }
1026
+ /**
1027
+ * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
1028
+ * @param {Psbt} psbt - The PSBT to sign.
1029
+ * @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.
1030
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
1031
+ * @returns {Promise<string>} The signed, serialized transaction.
1032
+ */
780
1033
  async signTransaction(psbt, inputs, transactions) {
1034
+ assertTruthy3(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
1035
+ assertTruthy3(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
781
1036
  return this.transportService.enqueue(async () => {
782
1037
  const ledgerInputs = this.getInputs(inputs, transactions);
783
1038
  const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
784
1039
  const outputScriptHex = this.getOutputScriptHex(psbt);
1040
+ const changePath = this.getChangePath(psbt);
785
1041
  return this.connection.createPaymentTransaction({
786
1042
  inputs: ledgerInputs,
787
1043
  associatedKeysets: paths,
788
1044
  outputScriptHex,
1045
+ // hw-app-btc throws if changePath matches no output, so omit it
1046
+ // when the transaction has no device-derived change output
1047
+ ...changePath ? { changePath } : {},
789
1048
  segwit: this.isSegwit(),
790
1049
  useTrustedInputForSegwit: this.isSegwit(),
791
1050
  additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
@@ -796,6 +1055,7 @@ var LedgerSigner = class _LedgerSigner {
796
1055
  export {
797
1056
  APIError,
798
1057
  AmountBelowMinError,
1058
+ FederationAddressError,
799
1059
  InvalidAddressError,
800
1060
  LedgerSigner,
801
1061
  NotEnoughFundsError,
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. |
@@ -0,0 +1,36 @@
1
+ # Bitcoin signers
2
+
3
+ `PowPegSDK` doesn't sign transactions itself — it delegates address derivation and PSBT signing to a `BitcoinSigner`, so any Bitcoin key-management backend (hardware wallet, custom key store, etc.) can be plugged in.
4
+
5
+ ## The contract
6
+
7
+ Defined in [`src/types.ts`](../src/types.ts):
8
+
9
+ ```ts
10
+ export interface BitcoinSigner {
11
+ getNonChangeAddresses(bundleSize: number): Promise<string[]>
12
+ getChangeAddresses(bundleSize: number): Promise<string[]>
13
+ signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise<string>
14
+ }
15
+ ```
16
+
17
+ - `getNonChangeAddresses` / `getChangeAddresses` — derive `bundleSize` receive/change addresses the signer controls. `PowPegSDK` uses these to find funded addresses and an unused refund/change address.
18
+ - `signTransaction` — signs a peg-in PSBT and returns the serialized signed transaction. `inputs`/`transactions` carry the UTXOs being spent and their raw hex, for signers (like Ledger) that need to verify each input.
19
+
20
+ ## Existing implementations
21
+
22
+ | Implementation | Location | Description |
23
+ |---|---|---|
24
+ | `TrezorSigner` | [`src/bitcoin-signers/trezor/trezor.ts`](../src/bitcoin-signers/trezor/trezor.ts) | Backed by a Trezor hardware wallet, connected via `@trezor/connect-web`. Initialized with the async `TrezorSigner.init(network?)` factory (constructor is private). |
25
+ | `LedgerSigner` | [`src/bitcoin-signers/ledger/ledger.ts`](../src/bitcoin-signers/ledger/ledger.ts) | Backed by a Ledger hardware wallet, connected over WebUSB (`@ledgerhq/hw-transport-webusb`). Initialized with the async `LedgerSigner.init(network?)` factory. Queues device operations through `LedgerTransportService` so only one runs against the transport at a time. |
26
+
27
+ Both support `'LEGACY'`, `'SEGWIT'` and `'NATIVE SEGWIT'` address types via their `addressType` getter/setter (see `supportedAddressTypes` and `networks` in [`src/constants.ts`](../src/constants.ts) for the derivation paths and network params behind each).
28
+
29
+ ## Adding a new signer
30
+
31
+ Following the pattern of the two existing implementations:
32
+
33
+ 1. Create a new file under `src/bitcoin-signers/<name>/<name>.ts` implementing `BitcoinSigner`.
34
+ 2. Keep vendor SDK/transport specifics (e.g. a hardware wallet's connection library) private to the class; expose only what the `BitcoinSigner` contract requires plus any signer-specific setup (e.g. an async `init` factory, as both existing signers do, if construction needs to await a connection).
35
+ 3. Pass an instance to `PowPegSDK`'s constructor (as `_bitcoinSigner`) or to `createAndFundPegin(...)`'s `signer` argument.
36
+ 4. Re-export the new class from [`src/index.ts`](../src/index.ts) if it's meant to be part of the public package surface.