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

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.d.mts CHANGED
@@ -192,6 +192,8 @@ declare class PowPegSDK {
192
192
  private network;
193
193
  private maxBundleSize;
194
194
  private burnDustValue;
195
+ private maxFeeRateSatPerByte;
196
+ private maxFeeToAmountRatio;
195
197
  private txHeaderSizeInBytes;
196
198
  private txOutputSizeInBytes;
197
199
  private txInputSizeInBytes;
@@ -199,6 +201,7 @@ declare class PowPegSDK {
199
201
  private powpegRsktHeader;
200
202
  private burnDustMaxValue;
201
203
  private funding;
204
+ private psbtSigner;
202
205
  private minPeginAmount;
203
206
  private peginFeeEstimationInputs;
204
207
  private minPegoutAmount;
@@ -215,8 +218,10 @@ declare class PowPegSDK {
215
218
  * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource.
216
219
  * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
217
220
  * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
221
+ * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000.
222
+ * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5.
218
223
  */
219
- constructor(_bitcoinSigner: BitcoinSigner | null, _bitcoinDataSource: BitcoinDataSource | null, network: Network, rpcProviderUrl?: string, apiUrl?: string, maxBundleSize?: number, burnDustValue?: number);
224
+ constructor(_bitcoinSigner: BitcoinSigner | null, _bitcoinDataSource: BitcoinDataSource | null, network: Network, rpcProviderUrl?: string, apiUrl?: string, maxBundleSize?: number, burnDustValue?: number, maxFeeRateSatPerByte?: number, maxFeeToAmountRatio?: number);
220
225
  private get bitcoinSigner();
221
226
  private set bitcoinSigner(value);
222
227
  private get bitcoinDataSource();
@@ -249,17 +254,20 @@ declare class PowPegSDK {
249
254
  createPegin(amount: bigint, recipientAddress: string, selectedUtxos?: Utxo[]): Promise<Psbt>;
250
255
  private selectInputs;
251
256
  private validatePeginAmount;
257
+ private validateFeeRate;
258
+ private getValidatedFeeRate;
252
259
  private calculatePeginFee;
253
260
  private calculateFeeAndSelectedInputs;
254
261
  /**
255
262
  * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
256
263
  * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
257
264
  * @param {Psbt} psbt - The peg-in PSBT to fund.
258
- * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
265
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. Ignored if `feeRate` is provided.
259
266
  * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
267
+ * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch.
260
268
  * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
261
269
  */
262
- fundPegin(psbt: Psbt, feeLevel?: FeeLevel, value?: bigint): Promise<{
270
+ fundPegin(psbt: Psbt, feeLevel?: FeeLevel, value?: bigint, feeRate?: number): Promise<{
263
271
  psbt: Psbt;
264
272
  inputs: Utxo[];
265
273
  transactions: string[];
@@ -282,9 +290,10 @@ declare class PowPegSDK {
282
290
  * @param {string} recipientAddress - Bitcoin address to receive the payment.
283
291
  * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
284
292
  * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
293
+ * @param {BitcoinSigner} [signer] - Signer to bind to the returned PSBT for {@link signAndBroadcastPegin}. Required to sign the result, since this method takes no signer otherwise.
285
294
  * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
286
295
  */
287
- createAndFundPsbt(amount: bigint, recipientAddress: string, utxos: Utxo[], feeLevel?: FeeLevel): Promise<UnsignedPegin>;
296
+ createAndFundPsbt(amount: bigint, recipientAddress: string, utxos: Utxo[], feeLevel?: FeeLevel, signer?: BitcoinSigner): Promise<UnsignedPegin>;
288
297
  private signPegin;
289
298
  /**
290
299
  * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
@@ -480,10 +489,14 @@ declare class APIError extends Error {
480
489
  declare class FederationAddressError extends Error {
481
490
  constructor(message?: string);
482
491
  }
483
- /** Thrown when one or more Bitcoin addresses don't belong to the SDK's configured network. */
492
+ /** Thrown when one or more addresses are invalid: a Bitcoin address that doesn't belong to the SDK's configured network, or a malformed Rootstock recipient address. */
484
493
  declare class InvalidAddressError extends Error {
485
494
  readonly invalidAddresses: string[];
486
495
  constructor(invalidAddresses: string[], message?: string);
487
496
  }
497
+ /** Thrown when a fee rate from the configured BitcoinDataSource is missing, non-numeric, non-positive, exceeds the configured bound, or produces a fee disproportionate to the amount being sent. */
498
+ declare class InvalidFeeRateError extends Error {
499
+ constructor(message?: string);
500
+ }
488
501
 
489
- export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, FederationAddressError, type FeeLevel, InvalidAddressError, LedgerSigner, NotEnoughFundsError, type PeginStatusData, PeginStatuses, type PeginTxDetails, type PegoutFeeEstimation, type PegoutStatusData, PegoutStatuses, type PegoutTxDetails, PowPegSDK, type RejectedPegoutReason, RejectedPegoutReasons, type StatusData, type SupportedBrowsers, TrezorSigner, TxType, type UnsignedPegin, type Utxo };
502
+ export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, FederationAddressError, type FeeLevel, InvalidAddressError, InvalidFeeRateError, LedgerSigner, NotEnoughFundsError, type PeginStatusData, PeginStatuses, type PeginTxDetails, type PegoutFeeEstimation, type PegoutStatusData, PegoutStatuses, type PegoutTxDetails, PowPegSDK, type RejectedPegoutReason, RejectedPegoutReasons, type StatusData, type SupportedBrowsers, TrezorSigner, TxType, type UnsignedPegin, type Utxo };
package/dist/index.d.ts CHANGED
@@ -192,6 +192,8 @@ declare class PowPegSDK {
192
192
  private network;
193
193
  private maxBundleSize;
194
194
  private burnDustValue;
195
+ private maxFeeRateSatPerByte;
196
+ private maxFeeToAmountRatio;
195
197
  private txHeaderSizeInBytes;
196
198
  private txOutputSizeInBytes;
197
199
  private txInputSizeInBytes;
@@ -199,6 +201,7 @@ declare class PowPegSDK {
199
201
  private powpegRsktHeader;
200
202
  private burnDustMaxValue;
201
203
  private funding;
204
+ private psbtSigner;
202
205
  private minPeginAmount;
203
206
  private peginFeeEstimationInputs;
204
207
  private minPegoutAmount;
@@ -215,8 +218,10 @@ declare class PowPegSDK {
215
218
  * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource.
216
219
  * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
217
220
  * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
221
+ * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000.
222
+ * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5.
218
223
  */
219
- constructor(_bitcoinSigner: BitcoinSigner | null, _bitcoinDataSource: BitcoinDataSource | null, network: Network, rpcProviderUrl?: string, apiUrl?: string, maxBundleSize?: number, burnDustValue?: number);
224
+ constructor(_bitcoinSigner: BitcoinSigner | null, _bitcoinDataSource: BitcoinDataSource | null, network: Network, rpcProviderUrl?: string, apiUrl?: string, maxBundleSize?: number, burnDustValue?: number, maxFeeRateSatPerByte?: number, maxFeeToAmountRatio?: number);
220
225
  private get bitcoinSigner();
221
226
  private set bitcoinSigner(value);
222
227
  private get bitcoinDataSource();
@@ -249,17 +254,20 @@ declare class PowPegSDK {
249
254
  createPegin(amount: bigint, recipientAddress: string, selectedUtxos?: Utxo[]): Promise<Psbt>;
250
255
  private selectInputs;
251
256
  private validatePeginAmount;
257
+ private validateFeeRate;
258
+ private getValidatedFeeRate;
252
259
  private calculatePeginFee;
253
260
  private calculateFeeAndSelectedInputs;
254
261
  /**
255
262
  * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
256
263
  * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
257
264
  * @param {Psbt} psbt - The peg-in PSBT to fund.
258
- * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
265
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. Ignored if `feeRate` is provided.
259
266
  * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
267
+ * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch.
260
268
  * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
261
269
  */
262
- fundPegin(psbt: Psbt, feeLevel?: FeeLevel, value?: bigint): Promise<{
270
+ fundPegin(psbt: Psbt, feeLevel?: FeeLevel, value?: bigint, feeRate?: number): Promise<{
263
271
  psbt: Psbt;
264
272
  inputs: Utxo[];
265
273
  transactions: string[];
@@ -282,9 +290,10 @@ declare class PowPegSDK {
282
290
  * @param {string} recipientAddress - Bitcoin address to receive the payment.
283
291
  * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
284
292
  * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
293
+ * @param {BitcoinSigner} [signer] - Signer to bind to the returned PSBT for {@link signAndBroadcastPegin}. Required to sign the result, since this method takes no signer otherwise.
285
294
  * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
286
295
  */
287
- createAndFundPsbt(amount: bigint, recipientAddress: string, utxos: Utxo[], feeLevel?: FeeLevel): Promise<UnsignedPegin>;
296
+ createAndFundPsbt(amount: bigint, recipientAddress: string, utxos: Utxo[], feeLevel?: FeeLevel, signer?: BitcoinSigner): Promise<UnsignedPegin>;
288
297
  private signPegin;
289
298
  /**
290
299
  * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
@@ -480,10 +489,14 @@ declare class APIError extends Error {
480
489
  declare class FederationAddressError extends Error {
481
490
  constructor(message?: string);
482
491
  }
483
- /** Thrown when one or more Bitcoin addresses don't belong to the SDK's configured network. */
492
+ /** Thrown when one or more addresses are invalid: a Bitcoin address that doesn't belong to the SDK's configured network, or a malformed Rootstock recipient address. */
484
493
  declare class InvalidAddressError extends Error {
485
494
  readonly invalidAddresses: string[];
486
495
  constructor(invalidAddresses: string[], message?: string);
487
496
  }
497
+ /** Thrown when a fee rate from the configured BitcoinDataSource is missing, non-numeric, non-positive, exceeds the configured bound, or produces a fee disproportionate to the amount being sent. */
498
+ declare class InvalidFeeRateError extends Error {
499
+ constructor(message?: string);
500
+ }
488
501
 
489
- export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, FederationAddressError, type FeeLevel, InvalidAddressError, LedgerSigner, NotEnoughFundsError, type PeginStatusData, PeginStatuses, type PeginTxDetails, type PegoutFeeEstimation, type PegoutStatusData, PegoutStatuses, type PegoutTxDetails, PowPegSDK, type RejectedPegoutReason, RejectedPegoutReasons, type StatusData, type SupportedBrowsers, TrezorSigner, TxType, type UnsignedPegin, type Utxo };
502
+ export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, FederationAddressError, type FeeLevel, InvalidAddressError, InvalidFeeRateError, LedgerSigner, NotEnoughFundsError, type PeginStatusData, PeginStatuses, type PeginTxDetails, type PegoutFeeEstimation, type PegoutStatusData, PegoutStatuses, type PegoutTxDetails, PowPegSDK, type RejectedPegoutReason, RejectedPegoutReasons, type StatusData, type SupportedBrowsers, TrezorSigner, TxType, type UnsignedPegin, type Utxo };
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  AmountBelowMinError: () => AmountBelowMinError,
35
35
  FederationAddressError: () => FederationAddressError,
36
36
  InvalidAddressError: () => InvalidAddressError,
37
+ InvalidFeeRateError: () => InvalidFeeRateError,
37
38
  LedgerSigner: () => LedgerSigner,
38
39
  NotEnoughFundsError: () => NotEnoughFundsError,
39
40
  PeginStatuses: () => PeginStatuses,
@@ -238,6 +239,12 @@ var InvalidAddressError = class extends Error {
238
239
  this.invalidAddresses = invalidAddresses;
239
240
  }
240
241
  };
242
+ var InvalidFeeRateError = class extends Error {
243
+ constructor(message) {
244
+ super(message);
245
+ this.name = "InvalidFeeRateError";
246
+ }
247
+ };
241
248
 
242
249
  // src/api/api.ts
243
250
  var import_bridges_core_sdk3 = require("@rsksmart/bridges-core-sdk");
@@ -341,13 +348,17 @@ var PowPegSDK = class {
341
348
  * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource.
342
349
  * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
343
350
  * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
351
+ * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000.
352
+ * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5.
344
353
  */
345
- constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3) {
354
+ constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3, maxFeeRateSatPerByte = 1e3, maxFeeToAmountRatio = 0.5) {
346
355
  this._bitcoinSigner = _bitcoinSigner;
347
356
  this._bitcoinDataSource = _bitcoinDataSource;
348
357
  this.network = network;
349
358
  this.maxBundleSize = maxBundleSize;
350
359
  this.burnDustValue = burnDustValue;
360
+ this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
361
+ this.maxFeeToAmountRatio = maxFeeToAmountRatio;
351
362
  this.btcNetworkConfig = networks[network];
352
363
  this.rskProvider = new import_bridges_core_sdk4.ethers.providers.JsonRpcProvider(rpcProviderUrl ?? this.publicNodes[network]);
353
364
  this.bridge = new Bridge(this.rskProvider);
@@ -360,6 +371,7 @@ var PowPegSDK = class {
360
371
  powpegRsktHeader = "52534b5401";
361
372
  burnDustMaxValue = 3e4;
362
373
  funding = /* @__PURE__ */ new WeakMap();
374
+ psbtSigner = /* @__PURE__ */ new WeakMap();
363
375
  minPeginAmount = 500000n;
364
376
  peginFeeEstimationInputs = 2;
365
377
  minPegoutAmount = "0.004";
@@ -384,7 +396,7 @@ var PowPegSDK = class {
384
396
  async getUtxos(addresses) {
385
397
  const rawAddresses = addresses.map((address2) => typeof address2 === "string" ? address2 : address2.address);
386
398
  const utxoLists = await Promise.all(rawAddresses.map((address2) => this.bitcoinDataSource.getOutputs(address2)));
387
- const allUtxos = utxoLists.flat();
399
+ const allUtxos = utxoLists.flatMap((utxos, i) => utxos.map((utxo) => ({ ...utxo, address: rawAddresses[i] })));
388
400
  const seen = /* @__PURE__ */ new Set();
389
401
  const uniqueUtxos = allUtxos.filter((utxo) => {
390
402
  const key = `${utxo.txid}:${utxo.vout}`;
@@ -398,7 +410,10 @@ var PowPegSDK = class {
398
410
  return uniqueUtxos;
399
411
  }
400
412
  async getAddressesWithDetails(addresses) {
401
- return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
413
+ return Promise.all(addresses.map(async (address2) => ({
414
+ ...await this.bitcoinDataSource.getAddressDetails(address2),
415
+ address: address2
416
+ })));
402
417
  }
403
418
  groupAddressesByUsage(addresses) {
404
419
  const used = [];
@@ -424,9 +439,9 @@ var PowPegSDK = class {
424
439
  });
425
440
  return { withBalance, withoutBalance };
426
441
  }
427
- async getAddressesGroupedByUsage() {
428
- const nonChangeAddresses = await this.bitcoinSigner.getNonChangeAddresses(this.maxBundleSize);
429
- const changeAddresses = await this.bitcoinSigner.getChangeAddresses(this.maxBundleSize);
442
+ async getAddressesGroupedByUsage(signer) {
443
+ const nonChangeAddresses = await signer.getNonChangeAddresses(this.maxBundleSize);
444
+ const changeAddresses = await signer.getChangeAddresses(this.maxBundleSize);
430
445
  const [nonChangeDetails, changeDetails] = await Promise.all([
431
446
  this.getAddressesWithDetails(nonChangeAddresses),
432
447
  this.getAddressesWithDetails(changeAddresses)
@@ -483,7 +498,7 @@ var PowPegSDK = class {
483
498
  * @returns {Promise<number>} The estimated total fee in satoshis.
484
499
  */
485
500
  async estimatePeginFee(amount, feeLevel = "fast", utxos) {
486
- const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
501
+ const feeRate = await this.getValidatedFeeRate(feeLevel);
487
502
  if (utxos) {
488
503
  const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
489
504
  return totalFee2;
@@ -502,7 +517,8 @@ var PowPegSDK = class {
502
517
  * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
503
518
  */
504
519
  async createPegin(amount, recipientAddress, selectedUtxos) {
505
- const addresses = await this.getAddressesGroupedByUsage();
520
+ const signer = this.bitcoinSigner;
521
+ const addresses = await this.getAddressesGroupedByUsage(signer);
506
522
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
507
523
  const refundAddress = addresses.nonChange.unused[0]?.address;
508
524
  const { output: script } = import_bitcoinjs_lib4.payments.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
@@ -526,6 +542,7 @@ var PowPegSDK = class {
526
542
  utxos = await this.getUtxos(withBalance);
527
543
  }
528
544
  this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
545
+ this.psbtSigner.set(psbt, signer);
529
546
  return psbt;
530
547
  }
531
548
  selectInputs(amount, utxos, baseFee, feePerInput) {
@@ -549,6 +566,16 @@ var PowPegSDK = class {
549
566
  throw new AmountBelowMinError(`Minimum allowed amount is ${this.minPeginAmount} satoshis.`);
550
567
  }
551
568
  }
569
+ validateFeeRate(feeRate) {
570
+ if (!Number.isInteger(feeRate) || feeRate <= 0 || feeRate > this.maxFeeRateSatPerByte) {
571
+ throw new InvalidFeeRateError(`Implausible fee rate: ${feeRate}`);
572
+ }
573
+ return feeRate;
574
+ }
575
+ async getValidatedFeeRate(feeLevel) {
576
+ const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
577
+ return this.validateFeeRate(feeRate);
578
+ }
552
579
  async calculatePeginFee(amount, feeRate) {
553
580
  this.validatePeginAmount(amount);
554
581
  const txSize = this.txHeaderSizeInBytes + this.txOutputSizeInBytes * this.pegInOutputs;
@@ -563,23 +590,36 @@ var PowPegSDK = class {
563
590
  throw new NotEnoughFundsError(`${rest} satoshis needed to cover the requested amount.`);
564
591
  }
565
592
  const totalFee = baseFee + feePerInput * inputs.length;
593
+ if (totalFee > Number(amount) * this.maxFeeToAmountRatio) {
594
+ throw new InvalidFeeRateError(`Fee ${totalFee} sat is disproportionate to the ${amount} sat being sent.`);
595
+ }
566
596
  return { inputs, change: Math.abs(rest), totalFee };
567
597
  }
568
598
  /**
569
599
  * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
570
600
  * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
571
601
  * @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'`.
602
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. Ignored if `feeRate` is provided.
573
603
  * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
604
+ * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch.
574
605
  * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
575
606
  */
576
- async fundPegin(psbt, feeLevel = "fast", value) {
607
+ async fundPegin(psbt, feeLevel = "fast", value, feeRate) {
577
608
  const funding = this.funding.get(psbt);
578
609
  (0, import_bridges_core_sdk4.assertTruthy)(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
579
610
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
580
- const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
581
- const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
582
- if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
611
+ const resolvedFeeRate = feeRate !== void 0 ? this.validateFeeRate(feeRate) : await this.getValidatedFeeRate(feeLevel);
612
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, resolvedFeeRate);
613
+ const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
614
+ const parsedOutputs = hexTransactions.map((hex, index) => {
615
+ const output = import_bitcoinjs_lib4.Transaction.fromHex(hex).outs[inputs[index].vout];
616
+ (0, import_bridges_core_sdk4.assertTruthy)(output, `UTXO ${inputs[index].txid}:${inputs[index].vout} was not found in the fetched transaction.`);
617
+ return output;
618
+ });
619
+ const initialInputCount = psbt.txInputs.length;
620
+ const initialOutputCount = psbt.txOutputs.length;
621
+ const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
622
+ if (addChange) {
583
623
  psbt.addOutput({
584
624
  // Fall back to the first funding input's address when every derived
585
625
  // change address has already been used.
@@ -587,18 +627,24 @@ var PowPegSDK = class {
587
627
  value: change
588
628
  });
589
629
  }
590
- const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
591
630
  inputs.forEach((input, index) => {
592
- const transaction = import_bitcoinjs_lib4.Transaction.fromHex(hexTransactions[index]);
631
+ const output = parsedOutputs[index];
593
632
  psbt.addInput({
594
633
  hash: input.txid,
595
634
  index: input.vout,
596
635
  witnessUtxo: {
597
- script: transaction.outs[input.vout].script,
598
- value: transaction.outs[input.vout].value
636
+ script: output.script,
637
+ value: output.value
599
638
  }
600
639
  });
601
640
  });
641
+ const expectedInputCount = initialInputCount + inputs.length;
642
+ const expectedOutputCount = initialOutputCount + (addChange ? 1 : 0);
643
+ (0, import_bridges_core_sdk4.assertTruthy)(
644
+ psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
645
+ `Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
646
+ );
647
+ this.funding.delete(psbt);
602
648
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
603
649
  }
604
650
  /**
@@ -623,19 +669,25 @@ var PowPegSDK = class {
623
669
  * @param {string} recipientAddress - Bitcoin address to receive the payment.
624
670
  * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
625
671
  * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
672
+ * @param {BitcoinSigner} [signer] - Signer to bind to the returned PSBT for {@link signAndBroadcastPegin}. Required to sign the result, since this method takes no signer otherwise.
626
673
  * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
627
674
  */
628
- async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
675
+ async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast", signer) {
629
676
  const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
630
677
  psbt.addOutput({
631
678
  address: recipientAddress,
632
679
  value: Number(amount)
633
680
  });
634
681
  this.funding.set(psbt, { utxos: [...utxos] });
682
+ if (signer) {
683
+ this.psbtSigner.set(psbt, signer);
684
+ }
635
685
  return this.fundPegin(psbt, feeLevel, amount);
636
686
  }
637
687
  async signPegin(psbt, inputs, transactions) {
638
- return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
688
+ const signer = this.psbtSigner.get(psbt);
689
+ (0, import_bridges_core_sdk4.assertTruthy)(signer, "No signer bound to this PSBT. Sign the PSBT returned by createPegin, createAndFundPegin, or createAndFundPsbt with a signer argument.");
690
+ return signer.signTransaction(psbt, inputs, transactions);
639
691
  }
640
692
  /**
641
693
  * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
@@ -1105,6 +1157,7 @@ var LedgerSigner = class _LedgerSigner {
1105
1157
  AmountBelowMinError,
1106
1158
  FederationAddressError,
1107
1159
  InvalidAddressError,
1160
+ InvalidFeeRateError,
1108
1161
  LedgerSigner,
1109
1162
  NotEnoughFundsError,
1110
1163
  PeginStatuses,
package/dist/index.mjs CHANGED
@@ -191,6 +191,12 @@ var InvalidAddressError = class extends Error {
191
191
  this.invalidAddresses = invalidAddresses;
192
192
  }
193
193
  };
194
+ var InvalidFeeRateError = class extends Error {
195
+ constructor(message) {
196
+ super(message);
197
+ this.name = "InvalidFeeRateError";
198
+ }
199
+ };
194
200
 
195
201
  // src/api/api.ts
196
202
  import { ethers as ethers2 } from "@rsksmart/bridges-core-sdk";
@@ -294,13 +300,17 @@ var PowPegSDK = class {
294
300
  * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource.
295
301
  * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
296
302
  * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
303
+ * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000.
304
+ * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5.
297
305
  */
298
- constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3) {
306
+ constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3, maxFeeRateSatPerByte = 1e3, maxFeeToAmountRatio = 0.5) {
299
307
  this._bitcoinSigner = _bitcoinSigner;
300
308
  this._bitcoinDataSource = _bitcoinDataSource;
301
309
  this.network = network;
302
310
  this.maxBundleSize = maxBundleSize;
303
311
  this.burnDustValue = burnDustValue;
312
+ this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
313
+ this.maxFeeToAmountRatio = maxFeeToAmountRatio;
304
314
  this.btcNetworkConfig = networks[network];
305
315
  this.rskProvider = new ethers3.providers.JsonRpcProvider(rpcProviderUrl ?? this.publicNodes[network]);
306
316
  this.bridge = new Bridge(this.rskProvider);
@@ -313,6 +323,7 @@ var PowPegSDK = class {
313
323
  powpegRsktHeader = "52534b5401";
314
324
  burnDustMaxValue = 3e4;
315
325
  funding = /* @__PURE__ */ new WeakMap();
326
+ psbtSigner = /* @__PURE__ */ new WeakMap();
316
327
  minPeginAmount = 500000n;
317
328
  peginFeeEstimationInputs = 2;
318
329
  minPegoutAmount = "0.004";
@@ -337,7 +348,7 @@ var PowPegSDK = class {
337
348
  async getUtxos(addresses) {
338
349
  const rawAddresses = addresses.map((address2) => typeof address2 === "string" ? address2 : address2.address);
339
350
  const utxoLists = await Promise.all(rawAddresses.map((address2) => this.bitcoinDataSource.getOutputs(address2)));
340
- const allUtxos = utxoLists.flat();
351
+ const allUtxos = utxoLists.flatMap((utxos, i) => utxos.map((utxo) => ({ ...utxo, address: rawAddresses[i] })));
341
352
  const seen = /* @__PURE__ */ new Set();
342
353
  const uniqueUtxos = allUtxos.filter((utxo) => {
343
354
  const key = `${utxo.txid}:${utxo.vout}`;
@@ -351,7 +362,10 @@ var PowPegSDK = class {
351
362
  return uniqueUtxos;
352
363
  }
353
364
  async getAddressesWithDetails(addresses) {
354
- return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
365
+ return Promise.all(addresses.map(async (address2) => ({
366
+ ...await this.bitcoinDataSource.getAddressDetails(address2),
367
+ address: address2
368
+ })));
355
369
  }
356
370
  groupAddressesByUsage(addresses) {
357
371
  const used = [];
@@ -377,9 +391,9 @@ var PowPegSDK = class {
377
391
  });
378
392
  return { withBalance, withoutBalance };
379
393
  }
380
- async getAddressesGroupedByUsage() {
381
- const nonChangeAddresses = await this.bitcoinSigner.getNonChangeAddresses(this.maxBundleSize);
382
- const changeAddresses = await this.bitcoinSigner.getChangeAddresses(this.maxBundleSize);
394
+ async getAddressesGroupedByUsage(signer) {
395
+ const nonChangeAddresses = await signer.getNonChangeAddresses(this.maxBundleSize);
396
+ const changeAddresses = await signer.getChangeAddresses(this.maxBundleSize);
383
397
  const [nonChangeDetails, changeDetails] = await Promise.all([
384
398
  this.getAddressesWithDetails(nonChangeAddresses),
385
399
  this.getAddressesWithDetails(changeAddresses)
@@ -436,7 +450,7 @@ var PowPegSDK = class {
436
450
  * @returns {Promise<number>} The estimated total fee in satoshis.
437
451
  */
438
452
  async estimatePeginFee(amount, feeLevel = "fast", utxos) {
439
- const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
453
+ const feeRate = await this.getValidatedFeeRate(feeLevel);
440
454
  if (utxos) {
441
455
  const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
442
456
  return totalFee2;
@@ -455,7 +469,8 @@ var PowPegSDK = class {
455
469
  * @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
456
470
  */
457
471
  async createPegin(amount, recipientAddress, selectedUtxos) {
458
- const addresses = await this.getAddressesGroupedByUsage();
472
+ const signer = this.bitcoinSigner;
473
+ const addresses = await this.getAddressesGroupedByUsage(signer);
459
474
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
460
475
  const refundAddress = addresses.nonChange.unused[0]?.address;
461
476
  const { output: script } = payments2.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
@@ -479,6 +494,7 @@ var PowPegSDK = class {
479
494
  utxos = await this.getUtxos(withBalance);
480
495
  }
481
496
  this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
497
+ this.psbtSigner.set(psbt, signer);
482
498
  return psbt;
483
499
  }
484
500
  selectInputs(amount, utxos, baseFee, feePerInput) {
@@ -502,6 +518,16 @@ var PowPegSDK = class {
502
518
  throw new AmountBelowMinError(`Minimum allowed amount is ${this.minPeginAmount} satoshis.`);
503
519
  }
504
520
  }
521
+ validateFeeRate(feeRate) {
522
+ if (!Number.isInteger(feeRate) || feeRate <= 0 || feeRate > this.maxFeeRateSatPerByte) {
523
+ throw new InvalidFeeRateError(`Implausible fee rate: ${feeRate}`);
524
+ }
525
+ return feeRate;
526
+ }
527
+ async getValidatedFeeRate(feeLevel) {
528
+ const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
529
+ return this.validateFeeRate(feeRate);
530
+ }
505
531
  async calculatePeginFee(amount, feeRate) {
506
532
  this.validatePeginAmount(amount);
507
533
  const txSize = this.txHeaderSizeInBytes + this.txOutputSizeInBytes * this.pegInOutputs;
@@ -516,23 +542,36 @@ var PowPegSDK = class {
516
542
  throw new NotEnoughFundsError(`${rest} satoshis needed to cover the requested amount.`);
517
543
  }
518
544
  const totalFee = baseFee + feePerInput * inputs.length;
545
+ if (totalFee > Number(amount) * this.maxFeeToAmountRatio) {
546
+ throw new InvalidFeeRateError(`Fee ${totalFee} sat is disproportionate to the ${amount} sat being sent.`);
547
+ }
519
548
  return { inputs, change: Math.abs(rest), totalFee };
520
549
  }
521
550
  /**
522
551
  * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
523
552
  * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
524
553
  * @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'`.
554
+ * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. Ignored if `feeRate` is provided.
526
555
  * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
556
+ * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch.
527
557
  * @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
528
558
  */
529
- async fundPegin(psbt, feeLevel = "fast", value) {
559
+ async fundPegin(psbt, feeLevel = "fast", value, feeRate) {
530
560
  const funding = this.funding.get(psbt);
531
561
  assertTruthy(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
532
562
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
533
- const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
534
- const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
535
- if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
563
+ const resolvedFeeRate = feeRate !== void 0 ? this.validateFeeRate(feeRate) : await this.getValidatedFeeRate(feeLevel);
564
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, resolvedFeeRate);
565
+ const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
566
+ const parsedOutputs = hexTransactions.map((hex, index) => {
567
+ const output = Transaction.fromHex(hex).outs[inputs[index].vout];
568
+ assertTruthy(output, `UTXO ${inputs[index].txid}:${inputs[index].vout} was not found in the fetched transaction.`);
569
+ return output;
570
+ });
571
+ const initialInputCount = psbt.txInputs.length;
572
+ const initialOutputCount = psbt.txOutputs.length;
573
+ const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
574
+ if (addChange) {
536
575
  psbt.addOutput({
537
576
  // Fall back to the first funding input's address when every derived
538
577
  // change address has already been used.
@@ -540,18 +579,24 @@ var PowPegSDK = class {
540
579
  value: change
541
580
  });
542
581
  }
543
- const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
544
582
  inputs.forEach((input, index) => {
545
- const transaction = Transaction.fromHex(hexTransactions[index]);
583
+ const output = parsedOutputs[index];
546
584
  psbt.addInput({
547
585
  hash: input.txid,
548
586
  index: input.vout,
549
587
  witnessUtxo: {
550
- script: transaction.outs[input.vout].script,
551
- value: transaction.outs[input.vout].value
588
+ script: output.script,
589
+ value: output.value
552
590
  }
553
591
  });
554
592
  });
593
+ const expectedInputCount = initialInputCount + inputs.length;
594
+ const expectedOutputCount = initialOutputCount + (addChange ? 1 : 0);
595
+ assertTruthy(
596
+ psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
597
+ `Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
598
+ );
599
+ this.funding.delete(psbt);
555
600
  return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
556
601
  }
557
602
  /**
@@ -576,19 +621,25 @@ var PowPegSDK = class {
576
621
  * @param {string} recipientAddress - Bitcoin address to receive the payment.
577
622
  * @param {Utxo[]} utxos - UTXOs to fund the transaction with.
578
623
  * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
624
+ * @param {BitcoinSigner} [signer] - Signer to bind to the returned PSBT for {@link signAndBroadcastPegin}. Required to sign the result, since this method takes no signer otherwise.
579
625
  * @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
580
626
  */
581
- async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
627
+ async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast", signer) {
582
628
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
583
629
  psbt.addOutput({
584
630
  address: recipientAddress,
585
631
  value: Number(amount)
586
632
  });
587
633
  this.funding.set(psbt, { utxos: [...utxos] });
634
+ if (signer) {
635
+ this.psbtSigner.set(psbt, signer);
636
+ }
588
637
  return this.fundPegin(psbt, feeLevel, amount);
589
638
  }
590
639
  async signPegin(psbt, inputs, transactions) {
591
- return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
640
+ const signer = this.psbtSigner.get(psbt);
641
+ assertTruthy(signer, "No signer bound to this PSBT. Sign the PSBT returned by createPegin, createAndFundPegin, or createAndFundPsbt with a signer argument.");
642
+ return signer.signTransaction(psbt, inputs, transactions);
592
643
  }
593
644
  /**
594
645
  * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
@@ -1057,6 +1108,7 @@ export {
1057
1108
  AmountBelowMinError,
1058
1109
  FederationAddressError,
1059
1110
  InvalidAddressError,
1111
+ InvalidFeeRateError,
1060
1112
  LedgerSigner,
1061
1113
  NotEnoughFundsError,
1062
1114
  PeginStatuses,
@@ -32,5 +32,5 @@ Following the pattern of the two existing implementations:
32
32
 
33
33
  1. Create a new file under `src/bitcoin-signers/<name>/<name>.ts` implementing `BitcoinSigner`.
34
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.
35
+ 3. Pass an instance to `PowPegSDK`'s constructor (as `_bitcoinSigner`), to `createAndFundPegin(...)`'s `signer` argument, or to `createAndFundPsbt(...)`'s `signer` argument. Whichever PSBT-creating method is used, `signAndBroadcastPegin` signs with the signer bound to that specific PSBT — a PSBT created without one cannot be signed later by setting the constructor-level signer alone.
36
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.
package/docs/setup.md CHANGED
@@ -51,6 +51,10 @@ pnpm add @rsksmart/powpeg-sdk
51
51
  | `network` | `'MAIN'` or `'TEST'` — selects Bitcoin network params and address validation rules | required |
52
52
  | `rpcProviderUrl` | Rootstock JSON-RPC endpoint used to read the bridge precompile and send peg-outs | RSK public node for the given network (`https://public-node.rsk.co` / `https://public-node.testnet.rsk.co`) |
53
53
  | `apiUrl` | 2WP API used as the default `BitcoinDataSource` (fee rates, UTXOs, tx broadcast, tx status) when no custom `BitcoinDataSource` is supplied | production 2WP API for the given network (`https://api.2wp.rootstock.io` / `https://api.2wp.testnet.rootstock.io`) |
54
+ | `maxBundleSize` | Number of addresses to derive per `BitcoinSigner` call while creating a peg-in | `10` |
55
+ | `burnDustValue` | Change amount, in satoshis, below which it's dropped into the fee instead of added as an output | `2000` |
56
+ | `maxFeeRateSatPerByte` | Upper bound, in sat/B, for a fee rate coming from the configured `BitcoinDataSource`; a higher value throws `InvalidFeeRateError` | `1000` |
57
+ | `maxFeeToAmountRatio` | Upper bound for the ratio of total fee to peg-in amount; a higher ratio throws `InvalidFeeRateError` | `0.5` |
54
58
 
55
59
  ## External dependencies
56
60
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsksmart/powpeg-sdk",
3
- "version": "1.2.0-beta.3",
3
+ "version": "1.2.0-beta.5",
4
4
  "description": "SDK for creating native peg-in and peg-out transactions following the PowPeg protocol.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",