@rsksmart/powpeg-sdk 1.2.0-beta.4 → 1.2.0-beta.6
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 +18 -5
- package/dist/index.d.ts +18 -5
- package/dist/index.js +66 -23
- package/dist/index.mjs +65 -23
- package/docs/bitcoin-signers.md +1 -1
- package/docs/setup.md +4 -0
- package/package.json +1 -1
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.
|
|
@@ -485,5 +494,9 @@ 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.
|
|
@@ -485,5 +494,9 @@ 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,24 +239,30 @@ 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");
|
|
244
251
|
var ApiService = class {
|
|
252
|
+
constructor(network, apiUrl, maxFeeRateSatPerByte = 1e3) {
|
|
253
|
+
this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
|
|
254
|
+
this.api = import_axios.default.create({ baseURL: apiUrl ?? this.apiUrls[network] });
|
|
255
|
+
}
|
|
245
256
|
apiUrls = {
|
|
246
257
|
MAIN: "https://api.2wp.rootstock.io",
|
|
247
258
|
TEST: "https://api.2wp.testnet.rootstock.io"
|
|
248
259
|
};
|
|
249
|
-
maxFeeRateSatPerByte = 1e3;
|
|
250
260
|
feeLevelBlocks = {
|
|
251
261
|
slow: 5,
|
|
252
262
|
average: 3,
|
|
253
263
|
fast: 1
|
|
254
264
|
};
|
|
255
265
|
api;
|
|
256
|
-
constructor(network, apiUrl) {
|
|
257
|
-
this.api = import_axios.default.create({ baseURL: apiUrl ?? this.apiUrls[network] });
|
|
258
|
-
}
|
|
259
266
|
handleError(error) {
|
|
260
267
|
if (import_axios.default.isAxiosError(error)) {
|
|
261
268
|
if (error.response) {
|
|
@@ -341,17 +348,21 @@ 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);
|
|
354
|
-
this.api = new ApiService(network, apiUrl);
|
|
365
|
+
this.api = new ApiService(network, apiUrl, maxFeeRateSatPerByte);
|
|
355
366
|
}
|
|
356
367
|
txHeaderSizeInBytes = 13;
|
|
357
368
|
txOutputSizeInBytes = 32;
|
|
@@ -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.
|
|
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) =>
|
|
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
|
|
429
|
-
const changeAddresses = await
|
|
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.
|
|
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
|
|
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,26 +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
|
|
581
|
-
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos,
|
|
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);
|
|
582
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
|
+
});
|
|
583
619
|
const initialInputCount = psbt.txInputs.length;
|
|
584
620
|
const initialOutputCount = psbt.txOutputs.length;
|
|
585
621
|
const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
|
|
622
|
+
this.funding.delete(psbt);
|
|
586
623
|
if (addChange) {
|
|
587
624
|
psbt.addOutput({
|
|
588
625
|
// Fall back to the first funding input's address when every derived
|
|
@@ -592,13 +629,13 @@ var PowPegSDK = class {
|
|
|
592
629
|
});
|
|
593
630
|
}
|
|
594
631
|
inputs.forEach((input, index) => {
|
|
595
|
-
const
|
|
632
|
+
const output = parsedOutputs[index];
|
|
596
633
|
psbt.addInput({
|
|
597
634
|
hash: input.txid,
|
|
598
635
|
index: input.vout,
|
|
599
636
|
witnessUtxo: {
|
|
600
|
-
script:
|
|
601
|
-
value:
|
|
637
|
+
script: output.script,
|
|
638
|
+
value: output.value
|
|
602
639
|
}
|
|
603
640
|
});
|
|
604
641
|
});
|
|
@@ -608,7 +645,6 @@ var PowPegSDK = class {
|
|
|
608
645
|
psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
|
|
609
646
|
`Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
|
|
610
647
|
);
|
|
611
|
-
this.funding.delete(psbt);
|
|
612
648
|
return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
|
|
613
649
|
}
|
|
614
650
|
/**
|
|
@@ -633,19 +669,25 @@ var PowPegSDK = class {
|
|
|
633
669
|
* @param {string} recipientAddress - Bitcoin address to receive the payment.
|
|
634
670
|
* @param {Utxo[]} utxos - UTXOs to fund the transaction with.
|
|
635
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.
|
|
636
673
|
* @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
|
|
637
674
|
*/
|
|
638
|
-
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
|
|
675
|
+
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast", signer) {
|
|
639
676
|
const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
|
|
640
677
|
psbt.addOutput({
|
|
641
678
|
address: recipientAddress,
|
|
642
679
|
value: Number(amount)
|
|
643
680
|
});
|
|
644
681
|
this.funding.set(psbt, { utxos: [...utxos] });
|
|
682
|
+
if (signer) {
|
|
683
|
+
this.psbtSigner.set(psbt, signer);
|
|
684
|
+
}
|
|
645
685
|
return this.fundPegin(psbt, feeLevel, amount);
|
|
646
686
|
}
|
|
647
687
|
async signPegin(psbt, inputs, transactions) {
|
|
648
|
-
|
|
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);
|
|
649
691
|
}
|
|
650
692
|
/**
|
|
651
693
|
* Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
|
|
@@ -1115,6 +1157,7 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
1115
1157
|
AmountBelowMinError,
|
|
1116
1158
|
FederationAddressError,
|
|
1117
1159
|
InvalidAddressError,
|
|
1160
|
+
InvalidFeeRateError,
|
|
1118
1161
|
LedgerSigner,
|
|
1119
1162
|
NotEnoughFundsError,
|
|
1120
1163
|
PeginStatuses,
|
package/dist/index.mjs
CHANGED
|
@@ -191,24 +191,30 @@ 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";
|
|
197
203
|
var ApiService = class {
|
|
204
|
+
constructor(network, apiUrl, maxFeeRateSatPerByte = 1e3) {
|
|
205
|
+
this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
|
|
206
|
+
this.api = axios.create({ baseURL: apiUrl ?? this.apiUrls[network] });
|
|
207
|
+
}
|
|
198
208
|
apiUrls = {
|
|
199
209
|
MAIN: "https://api.2wp.rootstock.io",
|
|
200
210
|
TEST: "https://api.2wp.testnet.rootstock.io"
|
|
201
211
|
};
|
|
202
|
-
maxFeeRateSatPerByte = 1e3;
|
|
203
212
|
feeLevelBlocks = {
|
|
204
213
|
slow: 5,
|
|
205
214
|
average: 3,
|
|
206
215
|
fast: 1
|
|
207
216
|
};
|
|
208
217
|
api;
|
|
209
|
-
constructor(network, apiUrl) {
|
|
210
|
-
this.api = axios.create({ baseURL: apiUrl ?? this.apiUrls[network] });
|
|
211
|
-
}
|
|
212
218
|
handleError(error) {
|
|
213
219
|
if (axios.isAxiosError(error)) {
|
|
214
220
|
if (error.response) {
|
|
@@ -294,17 +300,21 @@ 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);
|
|
307
|
-
this.api = new ApiService(network, apiUrl);
|
|
317
|
+
this.api = new ApiService(network, apiUrl, maxFeeRateSatPerByte);
|
|
308
318
|
}
|
|
309
319
|
txHeaderSizeInBytes = 13;
|
|
310
320
|
txOutputSizeInBytes = 32;
|
|
@@ -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.
|
|
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) =>
|
|
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
|
|
382
|
-
const changeAddresses = await
|
|
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.
|
|
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
|
|
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,26 +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
|
|
534
|
-
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos,
|
|
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);
|
|
535
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
|
+
});
|
|
536
571
|
const initialInputCount = psbt.txInputs.length;
|
|
537
572
|
const initialOutputCount = psbt.txOutputs.length;
|
|
538
573
|
const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
|
|
574
|
+
this.funding.delete(psbt);
|
|
539
575
|
if (addChange) {
|
|
540
576
|
psbt.addOutput({
|
|
541
577
|
// Fall back to the first funding input's address when every derived
|
|
@@ -545,13 +581,13 @@ var PowPegSDK = class {
|
|
|
545
581
|
});
|
|
546
582
|
}
|
|
547
583
|
inputs.forEach((input, index) => {
|
|
548
|
-
const
|
|
584
|
+
const output = parsedOutputs[index];
|
|
549
585
|
psbt.addInput({
|
|
550
586
|
hash: input.txid,
|
|
551
587
|
index: input.vout,
|
|
552
588
|
witnessUtxo: {
|
|
553
|
-
script:
|
|
554
|
-
value:
|
|
589
|
+
script: output.script,
|
|
590
|
+
value: output.value
|
|
555
591
|
}
|
|
556
592
|
});
|
|
557
593
|
});
|
|
@@ -561,7 +597,6 @@ var PowPegSDK = class {
|
|
|
561
597
|
psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
|
|
562
598
|
`Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
|
|
563
599
|
);
|
|
564
|
-
this.funding.delete(psbt);
|
|
565
600
|
return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
|
|
566
601
|
}
|
|
567
602
|
/**
|
|
@@ -586,19 +621,25 @@ var PowPegSDK = class {
|
|
|
586
621
|
* @param {string} recipientAddress - Bitcoin address to receive the payment.
|
|
587
622
|
* @param {Utxo[]} utxos - UTXOs to fund the transaction with.
|
|
588
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.
|
|
589
625
|
* @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
|
|
590
626
|
*/
|
|
591
|
-
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
|
|
627
|
+
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast", signer) {
|
|
592
628
|
const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
|
|
593
629
|
psbt.addOutput({
|
|
594
630
|
address: recipientAddress,
|
|
595
631
|
value: Number(amount)
|
|
596
632
|
});
|
|
597
633
|
this.funding.set(psbt, { utxos: [...utxos] });
|
|
634
|
+
if (signer) {
|
|
635
|
+
this.psbtSigner.set(psbt, signer);
|
|
636
|
+
}
|
|
598
637
|
return this.fundPegin(psbt, feeLevel, amount);
|
|
599
638
|
}
|
|
600
639
|
async signPegin(psbt, inputs, transactions) {
|
|
601
|
-
|
|
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);
|
|
602
643
|
}
|
|
603
644
|
/**
|
|
604
645
|
* Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
|
|
@@ -1067,6 +1108,7 @@ export {
|
|
|
1067
1108
|
AmountBelowMinError,
|
|
1068
1109
|
FederationAddressError,
|
|
1069
1110
|
InvalidAddressError,
|
|
1111
|
+
InvalidFeeRateError,
|
|
1070
1112
|
LedgerSigner,
|
|
1071
1113
|
NotEnoughFundsError,
|
|
1072
1114
|
PeginStatuses,
|
package/docs/bitcoin-signers.md
CHANGED
|
@@ -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 `
|
|
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