@rsksmart/powpeg-sdk 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,812 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ LedgerSigner: () => LedgerSigner,
34
+ PeginStatuses: () => PeginStatuses,
35
+ PegoutStatuses: () => PegoutStatuses,
36
+ PowPegSDK: () => PowPegSDK,
37
+ RejectedPegoutReasons: () => RejectedPegoutReasons,
38
+ TrezorSigner: () => TrezorSigner,
39
+ TxType: () => TxType
40
+ });
41
+ module.exports = __toCommonJS(index_exports);
42
+
43
+ // src/sdk/powpeg.ts
44
+ var import_bitcoinjs_lib4 = require("bitcoinjs-lib");
45
+
46
+ // src/constants.ts
47
+ var import_bitcoinjs_lib = require("bitcoinjs-lib");
48
+ var supportedAddressTypes = {
49
+ "NATIVE SEGWIT": {
50
+ path: "84",
51
+ format: "bech32"
52
+ },
53
+ "SEGWIT": {
54
+ path: "49",
55
+ format: "p2sh"
56
+ },
57
+ "LEGACY": {
58
+ path: "44",
59
+ format: "legacy"
60
+ }
61
+ };
62
+ var networks = {
63
+ TEST: {
64
+ currency: "bitcoin_testnet",
65
+ coin: "1",
66
+ lib: import_bitcoinjs_lib.networks.testnet,
67
+ xpubVersion: 70617039
68
+ },
69
+ MAIN: {
70
+ currency: "bitcoin",
71
+ coin: "0",
72
+ lib: import_bitcoinjs_lib.networks.bitcoin,
73
+ xpubVersion: 76067358
74
+ }
75
+ };
76
+
77
+ // src/utils.ts
78
+ var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
79
+ var ecc = __toESM(require("tiny-secp256k1"));
80
+ var import_bip32 = __toESM(require("bip32"));
81
+ function remove0x(hex) {
82
+ return hex.startsWith("0x") ? hex.slice(2) : hex;
83
+ }
84
+ var addressTypeRegex = {
85
+ TEST: {
86
+ LEGACY: /^[mn][1-9A-HJ-NP-Za-km-z]{26,35}/,
87
+ SEGWIT: /^[2][1-9A-HJ-NP-Za-km-z]{26,35}/,
88
+ NATIVE_SEGWIT: /^[tb1][0-9A-HJ-NP-Za-z]{41,62}/
89
+ },
90
+ MAIN: {
91
+ LEGACY: /^[1][1-9A-HJ-NP-Za-km-z]{26,35}/,
92
+ SEGWIT: /^[3][1-9A-HJ-NP-Za-km-z]{26,35}/,
93
+ NATIVE_SEGWIT: /^[bc1][0-9A-HJ-NP-Za-z]{41,62}/
94
+ }
95
+ };
96
+ function getAddressType(address2, network) {
97
+ const { LEGACY, SEGWIT, NATIVE_SEGWIT } = addressTypeRegex[network];
98
+ if (LEGACY.test(address2)) {
99
+ return "LEGACY";
100
+ }
101
+ if (SEGWIT.test(address2)) {
102
+ return "SEGWIT";
103
+ }
104
+ if (NATIVE_SEGWIT.test(address2)) {
105
+ return "NATIVE SEGWIT";
106
+ }
107
+ }
108
+ var pubkeyAddressGenerators = {
109
+ "LEGACY": (pubkey, network) => import_bitcoinjs_lib2.payments.p2pkh({ pubkey, network }),
110
+ "SEGWIT": (pubkey, network) => import_bitcoinjs_lib2.payments.p2sh({ redeem: import_bitcoinjs_lib2.payments.p2wpkh({ pubkey, network }), network }),
111
+ "NATIVE SEGWIT": (pubkey, network) => import_bitcoinjs_lib2.payments.p2wpkh({ pubkey, network })
112
+ };
113
+ function getAddressFromPubKey(pubkey, addressType, network) {
114
+ const generator = pubkeyAddressGenerators[addressType];
115
+ if (!generator) throw new Error(`Unsupported address type: ${addressType}`);
116
+ return generator(pubkey, network);
117
+ }
118
+ function deriveAddress(xpub, index, addressType, network) {
119
+ const { lib: networkLib } = networks[network];
120
+ (0, import_bitcoinjs_lib2.initEccLib)(ecc);
121
+ const bip32 = (0, import_bip32.default)(ecc);
122
+ const node = bip32.fromBase58(xpub, networkLib);
123
+ const pubkey = Buffer.from(node.derive(index).publicKey);
124
+ if (!pubkey) {
125
+ throw new Error(`Failed to derive public key for index ${index}`);
126
+ }
127
+ const { address: address2 } = getAddressFromPubKey(pubkey, addressType, networkLib);
128
+ if (!address2) {
129
+ throw new Error("Failed to generate address");
130
+ }
131
+ return address2;
132
+ }
133
+
134
+ // src/bridge.ts
135
+ var import_rsk_precompiled_abis = require("@rsksmart/rsk-precompiled-abis");
136
+ var import_bridges_core_sdk = require("@rsksmart/bridges-core-sdk");
137
+ var Bridge = class {
138
+ address = "0x0000000000000000000000000000000001000006";
139
+ bridgeContract;
140
+ constructor(provider) {
141
+ this.bridgeContract = new import_bridges_core_sdk.ethers.Contract(import_rsk_precompiled_abis.bridge.address, import_rsk_precompiled_abis.bridge.abi, provider);
142
+ }
143
+ async getFederationAddress() {
144
+ return this.bridgeContract.getFederationAddress?.();
145
+ }
146
+ async getPegoutEstimatedFee() {
147
+ const [nextPegoutCost, pegoutQueueCount] = await Promise.all([
148
+ this.bridgeContract.getEstimatedFeesForNextPegOutEvent(),
149
+ this.bridgeContract.getQueuedPegoutsCount()
150
+ ]);
151
+ return nextPegoutCost.div(pegoutQueueCount.add(1n)).toBigInt();
152
+ }
153
+ };
154
+
155
+ // src/api/api.ts
156
+ var import_axios = __toESM(require("axios"));
157
+
158
+ // src/types.ts
159
+ var import_bitcoinjs_lib3 = require("bitcoinjs-lib");
160
+ var TxType = /* @__PURE__ */ ((TxType3) => {
161
+ TxType3["PEGIN"] = "PEGIN";
162
+ TxType3["PEGOUT"] = "PEGOUT";
163
+ return TxType3;
164
+ })(TxType || {});
165
+ var PegoutStatuses = /* @__PURE__ */ ((PegoutStatuses2) => {
166
+ PegoutStatuses2["RECEIVED"] = "RECEIVED";
167
+ PegoutStatuses2["REJECTED"] = "REJECTED";
168
+ PegoutStatuses2["WAITING_FOR_CONFIRMATION"] = "WAITING_FOR_CONFIRMATION";
169
+ PegoutStatuses2["WAITING_FOR_SIGNATURE"] = "WAITING_FOR_SIGNATURE";
170
+ PegoutStatuses2["SIGNED"] = "SIGNED";
171
+ PegoutStatuses2["NOT_FOUND"] = "NOT_FOUND";
172
+ PegoutStatuses2["PENDING"] = "PENDING";
173
+ PegoutStatuses2["NOT_PEGOUT_TX"] = "NOT_PEGOUT_TX";
174
+ PegoutStatuses2["RELEASE_BTC"] = "RELEASE_BTC";
175
+ return PegoutStatuses2;
176
+ })(PegoutStatuses || {});
177
+ var PeginStatuses = /* @__PURE__ */ ((PeginStatuses2) => {
178
+ PeginStatuses2["NOT_IN_BTC_YET"] = "NOT_IN_BTC_YET";
179
+ PeginStatuses2["WAITING_CONFIRMATIONS"] = "WAITING_CONFIRMATIONS";
180
+ PeginStatuses2["NOT_IN_RSK_YET"] = "NOT_IN_RSK_YET";
181
+ PeginStatuses2["CONFIRMED"] = "CONFIRMED";
182
+ PeginStatuses2["REJECTED_NO_REFUND"] = "REJECTED_NO_REFUND";
183
+ PeginStatuses2["REJECTED_REFUND"] = "REJECTED_REFUND";
184
+ PeginStatuses2["ERROR_NOT_A_PEGIN"] = "ERROR_NOT_A_PEGIN";
185
+ PeginStatuses2["ERROR_BELOW_MIN"] = "ERROR_BELOW_MIN";
186
+ PeginStatuses2["ERROR_UNEXPECTED"] = "ERROR_UNEXPECTED";
187
+ return PeginStatuses2;
188
+ })(PeginStatuses || {});
189
+ var RejectedPegoutReasons = {
190
+ 1: "LOW_AMOUNT",
191
+ 2: "CALLER_CONTRACT",
192
+ 3: "FEE_ABOVE_VALUE"
193
+ };
194
+
195
+ // src/errors.ts
196
+ var AmountBelowMinError = class extends Error {
197
+ constructor(message) {
198
+ super(message);
199
+ this.name = "AmountBelowMinError";
200
+ }
201
+ };
202
+ var NotEnoughFundsError = class extends Error {
203
+ constructor(message) {
204
+ super(message);
205
+ this.name = "NotEnoughFundsError";
206
+ }
207
+ };
208
+ var APIError = class extends Error {
209
+ statusCode;
210
+ data;
211
+ constructor(message, statusCode, data) {
212
+ super(message);
213
+ this.name = "APIError";
214
+ this.statusCode = statusCode;
215
+ this.data = data;
216
+ }
217
+ };
218
+
219
+ // src/api/api.ts
220
+ var import_bridges_core_sdk2 = require("@rsksmart/bridges-core-sdk");
221
+ var ApiService = class {
222
+ apiUrls = {
223
+ MAIN: "https://api.2wp.rootstock.io",
224
+ TEST: "https://api.2wp.testnet.rootstock.io"
225
+ };
226
+ feeLevelBlocks = {
227
+ slow: 5,
228
+ average: 3,
229
+ fast: 1
230
+ };
231
+ api;
232
+ constructor(network, apiUrl) {
233
+ this.api = import_axios.default.create({ baseURL: apiUrl ?? this.apiUrls[network] });
234
+ }
235
+ handleError(error) {
236
+ if (import_axios.default.isAxiosError(error)) {
237
+ if (error.response) {
238
+ const { status, data } = error.response;
239
+ const message = data?.message || "Server error";
240
+ throw new APIError(message, status, data);
241
+ }
242
+ if (error.request) {
243
+ throw new APIError("No response from server");
244
+ }
245
+ }
246
+ if (error instanceof Error) {
247
+ throw new APIError(error.message);
248
+ }
249
+ throw new APIError("Unexpected error");
250
+ }
251
+ async getFeeRate(level) {
252
+ const blocks = this.feeLevelBlocks[level];
253
+ const response = await this.api.get(`/estimate-fee/${blocks}`).catch(this.handleError);
254
+ const rate = import_bridges_core_sdk2.ethers.utils.parseUnits(response.data.amount, 8).div(1e3).toNumber();
255
+ return rate;
256
+ }
257
+ async getTxHex(txId) {
258
+ const response = await this.api.get(`/tx?tx=${txId}`).catch(this.handleError);
259
+ return response.data.hex;
260
+ }
261
+ async getOutputs(address2) {
262
+ const response = await this.api.post("/utxo", { addressList: [address2] }).catch(this.handleError);
263
+ const { data: utxos } = response.data;
264
+ return utxos.map(({ address: address3, txid, vout, satoshis }) => ({
265
+ address: address3,
266
+ txid,
267
+ amount: BigInt(satoshis),
268
+ vout
269
+ }));
270
+ }
271
+ async getAddressDetails(address2) {
272
+ const response = await this.api.post("/addresses-info", { addressList: [address2] }).catch(this.handleError);
273
+ const [details] = response.data.addressesInfo;
274
+ return {
275
+ address: details.address,
276
+ balance: details.balance,
277
+ txCount: details.txs
278
+ };
279
+ }
280
+ async broadcast(hexTx) {
281
+ const response = await this.api.post("/broadcast", { data: hexTx }).catch(this.handleError);
282
+ return response.data.txId;
283
+ }
284
+ async getTransactionStatus(txHash, txType) {
285
+ const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
286
+ return response.data;
287
+ }
288
+ };
289
+
290
+ // src/sdk/powpeg.ts
291
+ var import_bridges_core_sdk3 = require("@rsksmart/bridges-core-sdk");
292
+ var PowPegSDK = class {
293
+ /**
294
+ * @param {BitcoinSigner | null} _bitcoinSigner - An instance of a class that implements the BitcoinSigner interface.
295
+ * @param {BitcoinDataSource | null} _bitcoinDataSource - An instance of a class that implements the BitcoinDataSource interface or null if you won't use peg-in operations.
296
+ * @param {Network} network - The network to use. Either 'MAIN' or 'TEST'.
297
+ * @param {string} rpcProviderUrl - URL of either your own Rootstock node, the Rootstock RPC API or a third-party node provider. If not provided, it will default to the Rootstock public node for the specified network.
298
+ * @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.
299
+ * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
300
+ * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
301
+ */
302
+ constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3) {
303
+ this._bitcoinSigner = _bitcoinSigner;
304
+ this._bitcoinDataSource = _bitcoinDataSource;
305
+ this.network = network;
306
+ this.maxBundleSize = maxBundleSize;
307
+ this.burnDustValue = burnDustValue;
308
+ this.bitcoinJsNetwork = networks[network].lib;
309
+ this.rskProvider = new import_bridges_core_sdk3.ethers.providers.JsonRpcProvider(rpcProviderUrl ?? this.publicNodes[network]);
310
+ this.bridge = new Bridge(this.rskProvider);
311
+ this.api = new ApiService(network, apiUrl);
312
+ }
313
+ txHeaderSizeInBytes = 13;
314
+ txOutputSizeInBytes = 32;
315
+ txInputSizeInBytes = 145;
316
+ pegInOutputs = 3;
317
+ powpegRsktHeader = "52534b5401";
318
+ burnDustMaxValue = 3e4;
319
+ utxos = [];
320
+ changeAddress;
321
+ minPeginAmount = 500000n;
322
+ peginFeeEstimationInputs = 2;
323
+ minPegoutAmount = "0.004";
324
+ bitcoinJsNetwork;
325
+ bridge;
326
+ api;
327
+ rskProvider;
328
+ publicNodes = {
329
+ MAIN: "https://public-node.rsk.co",
330
+ TEST: "https://public-node.testnet.rsk.co"
331
+ };
332
+ get bitcoinSigner() {
333
+ (0, import_bridges_core_sdk3.assertTruthy)(this._bitcoinSigner, "Bitcoin signer is required");
334
+ return this._bitcoinSigner;
335
+ }
336
+ set bitcoinSigner(signer) {
337
+ this._bitcoinSigner = signer;
338
+ }
339
+ get bitcoinDataSource() {
340
+ return this._bitcoinDataSource ?? this.api;
341
+ }
342
+ async getUtxos(addresses) {
343
+ return Promise.all(addresses.map(({ address: address2 }) => this.bitcoinDataSource.getOutputs(address2)));
344
+ }
345
+ async getAddressesWithDetails(addresses) {
346
+ return Promise.all(addresses.map((address2) => this.bitcoinDataSource.getAddressDetails(address2)));
347
+ }
348
+ groupAddressesByUsage(addresses) {
349
+ const used = [];
350
+ const unused = [];
351
+ addresses.forEach((address2) => {
352
+ if (address2.txCount > 0) {
353
+ used.push(address2);
354
+ } else {
355
+ unused.push(address2);
356
+ }
357
+ });
358
+ return { used, unused };
359
+ }
360
+ groupAddressesByBalance(addresses) {
361
+ const withBalance = [];
362
+ const withoutBalance = [];
363
+ addresses.forEach((address2) => {
364
+ if (address2.balance > 0) {
365
+ withBalance.push(address2);
366
+ } else {
367
+ withoutBalance.push(address2);
368
+ }
369
+ });
370
+ return { withBalance, withoutBalance };
371
+ }
372
+ async initPegin() {
373
+ const nonChangeAddresses = await this.bitcoinSigner.getNonChangeAddresses(this.maxBundleSize);
374
+ const changeAddresses = await this.bitcoinSigner.getChangeAddresses(this.maxBundleSize);
375
+ const [nonChangeAddressesWithDetails, changeAddressesWithDetails] = await Promise.all([
376
+ this.getAddressesWithDetails(nonChangeAddresses),
377
+ this.getAddressesWithDetails(changeAddresses)
378
+ ]);
379
+ const { used: usedNonChangeAddresses, unused: unusedNonChangeAddress } = this.groupAddressesByUsage(nonChangeAddressesWithDetails);
380
+ const { used: usedChangeAddresses, unused: unusedChangeAddresses } = this.groupAddressesByUsage(changeAddressesWithDetails);
381
+ const addresses = usedNonChangeAddresses.concat(usedChangeAddresses);
382
+ const { withBalance: addressesWithBalance } = this.groupAddressesByBalance(addresses);
383
+ const refundAddress = unusedNonChangeAddress[0];
384
+ const changeAddress = unusedChangeAddresses[0];
385
+ return { addressesWithBalance, refundAddress, changeAddress };
386
+ }
387
+ getRskOutput(recipientAddress, refundAddress) {
388
+ let output = `${this.powpegRsktHeader}${remove0x(recipientAddress)}`;
389
+ if (refundAddress) {
390
+ const refundAddressType = getAddressType(refundAddress, this.network);
391
+ const prefixes = {
392
+ LEGACY: "01",
393
+ SEGWIT: "02"
394
+ };
395
+ if (refundAddressType === "LEGACY" || refundAddressType === "SEGWIT") {
396
+ const hash = import_bitcoinjs_lib4.address.fromBase58Check(refundAddress).hash.toString("hex");
397
+ output += `${prefixes[refundAddressType]}${hash}`;
398
+ }
399
+ }
400
+ return Buffer.from(output, "hex");
401
+ }
402
+ async estimatePeginFee(amount, feeLevel = "fast") {
403
+ const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
404
+ const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
405
+ const totalFee = baseFee + feePerInput * this.peginFeeEstimationInputs;
406
+ return totalFee;
407
+ }
408
+ async createPegin(amount, recipientAddress) {
409
+ const { addressesWithBalance, refundAddress, changeAddress } = await this.initPegin();
410
+ const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.bitcoinJsNetwork });
411
+ const { output: script } = import_bitcoinjs_lib4.payments.embed({ data: [this.getRskOutput(recipientAddress, refundAddress?.address)] });
412
+ if (script) {
413
+ psbt.addOutput({
414
+ script,
415
+ value: 0
416
+ });
417
+ }
418
+ const bridgeAddress = await this.bridge.getFederationAddress();
419
+ psbt.addOutput({
420
+ address: bridgeAddress,
421
+ value: Number(amount)
422
+ });
423
+ this.utxos = (await this.getUtxos(addressesWithBalance)).flat();
424
+ this.changeAddress = changeAddress?.address;
425
+ return psbt;
426
+ }
427
+ selectInputs(amount, utxos, baseFee, feePerInput) {
428
+ const inputs = [];
429
+ let remainingSatoshisToBePaid = BigInt(amount) + BigInt(baseFee);
430
+ utxos.sort((a, b) => a.amount < b.amount ? -1 : a.amount > b.amount ? 1 : 0);
431
+ utxos.forEach((utxo) => {
432
+ if (remainingSatoshisToBePaid > 0) {
433
+ inputs.push(utxo);
434
+ remainingSatoshisToBePaid = remainingSatoshisToBePaid + BigInt(feePerInput) - BigInt(utxo.amount);
435
+ }
436
+ });
437
+ return { inputs, rest: Number(remainingSatoshisToBePaid) };
438
+ }
439
+ validatePeginAmount(amount) {
440
+ if (amount < this.minPeginAmount) {
441
+ throw new AmountBelowMinError(`Minimum allowed amount is ${this.minPeginAmount} satoshis.`);
442
+ }
443
+ }
444
+ async calculatePeginFee(amount, feeRate) {
445
+ this.validatePeginAmount(amount);
446
+ const txSize = this.txHeaderSizeInBytes + this.txOutputSizeInBytes * this.pegInOutputs;
447
+ const baseFee = feeRate * txSize;
448
+ const feePerInput = feeRate * this.txInputSizeInBytes;
449
+ return { baseFee, feePerInput };
450
+ }
451
+ async calculateFeeAndSelectedInputs(amount, utxos, feeRate) {
452
+ const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
453
+ const { inputs, rest } = this.selectInputs(amount, utxos, baseFee, feePerInput);
454
+ if (rest > 0) {
455
+ throw new NotEnoughFundsError(`${rest} satoshis needed to cover the requested amount.`);
456
+ }
457
+ const totalFee = baseFee + feePerInput * inputs.length;
458
+ return { inputs, change: Math.abs(rest), totalFee };
459
+ }
460
+ async fundPegin(psbt, feeLevel = "fast") {
461
+ const amount = BigInt(psbt.txOutputs[1].value);
462
+ const feeRate = await this.bitcoinDataSource.getFeeRate(feeLevel);
463
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, this.utxos, feeRate);
464
+ if (change > Math.min(this.burnDustValue, this.burnDustMaxValue)) {
465
+ psbt.addOutput({
466
+ address: this.changeAddress ?? inputs[0].address,
467
+ value: change
468
+ });
469
+ }
470
+ const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
471
+ inputs.forEach((input, index) => {
472
+ const transaction = import_bitcoinjs_lib4.Transaction.fromHex(hexTransactions[index]);
473
+ psbt.addInput({
474
+ hash: input.txid,
475
+ index: input.vout,
476
+ witnessUtxo: {
477
+ script: transaction.outs[input.vout].script,
478
+ value: transaction.outs[input.vout].value
479
+ }
480
+ });
481
+ });
482
+ return { psbt, inputs, transactions: hexTransactions, fee: totalFee };
483
+ }
484
+ async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast") {
485
+ this.bitcoinSigner = signer;
486
+ this.validatePeginAmount(amount);
487
+ const psbt = await this.createPegin(amount, recipientAddress);
488
+ return this.fundPegin(psbt, feeLevel);
489
+ }
490
+ async signPegin(psbt, inputs, transactions) {
491
+ return this.bitcoinSigner.signTransaction(psbt, inputs, transactions);
492
+ }
493
+ async signAndBroadcastPegin(psbt, inputs, transactions) {
494
+ const signedTx = await this.signPegin(psbt, inputs, transactions);
495
+ return this.bitcoinDataSource.broadcast(signedTx);
496
+ }
497
+ validateMinimumPegoutAmount(amount) {
498
+ const amountBN = import_bridges_core_sdk3.ethers.utils.parseUnits(amount, 18).toBigInt();
499
+ const minAmountBN = import_bridges_core_sdk3.ethers.utils.parseUnits(this.minPegoutAmount, 18).toBigInt();
500
+ if (amountBN < minAmountBN) {
501
+ throw new AmountBelowMinError(`Minimum allowed amount is ${this.minPegoutAmount}.`);
502
+ }
503
+ }
504
+ createPegoutTransaction(amount, fromAddress) {
505
+ const amountBN = import_bridges_core_sdk3.ethers.utils.parseUnits(amount, 18).toBigInt();
506
+ return {
507
+ from: fromAddress,
508
+ to: this.bridge.address,
509
+ value: amountBN.toString()
510
+ };
511
+ }
512
+ async estimatePegoutFees(amount, fromAddress = import_bridges_core_sdk3.ethers.constants.AddressZero) {
513
+ this.validateMinimumPegoutAmount(amount);
514
+ const tx = this.createPegoutTransaction(amount, fromAddress);
515
+ const [gas, gasPrice, bitcoinFee] = await Promise.all([
516
+ this.rskProvider.estimateGas(tx),
517
+ this.rskProvider.getGasPrice(),
518
+ this.bridge.getPegoutEstimatedFee()
519
+ ]);
520
+ const rootstockFee = gas.mul(gasPrice).toBigInt();
521
+ return {
522
+ bitcoinFee,
523
+ rootstockFee
524
+ };
525
+ }
526
+ async createPegout(amount, senderAccount) {
527
+ const fees = await this.estimatePegoutFees(amount, senderAccount);
528
+ const amountBN = import_bridges_core_sdk3.ethers.utils.parseUnits(amount, 18).toBigInt();
529
+ const balance = await this.rskProvider.getBalance(senderAccount);
530
+ if (balance.lt(amountBN)) {
531
+ throw new NotEnoughFundsError(`Requested amount ${amountBN} is greater than current balance ${balance}.`);
532
+ }
533
+ const tx = this.createPegoutTransaction(amount, senderAccount);
534
+ return {
535
+ tx,
536
+ rootstockFee: fees.rootstockFee,
537
+ bitcoinFee: fees.bitcoinFee
538
+ };
539
+ }
540
+ async signAndBroadcastPegout(tx, signer) {
541
+ const { hash } = await signer.sendTransaction(tx);
542
+ return signer.provider?.waitForTransaction(hash);
543
+ }
544
+ async getTransactionStatus(txHash, txType) {
545
+ return this.api.getTransactionStatus(txHash, txType);
546
+ }
547
+ };
548
+
549
+ // src/bitcoin-signers/trezor/trezor.ts
550
+ var import_connect_web = __toESM(require("@trezor/connect-web"));
551
+ var import_bitcoinjs_lib5 = require("bitcoinjs-lib");
552
+ var TrezorSigner = class _TrezorSigner {
553
+ constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
554
+ this.network = network;
555
+ this._addressType = _addressType;
556
+ }
557
+ bitcoinTxVersion = 1;
558
+ addresses = /* @__PURE__ */ new Map();
559
+ static async init(network, initOptions) {
560
+ await import_connect_web.default.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
561
+ return new _TrezorSigner(network);
562
+ }
563
+ static async reinit() {
564
+ import_connect_web.default.dispose();
565
+ return _TrezorSigner.init();
566
+ }
567
+ set addressType(addressType) {
568
+ this._addressType = addressType;
569
+ }
570
+ get addressType() {
571
+ return this._addressType;
572
+ }
573
+ getPathPurpose() {
574
+ return supportedAddressTypes[this._addressType].path;
575
+ }
576
+ getPathCoin() {
577
+ return networks[this.network].coin;
578
+ }
579
+ async getAddresses(bundleSize, change = false) {
580
+ const addresses = [];
581
+ const bundle = Array.from(
582
+ { length: bundleSize },
583
+ (_, i) => ({ path: `m/${this.getPathPurpose()}'/${this.getPathCoin()}'/0'/${change ? "1" : "0"}/${i}`, showOnTrezor: false, coin: this.network })
584
+ );
585
+ const result = await import_connect_web.default.getAddress({ bundle });
586
+ if (result.success) {
587
+ result.payload.forEach(({ address: address2, path }) => {
588
+ this.addresses.set(address2, path);
589
+ addresses.push(address2);
590
+ });
591
+ }
592
+ return addresses;
593
+ }
594
+ async getChangeAddresses(bundleSize) {
595
+ return this.getAddresses(bundleSize, true);
596
+ }
597
+ async getNonChangeAddresses(bundleSize) {
598
+ return this.getAddresses(bundleSize);
599
+ }
600
+ getScriptType(address2) {
601
+ const addressType = getAddressType(address2, this.network);
602
+ switch (addressType) {
603
+ case "SEGWIT":
604
+ return "SPENDP2SHWITNESS";
605
+ case "LEGACY":
606
+ return "SPENDADDRESS";
607
+ case "NATIVE SEGWIT":
608
+ return "SPENDWITNESS";
609
+ default:
610
+ return "SPENDADDRESS";
611
+ }
612
+ }
613
+ getInputs(utxos) {
614
+ return utxos.map((utxo) => {
615
+ return {
616
+ address_n: this.addresses.get(utxo.address) ?? [],
617
+ prev_hash: utxo.txid,
618
+ prev_index: utxo.vout,
619
+ script_type: this.getScriptType(utxo.address),
620
+ amount: Number(utxo.amount)
621
+ };
622
+ });
623
+ }
624
+ getOutputs(psbt) {
625
+ return psbt.txOutputs.map((output) => {
626
+ if (output.value === 0 && !output.address) {
627
+ return {
628
+ amount: output.value,
629
+ op_return_data: output.script.toString("hex").slice(4),
630
+ script_type: "PAYTOOPRETURN"
631
+ };
632
+ }
633
+ return {
634
+ address: output.address ?? "",
635
+ script_type: "PAYTOADDRESS",
636
+ amount: output.value
637
+ };
638
+ });
639
+ }
640
+ async signTransaction(psbt, utxos) {
641
+ const inputs = this.getInputs(utxos);
642
+ const outputs = this.getOutputs(psbt);
643
+ const result = await import_connect_web.default.signTransaction({
644
+ coin: this.network,
645
+ version: this.bitcoinTxVersion,
646
+ inputs,
647
+ outputs
648
+ });
649
+ if (result.success) {
650
+ return result.payload.serializedTx;
651
+ }
652
+ return "";
653
+ }
654
+ };
655
+
656
+ // src/bitcoin-signers/ledger/ledger.ts
657
+ var import_hw_app_btc = __toESM(require("@ledgerhq/hw-app-btc"));
658
+ var import_hw_transport_webusb = __toESM(require("@ledgerhq/hw-transport-webusb"));
659
+ var import_bitcoinjs_lib6 = require("bitcoinjs-lib");
660
+
661
+ // src/bitcoin-signers/ledger/ledger-transport.ts
662
+ var LedgerTransportService = class {
663
+ constructor(transport) {
664
+ this.transport = transport;
665
+ }
666
+ queue = [];
667
+ isProcessing = false;
668
+ async processQueue() {
669
+ if (this.isProcessing || this.queue.length === 0 || this.isDeviceBusy()) {
670
+ return;
671
+ }
672
+ this.isProcessing = true;
673
+ const item = this.queue.shift();
674
+ if (!item) {
675
+ this.isProcessing = false;
676
+ return;
677
+ }
678
+ try {
679
+ const result = await item.operation();
680
+ item.resolve(result);
681
+ } catch (error) {
682
+ item.reject(error instanceof Error ? error : new Error(String(error)));
683
+ } finally {
684
+ this.isProcessing = false;
685
+ this.processQueue();
686
+ }
687
+ }
688
+ async enqueue(operation) {
689
+ return new Promise((resolve, reject) => {
690
+ this.queue.push({
691
+ resolve,
692
+ reject,
693
+ operation
694
+ });
695
+ this.processQueue();
696
+ });
697
+ }
698
+ isDeviceBusy() {
699
+ return Boolean(this.transport._appAPIlock);
700
+ }
701
+ };
702
+
703
+ // src/bitcoin-signers/ledger/ledger.ts
704
+ var LedgerSigner = class _LedgerSigner {
705
+ constructor(connection, transport, network, _addressType = "NATIVE SEGWIT") {
706
+ this.connection = connection;
707
+ this.transport = transport;
708
+ this.network = network;
709
+ this._addressType = _addressType;
710
+ this.transportService = new LedgerTransportService(transport);
711
+ }
712
+ addresses = /* @__PURE__ */ new Map();
713
+ transportService;
714
+ static async init(network = "TEST") {
715
+ const transport = await import_hw_transport_webusb.default.create();
716
+ const connection = new import_hw_app_btc.default({ transport, currency: networks[network].currency });
717
+ return new _LedgerSigner(connection, transport, network);
718
+ }
719
+ async reinit() {
720
+ return this.transportService.enqueue(async () => {
721
+ await this.transport.close();
722
+ return _LedgerSigner.init();
723
+ });
724
+ }
725
+ set addressType(addressType) {
726
+ this._addressType = addressType;
727
+ }
728
+ get addressType() {
729
+ return this._addressType;
730
+ }
731
+ getPathPurpose() {
732
+ return supportedAddressTypes[this._addressType].path;
733
+ }
734
+ getPathCoin() {
735
+ return networks[this.network].coin;
736
+ }
737
+ getAddressFormat() {
738
+ return supportedAddressTypes[this._addressType].format;
739
+ }
740
+ getXpubVersion() {
741
+ return networks[this.network].xpubVersion;
742
+ }
743
+ isSegwit() {
744
+ return this._addressType === "SEGWIT" || this._addressType === "NATIVE SEGWIT";
745
+ }
746
+ async getAddresses(bundleSize, change = false) {
747
+ return this.transportService.enqueue(async () => {
748
+ const addresses = [];
749
+ const basePath = `m/${this.getPathPurpose()}'/${this.getPathCoin()}'/0'/${change ? "1" : "0"}`;
750
+ const xpub = await this.connection.getWalletXpub({ path: basePath, xpubVersion: this.getXpubVersion() });
751
+ for (let i = 0; i < bundleSize; i++) {
752
+ const path = `${basePath}/${i}`;
753
+ const address2 = deriveAddress(xpub, i, this.addressType, this.network);
754
+ if (address2) {
755
+ addresses.push(address2);
756
+ this.addresses.set(address2, path);
757
+ }
758
+ }
759
+ return addresses;
760
+ });
761
+ }
762
+ async getChangeAddresses(bundleSize) {
763
+ return this.getAddresses(bundleSize, true);
764
+ }
765
+ async getNonChangeAddresses(bundleSize) {
766
+ return this.getAddresses(bundleSize);
767
+ }
768
+ getInputs(inputs, transactions) {
769
+ return inputs.map((input, index) => {
770
+ const txHex = transactions[index];
771
+ const tx = import_bitcoinjs_lib6.Transaction.fromHex(txHex);
772
+ const deserializedTx = this.connection.splitTransaction(txHex, tx.hasWitnesses());
773
+ return [deserializedTx, input.vout, void 0, void 0];
774
+ });
775
+ }
776
+ getOutputScriptHex(psbt) {
777
+ const outputs = psbt.txOutputs.map((output) => {
778
+ const amount = Buffer.alloc(8);
779
+ amount.writeBigUInt64LE(BigInt(output.value));
780
+ return {
781
+ script: output.script,
782
+ amount
783
+ };
784
+ });
785
+ return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
786
+ }
787
+ async signTransaction(psbt, inputs, transactions) {
788
+ return this.transportService.enqueue(async () => {
789
+ const ledgerInputs = this.getInputs(inputs, transactions);
790
+ const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
791
+ const outputScriptHex = this.getOutputScriptHex(psbt);
792
+ return this.connection.createPaymentTransaction({
793
+ inputs: ledgerInputs,
794
+ associatedKeysets: paths,
795
+ outputScriptHex,
796
+ segwit: this.isSegwit(),
797
+ useTrustedInputForSegwit: this.isSegwit(),
798
+ additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
799
+ });
800
+ });
801
+ }
802
+ };
803
+ // Annotate the CommonJS export names for ESM import in node:
804
+ 0 && (module.exports = {
805
+ LedgerSigner,
806
+ PeginStatuses,
807
+ PegoutStatuses,
808
+ PowPegSDK,
809
+ RejectedPegoutReasons,
810
+ TrezorSigner,
811
+ TxType
812
+ });