@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.js CHANGED
@@ -32,6 +32,7 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  APIError: () => APIError,
34
34
  AmountBelowMinError: () => AmountBelowMinError,
35
+ FederationAddressError: () => FederationAddressError,
35
36
  InvalidAddressError: () => InvalidAddressError,
36
37
  LedgerSigner: () => LedgerSigner,
37
38
  NotEnoughFundsError: () => NotEnoughFundsError,
@@ -222,6 +223,12 @@ var APIError = class extends Error {
222
223
  this.data = data;
223
224
  }
224
225
  };
226
+ var FederationAddressError = class extends Error {
227
+ constructor(message) {
228
+ super(message);
229
+ this.name = "FederationAddressError";
230
+ }
231
+ };
225
232
  var InvalidAddressError = class extends Error {
226
233
  invalidAddresses;
227
234
  constructor(invalidAddresses, message) {
@@ -239,6 +246,7 @@ var ApiService = class {
239
246
  MAIN: "https://api.2wp.rootstock.io",
240
247
  TEST: "https://api.2wp.testnet.rootstock.io"
241
248
  };
249
+ maxFeeRateSatPerByte = 1e3;
242
250
  feeLevelBlocks = {
243
251
  slow: 5,
244
252
  average: 3,
@@ -267,8 +275,19 @@ var ApiService = class {
267
275
  async getFeeRate(level) {
268
276
  const blocks = this.feeLevelBlocks[level];
269
277
  const response = await this.api.get(`/estimate-fee/${blocks}`).catch(this.handleError);
270
- const rate = import_bridges_core_sdk3.ethers.utils.parseUnits(response.data.amount, 8).div(1e3).toNumber();
271
- return rate;
278
+ let satoshisPerKb;
279
+ try {
280
+ satoshisPerKb = import_bridges_core_sdk3.ethers.utils.parseUnits(String(response.data.amount), 8);
281
+ } catch {
282
+ throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
283
+ }
284
+ if (satoshisPerKb.lte(0)) {
285
+ throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
286
+ }
287
+ if (satoshisPerKb.gt(this.maxFeeRateSatPerByte * 1e3)) {
288
+ throw new APIError(`Fee rate out of bounds: ${response.data.amount}`);
289
+ }
290
+ return satoshisPerKb.add(999).div(1e3).toNumber();
272
291
  }
273
292
  async getTxHex(txId) {
274
293
  const response = await this.api.get(`/tx?tx=${txId}`).catch(this.handleError);
@@ -277,8 +296,8 @@ var ApiService = class {
277
296
  async getOutputs(address2) {
278
297
  const response = await this.api.post("/utxo", { addressList: [address2] }).catch(this.handleError);
279
298
  const { data: utxos } = response.data;
280
- return utxos.map(({ address: address3, txid, vout, satoshis }) => ({
281
- address: address3,
299
+ return utxos.map(({ txid, vout, satoshis }) => ({
300
+ address: address2,
282
301
  txid,
283
302
  amount: BigInt(satoshis),
284
303
  vout
@@ -288,7 +307,7 @@ var ApiService = class {
288
307
  const response = await this.api.post("/addresses-info", { addressList: [address2] }).catch(this.handleError);
289
308
  const [details] = response.data.addressesInfo;
290
309
  return {
291
- address: details.address,
310
+ address: address2,
292
311
  balance: details.balance,
293
312
  txCount: details.txs
294
313
  };
@@ -301,6 +320,14 @@ var ApiService = class {
301
320
  const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
302
321
  return response.data;
303
322
  }
323
+ async getPeginConfiguration() {
324
+ const response = await this.api.get("/pegin-configuration").catch(this.handleError);
325
+ return response.data;
326
+ }
327
+ async getFeatures() {
328
+ const response = await this.api.get("/features").catch(this.handleError);
329
+ return response.data;
330
+ }
304
331
  };
305
332
 
306
333
  // src/sdk/powpeg.ts
@@ -332,8 +359,7 @@ var PowPegSDK = class {
332
359
  pegInOutputs = 3;
333
360
  powpegRsktHeader = "52534b5401";
334
361
  burnDustMaxValue = 3e4;
335
- utxos = [];
336
- changeAddress;
362
+ funding = /* @__PURE__ */ new WeakMap();
337
363
  minPeginAmount = 500000n;
338
364
  peginFeeEstimationInputs = 2;
339
365
  minPegoutAmount = "0.004";
@@ -358,7 +384,18 @@ var PowPegSDK = class {
358
384
  async getUtxos(addresses) {
359
385
  const rawAddresses = addresses.map((address2) => typeof address2 === "string" ? address2 : address2.address);
360
386
  const utxoLists = await Promise.all(rawAddresses.map((address2) => this.bitcoinDataSource.getOutputs(address2)));
361
- return utxoLists.flat();
387
+ const allUtxos = utxoLists.flat();
388
+ const seen = /* @__PURE__ */ new Set();
389
+ const uniqueUtxos = allUtxos.filter((utxo) => {
390
+ const key = `${utxo.txid}:${utxo.vout}`;
391
+ if (seen.has(key)) {
392
+ console.warn(`[PowPegSDK] Duplicate UTXO detected and skipped: ${key}`);
393
+ return false;
394
+ }
395
+ seen.add(key);
396
+ return true;
397
+ });
398
+ return uniqueUtxos;
362
399
  }
363
400
  async getAddressesWithDetails(addresses) {
364
401
  return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
@@ -399,8 +436,31 @@ var PowPegSDK = class {
399
436
  change: this.groupAddressesByUsage(changeDetails)
400
437
  };
401
438
  }
439
+ validateRskRecipient(recipientAddress) {
440
+ const trimmed = recipientAddress.trim();
441
+ if (!/^(0x)?[0-9a-fA-F]{40}$/.test(trimmed)) {
442
+ throw new InvalidAddressError([recipientAddress], `Invalid Rootstock recipient: ${recipientAddress}`);
443
+ }
444
+ return trimmed.toLowerCase();
445
+ }
446
+ async getVerifiedFederationAddress() {
447
+ const [bridgeAddress, peginConfiguration] = await Promise.all([
448
+ this.bridge.getFederationAddress().catch((error) => {
449
+ const reason = error instanceof Error ? error.message : String(error);
450
+ throw new FederationAddressError(`Could not retrieve the federation address from the Bridge contract: ${reason}`);
451
+ }),
452
+ this.api.getPeginConfiguration().catch((error) => {
453
+ const reason = error instanceof Error ? error.message : String(error);
454
+ throw new FederationAddressError(`Could not retrieve the pegin configuration: ${reason}`);
455
+ })
456
+ ]);
457
+ if (peginConfiguration.federationAddress !== bridgeAddress) {
458
+ throw new FederationAddressError("Federation address mismatch between the Bridge contract and the pegin configuration.");
459
+ }
460
+ return bridgeAddress;
461
+ }
402
462
  getRskOutput(recipientAddress, refundAddress) {
403
- let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
463
+ let output = `${this.powpegRsktHeader}${remove0x(this.validateRskRecipient(recipientAddress))}`;
404
464
  if (refundAddress) {
405
465
  const refundAddressType = getAddressType(refundAddress, this.network);
406
466
  const prefixes = {
@@ -414,12 +474,33 @@ var PowPegSDK = class {
414
474
  }
415
475
  return Buffer.from(output, "hex");
416
476
  }
417
- async estimatePeginFee(amount, feeLevel = "fast") {
477
+ /**
478
+ * Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
479
+ * @param {bigint} amount - Amount to peg in, in satoshis.
480
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
481
+ * @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
482
+ * same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
483
+ * @returns {Promise<number>} The estimated total fee in satoshis.
484
+ */
485
+ async estimatePeginFee(amount, feeLevel = "fast", utxos) {
418
486
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
487
+ if (utxos) {
488
+ const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
489
+ return totalFee2;
490
+ }
419
491
  const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
420
492
  const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
421
493
  return totalFee;
422
494
  }
495
+ /**
496
+ * Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
497
+ * encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
498
+ * Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction.
499
+ * @param {bigint} amount - Amount to peg in, in satoshis.
500
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
501
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
502
+ * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
503
+ */
423
504
  async createPegin(amount, recipientAddress, selectedUtxos) {
424
505
  const addresses = await this.getAddressesGroupedByUsage();
425
506
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
@@ -431,31 +512,36 @@ var PowPegSDK = class {
431
512
  value: 0
432
513
  });
433
514
  }
434
- const bridgeAddress = await this.bridge.getFederationAddress();
515
+ const bridgeAddress = await this.getVerifiedFederationAddress();
435
516
  psbt.addOutput({
436
517
  address: bridgeAddress,
437
518
  value: Number(amount)
438
519
  });
520
+ let utxos;
439
521
  if (selectedUtxos) {
440
- this.utxos = selectedUtxos;
522
+ utxos = [...selectedUtxos];
441
523
  } else {
442
524
  const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
443
525
  const { withBalance } = this.groupAddressesByBalance(usedAddresses);
444
- this.utxos = await this.getUtxos(withBalance);
526
+ utxos = await this.getUtxos(withBalance);
445
527
  }
446
- this.changeAddress = addresses.change.unused[0]?.address;
528
+ this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
447
529
  return psbt;
448
530
  }
449
531
  selectInputs(amount, utxos, baseFee, feePerInput) {
450
532
  const inputs = [];
451
533
  let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
452
- utxos.sort((a, b) => a.amount < b.amount ? -1 : a.amount > b.amount ? 1 : 0);
453
- utxos.forEach((utxo) => {
454
- if (remainingSatoshisToBePaid > 0) {
455
- inputs.push(utxo);
456
- remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
534
+ const candidates = [...utxos].sort((a, b) => Number(b.amount - a.amount));
535
+ for (const utxo of candidates) {
536
+ if (remainingSatoshisToBePaid <= 0) {
537
+ break;
457
538
  }
458
- });
539
+ if (BigInt(utxo.amount) <= BigInt(feePerInput)) {
540
+ continue;
541
+ }
542
+ inputs.push(utxo);
543
+ remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
544
+ }
459
545
  return { inputs, rest: Number(remainingSatoshisToBePaid) };
460
546
  }
461
547
  validatePeginAmount(amount) {
@@ -479,17 +565,32 @@ var PowPegSDK = class {
479
565
  const totalFee = baseFee + feePerInput * inputs.length;
480
566
  return { inputs, change: Math.abs(rest), totalFee };
481
567
  }
568
+ /**
569
+ * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
570
+ * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
571
+ * @param {Psbt} psbt - The peg-in PSBT to fund.
572
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
573
+ * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
574
+ * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
575
+ */
482
576
  async fundPegin(psbt, feeLevel = "fast", value) {
577
+ const funding = this.funding.get(psbt);
578
+ (0, import_bridges_core_sdk4.assertTruthy)(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
483
579
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
484
580
  const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
485
- const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, this.utxos, feeRate);
486
- if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
581
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
582
+ const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
583
+ const initialInputCount = psbt.txInputs.length;
584
+ const initialOutputCount = psbt.txOutputs.length;
585
+ const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
586
+ if (addChange) {
487
587
  psbt.addOutput({
488
- address: this.changeAddress ?? inputs[0].address,
588
+ // Fall back to the first funding input's address when every derived
589
+ // change address has already been used.
590
+ address: funding.changeAddress ?? inputs[0].address,
489
591
  value: change
490
592
  });
491
593
  }
492
- const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
493
594
  inputs.forEach((input, index) => {
494
595
  const transaction = import_bitcoinjs_lib4.Transaction.fromHex(hexTransactions[index]);
495
596
  psbt.addInput({
@@ -501,26 +602,58 @@ var PowPegSDK = class {
501
602
  }
502
603
  });
503
604
  });
605
+ const expectedInputCount = initialInputCount + inputs.length;
606
+ const expectedOutputCount = initialOutputCount + (addChange ? 1 : 0);
607
+ (0, import_bridges_core_sdk4.assertTruthy)(
608
+ psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
609
+ `Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
610
+ );
611
+ this.funding.delete(psbt);
504
612
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
505
613
  }
614
+ /**
615
+ * Convenience method that creates and funds a peg-in PSBT in one call.
616
+ * @param {bigint} amount - Amount to peg in, in satoshis.
617
+ * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
618
+ * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
619
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
620
+ * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
621
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
622
+ */
506
623
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
507
624
  this.bitcoinSigner = signer;
508
625
  this.validatePeginAmount(amount);
509
626
  const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
510
627
  return this.fundPegin(psbt, feeLevel);
511
628
  }
629
+ /**
630
+ * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
631
+ * without routing through the federation address (unlike {@link createPegin}).
632
+ * @param {bigint} amount - Amount to send, in satoshis.
633
+ * @param {string} recipientAddress - Bitcoin address to receive the payment.
634
+ * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
635
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
636
+ * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
637
+ */
512
638
  async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
513
639
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
514
640
  psbt.addOutput({
515
641
  address: recipientAddress,
516
642
  value: Number(amount)
517
643
  });
518
- this.utxos = utxos;
644
+ this.funding.set(psbt, { utxos: [...utxos] });
519
645
  return this.fundPegin(psbt, feeLevel, amount);
520
646
  }
521
647
  async signPegin(psbt, inputs, transactions) {
522
648
  return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
523
649
  }
650
+ /**
651
+ * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
652
+ * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
653
+ * @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.
654
+ * @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.
655
+ * @returns {Promise<string>} The broadcast transaction's ID.
656
+ */
524
657
  async signAndBroadcastPegin(psbt, inputs, transactions) {
525
658
  const signedTx = await this.signPegin(psbt, inputs, transactions);
526
659
  return this.bitcoinDataSource.broadcast(signedTx);
@@ -540,6 +673,12 @@ var PowPegSDK = class {
540
673
  value: amountBN.toString()
541
674
  };
542
675
  }
676
+ /**
677
+ * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
678
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
679
+ * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
680
+ * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
681
+ */
543
682
  async estimatePegoutFees(amount, fromAddress = import_bridges_core_sdk4.ethers.constants.AddressZero) {
544
683
  this.validateMinimumPegoutAmount(amount);
545
684
  const tx = this.createPegoutTransaction(amount, fromAddress);
@@ -554,6 +693,14 @@ var PowPegSDK = class {
554
693
  rootstockFee
555
694
  };
556
695
  }
696
+ /**
697
+ * Validates the requested amount and the sender's balance, then builds an unsigned peg-out
698
+ * transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
699
+ * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
700
+ * @param {string} senderAccount - Rootstock address that will send the peg-out.
701
+ * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
702
+ * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
703
+ */
557
704
  async createPegout(amount, senderAccount) {
558
705
  const fees = await this.estimatePegoutFees(amount, senderAccount);
559
706
  const amountBN = import_bridges_core_sdk4.ethers.utils.parseUnits(amount, 18).toBigInt();
@@ -568,13 +715,39 @@ var PowPegSDK = class {
568
715
  bitcoinFee: fees.bitcoinFee
569
716
  };
570
717
  }
718
+ /**
719
+ * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
720
+ * and waits for it to be mined.
721
+ * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
722
+ * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
723
+ * @returns The mined transaction receipt, if the signer's provider is set.
724
+ */
571
725
  async signAndBroadcastPegout(tx, signer) {
572
726
  const { hash } = await signer.sendTransaction(tx);
573
727
  return signer.provider?.waitForTransaction(hash);
574
728
  }
729
+ /**
730
+ * Fetches the current status of a peg-in or peg-out transaction from the configured API.
731
+ * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
732
+ * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
733
+ * @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
734
+ */
575
735
  async getTransactionStatus(txHash, txType) {
576
736
  return this.api.getTransactionStatus(txHash, txType);
577
737
  }
738
+ /**
739
+ * Retrieves the feature flags from the 2WP API `/features` endpoint.
740
+ * @returns {Promise<Feature[]>} The feature flags as returned by the API.
741
+ */
742
+ async getFeatures() {
743
+ return this.api.getFeatures();
744
+ }
745
+ /**
746
+ * Returns the spendable UTXOs for the given Bitcoin address(es).
747
+ * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
748
+ * @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
749
+ * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
750
+ */
578
751
  async getAvailableUtxos(addresses) {
579
752
  const addressList = Array.isArray(addresses) ? addresses : [addresses];
580
753
  const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
@@ -587,6 +760,7 @@ var PowPegSDK = class {
587
760
 
588
761
  // src/bitcoin-signers/trezor/trezor.ts
589
762
  var import_connect_web = __toESM(require("@trezor/connect-web"));
763
+ var import_bridges_core_sdk5 = require("@rsksmart/bridges-core-sdk");
590
764
  var import_bitcoinjs_lib5 = require("bitcoinjs-lib");
591
765
  var TrezorSigner = class _TrezorSigner {
592
766
  constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
@@ -595,14 +769,25 @@ var TrezorSigner = class _TrezorSigner {
595
769
  }
596
770
  bitcoinTxVersion = 1;
597
771
  addresses = /* @__PURE__ */ new Map();
772
+ /**
773
+ * Initializes the Trezor connection and returns a ready-to-use signer.
774
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
775
+ * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
776
+ * @returns {Promise<TrezorSigner>} The initialized signer.
777
+ */
598
778
  static async init(network, initOptions) {
599
779
  await import_connect_web.default.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
600
780
  return new _TrezorSigner(network);
601
781
  }
782
+ /**
783
+ * Disposes the current Trezor connection and re-initializes it.
784
+ * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
785
+ */
602
786
  static async reinit() {
603
787
  import_connect_web.default.dispose();
604
788
  return _TrezorSigner.init();
605
789
  }
790
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
606
791
  set addressType(addressType) {
607
792
  this._addressType = addressType;
608
793
  }
@@ -630,9 +815,17 @@ var TrezorSigner = class _TrezorSigner {
630
815
  }
631
816
  return addresses;
632
817
  }
818
+ /**
819
+ * @param {number} bundleSize - Number of change addresses to derive.
820
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
821
+ */
633
822
  async getChangeAddresses(bundleSize) {
634
823
  return this.getAddresses(bundleSize, true);
635
824
  }
825
+ /**
826
+ * @param {number} bundleSize - Number of receive addresses to derive.
827
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
828
+ */
636
829
  async getNonChangeAddresses(bundleSize) {
637
830
  return this.getAddresses(bundleSize);
638
831
  }
@@ -660,8 +853,23 @@ var TrezorSigner = class _TrezorSigner {
660
853
  };
661
854
  });
662
855
  }
856
+ getOutputScriptType(address2) {
857
+ const addressType = getAddressType(address2, this.network);
858
+ switch (addressType) {
859
+ case "SEGWIT":
860
+ return "PAYTOP2SHWITNESS";
861
+ case "NATIVE SEGWIT":
862
+ return "PAYTOWITNESS";
863
+ default:
864
+ return "PAYTOADDRESS";
865
+ }
866
+ }
867
+ isChangePath(path) {
868
+ return path.length === 5 && path[3] === 1;
869
+ }
663
870
  getOutputs(psbt) {
664
- return psbt.txOutputs.map((output) => {
871
+ const lastIndex = psbt.txOutputs.length - 1;
872
+ return psbt.txOutputs.map((output, index) => {
665
873
  if (output.value === 0 && !output.address) {
666
874
  return {
667
875
  amount: output.value,
@@ -669,6 +877,14 @@ var TrezorSigner = class _TrezorSigner {
669
877
  script_type: "PAYTOOPRETURN"
670
878
  };
671
879
  }
880
+ const path = output.address ? this.addresses.get(output.address) : void 0;
881
+ if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
882
+ return {
883
+ address_n: path,
884
+ script_type: this.getOutputScriptType(output.address),
885
+ amount: output.value
886
+ };
887
+ }
672
888
  return {
673
889
  address: output.address ?? "",
674
890
  script_type: "PAYTOADDRESS",
@@ -676,7 +892,14 @@ var TrezorSigner = class _TrezorSigner {
676
892
  };
677
893
  });
678
894
  }
895
+ /**
896
+ * Signs the given PSBT's inputs/outputs on the Trezor device.
897
+ * @param {Psbt} psbt - The PSBT to sign.
898
+ * @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.
899
+ * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
900
+ */
679
901
  async signTransaction(psbt, utxos) {
902
+ (0, import_bridges_core_sdk5.assertTruthy)(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
680
903
  const inputs = this.getInputs(utxos);
681
904
  const outputs = this.getOutputs(psbt);
682
905
  const result = await import_connect_web.default.signTransaction({
@@ -695,6 +918,7 @@ var TrezorSigner = class _TrezorSigner {
695
918
  // src/bitcoin-signers/ledger/ledger.ts
696
919
  var import_hw_app_btc = __toESM(require("@ledgerhq/hw-app-btc"));
697
920
  var import_hw_transport_webusb = __toESM(require("@ledgerhq/hw-transport-webusb"));
921
+ var import_bridges_core_sdk6 = require("@rsksmart/bridges-core-sdk");
698
922
  var import_bitcoinjs_lib6 = require("bitcoinjs-lib");
699
923
 
700
924
  // src/bitcoin-signers/ledger/ledger-transport.ts
@@ -750,17 +974,27 @@ var LedgerSigner = class _LedgerSigner {
750
974
  }
751
975
  addresses = /* @__PURE__ */ new Map();
752
976
  transportService;
977
+ /**
978
+ * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
979
+ * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
980
+ * @returns {Promise<LedgerSigner>} The initialized signer.
981
+ */
753
982
  static async init(network = "TEST") {
754
983
  const transport = await import_hw_transport_webusb.default.create();
755
984
  const connection = new import_hw_app_btc.default({ transport, currency: networks[network].currency });
756
985
  return new _LedgerSigner(connection, transport, network);
757
986
  }
987
+ /**
988
+ * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
989
+ * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
990
+ */
758
991
  async reinit() {
759
992
  return this.transportService.enqueue(async () => {
760
993
  await this.transport.close();
761
994
  return _LedgerSigner.init();
762
995
  });
763
996
  }
997
+ /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
764
998
  set addressType(addressType) {
765
999
  this._addressType = addressType;
766
1000
  }
@@ -798,9 +1032,17 @@ var LedgerSigner = class _LedgerSigner {
798
1032
  return addresses;
799
1033
  });
800
1034
  }
1035
+ /**
1036
+ * @param {number} bundleSize - Number of change addresses to derive.
1037
+ * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
1038
+ */
801
1039
  async getChangeAddresses(bundleSize) {
802
1040
  return this.getAddresses(bundleSize, true);
803
1041
  }
1042
+ /**
1043
+ * @param {number} bundleSize - Number of receive addresses to derive.
1044
+ * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
1045
+ */
804
1046
  async getNonChangeAddresses(bundleSize) {
805
1047
  return this.getAddresses(bundleSize);
806
1048
  }
@@ -812,6 +1054,21 @@ var LedgerSigner = class _LedgerSigner {
812
1054
  return [deserializedTx, input.vout, void 0, void 0];
813
1055
  });
814
1056
  }
1057
+ isChangePath(path) {
1058
+ const segments = path.split("/");
1059
+ return segments.length === 6 && segments[4] === "1";
1060
+ }
1061
+ getChangePath(psbt) {
1062
+ if (psbt.txOutputs.length < 2) {
1063
+ return void 0;
1064
+ }
1065
+ const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
1066
+ if (!lastOutput.address) {
1067
+ return void 0;
1068
+ }
1069
+ const path = this.addresses.get(lastOutput.address);
1070
+ return path && this.isChangePath(path) ? path : void 0;
1071
+ }
815
1072
  getOutputScriptHex(psbt) {
816
1073
  const outputs = psbt.txOutputs.map((output) => {
817
1074
  const amount = Buffer.alloc(8);
@@ -823,15 +1080,28 @@ var LedgerSigner = class _LedgerSigner {
823
1080
  });
824
1081
  return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
825
1082
  }
1083
+ /**
1084
+ * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
1085
+ * @param {Psbt} psbt - The PSBT to sign.
1086
+ * @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.
1087
+ * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
1088
+ * @returns {Promise<string>} The signed, serialized transaction.
1089
+ */
826
1090
  async signTransaction(psbt, inputs, transactions) {
1091
+ (0, import_bridges_core_sdk6.assertTruthy)(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
1092
+ (0, import_bridges_core_sdk6.assertTruthy)(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
827
1093
  return this.transportService.enqueue(async () => {
828
1094
  const ledgerInputs = this.getInputs(inputs, transactions);
829
1095
  const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
830
1096
  const outputScriptHex = this.getOutputScriptHex(psbt);
1097
+ const changePath = this.getChangePath(psbt);
831
1098
  return this.connection.createPaymentTransaction({
832
1099
  inputs: ledgerInputs,
833
1100
  associatedKeysets: paths,
834
1101
  outputScriptHex,
1102
+ // hw-app-btc throws if changePath matches no output, so omit it
1103
+ // when the transaction has no device-derived change output
1104
+ ...changePath ? { changePath } : {},
835
1105
  segwit: this.isSegwit(),
836
1106
  useTrustedInputForSegwit: this.isSegwit(),
837
1107
  additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
@@ -843,6 +1113,7 @@ var LedgerSigner = class _LedgerSigner {
843
1113
  0 && (module.exports = {
844
1114
  APIError,
845
1115
  AmountBelowMinError,
1116
+ FederationAddressError,
846
1117
  InvalidAddressError,
847
1118
  LedgerSigner,
848
1119
  NotEnoughFundsError,