@rsksmart/powpeg-sdk 1.2.0-beta → 1.2.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +15 -4
- package/dist/index.d.ts +15 -4
- package/dist/index.js +126 -23
- package/dist/index.mjs +125 -23
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -198,8 +198,7 @@ declare class PowPegSDK {
|
|
|
198
198
|
private pegInOutputs;
|
|
199
199
|
private powpegRsktHeader;
|
|
200
200
|
private burnDustMaxValue;
|
|
201
|
-
private
|
|
202
|
-
private changeAddress?;
|
|
201
|
+
private funding;
|
|
203
202
|
private minPeginAmount;
|
|
204
203
|
private peginFeeEstimationInputs;
|
|
205
204
|
private minPegoutAmount;
|
|
@@ -226,14 +225,18 @@ declare class PowPegSDK {
|
|
|
226
225
|
private groupAddressesByUsage;
|
|
227
226
|
private groupAddressesByBalance;
|
|
228
227
|
private getAddressesGroupedByUsage;
|
|
228
|
+
private validateRskRecipient;
|
|
229
|
+
private getVerifiedFederationAddress;
|
|
229
230
|
private getRskOutput;
|
|
230
231
|
/**
|
|
231
232
|
* Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
|
|
232
233
|
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
233
234
|
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
235
|
+
* @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
|
|
236
|
+
* same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
|
|
234
237
|
* @returns {Promise<number>} The estimated total fee in satoshis.
|
|
235
238
|
*/
|
|
236
|
-
estimatePeginFee(amount: bigint, feeLevel?: FeeLevel): Promise<number>;
|
|
239
|
+
estimatePeginFee(amount: bigint, feeLevel?: FeeLevel, utxos?: Utxo[]): Promise<number>;
|
|
237
240
|
/**
|
|
238
241
|
* Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
|
|
239
242
|
* encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
|
|
@@ -391,6 +394,8 @@ declare class TrezorSigner implements BitcoinSigner {
|
|
|
391
394
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
392
395
|
private getScriptType;
|
|
393
396
|
private getInputs;
|
|
397
|
+
private getOutputScriptType;
|
|
398
|
+
private isChangePath;
|
|
394
399
|
private getOutputs;
|
|
395
400
|
/**
|
|
396
401
|
* Signs the given PSBT's inputs/outputs on the Trezor device.
|
|
@@ -444,6 +449,8 @@ declare class LedgerSigner implements BitcoinSigner {
|
|
|
444
449
|
*/
|
|
445
450
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
446
451
|
getInputs(inputs: Utxo[], transactions: string[]): CreateTransactionArg['inputs'];
|
|
452
|
+
private isChangePath;
|
|
453
|
+
private getChangePath;
|
|
447
454
|
getOutputScriptHex(psbt: Psbt): string;
|
|
448
455
|
/**
|
|
449
456
|
* Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
|
|
@@ -469,10 +476,14 @@ declare class APIError extends Error {
|
|
|
469
476
|
readonly data?: unknown;
|
|
470
477
|
constructor(message: string, statusCode?: number, data?: unknown);
|
|
471
478
|
}
|
|
479
|
+
/** Thrown when the federation address can't be retrieved from the pegin configuration endpoint or doesn't match the Bridge contract's value. */
|
|
480
|
+
declare class FederationAddressError extends Error {
|
|
481
|
+
constructor(message?: string);
|
|
482
|
+
}
|
|
472
483
|
/** Thrown when one or more Bitcoin addresses don't belong to the SDK's configured network. */
|
|
473
484
|
declare class InvalidAddressError extends Error {
|
|
474
485
|
readonly invalidAddresses: string[];
|
|
475
486
|
constructor(invalidAddresses: string[], message?: string);
|
|
476
487
|
}
|
|
477
488
|
|
|
478
|
-
export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, 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 };
|
|
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -198,8 +198,7 @@ declare class PowPegSDK {
|
|
|
198
198
|
private pegInOutputs;
|
|
199
199
|
private powpegRsktHeader;
|
|
200
200
|
private burnDustMaxValue;
|
|
201
|
-
private
|
|
202
|
-
private changeAddress?;
|
|
201
|
+
private funding;
|
|
203
202
|
private minPeginAmount;
|
|
204
203
|
private peginFeeEstimationInputs;
|
|
205
204
|
private minPegoutAmount;
|
|
@@ -226,14 +225,18 @@ declare class PowPegSDK {
|
|
|
226
225
|
private groupAddressesByUsage;
|
|
227
226
|
private groupAddressesByBalance;
|
|
228
227
|
private getAddressesGroupedByUsage;
|
|
228
|
+
private validateRskRecipient;
|
|
229
|
+
private getVerifiedFederationAddress;
|
|
229
230
|
private getRskOutput;
|
|
230
231
|
/**
|
|
231
232
|
* Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
|
|
232
233
|
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
233
234
|
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
235
|
+
* @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
|
|
236
|
+
* same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
|
|
234
237
|
* @returns {Promise<number>} The estimated total fee in satoshis.
|
|
235
238
|
*/
|
|
236
|
-
estimatePeginFee(amount: bigint, feeLevel?: FeeLevel): Promise<number>;
|
|
239
|
+
estimatePeginFee(amount: bigint, feeLevel?: FeeLevel, utxos?: Utxo[]): Promise<number>;
|
|
237
240
|
/**
|
|
238
241
|
* Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
|
|
239
242
|
* encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
|
|
@@ -391,6 +394,8 @@ declare class TrezorSigner implements BitcoinSigner {
|
|
|
391
394
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
392
395
|
private getScriptType;
|
|
393
396
|
private getInputs;
|
|
397
|
+
private getOutputScriptType;
|
|
398
|
+
private isChangePath;
|
|
394
399
|
private getOutputs;
|
|
395
400
|
/**
|
|
396
401
|
* Signs the given PSBT's inputs/outputs on the Trezor device.
|
|
@@ -444,6 +449,8 @@ declare class LedgerSigner implements BitcoinSigner {
|
|
|
444
449
|
*/
|
|
445
450
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
446
451
|
getInputs(inputs: Utxo[], transactions: string[]): CreateTransactionArg['inputs'];
|
|
452
|
+
private isChangePath;
|
|
453
|
+
private getChangePath;
|
|
447
454
|
getOutputScriptHex(psbt: Psbt): string;
|
|
448
455
|
/**
|
|
449
456
|
* Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
|
|
@@ -469,10 +476,14 @@ declare class APIError extends Error {
|
|
|
469
476
|
readonly data?: unknown;
|
|
470
477
|
constructor(message: string, statusCode?: number, data?: unknown);
|
|
471
478
|
}
|
|
479
|
+
/** Thrown when the federation address can't be retrieved from the pegin configuration endpoint or doesn't match the Bridge contract's value. */
|
|
480
|
+
declare class FederationAddressError extends Error {
|
|
481
|
+
constructor(message?: string);
|
|
482
|
+
}
|
|
472
483
|
/** Thrown when one or more Bitcoin addresses don't belong to the SDK's configured network. */
|
|
473
484
|
declare class InvalidAddressError extends Error {
|
|
474
485
|
readonly invalidAddresses: string[];
|
|
475
486
|
constructor(invalidAddresses: string[], message?: string);
|
|
476
487
|
}
|
|
477
488
|
|
|
478
|
-
export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, 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 };
|
|
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 };
|
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
|
-
|
|
271
|
-
|
|
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(({
|
|
281
|
-
address:
|
|
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:
|
|
310
|
+
address: address2,
|
|
292
311
|
balance: details.balance,
|
|
293
312
|
txCount: details.txs
|
|
294
313
|
};
|
|
@@ -301,6 +320,10 @@ 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
|
+
}
|
|
304
327
|
async getFeatures() {
|
|
305
328
|
const response = await this.api.get("/features").catch(this.handleError);
|
|
306
329
|
return response.data;
|
|
@@ -336,8 +359,7 @@ var PowPegSDK = class {
|
|
|
336
359
|
pegInOutputs = 3;
|
|
337
360
|
powpegRsktHeader = "52534b5401";
|
|
338
361
|
burnDustMaxValue = 3e4;
|
|
339
|
-
|
|
340
|
-
changeAddress;
|
|
362
|
+
funding = /* @__PURE__ */ new WeakMap();
|
|
341
363
|
minPeginAmount = 500000n;
|
|
342
364
|
peginFeeEstimationInputs = 2;
|
|
343
365
|
minPegoutAmount = "0.004";
|
|
@@ -414,8 +436,31 @@ var PowPegSDK = class {
|
|
|
414
436
|
change: this.groupAddressesByUsage(changeDetails)
|
|
415
437
|
};
|
|
416
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
|
+
}
|
|
417
462
|
getRskOutput(recipientAddress, refundAddress) {
|
|
418
|
-
let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
|
|
463
|
+
let output = `${this.powpegRsktHeader}${remove0x(this.validateRskRecipient(recipientAddress))}`;
|
|
419
464
|
if (refundAddress) {
|
|
420
465
|
const refundAddressType = getAddressType(refundAddress, this.network);
|
|
421
466
|
const prefixes = {
|
|
@@ -433,10 +478,16 @@ var PowPegSDK = class {
|
|
|
433
478
|
* Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
|
|
434
479
|
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
435
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.
|
|
436
483
|
* @returns {Promise<number>} The estimated total fee in satoshis.
|
|
437
484
|
*/
|
|
438
|
-
async estimatePeginFee(amount, feeLevel = "fast") {
|
|
485
|
+
async estimatePeginFee(amount, feeLevel = "fast", utxos) {
|
|
439
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
|
+
}
|
|
440
491
|
const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
|
|
441
492
|
const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
|
|
442
493
|
return totalFee;
|
|
@@ -461,31 +512,36 @@ var PowPegSDK = class {
|
|
|
461
512
|
value: 0
|
|
462
513
|
});
|
|
463
514
|
}
|
|
464
|
-
const bridgeAddress = await this.
|
|
515
|
+
const bridgeAddress = await this.getVerifiedFederationAddress();
|
|
465
516
|
psbt.addOutput({
|
|
466
517
|
address: bridgeAddress,
|
|
467
518
|
value: Number(amount)
|
|
468
519
|
});
|
|
520
|
+
let utxos;
|
|
469
521
|
if (selectedUtxos) {
|
|
470
|
-
|
|
522
|
+
utxos = [...selectedUtxos];
|
|
471
523
|
} else {
|
|
472
524
|
const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
|
|
473
525
|
const { withBalance } = this.groupAddressesByBalance(usedAddresses);
|
|
474
|
-
|
|
526
|
+
utxos = await this.getUtxos(withBalance);
|
|
475
527
|
}
|
|
476
|
-
this.changeAddress
|
|
528
|
+
this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
|
|
477
529
|
return psbt;
|
|
478
530
|
}
|
|
479
531
|
selectInputs(amount, utxos, baseFee, feePerInput) {
|
|
480
532
|
const inputs = [];
|
|
481
533
|
let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
|
|
482
|
-
utxos.sort((a, b) =>
|
|
483
|
-
|
|
484
|
-
if (remainingSatoshisToBePaid
|
|
485
|
-
|
|
486
|
-
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;
|
|
487
538
|
}
|
|
488
|
-
|
|
539
|
+
if (BigInt(utxo.amount) <= BigInt(feePerInput)) {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
inputs.push(utxo);
|
|
543
|
+
remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
|
|
544
|
+
}
|
|
489
545
|
return { inputs, rest: Number(remainingSatoshisToBePaid) };
|
|
490
546
|
}
|
|
491
547
|
validatePeginAmount(amount) {
|
|
@@ -518,12 +574,16 @@ var PowPegSDK = class {
|
|
|
518
574
|
* @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
|
|
519
575
|
*/
|
|
520
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.");
|
|
521
579
|
const amount = value ?? BigInt(psbt.txOutputs[1].value);
|
|
522
580
|
const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
|
|
523
|
-
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount,
|
|
581
|
+
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
|
|
524
582
|
if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
|
|
525
583
|
psbt.addOutput({
|
|
526
|
-
address
|
|
584
|
+
// Fall back to the first funding input's address when every derived
|
|
585
|
+
// change address has already been used.
|
|
586
|
+
address: funding.changeAddress ?? inputs[0].address,
|
|
527
587
|
value: change
|
|
528
588
|
});
|
|
529
589
|
}
|
|
@@ -571,7 +631,7 @@ var PowPegSDK = class {
|
|
|
571
631
|
address: recipientAddress,
|
|
572
632
|
value: Number(amount)
|
|
573
633
|
});
|
|
574
|
-
this.utxos
|
|
634
|
+
this.funding.set(psbt, { utxos: [...utxos] });
|
|
575
635
|
return this.fundPegin(psbt, feeLevel, amount);
|
|
576
636
|
}
|
|
577
637
|
async signPegin(psbt, inputs, transactions) {
|
|
@@ -783,8 +843,23 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
783
843
|
};
|
|
784
844
|
});
|
|
785
845
|
}
|
|
846
|
+
getOutputScriptType(address2) {
|
|
847
|
+
const addressType = getAddressType(address2, this.network);
|
|
848
|
+
switch (addressType) {
|
|
849
|
+
case "SEGWIT":
|
|
850
|
+
return "PAYTOP2SHWITNESS";
|
|
851
|
+
case "NATIVE SEGWIT":
|
|
852
|
+
return "PAYTOWITNESS";
|
|
853
|
+
default:
|
|
854
|
+
return "PAYTOADDRESS";
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
isChangePath(path) {
|
|
858
|
+
return path.length === 5 && path[3] === 1;
|
|
859
|
+
}
|
|
786
860
|
getOutputs(psbt) {
|
|
787
|
-
|
|
861
|
+
const lastIndex = psbt.txOutputs.length - 1;
|
|
862
|
+
return psbt.txOutputs.map((output, index) => {
|
|
788
863
|
if (output.value === 0 && !output.address) {
|
|
789
864
|
return {
|
|
790
865
|
amount: output.value,
|
|
@@ -792,6 +867,14 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
792
867
|
script_type: "PAYTOOPRETURN"
|
|
793
868
|
};
|
|
794
869
|
}
|
|
870
|
+
const path = output.address ? this.addresses.get(output.address) : void 0;
|
|
871
|
+
if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
|
|
872
|
+
return {
|
|
873
|
+
address_n: path,
|
|
874
|
+
script_type: this.getOutputScriptType(output.address),
|
|
875
|
+
amount: output.value
|
|
876
|
+
};
|
|
877
|
+
}
|
|
795
878
|
return {
|
|
796
879
|
address: output.address ?? "",
|
|
797
880
|
script_type: "PAYTOADDRESS",
|
|
@@ -961,6 +1044,21 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
961
1044
|
return [deserializedTx, input.vout, void 0, void 0];
|
|
962
1045
|
});
|
|
963
1046
|
}
|
|
1047
|
+
isChangePath(path) {
|
|
1048
|
+
const segments = path.split("/");
|
|
1049
|
+
return segments.length === 6 && segments[4] === "1";
|
|
1050
|
+
}
|
|
1051
|
+
getChangePath(psbt) {
|
|
1052
|
+
if (psbt.txOutputs.length < 2) {
|
|
1053
|
+
return void 0;
|
|
1054
|
+
}
|
|
1055
|
+
const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
|
|
1056
|
+
if (!lastOutput.address) {
|
|
1057
|
+
return void 0;
|
|
1058
|
+
}
|
|
1059
|
+
const path = this.addresses.get(lastOutput.address);
|
|
1060
|
+
return path && this.isChangePath(path) ? path : void 0;
|
|
1061
|
+
}
|
|
964
1062
|
getOutputScriptHex(psbt) {
|
|
965
1063
|
const outputs = psbt.txOutputs.map((output) => {
|
|
966
1064
|
const amount = Buffer.alloc(8);
|
|
@@ -986,10 +1084,14 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
986
1084
|
const ledgerInputs = this.getInputs(inputs, transactions);
|
|
987
1085
|
const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
|
|
988
1086
|
const outputScriptHex = this.getOutputScriptHex(psbt);
|
|
1087
|
+
const changePath = this.getChangePath(psbt);
|
|
989
1088
|
return this.connection.createPaymentTransaction({
|
|
990
1089
|
inputs: ledgerInputs,
|
|
991
1090
|
associatedKeysets: paths,
|
|
992
1091
|
outputScriptHex,
|
|
1092
|
+
// hw-app-btc throws if changePath matches no output, so omit it
|
|
1093
|
+
// when the transaction has no device-derived change output
|
|
1094
|
+
...changePath ? { changePath } : {},
|
|
993
1095
|
segwit: this.isSegwit(),
|
|
994
1096
|
useTrustedInputForSegwit: this.isSegwit(),
|
|
995
1097
|
additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
|
|
@@ -1001,6 +1103,7 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
1001
1103
|
0 && (module.exports = {
|
|
1002
1104
|
APIError,
|
|
1003
1105
|
AmountBelowMinError,
|
|
1106
|
+
FederationAddressError,
|
|
1004
1107
|
InvalidAddressError,
|
|
1005
1108
|
LedgerSigner,
|
|
1006
1109
|
NotEnoughFundsError,
|
package/dist/index.mjs
CHANGED
|
@@ -176,6 +176,12 @@ var APIError = class extends Error {
|
|
|
176
176
|
this.data = data;
|
|
177
177
|
}
|
|
178
178
|
};
|
|
179
|
+
var FederationAddressError = class extends Error {
|
|
180
|
+
constructor(message) {
|
|
181
|
+
super(message);
|
|
182
|
+
this.name = "FederationAddressError";
|
|
183
|
+
}
|
|
184
|
+
};
|
|
179
185
|
var InvalidAddressError = class extends Error {
|
|
180
186
|
invalidAddresses;
|
|
181
187
|
constructor(invalidAddresses, message) {
|
|
@@ -193,6 +199,7 @@ var ApiService = class {
|
|
|
193
199
|
MAIN: "https://api.2wp.rootstock.io",
|
|
194
200
|
TEST: "https://api.2wp.testnet.rootstock.io"
|
|
195
201
|
};
|
|
202
|
+
maxFeeRateSatPerByte = 1e3;
|
|
196
203
|
feeLevelBlocks = {
|
|
197
204
|
slow: 5,
|
|
198
205
|
average: 3,
|
|
@@ -221,8 +228,19 @@ var ApiService = class {
|
|
|
221
228
|
async getFeeRate(level) {
|
|
222
229
|
const blocks = this.feeLevelBlocks[level];
|
|
223
230
|
const response = await this.api.get(`/estimate-fee/${blocks}`).catch(this.handleError);
|
|
224
|
-
|
|
225
|
-
|
|
231
|
+
let satoshisPerKb;
|
|
232
|
+
try {
|
|
233
|
+
satoshisPerKb = ethers2.utils.parseUnits(String(response.data.amount), 8);
|
|
234
|
+
} catch {
|
|
235
|
+
throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
|
|
236
|
+
}
|
|
237
|
+
if (satoshisPerKb.lte(0)) {
|
|
238
|
+
throw new APIError(`Invalid fee rate received: ${response.data.amount}`);
|
|
239
|
+
}
|
|
240
|
+
if (satoshisPerKb.gt(this.maxFeeRateSatPerByte * 1e3)) {
|
|
241
|
+
throw new APIError(`Fee rate out of bounds: ${response.data.amount}`);
|
|
242
|
+
}
|
|
243
|
+
return satoshisPerKb.add(999).div(1e3).toNumber();
|
|
226
244
|
}
|
|
227
245
|
async getTxHex(txId) {
|
|
228
246
|
const response = await this.api.get(`/tx?tx=${txId}`).catch(this.handleError);
|
|
@@ -231,8 +249,8 @@ var ApiService = class {
|
|
|
231
249
|
async getOutputs(address2) {
|
|
232
250
|
const response = await this.api.post("/utxo", { addressList: [address2] }).catch(this.handleError);
|
|
233
251
|
const { data: utxos } = response.data;
|
|
234
|
-
return utxos.map(({
|
|
235
|
-
address:
|
|
252
|
+
return utxos.map(({ txid, vout, satoshis }) => ({
|
|
253
|
+
address: address2,
|
|
236
254
|
txid,
|
|
237
255
|
amount: BigInt(satoshis),
|
|
238
256
|
vout
|
|
@@ -242,7 +260,7 @@ var ApiService = class {
|
|
|
242
260
|
const response = await this.api.post("/addresses-info", { addressList: [address2] }).catch(this.handleError);
|
|
243
261
|
const [details] = response.data.addressesInfo;
|
|
244
262
|
return {
|
|
245
|
-
address:
|
|
263
|
+
address: address2,
|
|
246
264
|
balance: details.balance,
|
|
247
265
|
txCount: details.txs
|
|
248
266
|
};
|
|
@@ -255,6 +273,10 @@ var ApiService = class {
|
|
|
255
273
|
const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
|
|
256
274
|
return response.data;
|
|
257
275
|
}
|
|
276
|
+
async getPeginConfiguration() {
|
|
277
|
+
const response = await this.api.get("/pegin-configuration").catch(this.handleError);
|
|
278
|
+
return response.data;
|
|
279
|
+
}
|
|
258
280
|
async getFeatures() {
|
|
259
281
|
const response = await this.api.get("/features").catch(this.handleError);
|
|
260
282
|
return response.data;
|
|
@@ -290,8 +312,7 @@ var PowPegSDK = class {
|
|
|
290
312
|
pegInOutputs = 3;
|
|
291
313
|
powpegRsktHeader = "52534b5401";
|
|
292
314
|
burnDustMaxValue = 3e4;
|
|
293
|
-
|
|
294
|
-
changeAddress;
|
|
315
|
+
funding = /* @__PURE__ */ new WeakMap();
|
|
295
316
|
minPeginAmount = 500000n;
|
|
296
317
|
peginFeeEstimationInputs = 2;
|
|
297
318
|
minPegoutAmount = "0.004";
|
|
@@ -368,8 +389,31 @@ var PowPegSDK = class {
|
|
|
368
389
|
change: this.groupAddressesByUsage(changeDetails)
|
|
369
390
|
};
|
|
370
391
|
}
|
|
392
|
+
validateRskRecipient(recipientAddress) {
|
|
393
|
+
const trimmed = recipientAddress.trim();
|
|
394
|
+
if (!/^(0x)?[0-9a-fA-F]{40}$/.test(trimmed)) {
|
|
395
|
+
throw new InvalidAddressError([recipientAddress], `Invalid Rootstock recipient: ${recipientAddress}`);
|
|
396
|
+
}
|
|
397
|
+
return trimmed.toLowerCase();
|
|
398
|
+
}
|
|
399
|
+
async getVerifiedFederationAddress() {
|
|
400
|
+
const [bridgeAddress, peginConfiguration] = await Promise.all([
|
|
401
|
+
this.bridge.getFederationAddress().catch((error) => {
|
|
402
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
403
|
+
throw new FederationAddressError(`Could not retrieve the federation address from the Bridge contract: ${reason}`);
|
|
404
|
+
}),
|
|
405
|
+
this.api.getPeginConfiguration().catch((error) => {
|
|
406
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
407
|
+
throw new FederationAddressError(`Could not retrieve the pegin configuration: ${reason}`);
|
|
408
|
+
})
|
|
409
|
+
]);
|
|
410
|
+
if (peginConfiguration.federationAddress !== bridgeAddress) {
|
|
411
|
+
throw new FederationAddressError("Federation address mismatch between the Bridge contract and the pegin configuration.");
|
|
412
|
+
}
|
|
413
|
+
return bridgeAddress;
|
|
414
|
+
}
|
|
371
415
|
getRskOutput(recipientAddress, refundAddress) {
|
|
372
|
-
let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
|
|
416
|
+
let output = `${this.powpegRsktHeader}${remove0x(this.validateRskRecipient(recipientAddress))}`;
|
|
373
417
|
if (refundAddress) {
|
|
374
418
|
const refundAddressType = getAddressType(refundAddress, this.network);
|
|
375
419
|
const prefixes = {
|
|
@@ -387,10 +431,16 @@ var PowPegSDK = class {
|
|
|
387
431
|
* Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
|
|
388
432
|
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
389
433
|
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
434
|
+
* @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
|
|
435
|
+
* same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
|
|
390
436
|
* @returns {Promise<number>} The estimated total fee in satoshis.
|
|
391
437
|
*/
|
|
392
|
-
async estimatePeginFee(amount, feeLevel = "fast") {
|
|
438
|
+
async estimatePeginFee(amount, feeLevel = "fast", utxos) {
|
|
393
439
|
const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
|
|
440
|
+
if (utxos) {
|
|
441
|
+
const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
|
|
442
|
+
return totalFee2;
|
|
443
|
+
}
|
|
394
444
|
const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
|
|
395
445
|
const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
|
|
396
446
|
return totalFee;
|
|
@@ -415,31 +465,36 @@ var PowPegSDK = class {
|
|
|
415
465
|
value: 0
|
|
416
466
|
});
|
|
417
467
|
}
|
|
418
|
-
const bridgeAddress = await this.
|
|
468
|
+
const bridgeAddress = await this.getVerifiedFederationAddress();
|
|
419
469
|
psbt.addOutput({
|
|
420
470
|
address: bridgeAddress,
|
|
421
471
|
value: Number(amount)
|
|
422
472
|
});
|
|
473
|
+
let utxos;
|
|
423
474
|
if (selectedUtxos) {
|
|
424
|
-
|
|
475
|
+
utxos = [...selectedUtxos];
|
|
425
476
|
} else {
|
|
426
477
|
const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
|
|
427
478
|
const { withBalance } = this.groupAddressesByBalance(usedAddresses);
|
|
428
|
-
|
|
479
|
+
utxos = await this.getUtxos(withBalance);
|
|
429
480
|
}
|
|
430
|
-
this.changeAddress
|
|
481
|
+
this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
|
|
431
482
|
return psbt;
|
|
432
483
|
}
|
|
433
484
|
selectInputs(amount, utxos, baseFee, feePerInput) {
|
|
434
485
|
const inputs = [];
|
|
435
486
|
let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
|
|
436
|
-
utxos.sort((a, b) =>
|
|
437
|
-
|
|
438
|
-
if (remainingSatoshisToBePaid
|
|
439
|
-
|
|
440
|
-
remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
|
|
487
|
+
const candidates = [...utxos].sort((a, b) => Number(b.amount - a.amount));
|
|
488
|
+
for (const utxo of candidates) {
|
|
489
|
+
if (remainingSatoshisToBePaid <= 0) {
|
|
490
|
+
break;
|
|
441
491
|
}
|
|
442
|
-
|
|
492
|
+
if (BigInt(utxo.amount) <= BigInt(feePerInput)) {
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
inputs.push(utxo);
|
|
496
|
+
remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
|
|
497
|
+
}
|
|
443
498
|
return { inputs, rest: Number(remainingSatoshisToBePaid) };
|
|
444
499
|
}
|
|
445
500
|
validatePeginAmount(amount) {
|
|
@@ -472,12 +527,16 @@ var PowPegSDK = class {
|
|
|
472
527
|
* @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
|
|
473
528
|
*/
|
|
474
529
|
async fundPegin(psbt, feeLevel = "fast", value) {
|
|
530
|
+
const funding = this.funding.get(psbt);
|
|
531
|
+
assertTruthy(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
|
|
475
532
|
const amount = value ?? BigInt(psbt.txOutputs[1].value);
|
|
476
533
|
const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
|
|
477
|
-
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount,
|
|
534
|
+
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
|
|
478
535
|
if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
|
|
479
536
|
psbt.addOutput({
|
|
480
|
-
address
|
|
537
|
+
// Fall back to the first funding input's address when every derived
|
|
538
|
+
// change address has already been used.
|
|
539
|
+
address: funding.changeAddress ?? inputs[0].address,
|
|
481
540
|
value: change
|
|
482
541
|
});
|
|
483
542
|
}
|
|
@@ -525,7 +584,7 @@ var PowPegSDK = class {
|
|
|
525
584
|
address: recipientAddress,
|
|
526
585
|
value: Number(amount)
|
|
527
586
|
});
|
|
528
|
-
this.utxos
|
|
587
|
+
this.funding.set(psbt, { utxos: [...utxos] });
|
|
529
588
|
return this.fundPegin(psbt, feeLevel, amount);
|
|
530
589
|
}
|
|
531
590
|
async signPegin(psbt, inputs, transactions) {
|
|
@@ -737,8 +796,23 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
737
796
|
};
|
|
738
797
|
});
|
|
739
798
|
}
|
|
799
|
+
getOutputScriptType(address2) {
|
|
800
|
+
const addressType = getAddressType(address2, this.network);
|
|
801
|
+
switch (addressType) {
|
|
802
|
+
case "SEGWIT":
|
|
803
|
+
return "PAYTOP2SHWITNESS";
|
|
804
|
+
case "NATIVE SEGWIT":
|
|
805
|
+
return "PAYTOWITNESS";
|
|
806
|
+
default:
|
|
807
|
+
return "PAYTOADDRESS";
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
isChangePath(path) {
|
|
811
|
+
return path.length === 5 && path[3] === 1;
|
|
812
|
+
}
|
|
740
813
|
getOutputs(psbt) {
|
|
741
|
-
|
|
814
|
+
const lastIndex = psbt.txOutputs.length - 1;
|
|
815
|
+
return psbt.txOutputs.map((output, index) => {
|
|
742
816
|
if (output.value === 0 && !output.address) {
|
|
743
817
|
return {
|
|
744
818
|
amount: output.value,
|
|
@@ -746,6 +820,14 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
746
820
|
script_type: "PAYTOOPRETURN"
|
|
747
821
|
};
|
|
748
822
|
}
|
|
823
|
+
const path = output.address ? this.addresses.get(output.address) : void 0;
|
|
824
|
+
if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
|
|
825
|
+
return {
|
|
826
|
+
address_n: path,
|
|
827
|
+
script_type: this.getOutputScriptType(output.address),
|
|
828
|
+
amount: output.value
|
|
829
|
+
};
|
|
830
|
+
}
|
|
749
831
|
return {
|
|
750
832
|
address: output.address ?? "",
|
|
751
833
|
script_type: "PAYTOADDRESS",
|
|
@@ -915,6 +997,21 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
915
997
|
return [deserializedTx, input.vout, void 0, void 0];
|
|
916
998
|
});
|
|
917
999
|
}
|
|
1000
|
+
isChangePath(path) {
|
|
1001
|
+
const segments = path.split("/");
|
|
1002
|
+
return segments.length === 6 && segments[4] === "1";
|
|
1003
|
+
}
|
|
1004
|
+
getChangePath(psbt) {
|
|
1005
|
+
if (psbt.txOutputs.length < 2) {
|
|
1006
|
+
return void 0;
|
|
1007
|
+
}
|
|
1008
|
+
const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
|
|
1009
|
+
if (!lastOutput.address) {
|
|
1010
|
+
return void 0;
|
|
1011
|
+
}
|
|
1012
|
+
const path = this.addresses.get(lastOutput.address);
|
|
1013
|
+
return path && this.isChangePath(path) ? path : void 0;
|
|
1014
|
+
}
|
|
918
1015
|
getOutputScriptHex(psbt) {
|
|
919
1016
|
const outputs = psbt.txOutputs.map((output) => {
|
|
920
1017
|
const amount = Buffer.alloc(8);
|
|
@@ -940,10 +1037,14 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
940
1037
|
const ledgerInputs = this.getInputs(inputs, transactions);
|
|
941
1038
|
const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
|
|
942
1039
|
const outputScriptHex = this.getOutputScriptHex(psbt);
|
|
1040
|
+
const changePath = this.getChangePath(psbt);
|
|
943
1041
|
return this.connection.createPaymentTransaction({
|
|
944
1042
|
inputs: ledgerInputs,
|
|
945
1043
|
associatedKeysets: paths,
|
|
946
1044
|
outputScriptHex,
|
|
1045
|
+
// hw-app-btc throws if changePath matches no output, so omit it
|
|
1046
|
+
// when the transaction has no device-derived change output
|
|
1047
|
+
...changePath ? { changePath } : {},
|
|
947
1048
|
segwit: this.isSegwit(),
|
|
948
1049
|
useTrustedInputForSegwit: this.isSegwit(),
|
|
949
1050
|
additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
|
|
@@ -954,6 +1055,7 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
954
1055
|
export {
|
|
955
1056
|
APIError,
|
|
956
1057
|
AmountBelowMinError,
|
|
1058
|
+
FederationAddressError,
|
|
957
1059
|
InvalidAddressError,
|
|
958
1060
|
LedgerSigner,
|
|
959
1061
|
NotEnoughFundsError,
|
package/package.json
CHANGED