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

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,17 +518,32 @@ 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);
440
- if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
534
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
535
+ const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
536
+ const initialInputCount = psbt.txInputs.length;
537
+ const initialOutputCount = psbt.txOutputs.length;
538
+ const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
539
+ if (addChange) {
441
540
  psbt.addOutput({
442
- address: this.changeAddress ?? inputs[0].address,
541
+ // Fall back to the first funding input's address when every derived
542
+ // change address has already been used.
543
+ address: funding.changeAddress ?? inputs[0].address,
443
544
  value: change
444
545
  });
445
546
  }
446
- const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
447
547
  inputs.forEach((input, index) => {
448
548
  const transaction = Transaction.fromHex(hexTransactions[index]);
449
549
  psbt.addInput({
@@ -455,26 +555,58 @@ var PowPegSDK = class {
455
555
  }
456
556
  });
457
557
  });
558
+ const expectedInputCount = initialInputCount + inputs.length;
559
+ const expectedOutputCount = initialOutputCount + (addChange ? 1 : 0);
560
+ assertTruthy(
561
+ psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
562
+ `Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
563
+ );
564
+ this.funding.delete(psbt);
458
565
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
459
566
  }
567
+ /**
568
+ * Convenience method that creates and funds a peg-in PSBT in one call.
569
+ * @param {bigint} amount - Amount to peg in, in satoshis.
570
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
571
+ * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
572
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
573
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
574
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
575
+ */
460
576
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
461
577
  this.bitcoinSigner = signer;
462
578
  this.validatePeginAmount(amount);
463
579
  const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
464
580
  return this.fundPegin(psbt, feeLevel);
465
581
  }
582
+ /**
583
+ * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
584
+ * without routing through the federation address (unlike {@link createPegin}).
585
+ * @param {bigint} amount - Amount to send, in satoshis.
586
+ * @param {string} recipientAddress - Bitcoin address to receive the payment.
587
+ * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
588
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
589
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
590
+ */
466
591
  async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
467
592
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
468
593
  psbt.addOutput({
469
594
  address: recipientAddress,
470
595
  value: Number(amount)
471
596
  });
472
- this.utxos = utxos;
597
+ this.funding.set(psbt, { utxos: [...utxos] });
473
598
  return this.fundPegin(psbt, feeLevel, amount);
474
599
  }
475
600
  async signPegin(psbt, inputs, transactions) {
476
601
  return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
477
602
  }
603
+ /**
604
+ * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
605
+ * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
606
+ * @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.
607
+ * @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.
608
+ * @returns {Promise<string>} The broadcast transaction's ID.
609
+ */
478
610
  async signAndBroadcastPegin(psbt, inputs, transactions) {
479
611
  const signedTx = await this.signPegin(psbt, inputs, transactions);
480
612
  return this.bitcoinDataSource.broadcast(signedTx);
@@ -494,6 +626,12 @@ var PowPegSDK = class {
494
626
  value: amountBN.toString()
495
627
  };
496
628
  }
629
+ /**
630
+ * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
631
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
632
+ * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
633
+ * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
634
+ */
497
635
  async estimatePegoutFees(amount, fromAddress = ethers3.constants.AddressZero) {
498
636
  this.validateMinimumPegoutAmount(amount);
499
637
  const tx = this.createPegoutTransaction(amount, fromAddress);
@@ -508,6 +646,14 @@ var PowPegSDK = class {
508
646
  rootstockFee
509
647
  };
510
648
  }
649
+ /**
650
+ * Validates the requested amount and the sender's balance, then builds an unsigned peg-out
651
+ * transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
652
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
653
+ * @param {string} senderAccount - Rootstock address that will send the peg-out.
654
+ * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
655
+ * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
656
+ */
511
657
  async createPegout(amount, senderAccount) {
512
658
  const fees = await this.estimatePegoutFees(amount, senderAccount);
513
659
  const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
@@ -522,13 +668,39 @@ var PowPegSDK = class {
522
668
  bitcoinFee: fees.bitcoinFee
523
669
  };
524
670
  }
671
+ /**
672
+ * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
673
+ * and waits for it to be mined.
674
+ * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
675
+ * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
676
+ * @returns The mined transaction receipt, if the signer's provider is set.
677
+ */
525
678
  async signAndBroadcastPegout(tx, signer) {
526
679
  const { hash } = await signer.sendTransaction(tx);
527
680
  return signer.provider?.waitForTransaction(hash);
528
681
  }
682
+ /**
683
+ * Fetches the current status of a peg-in or peg-out transaction from the configured API.
684
+ * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
685
+ * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
686
+ * @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
687
+ */
529
688
  async getTransactionStatus(txHash, txType) {
530
689
  return this.api.getTransactionStatus(txHash, txType);
531
690
  }
691
+ /**
692
+ * Retrieves the feature flags from the 2WP API `/features` endpoint.
693
+ * @returns {Promise<Feature[]>} The feature flags as returned by the API.
694
+ */
695
+ async getFeatures() {
696
+ return this.api.getFeatures();
697
+ }
698
+ /**
699
+ * Returns the spendable UTXOs for the given Bitcoin address(es).
700
+ * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
701
+ * @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
702
+ * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
703
+ */
532
704
  async getAvailableUtxos(addresses) {
533
705
  const addressList = Array.isArray(addresses) ? addresses : [addresses];
534
706
  const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
@@ -541,6 +713,7 @@ var PowPegSDK = class {
541
713
 
542
714
  // src/bitcoin-signers/trezor/trezor.ts
543
715
  import TrezorConnect from "@trezor/connect-web";
716
+ import { assertTruthy as assertTruthy2 } from "@rsksmart/bridges-core-sdk";
544
717
  import "bitcoinjs-lib";
545
718
  var TrezorSigner = class _TrezorSigner {
546
719
  constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
@@ -549,14 +722,25 @@ var TrezorSigner = class _TrezorSigner {
549
722
  }
550
723
  bitcoinTxVersion = 1;
551
724
  addresses = /* @__PURE__ */ new Map();
725
+ /**
726
+ * Initializes the Trezor connection and returns a ready-to-use signer.
727
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
728
+ * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
729
+ * @returns {Promise<TrezorSigner>} The initialized signer.
730
+ */
552
731
  static async init(network, initOptions) {
553
732
  await TrezorConnect.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
554
733
  return new _TrezorSigner(network);
555
734
  }
735
+ /**
736
+ * Disposes the current Trezor connection and re-initializes it.
737
+ * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
738
+ */
556
739
  static async reinit() {
557
740
  TrezorConnect.dispose();
558
741
  return _TrezorSigner.init();
559
742
  }
743
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
560
744
  set addressType(addressType) {
561
745
  this._addressType = addressType;
562
746
  }
@@ -584,9 +768,17 @@ var TrezorSigner = class _TrezorSigner {
584
768
  }
585
769
  return addresses;
586
770
  }
771
+ /**
772
+ * @param {number} bundleSize - Number of change addresses to derive.
773
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
774
+ */
587
775
  async getChangeAddresses(bundleSize) {
588
776
  return this.getAddresses(bundleSize, true);
589
777
  }
778
+ /**
779
+ * @param {number} bundleSize - Number of receive addresses to derive.
780
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
781
+ */
590
782
  async getNonChangeAddresses(bundleSize) {
591
783
  return this.getAddresses(bundleSize);
592
784
  }
@@ -614,8 +806,23 @@ var TrezorSigner = class _TrezorSigner {
614
806
  };
615
807
  });
616
808
  }
809
+ getOutputScriptType(address2) {
810
+ const addressType = getAddressType(address2, this.network);
811
+ switch (addressType) {
812
+ case "SEGWIT":
813
+ return "PAYTOP2SHWITNESS";
814
+ case "NATIVE SEGWIT":
815
+ return "PAYTOWITNESS";
816
+ default:
817
+ return "PAYTOADDRESS";
818
+ }
819
+ }
820
+ isChangePath(path) {
821
+ return path.length === 5 && path[3] === 1;
822
+ }
617
823
  getOutputs(psbt) {
618
- return psbt.txOutputs.map((output) => {
824
+ const lastIndex = psbt.txOutputs.length - 1;
825
+ return psbt.txOutputs.map((output, index) => {
619
826
  if (output.value === 0 && !output.address) {
620
827
  return {
621
828
  amount: output.value,
@@ -623,6 +830,14 @@ var TrezorSigner = class _TrezorSigner {
623
830
  script_type: "PAYTOOPRETURN"
624
831
  };
625
832
  }
833
+ const path = output.address ? this.addresses.get(output.address) : void 0;
834
+ if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
835
+ return {
836
+ address_n: path,
837
+ script_type: this.getOutputScriptType(output.address),
838
+ amount: output.value
839
+ };
840
+ }
626
841
  return {
627
842
  address: output.address ?? "",
628
843
  script_type: "PAYTOADDRESS",
@@ -630,7 +845,14 @@ var TrezorSigner = class _TrezorSigner {
630
845
  };
631
846
  });
632
847
  }
848
+ /**
849
+ * Signs the given PSBT's inputs/outputs on the Trezor device.
850
+ * @param {Psbt} psbt - The PSBT to sign.
851
+ * @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.
852
+ * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
853
+ */
633
854
  async signTransaction(psbt, utxos) {
855
+ assertTruthy2(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
634
856
  const inputs = this.getInputs(utxos);
635
857
  const outputs = this.getOutputs(psbt);
636
858
  const result = await TrezorConnect.signTransaction({
@@ -649,6 +871,7 @@ var TrezorSigner = class _TrezorSigner {
649
871
  // src/bitcoin-signers/ledger/ledger.ts
650
872
  import Btc from "@ledgerhq/hw-app-btc";
651
873
  import TransportWebUSB from "@ledgerhq/hw-transport-webusb";
874
+ import { assertTruthy as assertTruthy3 } from "@rsksmart/bridges-core-sdk";
652
875
  import { Transaction as Transaction2 } from "bitcoinjs-lib";
653
876
 
654
877
  // src/bitcoin-signers/ledger/ledger-transport.ts
@@ -704,17 +927,27 @@ var LedgerSigner = class _LedgerSigner {
704
927
  }
705
928
  addresses = /* @__PURE__ */ new Map();
706
929
  transportService;
930
+ /**
931
+ * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
932
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
933
+ * @returns {Promise<LedgerSigner>} The initialized signer.
934
+ */
707
935
  static async init(network = "TEST") {
708
936
  const transport = await TransportWebUSB.create();
709
937
  const connection = new Btc({ transport, currency: networks[network].currency });
710
938
  return new _LedgerSigner(connection, transport, network);
711
939
  }
940
+ /**
941
+ * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
942
+ * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
943
+ */
712
944
  async reinit() {
713
945
  return this.transportService.enqueue(async () => {
714
946
  await this.transport.close();
715
947
  return _LedgerSigner.init();
716
948
  });
717
949
  }
950
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
718
951
  set addressType(addressType) {
719
952
  this._addressType = addressType;
720
953
  }
@@ -752,9 +985,17 @@ var LedgerSigner = class _LedgerSigner {
752
985
  return addresses;
753
986
  });
754
987
  }
988
+ /**
989
+ * @param {number} bundleSize - Number of change addresses to derive.
990
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
991
+ */
755
992
  async getChangeAddresses(bundleSize) {
756
993
  return this.getAddresses(bundleSize, true);
757
994
  }
995
+ /**
996
+ * @param {number} bundleSize - Number of receive addresses to derive.
997
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
998
+ */
758
999
  async getNonChangeAddresses(bundleSize) {
759
1000
  return this.getAddresses(bundleSize);
760
1001
  }
@@ -766,6 +1007,21 @@ var LedgerSigner = class _LedgerSigner {
766
1007
  return [deserializedTx, input.vout, void 0, void 0];
767
1008
  });
768
1009
  }
1010
+ isChangePath(path) {
1011
+ const segments = path.split("/");
1012
+ return segments.length === 6 && segments[4] === "1";
1013
+ }
1014
+ getChangePath(psbt) {
1015
+ if (psbt.txOutputs.length < 2) {
1016
+ return void 0;
1017
+ }
1018
+ const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
1019
+ if (!lastOutput.address) {
1020
+ return void 0;
1021
+ }
1022
+ const path = this.addresses.get(lastOutput.address);
1023
+ return path && this.isChangePath(path) ? path : void 0;
1024
+ }
769
1025
  getOutputScriptHex(psbt) {
770
1026
  const outputs = psbt.txOutputs.map((output) => {
771
1027
  const amount = Buffer.alloc(8);
@@ -777,15 +1033,28 @@ var LedgerSigner = class _LedgerSigner {
777
1033
  });
778
1034
  return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
779
1035
  }
1036
+ /**
1037
+ * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
1038
+ * @param {Psbt} psbt - The PSBT to sign.
1039
+ * @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.
1040
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
1041
+ * @returns {Promise<string>} The signed, serialized transaction.
1042
+ */
780
1043
  async signTransaction(psbt, inputs, transactions) {
1044
+ assertTruthy3(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
1045
+ assertTruthy3(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
781
1046
  return this.transportService.enqueue(async () => {
782
1047
  const ledgerInputs = this.getInputs(inputs, transactions);
783
1048
  const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
784
1049
  const outputScriptHex = this.getOutputScriptHex(psbt);
1050
+ const changePath = this.getChangePath(psbt);
785
1051
  return this.connection.createPaymentTransaction({
786
1052
  inputs: ledgerInputs,
787
1053
  associatedKeysets: paths,
788
1054
  outputScriptHex,
1055
+ // hw-app-btc throws if changePath matches no output, so omit it
1056
+ // when the transaction has no device-derived change output
1057
+ ...changePath ? { changePath } : {},
789
1058
  segwit: this.isSegwit(),
790
1059
  useTrustedInputForSegwit: this.isSegwit(),
791
1060
  additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
@@ -796,6 +1065,7 @@ var LedgerSigner = class _LedgerSigner {
796
1065
  export {
797
1066
  APIError,
798
1067
  AmountBelowMinError,
1068
+ FederationAddressError,
799
1069
  InvalidAddressError,
800
1070
  LedgerSigner,
801
1071
  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. |