@rsksmart/powpeg-sdk 1.2.0-beta.2 → 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/README.md +40 -0
- package/SECURITY.md +7 -132
- package/dist/index.d.mts +207 -7
- package/dist/index.d.ts +207 -7
- package/dist/index.js +285 -24
- package/dist/index.mjs +284 -24
- package/docs/api.md +51 -0
- package/docs/bitcoin-signers.md +36 -0
- package/docs/setup.md +61 -0
- package/package.json +13 -4
- package/pnpm-workspace.yaml +2 -0
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,14 @@ var ApiService = class {
|
|
|
301
320
|
const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
|
|
302
321
|
return response.data;
|
|
303
322
|
}
|
|
323
|
+
async getPeginConfiguration() {
|
|
324
|
+
const response = await this.api.get("/pegin-configuration").catch(this.handleError);
|
|
325
|
+
return response.data;
|
|
326
|
+
}
|
|
327
|
+
async getFeatures() {
|
|
328
|
+
const response = await this.api.get("/features").catch(this.handleError);
|
|
329
|
+
return response.data;
|
|
330
|
+
}
|
|
304
331
|
};
|
|
305
332
|
|
|
306
333
|
// src/sdk/powpeg.ts
|
|
@@ -332,8 +359,7 @@ var PowPegSDK = class {
|
|
|
332
359
|
pegInOutputs = 3;
|
|
333
360
|
powpegRsktHeader = "52534b5401";
|
|
334
361
|
burnDustMaxValue = 3e4;
|
|
335
|
-
|
|
336
|
-
changeAddress;
|
|
362
|
+
funding = /* @__PURE__ */ new WeakMap();
|
|
337
363
|
minPeginAmount = 500000n;
|
|
338
364
|
peginFeeEstimationInputs = 2;
|
|
339
365
|
minPegoutAmount = "0.004";
|
|
@@ -358,7 +384,18 @@ var PowPegSDK = class {
|
|
|
358
384
|
async getUtxos(addresses) {
|
|
359
385
|
const rawAddresses = addresses.map((address2) => typeof address2 === "string" ? address2 : address2.address);
|
|
360
386
|
const utxoLists = await Promise.all(rawAddresses.map((address2) => this.bitcoinDataSource.getOutputs(address2)));
|
|
361
|
-
|
|
387
|
+
const allUtxos = utxoLists.flat();
|
|
388
|
+
const seen = /* @__PURE__ */ new Set();
|
|
389
|
+
const uniqueUtxos = allUtxos.filter((utxo) => {
|
|
390
|
+
const key = `${utxo.txid}:${utxo.vout}`;
|
|
391
|
+
if (seen.has(key)) {
|
|
392
|
+
console.warn(`[PowPegSDK] Duplicate UTXO detected and skipped: ${key}`);
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
seen.add(key);
|
|
396
|
+
return true;
|
|
397
|
+
});
|
|
398
|
+
return uniqueUtxos;
|
|
362
399
|
}
|
|
363
400
|
async getAddressesWithDetails(addresses) {
|
|
364
401
|
return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
|
|
@@ -399,8 +436,31 @@ var PowPegSDK = class {
|
|
|
399
436
|
change: this.groupAddressesByUsage(changeDetails)
|
|
400
437
|
};
|
|
401
438
|
}
|
|
439
|
+
validateRskRecipient(recipientAddress) {
|
|
440
|
+
const trimmed = recipientAddress.trim();
|
|
441
|
+
if (!/^(0x)?[0-9a-fA-F]{40}$/.test(trimmed)) {
|
|
442
|
+
throw new InvalidAddressError([recipientAddress], `Invalid Rootstock recipient: ${recipientAddress}`);
|
|
443
|
+
}
|
|
444
|
+
return trimmed.toLowerCase();
|
|
445
|
+
}
|
|
446
|
+
async getVerifiedFederationAddress() {
|
|
447
|
+
const [bridgeAddress, peginConfiguration] = await Promise.all([
|
|
448
|
+
this.bridge.getFederationAddress().catch((error) => {
|
|
449
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
450
|
+
throw new FederationAddressError(`Could not retrieve the federation address from the Bridge contract: ${reason}`);
|
|
451
|
+
}),
|
|
452
|
+
this.api.getPeginConfiguration().catch((error) => {
|
|
453
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
454
|
+
throw new FederationAddressError(`Could not retrieve the pegin configuration: ${reason}`);
|
|
455
|
+
})
|
|
456
|
+
]);
|
|
457
|
+
if (peginConfiguration.federationAddress !== bridgeAddress) {
|
|
458
|
+
throw new FederationAddressError("Federation address mismatch between the Bridge contract and the pegin configuration.");
|
|
459
|
+
}
|
|
460
|
+
return bridgeAddress;
|
|
461
|
+
}
|
|
402
462
|
getRskOutput(recipientAddress, refundAddress) {
|
|
403
|
-
let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
|
|
463
|
+
let output = `${this.powpegRsktHeader}${remove0x(this.validateRskRecipient(recipientAddress))}`;
|
|
404
464
|
if (refundAddress) {
|
|
405
465
|
const refundAddressType = getAddressType(refundAddress, this.network);
|
|
406
466
|
const prefixes = {
|
|
@@ -414,12 +474,33 @@ var PowPegSDK = class {
|
|
|
414
474
|
}
|
|
415
475
|
return Buffer.from(output, "hex");
|
|
416
476
|
}
|
|
417
|
-
|
|
477
|
+
/**
|
|
478
|
+
* Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount.
|
|
479
|
+
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
480
|
+
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
481
|
+
* @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the
|
|
482
|
+
* same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs.
|
|
483
|
+
* @returns {Promise<number>} The estimated total fee in satoshis.
|
|
484
|
+
*/
|
|
485
|
+
async estimatePeginFee(amount, feeLevel = "fast", utxos) {
|
|
418
486
|
const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
|
|
487
|
+
if (utxos) {
|
|
488
|
+
const { totalFee: totalFee2 } = await this.calculateFeeAndSelectedInputs(amount, utxos, feeRate);
|
|
489
|
+
return totalFee2;
|
|
490
|
+
}
|
|
419
491
|
const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
|
|
420
492
|
const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
|
|
421
493
|
return totalFee;
|
|
422
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address,
|
|
497
|
+
* encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output.
|
|
498
|
+
* Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction.
|
|
499
|
+
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
500
|
+
* @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
|
|
501
|
+
* @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
|
|
502
|
+
* @returns {Promise<Psbt>} The unsigned, unfunded peg-in PSBT.
|
|
503
|
+
*/
|
|
423
504
|
async createPegin(amount, recipientAddress, selectedUtxos) {
|
|
424
505
|
const addresses = await this.getAddressesGroupedByUsage();
|
|
425
506
|
const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
|
|
@@ -431,31 +512,36 @@ var PowPegSDK = class {
|
|
|
431
512
|
value: 0
|
|
432
513
|
});
|
|
433
514
|
}
|
|
434
|
-
const bridgeAddress = await this.
|
|
515
|
+
const bridgeAddress = await this.getVerifiedFederationAddress();
|
|
435
516
|
psbt.addOutput({
|
|
436
517
|
address: bridgeAddress,
|
|
437
518
|
value: Number(amount)
|
|
438
519
|
});
|
|
520
|
+
let utxos;
|
|
439
521
|
if (selectedUtxos) {
|
|
440
|
-
|
|
522
|
+
utxos = [...selectedUtxos];
|
|
441
523
|
} else {
|
|
442
524
|
const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
|
|
443
525
|
const { withBalance } = this.groupAddressesByBalance(usedAddresses);
|
|
444
|
-
|
|
526
|
+
utxos = await this.getUtxos(withBalance);
|
|
445
527
|
}
|
|
446
|
-
this.changeAddress
|
|
528
|
+
this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
|
|
447
529
|
return psbt;
|
|
448
530
|
}
|
|
449
531
|
selectInputs(amount, utxos, baseFee, feePerInput) {
|
|
450
532
|
const inputs = [];
|
|
451
533
|
let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
|
|
452
|
-
utxos.sort((a, b) =>
|
|
453
|
-
|
|
454
|
-
if (remainingSatoshisToBePaid
|
|
455
|
-
|
|
456
|
-
remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
|
|
534
|
+
const candidates = [...utxos].sort((a, b) => Number(b.amount - a.amount));
|
|
535
|
+
for (const utxo of candidates) {
|
|
536
|
+
if (remainingSatoshisToBePaid <= 0) {
|
|
537
|
+
break;
|
|
457
538
|
}
|
|
458
|
-
|
|
539
|
+
if (BigInt(utxo.amount) <= BigInt(feePerInput)) {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
inputs.push(utxo);
|
|
543
|
+
remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
|
|
544
|
+
}
|
|
459
545
|
return { inputs, rest: Number(remainingSatoshisToBePaid) };
|
|
460
546
|
}
|
|
461
547
|
validatePeginAmount(amount) {
|
|
@@ -479,13 +565,25 @@ var PowPegSDK = class {
|
|
|
479
565
|
const totalFee = baseFee + feePerInput * inputs.length;
|
|
480
566
|
return { inputs, change: Math.abs(rest), totalFee };
|
|
481
567
|
}
|
|
568
|
+
/**
|
|
569
|
+
* Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
|
|
570
|
+
* using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
|
|
571
|
+
* @param {Psbt} psbt - The peg-in PSBT to fund.
|
|
572
|
+
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
573
|
+
* @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value.
|
|
574
|
+
* @returns {Promise<UnsignedPegin>} The funded PSBT along with its inputs, their raw transactions, and the total fee.
|
|
575
|
+
*/
|
|
482
576
|
async fundPegin(psbt, feeLevel = "fast", value) {
|
|
577
|
+
const funding = this.funding.get(psbt);
|
|
578
|
+
(0, import_bridges_core_sdk4.assertTruthy)(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
|
|
483
579
|
const amount = value ?? BigInt(psbt.txOutputs[1].value);
|
|
484
580
|
const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
|
|
485
|
-
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount,
|
|
581
|
+
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, feeRate);
|
|
486
582
|
if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
|
|
487
583
|
psbt.addOutput({
|
|
488
|
-
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,
|
|
489
587
|
value: change
|
|
490
588
|
});
|
|
491
589
|
}
|
|
@@ -503,24 +601,49 @@ var PowPegSDK = class {
|
|
|
503
601
|
});
|
|
504
602
|
return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
|
|
505
603
|
}
|
|
604
|
+
/**
|
|
605
|
+
* Convenience method that creates and funds a peg-in PSBT in one call.
|
|
606
|
+
* @param {bigint} amount - Amount to peg in, in satoshis.
|
|
607
|
+
* @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC.
|
|
608
|
+
* @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
|
|
609
|
+
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
610
|
+
* @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
|
|
611
|
+
* @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
|
|
612
|
+
*/
|
|
506
613
|
async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos) {
|
|
507
614
|
this.bitcoinSigner = signer;
|
|
508
615
|
this.validatePeginAmount(amount);
|
|
509
616
|
const psbt = await this.createPegin(amount, recipientAddress, selectedUtxos);
|
|
510
617
|
return this.fundPegin(psbt, feeLevel);
|
|
511
618
|
}
|
|
619
|
+
/**
|
|
620
|
+
* Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs,
|
|
621
|
+
* without routing through the federation address (unlike {@link createPegin}).
|
|
622
|
+
* @param {bigint} amount - Amount to send, in satoshis.
|
|
623
|
+
* @param {string} recipientAddress - Bitcoin address to receive the payment.
|
|
624
|
+
* @param {Utxo[]} utxos - UTXOs to fund the transaction with.
|
|
625
|
+
* @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
|
|
626
|
+
* @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
|
|
627
|
+
*/
|
|
512
628
|
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast") {
|
|
513
629
|
const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
|
|
514
630
|
psbt.addOutput({
|
|
515
631
|
address: recipientAddress,
|
|
516
632
|
value: Number(amount)
|
|
517
633
|
});
|
|
518
|
-
this.utxos
|
|
634
|
+
this.funding.set(psbt, { utxos: [...utxos] });
|
|
519
635
|
return this.fundPegin(psbt, feeLevel, amount);
|
|
520
636
|
}
|
|
521
637
|
async signPegin(psbt, inputs, transactions) {
|
|
522
638
|
return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
|
|
523
639
|
}
|
|
640
|
+
/**
|
|
641
|
+
* Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
|
|
642
|
+
* @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
|
|
643
|
+
* @param {Utxo[]} [inputs] - The PSBT's funding UTXOs (the `inputs` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
|
|
644
|
+
* @param {string[]} [transactions] - Raw hex transactions for `inputs` (the `transactions` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT.
|
|
645
|
+
* @returns {Promise<string>} The broadcast transaction's ID.
|
|
646
|
+
*/
|
|
524
647
|
async signAndBroadcastPegin(psbt, inputs, transactions) {
|
|
525
648
|
const signedTx = await this.signPegin(psbt, inputs, transactions);
|
|
526
649
|
return this.bitcoinDataSource.broadcast(signedTx);
|
|
@@ -540,6 +663,12 @@ var PowPegSDK = class {
|
|
|
540
663
|
value: amountBN.toString()
|
|
541
664
|
};
|
|
542
665
|
}
|
|
666
|
+
/**
|
|
667
|
+
* Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount.
|
|
668
|
+
* @param {string} amount - Amount to peg out, in RBTC (18 decimals).
|
|
669
|
+
* @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
|
|
670
|
+
* @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
|
|
671
|
+
*/
|
|
543
672
|
async estimatePegoutFees(amount, fromAddress = import_bridges_core_sdk4.ethers.constants.AddressZero) {
|
|
544
673
|
this.validateMinimumPegoutAmount(amount);
|
|
545
674
|
const tx = this.createPegoutTransaction(amount, fromAddress);
|
|
@@ -554,6 +683,14 @@ var PowPegSDK = class {
|
|
|
554
683
|
rootstockFee
|
|
555
684
|
};
|
|
556
685
|
}
|
|
686
|
+
/**
|
|
687
|
+
* Validates the requested amount and the sender's balance, then builds an unsigned peg-out
|
|
688
|
+
* transaction (a value-transfer call to the bridge precompile) together with its estimated fees.
|
|
689
|
+
* @param {string} amount - Amount to peg out, in RBTC (18 decimals).
|
|
690
|
+
* @param {string} senderAccount - Rootstock address that will send the peg-out.
|
|
691
|
+
* @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
|
|
692
|
+
* @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
|
|
693
|
+
*/
|
|
557
694
|
async createPegout(amount, senderAccount) {
|
|
558
695
|
const fees = await this.estimatePegoutFees(amount, senderAccount);
|
|
559
696
|
const amountBN = import_bridges_core_sdk4.ethers.utils.parseUnits(amount, 18).toBigInt();
|
|
@@ -568,13 +705,39 @@ var PowPegSDK = class {
|
|
|
568
705
|
bitcoinFee: fees.bitcoinFee
|
|
569
706
|
};
|
|
570
707
|
}
|
|
708
|
+
/**
|
|
709
|
+
* Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
|
|
710
|
+
* and waits for it to be mined.
|
|
711
|
+
* @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
|
|
712
|
+
* @param {ethers.Signer} signer - Ethers signer used to send the transaction.
|
|
713
|
+
* @returns The mined transaction receipt, if the signer's provider is set.
|
|
714
|
+
*/
|
|
571
715
|
async signAndBroadcastPegout(tx, signer) {
|
|
572
716
|
const { hash } = await signer.sendTransaction(tx);
|
|
573
717
|
return signer.provider?.waitForTransaction(hash);
|
|
574
718
|
}
|
|
719
|
+
/**
|
|
720
|
+
* Fetches the current status of a peg-in or peg-out transaction from the configured API.
|
|
721
|
+
* @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
|
|
722
|
+
* @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction.
|
|
723
|
+
* @returns {Promise<Extract<StatusData, { type: T }>>} The transaction's type-narrowed status details.
|
|
724
|
+
*/
|
|
575
725
|
async getTransactionStatus(txHash, txType) {
|
|
576
726
|
return this.api.getTransactionStatus(txHash, txType);
|
|
577
727
|
}
|
|
728
|
+
/**
|
|
729
|
+
* Retrieves the feature flags from the 2WP API `/features` endpoint.
|
|
730
|
+
* @returns {Promise<Feature[]>} The feature flags as returned by the API.
|
|
731
|
+
*/
|
|
732
|
+
async getFeatures() {
|
|
733
|
+
return this.api.getFeatures();
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Returns the spendable UTXOs for the given Bitcoin address(es).
|
|
737
|
+
* @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for.
|
|
738
|
+
* @returns {Promise<Utxo[]>} The UTXOs available across the given address(es).
|
|
739
|
+
* @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network.
|
|
740
|
+
*/
|
|
578
741
|
async getAvailableUtxos(addresses) {
|
|
579
742
|
const addressList = Array.isArray(addresses) ? addresses : [addresses];
|
|
580
743
|
const invalidAddresses = addressList.filter((address2) => !this.btcNetworkConfig.isBtcAddress(address2));
|
|
@@ -587,6 +750,7 @@ var PowPegSDK = class {
|
|
|
587
750
|
|
|
588
751
|
// src/bitcoin-signers/trezor/trezor.ts
|
|
589
752
|
var import_connect_web = __toESM(require("@trezor/connect-web"));
|
|
753
|
+
var import_bridges_core_sdk5 = require("@rsksmart/bridges-core-sdk");
|
|
590
754
|
var import_bitcoinjs_lib5 = require("bitcoinjs-lib");
|
|
591
755
|
var TrezorSigner = class _TrezorSigner {
|
|
592
756
|
constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
|
|
@@ -595,14 +759,25 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
595
759
|
}
|
|
596
760
|
bitcoinTxVersion = 1;
|
|
597
761
|
addresses = /* @__PURE__ */ new Map();
|
|
762
|
+
/**
|
|
763
|
+
* Initializes the Trezor connection and returns a ready-to-use signer.
|
|
764
|
+
* @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
|
|
765
|
+
* @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
|
|
766
|
+
* @returns {Promise<TrezorSigner>} The initialized signer.
|
|
767
|
+
*/
|
|
598
768
|
static async init(network, initOptions) {
|
|
599
769
|
await import_connect_web.default.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
|
|
600
770
|
return new _TrezorSigner(network);
|
|
601
771
|
}
|
|
772
|
+
/**
|
|
773
|
+
* Disposes the current Trezor connection and re-initializes it.
|
|
774
|
+
* @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
|
|
775
|
+
*/
|
|
602
776
|
static async reinit() {
|
|
603
777
|
import_connect_web.default.dispose();
|
|
604
778
|
return _TrezorSigner.init();
|
|
605
779
|
}
|
|
780
|
+
/** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
|
|
606
781
|
set addressType(addressType) {
|
|
607
782
|
this._addressType = addressType;
|
|
608
783
|
}
|
|
@@ -630,9 +805,17 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
630
805
|
}
|
|
631
806
|
return addresses;
|
|
632
807
|
}
|
|
808
|
+
/**
|
|
809
|
+
* @param {number} bundleSize - Number of change addresses to derive.
|
|
810
|
+
* @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
|
|
811
|
+
*/
|
|
633
812
|
async getChangeAddresses(bundleSize) {
|
|
634
813
|
return this.getAddresses(bundleSize, true);
|
|
635
814
|
}
|
|
815
|
+
/**
|
|
816
|
+
* @param {number} bundleSize - Number of receive addresses to derive.
|
|
817
|
+
* @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
|
|
818
|
+
*/
|
|
636
819
|
async getNonChangeAddresses(bundleSize) {
|
|
637
820
|
return this.getAddresses(bundleSize);
|
|
638
821
|
}
|
|
@@ -660,8 +843,23 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
660
843
|
};
|
|
661
844
|
});
|
|
662
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
|
+
}
|
|
663
860
|
getOutputs(psbt) {
|
|
664
|
-
|
|
861
|
+
const lastIndex = psbt.txOutputs.length - 1;
|
|
862
|
+
return psbt.txOutputs.map((output, index) => {
|
|
665
863
|
if (output.value === 0 && !output.address) {
|
|
666
864
|
return {
|
|
667
865
|
amount: output.value,
|
|
@@ -669,6 +867,14 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
669
867
|
script_type: "PAYTOOPRETURN"
|
|
670
868
|
};
|
|
671
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
|
+
}
|
|
672
878
|
return {
|
|
673
879
|
address: output.address ?? "",
|
|
674
880
|
script_type: "PAYTOADDRESS",
|
|
@@ -676,7 +882,14 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
676
882
|
};
|
|
677
883
|
});
|
|
678
884
|
}
|
|
885
|
+
/**
|
|
886
|
+
* Signs the given PSBT's inputs/outputs on the Trezor device.
|
|
887
|
+
* @param {Psbt} psbt - The PSBT to sign.
|
|
888
|
+
* @param {Utxo[]} [utxos] - The PSBT's inputs, used to look up each input's derivation path and script type. Required — TrezorSigner cannot sign from the PSBT alone.
|
|
889
|
+
* @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
|
|
890
|
+
*/
|
|
679
891
|
async signTransaction(psbt, utxos) {
|
|
892
|
+
(0, import_bridges_core_sdk5.assertTruthy)(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
|
|
680
893
|
const inputs = this.getInputs(utxos);
|
|
681
894
|
const outputs = this.getOutputs(psbt);
|
|
682
895
|
const result = await import_connect_web.default.signTransaction({
|
|
@@ -695,6 +908,7 @@ var TrezorSigner = class _TrezorSigner {
|
|
|
695
908
|
// src/bitcoin-signers/ledger/ledger.ts
|
|
696
909
|
var import_hw_app_btc = __toESM(require("@ledgerhq/hw-app-btc"));
|
|
697
910
|
var import_hw_transport_webusb = __toESM(require("@ledgerhq/hw-transport-webusb"));
|
|
911
|
+
var import_bridges_core_sdk6 = require("@rsksmart/bridges-core-sdk");
|
|
698
912
|
var import_bitcoinjs_lib6 = require("bitcoinjs-lib");
|
|
699
913
|
|
|
700
914
|
// src/bitcoin-signers/ledger/ledger-transport.ts
|
|
@@ -750,17 +964,27 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
750
964
|
}
|
|
751
965
|
addresses = /* @__PURE__ */ new Map();
|
|
752
966
|
transportService;
|
|
967
|
+
/**
|
|
968
|
+
* Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
|
|
969
|
+
* @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
|
|
970
|
+
* @returns {Promise<LedgerSigner>} The initialized signer.
|
|
971
|
+
*/
|
|
753
972
|
static async init(network = "TEST") {
|
|
754
973
|
const transport = await import_hw_transport_webusb.default.create();
|
|
755
974
|
const connection = new import_hw_app_btc.default({ transport, currency: networks[network].currency });
|
|
756
975
|
return new _LedgerSigner(connection, transport, network);
|
|
757
976
|
}
|
|
977
|
+
/**
|
|
978
|
+
* Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
|
|
979
|
+
* @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
|
|
980
|
+
*/
|
|
758
981
|
async reinit() {
|
|
759
982
|
return this.transportService.enqueue(async () => {
|
|
760
983
|
await this.transport.close();
|
|
761
984
|
return _LedgerSigner.init();
|
|
762
985
|
});
|
|
763
986
|
}
|
|
987
|
+
/** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
|
|
764
988
|
set addressType(addressType) {
|
|
765
989
|
this._addressType = addressType;
|
|
766
990
|
}
|
|
@@ -798,9 +1022,17 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
798
1022
|
return addresses;
|
|
799
1023
|
});
|
|
800
1024
|
}
|
|
1025
|
+
/**
|
|
1026
|
+
* @param {number} bundleSize - Number of change addresses to derive.
|
|
1027
|
+
* @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
|
|
1028
|
+
*/
|
|
801
1029
|
async getChangeAddresses(bundleSize) {
|
|
802
1030
|
return this.getAddresses(bundleSize, true);
|
|
803
1031
|
}
|
|
1032
|
+
/**
|
|
1033
|
+
* @param {number} bundleSize - Number of receive addresses to derive.
|
|
1034
|
+
* @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
|
|
1035
|
+
*/
|
|
804
1036
|
async getNonChangeAddresses(bundleSize) {
|
|
805
1037
|
return this.getAddresses(bundleSize);
|
|
806
1038
|
}
|
|
@@ -812,6 +1044,21 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
812
1044
|
return [deserializedTx, input.vout, void 0, void 0];
|
|
813
1045
|
});
|
|
814
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
|
+
}
|
|
815
1062
|
getOutputScriptHex(psbt) {
|
|
816
1063
|
const outputs = psbt.txOutputs.map((output) => {
|
|
817
1064
|
const amount = Buffer.alloc(8);
|
|
@@ -823,15 +1070,28 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
823
1070
|
});
|
|
824
1071
|
return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
|
|
825
1072
|
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
|
|
1075
|
+
* @param {Psbt} psbt - The PSBT to sign.
|
|
1076
|
+
* @param {Utxo[]} [inputs] - The PSBT's inputs, used to look up each input's previously derived address path. Required — LedgerSigner cannot sign from the PSBT alone.
|
|
1077
|
+
* @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
|
|
1078
|
+
* @returns {Promise<string>} The signed, serialized transaction.
|
|
1079
|
+
*/
|
|
826
1080
|
async signTransaction(psbt, inputs, transactions) {
|
|
1081
|
+
(0, import_bridges_core_sdk6.assertTruthy)(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
|
|
1082
|
+
(0, import_bridges_core_sdk6.assertTruthy)(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
|
|
827
1083
|
return this.transportService.enqueue(async () => {
|
|
828
1084
|
const ledgerInputs = this.getInputs(inputs, transactions);
|
|
829
1085
|
const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
|
|
830
1086
|
const outputScriptHex = this.getOutputScriptHex(psbt);
|
|
1087
|
+
const changePath = this.getChangePath(psbt);
|
|
831
1088
|
return this.connection.createPaymentTransaction({
|
|
832
1089
|
inputs: ledgerInputs,
|
|
833
1090
|
associatedKeysets: paths,
|
|
834
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 } : {},
|
|
835
1095
|
segwit: this.isSegwit(),
|
|
836
1096
|
useTrustedInputForSegwit: this.isSegwit(),
|
|
837
1097
|
additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
|
|
@@ -843,6 +1103,7 @@ var LedgerSigner = class _LedgerSigner {
|
|
|
843
1103
|
0 && (module.exports = {
|
|
844
1104
|
APIError,
|
|
845
1105
|
AmountBelowMinError,
|
|
1106
|
+
FederationAddressError,
|
|
846
1107
|
InvalidAddressError,
|
|
847
1108
|
LedgerSigner,
|
|
848
1109
|
NotEnoughFundsError,
|