@rsksmart/powpeg-sdk 1.3.0-beta → 2.0.0-beta.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.mjs CHANGED
@@ -1,44 +1,62 @@
1
1
  // src/sdk/powpeg.ts
2
- import { address, payments as payments2, Psbt as Psbt2, Transaction } from "bitcoinjs-lib";
2
+ import { address, payments, Psbt as Psbt2, Transaction } from "bitcoinjs-lib";
3
+
4
+ // src/types.ts
5
+ import "bitcoinjs-lib";
6
+ var TxType = /* @__PURE__ */ ((TxType3) => {
7
+ TxType3["PEGIN"] = "PEGIN";
8
+ TxType3["PEGOUT"] = "PEGOUT";
9
+ return TxType3;
10
+ })(TxType || {});
11
+ var PegoutStatuses = /* @__PURE__ */ ((PegoutStatuses2) => {
12
+ PegoutStatuses2["RECEIVED"] = "RECEIVED";
13
+ PegoutStatuses2["REJECTED"] = "REJECTED";
14
+ PegoutStatuses2["WAITING_FOR_CONFIRMATION"] = "WAITING_FOR_CONFIRMATION";
15
+ PegoutStatuses2["WAITING_FOR_SIGNATURE"] = "WAITING_FOR_SIGNATURE";
16
+ PegoutStatuses2["SIGNED"] = "SIGNED";
17
+ PegoutStatuses2["NOT_FOUND"] = "NOT_FOUND";
18
+ PegoutStatuses2["PENDING"] = "PENDING";
19
+ PegoutStatuses2["NOT_PEGOUT_TX"] = "NOT_PEGOUT_TX";
20
+ PegoutStatuses2["RELEASE_BTC"] = "RELEASE_BTC";
21
+ return PegoutStatuses2;
22
+ })(PegoutStatuses || {});
23
+ var PeginStatuses = /* @__PURE__ */ ((PeginStatuses2) => {
24
+ PeginStatuses2["NOT_IN_BTC_YET"] = "NOT_IN_BTC_YET";
25
+ PeginStatuses2["WAITING_CONFIRMATIONS"] = "WAITING_CONFIRMATIONS";
26
+ PeginStatuses2["NOT_IN_RSK_YET"] = "NOT_IN_RSK_YET";
27
+ PeginStatuses2["CONFIRMED"] = "CONFIRMED";
28
+ PeginStatuses2["REJECTED_NO_REFUND"] = "REJECTED_NO_REFUND";
29
+ PeginStatuses2["REJECTED_REFUND"] = "REJECTED_REFUND";
30
+ PeginStatuses2["ERROR_NOT_A_PEGIN"] = "ERROR_NOT_A_PEGIN";
31
+ PeginStatuses2["ERROR_BELOW_MIN"] = "ERROR_BELOW_MIN";
32
+ PeginStatuses2["ERROR_UNEXPECTED"] = "ERROR_UNEXPECTED";
33
+ return PeginStatuses2;
34
+ })(PeginStatuses || {});
35
+ var RejectedPegoutReasons = {
36
+ 1: "LOW_AMOUNT",
37
+ 2: "CALLER_CONTRACT",
38
+ 3: "FEE_ABOVE_VALUE"
39
+ };
3
40
 
4
41
  // src/constants.ts
5
42
  import { isBtcMainnetAddress, isBtcTestnetAddress } from "@rsksmart/bridges-core-sdk";
6
43
  import { networks as bitcoinJsNetworks } from "bitcoinjs-lib";
7
- var supportedAddressTypes = {
8
- "NATIVE SEGWIT": {
9
- path: "84",
10
- format: "bech32"
11
- },
12
- "SEGWIT": {
13
- path: "49",
14
- format: "p2sh"
15
- },
16
- "LEGACY": {
17
- path: "44",
18
- format: "legacy"
19
- }
20
- };
21
44
  var networks = {
22
45
  TEST: {
23
- currency: "bitcoin_testnet",
24
- coin: "1",
25
46
  lib: bitcoinJsNetworks.testnet,
26
- xpubVersion: 70617039,
27
47
  isBtcAddress: isBtcTestnetAddress
28
48
  },
29
49
  MAIN: {
30
- currency: "bitcoin",
31
- coin: "0",
32
50
  lib: bitcoinJsNetworks.bitcoin,
33
- xpubVersion: 76067358,
34
51
  isBtcAddress: isBtcMainnetAddress
35
52
  }
36
53
  };
54
+ var Network = {
55
+ MAIN: "MAIN",
56
+ TEST: "TEST"
57
+ };
37
58
 
38
59
  // src/utils.ts
39
- import { initEccLib, payments } from "bitcoinjs-lib";
40
- import * as ecc from "tiny-secp256k1";
41
- import BIP32Factory from "bip32";
42
60
  function remove0x(hex) {
43
61
  return hex.startsWith("0x") ? hex.slice(2) : hex;
44
62
  }
@@ -66,37 +84,34 @@ function getAddressType(address2, network) {
66
84
  return "NATIVE SEGWIT";
67
85
  }
68
86
  }
69
- var pubkeyAddressGenerators = {
70
- "LEGACY": (pubkey, network) => payments.p2pkh({ pubkey, network }),
71
- "SEGWIT": (pubkey, network) => payments.p2sh({ redeem: payments.p2wpkh({ pubkey, network }), network }),
72
- "NATIVE SEGWIT": (pubkey, network) => payments.p2wpkh({ pubkey, network })
73
- };
74
- function getAddressFromPubKey(pubkey, addressType, network) {
75
- const generator = pubkeyAddressGenerators[addressType];
76
- if (!generator) throw new Error(`Unsupported address type: ${addressType}`);
77
- return generator(pubkey, network);
87
+ function isP2shScript(script) {
88
+ return script.length === 23 && script[0] === 169 && script[1] === 20 && script[22] === 135;
89
+ }
90
+ function isWitnessProgramScript(script) {
91
+ if (script.length < 4 || script.length > 42) {
92
+ return false;
93
+ }
94
+ const version = script[0];
95
+ if (version !== 0 && (version < 81 || version > 96)) {
96
+ return false;
97
+ }
98
+ return script[1] === script.length - 2;
99
+ }
100
+ function isP2pkhScript(script) {
101
+ return script.length === 25 && script[0] === 118 && script[1] === 169 && script[2] === 20 && script[23] === 136 && script[24] === 172;
78
102
  }
79
- function deriveAddress(xpub, index, addressType, network) {
80
- const { lib: networkLib } = networks[network];
81
- initEccLib(ecc);
82
- const bip32 = BIP32Factory(ecc);
83
- const node = bip32.fromBase58(xpub, networkLib);
84
- const pubkey = Buffer.from(node.derive(index).publicKey);
85
- if (!pubkey) {
86
- throw new Error(`Failed to derive public key for index ${index}`);
87
- }
88
- const { address: address2 } = getAddressFromPubKey(pubkey, addressType, networkLib);
89
- if (!address2) {
90
- throw new Error("Failed to generate address");
91
- }
92
- return address2;
103
+ function isP2wpkhScript(script) {
104
+ return script.length === 22 && script[0] === 0 && script[1] === 20;
105
+ }
106
+ function isSupportedFundingScript(script) {
107
+ return isP2pkhScript(script) || isP2wpkhScript(script);
93
108
  }
94
109
 
95
110
  // src/bridge.ts
96
111
  import { bridge } from "@rsksmart/rsk-precompiled-abis";
97
112
  import { ethers } from "@rsksmart/bridges-core-sdk";
98
113
  var Bridge = class {
99
- address = "0x0000000000000000000000000000000001000006";
114
+ address = bridge.address;
100
115
  bridgeContract;
101
116
  constructor(provider) {
102
117
  this.bridgeContract = new ethers.Contract(bridge.address, bridge.abi, provider);
@@ -104,6 +119,34 @@ var Bridge = class {
104
119
  async getFederationAddress() {
105
120
  return this.bridgeContract.getFederationAddress?.();
106
121
  }
122
+ async getFeePerKb() {
123
+ const feePerKb = await this.bridgeContract.getFeePerKb();
124
+ return feePerKb.toBigInt();
125
+ }
126
+ async getActivePowpegRedeemScript() {
127
+ return this.bridgeContract.getActivePowpegRedeemScript();
128
+ }
129
+ async getFederationThreshold() {
130
+ const threshold = await this.bridgeContract.getFederationThreshold();
131
+ return threshold.toNumber();
132
+ }
133
+ /** Reads a `release_request_rejected` event out of a peg-out receipt's logs, if the Bridge emitted one. */
134
+ findRejectedPegout(logs) {
135
+ for (const log of logs) {
136
+ if (log.address?.toLowerCase() !== this.address.toLowerCase()) {
137
+ continue;
138
+ }
139
+ let parsed;
140
+ try {
141
+ parsed = this.bridgeContract.interface.parseLog(log);
142
+ } catch {
143
+ continue;
144
+ }
145
+ if (parsed.name === "release_request_rejected") {
146
+ return { amount: parsed.args[1].toBigInt(), reason: parsed.args[2].toNumber() };
147
+ }
148
+ }
149
+ }
107
150
  async getPegoutEstimatedFee() {
108
151
  const [nextPegoutCost, pegoutQueueCount] = await Promise.all([
109
152
  this.bridgeContract.getEstimatedFeesForNextPegOutEvent(),
@@ -116,43 +159,6 @@ var Bridge = class {
116
159
  // src/api/api.ts
117
160
  import axios from "axios";
118
161
 
119
- // src/types.ts
120
- import "bitcoinjs-lib";
121
- var TxType = /* @__PURE__ */ ((TxType3) => {
122
- TxType3["PEGIN"] = "PEGIN";
123
- TxType3["PEGOUT"] = "PEGOUT";
124
- return TxType3;
125
- })(TxType || {});
126
- var PegoutStatuses = /* @__PURE__ */ ((PegoutStatuses2) => {
127
- PegoutStatuses2["RECEIVED"] = "RECEIVED";
128
- PegoutStatuses2["REJECTED"] = "REJECTED";
129
- PegoutStatuses2["WAITING_FOR_CONFIRMATION"] = "WAITING_FOR_CONFIRMATION";
130
- PegoutStatuses2["WAITING_FOR_SIGNATURE"] = "WAITING_FOR_SIGNATURE";
131
- PegoutStatuses2["SIGNED"] = "SIGNED";
132
- PegoutStatuses2["NOT_FOUND"] = "NOT_FOUND";
133
- PegoutStatuses2["PENDING"] = "PENDING";
134
- PegoutStatuses2["NOT_PEGOUT_TX"] = "NOT_PEGOUT_TX";
135
- PegoutStatuses2["RELEASE_BTC"] = "RELEASE_BTC";
136
- return PegoutStatuses2;
137
- })(PegoutStatuses || {});
138
- var PeginStatuses = /* @__PURE__ */ ((PeginStatuses2) => {
139
- PeginStatuses2["NOT_IN_BTC_YET"] = "NOT_IN_BTC_YET";
140
- PeginStatuses2["WAITING_CONFIRMATIONS"] = "WAITING_CONFIRMATIONS";
141
- PeginStatuses2["NOT_IN_RSK_YET"] = "NOT_IN_RSK_YET";
142
- PeginStatuses2["CONFIRMED"] = "CONFIRMED";
143
- PeginStatuses2["REJECTED_NO_REFUND"] = "REJECTED_NO_REFUND";
144
- PeginStatuses2["REJECTED_REFUND"] = "REJECTED_REFUND";
145
- PeginStatuses2["ERROR_NOT_A_PEGIN"] = "ERROR_NOT_A_PEGIN";
146
- PeginStatuses2["ERROR_BELOW_MIN"] = "ERROR_BELOW_MIN";
147
- PeginStatuses2["ERROR_UNEXPECTED"] = "ERROR_UNEXPECTED";
148
- return PeginStatuses2;
149
- })(PeginStatuses || {});
150
- var RejectedPegoutReasons = {
151
- 1: "LOW_AMOUNT",
152
- 2: "CALLER_CONTRACT",
153
- 3: "FEE_ABOVE_VALUE"
154
- };
155
-
156
162
  // src/errors.ts
157
163
  var AmountBelowMinError = class extends Error {
158
164
  constructor(message) {
@@ -191,19 +197,141 @@ var InvalidAddressError = class extends Error {
191
197
  this.invalidAddresses = invalidAddresses;
192
198
  }
193
199
  };
200
+ var SigningError = class extends Error {
201
+ constructor(message) {
202
+ super(message);
203
+ this.name = "SigningError";
204
+ }
205
+ };
194
206
  var InvalidFeeRateError = class extends Error {
195
207
  constructor(message) {
196
208
  super(message);
197
209
  this.name = "InvalidFeeRateError";
198
210
  }
199
211
  };
212
+ var WrongNetworkError = class extends Error {
213
+ constructor(message) {
214
+ super(message);
215
+ this.name = "WrongNetworkError";
216
+ }
217
+ };
218
+ var PegoutRejectedError = class extends Error {
219
+ reason;
220
+ txHash;
221
+ amount;
222
+ constructor(reason, txHash, amount, message) {
223
+ super(message);
224
+ this.name = "PegoutRejectedError";
225
+ this.reason = reason;
226
+ this.txHash = txHash;
227
+ this.amount = amount;
228
+ }
229
+ };
230
+ var UnsupportedSenderError = class extends Error {
231
+ constructor(message) {
232
+ super(message);
233
+ this.name = "UnsupportedSenderError";
234
+ }
235
+ };
236
+ var TransactionRevertedError = class extends Error {
237
+ txHash;
238
+ receipt;
239
+ constructor(txHash, receipt, message) {
240
+ super(message);
241
+ this.name = "TransactionRevertedError";
242
+ this.txHash = txHash;
243
+ this.receipt = receipt;
244
+ }
245
+ };
246
+ var UnsupportedAddressTypeError = class extends Error {
247
+ address;
248
+ constructor(address2, message) {
249
+ super(message);
250
+ this.name = "UnsupportedAddressTypeError";
251
+ this.address = address2;
252
+ }
253
+ };
200
254
 
201
255
  // src/api/api.ts
202
- import { ethers as ethers2 } from "@rsksmart/bridges-core-sdk";
256
+ import { assertTruthy, ethers as ethers2 } from "@rsksmart/bridges-core-sdk";
257
+ var maxErrorMessageLength = 300;
258
+ var maxRequestTimeoutMs = 2147483647;
259
+ function firstNonEmptyString(candidates) {
260
+ return candidates.find((candidate) => typeof candidate === "string" && candidate.length > 0);
261
+ }
262
+ function unwrapJsonMessage(message) {
263
+ if (!message.startsWith("{")) {
264
+ return message;
265
+ }
266
+ let parsed;
267
+ try {
268
+ parsed = JSON.parse(message);
269
+ } catch {
270
+ return message;
271
+ }
272
+ return firstNonEmptyString([
273
+ parsed?.error,
274
+ parsed?.message
275
+ ]) ?? message;
276
+ }
277
+ function originOf(url) {
278
+ if (!url) {
279
+ return void 0;
280
+ }
281
+ try {
282
+ return new URL(url).origin;
283
+ } catch {
284
+ return void 0;
285
+ }
286
+ }
287
+ function finalUrlOf(response) {
288
+ const request = response.request;
289
+ return request?.responseURL ?? request?.res?.responseUrl;
290
+ }
291
+ function sanitizeMessage(message) {
292
+ const stripped = message.replace(/[\u0000-\u001F\u007F-\u009F]/g, " ").trim();
293
+ if (stripped.length <= maxErrorMessageLength) {
294
+ return stripped;
295
+ }
296
+ return `${[...stripped].slice(0, maxErrorMessageLength).join("")}\u2026`;
297
+ }
298
+ function getErrorMessage(data) {
299
+ const message = firstNonEmptyString([
300
+ data?.error?.message,
301
+ data?.message
302
+ ]);
303
+ const sanitized = message ? sanitizeMessage(unwrapJsonMessage(message)) : "";
304
+ return sanitized || "Server error";
305
+ }
203
306
  var ApiService = class {
204
- constructor(network, apiUrl, maxFeeRateSatPerByte = 1e3) {
307
+ constructor(network, apiUrl, maxFeeRateSatPerByte = 1e3, requestTimeoutMs = 1e4) {
205
308
  this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
206
- this.api = axios.create({ baseURL: apiUrl ?? this.apiUrls[network] });
309
+ this.requestTimeoutMs = requestTimeoutMs;
310
+ assertTruthy(Number.isInteger(requestTimeoutMs) && requestTimeoutMs > 0 && requestTimeoutMs <= maxRequestTimeoutMs, `requestTimeoutMs must be a positive integer no greater than ${maxRequestTimeoutMs}, got ${requestTimeoutMs}.`);
311
+ const baseURL = apiUrl ?? this.apiUrls[network];
312
+ this.apiOrigin = originOf(baseURL);
313
+ this.api = axios.create({
314
+ baseURL,
315
+ timeout: this.requestTimeoutMs,
316
+ maxContentLength: this.maxResponseBytes,
317
+ maxBodyLength: this.maxResponseBytes,
318
+ maxRedirects: 0,
319
+ adapter: ["xhr", "http", "fetch"],
320
+ fetchOptions: { redirect: "error" }
321
+ });
322
+ this.api.interceptors.request.use((config) => {
323
+ config.signal ??= AbortSignal.timeout(config.timeout || this.requestTimeoutMs);
324
+ return config;
325
+ });
326
+ this.api.interceptors.response.use(
327
+ (response) => this.assertSameOrigin(response),
328
+ (error) => {
329
+ if (axios.isAxiosError(error) && error.response) {
330
+ this.assertSameOrigin(error.response);
331
+ }
332
+ throw error;
333
+ }
334
+ );
207
335
  }
208
336
  apiUrls = {
209
337
  MAIN: "https://api.2wp.rootstock.io",
@@ -215,12 +343,42 @@ var ApiService = class {
215
343
  fast: 1
216
344
  };
217
345
  api;
346
+ apiOrigin;
347
+ maxResponseBytes = 10 * 1024 * 1024;
348
+ minBroadcastTimeoutMs = 6e4;
349
+ /**
350
+ * Rejects a response served by a host other than the configured one. `maxRedirects` is only honoured
351
+ * by the Node adapter, so this covers the browser one, which follows redirects on its own and reports
352
+ * the final URL. Requests the Node adapter serves never reach here with a foreign origin, since a 3xx
353
+ * is surfaced as an error before any redirect is followed.
354
+ */
355
+ assertSameOrigin(response) {
356
+ const responseOrigin = originOf(finalUrlOf(response));
357
+ if (this.apiOrigin && responseOrigin && responseOrigin !== this.apiOrigin) {
358
+ throw new APIError(`The response came from ${responseOrigin}, not the configured ${this.apiOrigin}.`);
359
+ }
360
+ return response;
361
+ }
218
362
  handleError(error) {
363
+ if (error instanceof APIError) {
364
+ throw error;
365
+ }
219
366
  if (axios.isAxiosError(error)) {
220
367
  if (error.response) {
221
368
  const { status, data } = error.response;
222
- const message = data?.message || "Server error";
223
- throw new APIError(message, status, data);
369
+ if (status >= 300 && status < 400) {
370
+ throw new APIError(`The API responded with a redirect (${status}); apiUrl must point at the final host.`, status, data);
371
+ }
372
+ throw new APIError(getErrorMessage(data), status, data);
373
+ }
374
+ if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
375
+ throw new APIError(`The API did not respond in time: ${error.message}`);
376
+ }
377
+ if (error.code === "ERR_CANCELED") {
378
+ throw new APIError(`The API did not answer within the ${error.config?.timeout}ms deadline.`);
379
+ }
380
+ if (error.code === "ERR_BAD_RESPONSE") {
381
+ throw new APIError(`The API response was rejected: ${error.message}`);
224
382
  }
225
383
  if (error.request) {
226
384
  throw new APIError("No response from server");
@@ -232,6 +390,7 @@ var ApiService = class {
232
390
  throw new APIError("Unexpected error");
233
391
  }
234
392
  async getFeeRate(level) {
393
+ assertTruthy(Object.prototype.hasOwnProperty.call(this.feeLevelBlocks, level), `Unknown fee level ${String(level)}; use 'slow', 'average' or 'fast'.`);
235
394
  const blocks = this.feeLevelBlocks[level];
236
395
  const response = await this.api.get(`/estimate-fee/${blocks}`).catch(this.handleError);
237
396
  let satoshisPerKb;
@@ -249,7 +408,7 @@ var ApiService = class {
249
408
  return satoshisPerKb.add(999).div(1e3).toNumber();
250
409
  }
251
410
  async getTxHex(txId) {
252
- const response = await this.api.get(`/tx?tx=${txId}`).catch(this.handleError);
411
+ const response = await this.api.get(`/tx?tx=${encodeURIComponent(txId)}`).catch(this.handleError);
253
412
  return response.data.hex;
254
413
  }
255
414
  async getOutputs(address2) {
@@ -272,11 +431,12 @@ var ApiService = class {
272
431
  };
273
432
  }
274
433
  async broadcast(hexTx) {
275
- const response = await this.api.post("/broadcast", { data: hexTx }).catch(this.handleError);
434
+ const timeout = Math.max(this.requestTimeoutMs, this.minBroadcastTimeoutMs);
435
+ const response = await this.api.post("/broadcast", { data: hexTx }, { timeout }).catch(this.handleError);
276
436
  return response.data.txId;
277
437
  }
278
438
  async getTransactionStatus(txHash, txType) {
279
- const response = await this.api.get(`/tx-status-by-type/${txHash}/${txType}`).catch(this.handleError);
439
+ const response = await this.api.get(`/tx-status-by-type/${encodeURIComponent(txHash)}/${encodeURIComponent(txType)}`).catch(this.handleError);
280
440
  return response.data;
281
441
  }
282
442
  async getPeginConfiguration() {
@@ -290,32 +450,8 @@ var ApiService = class {
290
450
  };
291
451
 
292
452
  // src/sdk/powpeg.ts
293
- import { assertTruthy, ethers as ethers3 } from "@rsksmart/bridges-core-sdk";
453
+ import { assertTruthy as assertTruthy2, ethers as ethers3 } from "@rsksmart/bridges-core-sdk";
294
454
  var PowPegSDK = class {
295
- /**
296
- * @param {BitcoinSigner | null} _bitcoinSigner - An instance of a class that implements the BitcoinSigner interface.
297
- * @param {BitcoinDataSource | null} _bitcoinDataSource - An instance of a class that implements the BitcoinDataSource interface or null if you won't use peg-in operations.
298
- * @param {Network} network - The network to use. Either 'MAIN' or 'TEST'.
299
- * @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.
300
- * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource.
301
- * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10.
302
- * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000.
303
- * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000.
304
- * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5.
305
- */
306
- constructor(_bitcoinSigner, _bitcoinDataSource, network, rpcProviderUrl, apiUrl, maxBundleSize = 10, burnDustValue = 2e3, maxFeeRateSatPerByte = 1e3, maxFeeToAmountRatio = 0.5) {
307
- this._bitcoinSigner = _bitcoinSigner;
308
- this._bitcoinDataSource = _bitcoinDataSource;
309
- this.network = network;
310
- this.maxBundleSize = maxBundleSize;
311
- this.burnDustValue = burnDustValue;
312
- this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
313
- this.maxFeeToAmountRatio = maxFeeToAmountRatio;
314
- this.btcNetworkConfig = networks[network];
315
- this.rskProvider = new ethers3.providers.JsonRpcProvider(rpcProviderUrl ?? this.publicNodes[network]);
316
- this.bridge = new Bridge(this.rskProvider);
317
- this.api = new ApiService(network, apiUrl, maxFeeRateSatPerByte);
318
- }
319
455
  txHeaderSizeInBytes = 13;
320
456
  txOutputSizeInBytes = 32;
321
457
  txInputSizeInBytes = 145;
@@ -326,17 +462,75 @@ var PowPegSDK = class {
326
462
  psbtSigner = /* @__PURE__ */ new WeakMap();
327
463
  minPeginAmount = 500000n;
328
464
  peginFeeEstimationInputs = 2;
329
- minPegoutAmount = "0.004";
465
+ minPegoutSatoshis = {
466
+ MAIN: 400000n,
467
+ TEST: 250000n
468
+ };
469
+ pegoutFeeGapPercentage = 80n;
470
+ pegoutSimulationInputs = 2;
471
+ pegoutSimulationOutputs = 2;
472
+ pegoutScriptSigSize = 36;
473
+ maxScriptSigRedeemScriptSize = 520;
474
+ pegoutSignatureSize = 73;
475
+ pegoutDeployedSignatureSize = 72;
476
+ weiPerSatoshi = 10000000000n;
477
+ pegoutRejectionReasons = {
478
+ LOW_AMOUNT: "the amount was below the minimum the Bridge enforces, and was refunded",
479
+ CALLER_CONTRACT: "peg-outs are only allowed from an externally owned account and the caller is a contract; the amount was NOT refunded and remains held by the Bridge",
480
+ FEE_ABOVE_VALUE: "the fee would have exceeded the amount being released, and the amount was refunded"
481
+ };
330
482
  btcNetworkConfig;
331
483
  bridge;
332
484
  api;
333
485
  rskProvider;
334
- publicNodes = {
335
- MAIN: "https://public-node.rsk.co",
336
- TEST: "https://public-node.testnet.rsk.co"
486
+ rskNetworks = {
487
+ MAIN: { url: "https://public-node.rsk.co", chainId: 30 },
488
+ TEST: { url: "https://public-node.testnet.rsk.co", chainId: 31 }
337
489
  };
490
+ network;
491
+ _bitcoinSigner;
492
+ _bitcoinDataSource;
493
+ maxBundleSize;
494
+ burnDustValue;
495
+ maxFeeRateSatPerByte;
496
+ maxFeeToAmountRatio;
497
+ /**
498
+ * @param {PowPegSDKOptions} options - SDK configuration. Only `network` is required; every other field
499
+ * falls back to the default documented on {@link PowPegSDKOptions}.
500
+ */
501
+ constructor(options) {
502
+ assertTruthy2(options, "PowPegSDK takes a single options object; see PowPegSDKOptions.");
503
+ assertTruthy2(Object.prototype.hasOwnProperty.call(networks, options.network), `Unknown network ${String(options.network)}; use Network.MAIN or Network.TEST.`);
504
+ const {
505
+ network,
506
+ bitcoinSigner = null,
507
+ bitcoinDataSource = null,
508
+ rpcProviderUrl,
509
+ apiUrl,
510
+ maxBundleSize = 10,
511
+ burnDustValue = 2e3,
512
+ maxFeeRateSatPerByte = 1e3,
513
+ maxFeeToAmountRatio = 0.5,
514
+ requestTimeoutMs = 1e4
515
+ } = options;
516
+ assertTruthy2(Number.isInteger(maxBundleSize) && maxBundleSize > 0, `maxBundleSize must be a positive integer, got ${maxBundleSize}.`);
517
+ assertTruthy2(Number.isInteger(burnDustValue) && burnDustValue >= 0, `burnDustValue must be a non-negative integer, got ${burnDustValue}.`);
518
+ assertTruthy2(Number.isInteger(maxFeeRateSatPerByte) && maxFeeRateSatPerByte > 0, `maxFeeRateSatPerByte must be a positive integer, got ${maxFeeRateSatPerByte}.`);
519
+ assertTruthy2(Number.isFinite(maxFeeToAmountRatio) && maxFeeToAmountRatio > 0 && maxFeeToAmountRatio <= 1, `maxFeeToAmountRatio must be greater than 0 and at most 1, got ${maxFeeToAmountRatio}.`);
520
+ this.network = network;
521
+ this._bitcoinSigner = bitcoinSigner;
522
+ this._bitcoinDataSource = bitcoinDataSource;
523
+ this.maxBundleSize = maxBundleSize;
524
+ this.burnDustValue = burnDustValue;
525
+ this.maxFeeRateSatPerByte = maxFeeRateSatPerByte;
526
+ this.maxFeeToAmountRatio = maxFeeToAmountRatio;
527
+ this.btcNetworkConfig = networks[network];
528
+ this.rskProvider = new ethers3.providers.JsonRpcProvider(rpcProviderUrl ?? this.rskNetworks[network].url, this.rskNetworks[network].chainId);
529
+ this.bridge = new Bridge(this.rskProvider);
530
+ this.api = new ApiService(network, apiUrl, maxFeeRateSatPerByte, requestTimeoutMs);
531
+ }
338
532
  get bitcoinSigner() {
339
- assertTruthy(this._bitcoinSigner, "Bitcoin signer is required");
533
+ assertTruthy2(this._bitcoinSigner, "Bitcoin signer is required");
340
534
  return this._bitcoinSigner;
341
535
  }
342
536
  set bitcoinSigner(signer) {
@@ -379,6 +573,13 @@ var PowPegSDK = class {
379
573
  });
380
574
  return { used, unused };
381
575
  }
576
+ isSpendableAddress(btcAddress) {
577
+ try {
578
+ return isSupportedFundingScript(address.toOutputScript(btcAddress, this.btcNetworkConfig.lib));
579
+ } catch {
580
+ return false;
581
+ }
582
+ }
382
583
  groupAddressesByBalance(addresses) {
383
584
  const withBalance = [];
384
585
  const withoutBalance = [];
@@ -473,7 +674,7 @@ var PowPegSDK = class {
473
674
  const addresses = await this.getAddressesGroupedByUsage(signer);
474
675
  const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
475
676
  const refundAddress = addresses.nonChange.unused[0]?.address;
476
- const { output: script } = payments2.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
677
+ const { output: script } = payments.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
477
678
  if (script) {
478
679
  psbt.addOutput({
479
680
  script,
@@ -486,14 +687,21 @@ var PowPegSDK = class {
486
687
  value: Number(amount)
487
688
  });
488
689
  let utxos;
690
+ let skippedSatoshis = 0n;
489
691
  if (selectedUtxos) {
490
692
  utxos = [...selectedUtxos];
491
693
  } else {
492
694
  const usedAddresses = addresses.nonChange.used.concat(addresses.change.used);
695
+ if (!usedAddresses.length && !addresses.nonChange.unused.length && !addresses.change.unused.length) {
696
+ throw new SigningError("The signer derived no addresses, so there is nothing to discover UTXOs from. Pass selectedUtxos to fund from a set you resolved yourself.");
697
+ }
493
698
  const { withBalance } = this.groupAddressesByBalance(usedAddresses);
494
- utxos = await this.getUtxos(withBalance);
699
+ const spendable = withBalance.filter((address2) => this.isSpendableAddress(address2.address));
700
+ skippedSatoshis = withBalance.filter((address2) => !this.isSpendableAddress(address2.address)).reduce((total, address2) => total + BigInt(address2.balance), 0n);
701
+ utxos = await this.getUtxos(spendable);
495
702
  }
496
- this.funding.set(psbt, { utxos, changeAddress: addresses.change.unused[0]?.address });
703
+ const changeAddress = addresses.change.unused.find((address2) => this.isSpendableAddress(address2.address)) ?? addresses.change.unused[0];
704
+ this.funding.set(psbt, { utxos, changeAddress: changeAddress?.address, skippedSatoshis });
497
705
  this.psbtSigner.set(psbt, signer);
498
706
  return psbt;
499
707
  }
@@ -535,11 +743,12 @@ var PowPegSDK = class {
535
743
  const feePerInput = feeRate * this.txInputSizeInBytes;
536
744
  return { baseFee, feePerInput };
537
745
  }
538
- async calculateFeeAndSelectedInputs(amount, utxos, feeRate) {
746
+ async calculateFeeAndSelectedInputs(amount, utxos, feeRate, skippedSatoshis = 0n) {
539
747
  const { baseFee, feePerInput } = await this.calculatePeginFee(amount, feeRate);
540
748
  const { inputs, rest } = this.selectInputs(amount, utxos, baseFee, feePerInput);
541
749
  if (rest > 0) {
542
- throw new NotEnoughFundsError(`${rest} satoshis needed to cover the requested amount.`);
750
+ const skipped = skippedSatoshis > 0n ? ` A further ${skippedSatoshis} satoshis are held by addresses whose script type the SDK cannot build a signable input for; pass selectedUtxos to fund from a set you resolved yourself.` : "";
751
+ throw new NotEnoughFundsError(`${rest} satoshis needed to cover the requested amount.${skipped}`);
543
752
  }
544
753
  const totalFee = baseFee + feePerInput * inputs.length;
545
754
  if (totalFee > Number(amount) * this.maxFeeToAmountRatio) {
@@ -558,25 +767,35 @@ var PowPegSDK = class {
558
767
  */
559
768
  async fundPegin(psbt, feeLevel = "fast", value, feeRate) {
560
769
  const funding = this.funding.get(psbt);
561
- assertTruthy(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
770
+ assertTruthy2(funding, "No funding context found for this PSBT. Create it with createPegin or createAndFundPsbt first.");
562
771
  const amount = value ?? BigInt(psbt.txOutputs[1].value);
563
772
  const resolvedFeeRate = feeRate !== void 0 ? this.validateFeeRate(feeRate) : await this.getValidatedFeeRate(feeLevel);
564
- const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, resolvedFeeRate);
773
+ const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, resolvedFeeRate, funding.skippedSatoshis);
565
774
  const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
566
775
  const parsedOutputs = hexTransactions.map((hex, index) => {
567
776
  const tx = Transaction.fromHex(hex);
568
- assertTruthy(
777
+ assertTruthy2(
569
778
  tx.getId() === inputs[index].txid,
570
779
  `Fetched transaction for UTXO ${inputs[index].txid}:${inputs[index].vout} does not match the requested txid (got ${tx.getId()}).`
571
780
  );
572
781
  const output = tx.outs[inputs[index].vout];
573
- assertTruthy(output, `UTXO ${inputs[index].txid}:${inputs[index].vout} was not found in the fetched transaction.`);
574
- assertTruthy(
782
+ assertTruthy2(output, `UTXO ${inputs[index].txid}:${inputs[index].vout} was not found in the fetched transaction.`);
783
+ assertTruthy2(
575
784
  BigInt(output.value) === inputs[index].amount,
576
785
  `UTXO ${inputs[index].txid}:${inputs[index].vout} value mismatch: fetched transaction reports ${output.value}, expected ${inputs[index].amount}.`
577
786
  );
578
787
  return output;
579
788
  });
789
+ inputs.forEach((input, index) => {
790
+ const script = parsedOutputs[index].script;
791
+ if (!isSupportedFundingScript(script)) {
792
+ const detail = isP2shScript(script) ? `the P2SH address ${input.address}. Signing it needs a redeem script the SDK cannot derive, because BitcoinSigner exposes addresses but not the public keys behind them.` : `${input.address}, whose script type the SDK cannot build a signable input for.`;
793
+ throw new UnsupportedAddressTypeError(
794
+ input.address,
795
+ `UTXO ${input.txid}:${input.vout} is held by ${detail} Fund the peg-in from a legacy (P2PKH) or native segwit (P2WPKH) address, or pass selectedUtxos that exclude this one.`
796
+ );
797
+ }
798
+ });
580
799
  const initialInputCount = psbt.txInputs.length;
581
800
  const initialOutputCount = psbt.txOutputs.length;
582
801
  const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
@@ -594,6 +813,8 @@ var PowPegSDK = class {
594
813
  psbt.addInput({
595
814
  hash: input.txid,
596
815
  index: input.vout,
816
+ // A witness input is signed from witnessUtxo alone; a legacy input needs its parent transaction.
817
+ ...isWitnessProgramScript(output.script) ? {} : { nonWitnessUtxo: Buffer.from(hexTransactions[index], "hex") },
597
818
  witnessUtxo: {
598
819
  script: output.script,
599
820
  value: output.value
@@ -602,7 +823,7 @@ var PowPegSDK = class {
602
823
  });
603
824
  const expectedInputCount = initialInputCount + inputs.length;
604
825
  const expectedOutputCount = initialOutputCount + (addChange ? 1 : 0);
605
- assertTruthy(
826
+ assertTruthy2(
606
827
  psbt.txInputs.length === expectedInputCount && psbt.txOutputs.length === expectedOutputCount,
607
828
  `Funded PSBT structure mismatch: expected ${expectedInputCount} inputs and ${expectedOutputCount} outputs, got ${psbt.txInputs.length} and ${psbt.txOutputs.length}.`
608
829
  );
@@ -615,7 +836,7 @@ var PowPegSDK = class {
615
836
  * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in.
616
837
  * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`.
617
838
  * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses.
618
- * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently (e.g. from a prior `estimatePeginFee` call) to pin funding to that exact value instead of risking a second, possibly different, fetch.
839
+ * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch.
619
840
  * @returns {Promise<UnsignedPegin>} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee.
620
841
  */
621
842
  async createAndFundPegin(amount, recipientAddress, signer, feeLevel = "fast", selectedUtxos, feeRate) {
@@ -639,7 +860,7 @@ var PowPegSDK = class {
639
860
  address: recipientAddress,
640
861
  value: Number(amount)
641
862
  });
642
- this.funding.set(psbt, { utxos: [...utxos] });
863
+ this.funding.set(psbt, { utxos: [...utxos], skippedSatoshis: 0n });
643
864
  if (signer) {
644
865
  this.psbtSigner.set(psbt, signer);
645
866
  }
@@ -647,26 +868,156 @@ var PowPegSDK = class {
647
868
  }
648
869
  async signPegin(psbt, inputs, transactions) {
649
870
  const signer = this.psbtSigner.get(psbt);
650
- assertTruthy(signer, "No signer bound to this PSBT. Sign the PSBT returned by createPegin, createAndFundPegin, or createAndFundPsbt with a signer argument.");
651
- return signer.signTransaction(psbt, inputs, transactions);
871
+ assertTruthy2(signer, "No signer bound to this PSBT. Sign the PSBT returned by createPegin, createAndFundPegin, or createAndFundPsbt with a signer argument.");
872
+ const signedTx = await signer.signTransaction(psbt, inputs, transactions);
873
+ if (!signedTx) {
874
+ throw new SigningError("The signer returned no signed transaction.");
875
+ }
876
+ return signedTx;
652
877
  }
653
878
  /**
654
879
  * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source.
655
880
  * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast.
656
- * @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.
657
- * @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.
881
+ * @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 signers that must verify each input against its funding transaction; optional only for signers that can sign directly from the PSBT.
882
+ * @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 signers that must verify each input against its funding transaction; optional only for signers that can sign directly from the PSBT.
658
883
  * @returns {Promise<string>} The broadcast transaction's ID.
884
+ * @throws {SigningError} If the signer returns no signed transaction.
659
885
  */
660
886
  async signAndBroadcastPegin(psbt, inputs, transactions) {
661
887
  const signedTx = await this.signPegin(psbt, inputs, transactions);
662
888
  return this.bitcoinDataSource.broadcast(signedTx);
663
889
  }
664
- validateMinimumPegoutAmount(amount) {
665
- const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
666
- const minAmountBN = ethers3.utils.parseUnits(this.minPegoutAmount, 18).toBigInt();
667
- if (amountBN < minAmountBN) {
668
- throw new AmountBelowMinError(`Minimum allowed amount is ${this.minPegoutAmount}.`);
890
+ varIntSize(value) {
891
+ if (value < 253) {
892
+ return 1;
893
+ }
894
+ if (value <= 65535) {
895
+ return 3;
896
+ }
897
+ if (value <= 4294967295) {
898
+ return 5;
669
899
  }
900
+ return 9;
901
+ }
902
+ /**
903
+ * Witness bytes each input contributes once signed: the stack item count, the two empty elements the
904
+ * federation's script pushes, one signature per required signer, and the redeem script itself.
905
+ */
906
+ estimateSigningSizePerInput(redeemScriptSize, threshold) {
907
+ const stackItemCount = threshold + 3;
908
+ return this.varIntSize(stackItemCount) + 1 + (this.varIntSize(this.pegoutSignatureSize) + this.pegoutSignatureSize) * threshold + 1 + this.varIntSize(redeemScriptSize) + redeemScriptSize;
909
+ }
910
+ /**
911
+ * Resolves the federation's output script from its redeem script, and with it the transaction format
912
+ * the Bridge builds. The address is required to derive from the redeem script: a P2SH wrapping the
913
+ * witness program means P2SH-P2WSH, a P2SH wrapping the redeem script itself means a legacy multisig.
914
+ */
915
+ resolveFederationOutput(redeemScript, federationAddress) {
916
+ const network = this.btcNetworkConfig.lib;
917
+ const derivations = [
918
+ () => {
919
+ const segwit = payments.p2sh({ redeem: payments.p2wsh({ redeem: { output: redeemScript }, network }), network });
920
+ return segwit.output && federationAddress === segwit.address ? { outputScript: segwit.output, isSegwit: true } : void 0;
921
+ },
922
+ () => {
923
+ if (redeemScript.length > this.maxScriptSigRedeemScriptSize) {
924
+ return void 0;
925
+ }
926
+ const legacy = payments.p2sh({ redeem: { output: redeemScript }, network });
927
+ return legacy.output && federationAddress === legacy.address ? { outputScript: legacy.output, isSegwit: false } : void 0;
928
+ }
929
+ ];
930
+ let lastError;
931
+ for (const derive of derivations) {
932
+ try {
933
+ const candidate = derive();
934
+ if (candidate) {
935
+ return candidate;
936
+ }
937
+ } catch (error) {
938
+ lastError = error;
939
+ }
940
+ }
941
+ if (lastError) {
942
+ throw new FederationAddressError(`The active powpeg redeem script could not be interpreted: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
943
+ }
944
+ throw new FederationAddressError(`Federation address ${federationAddress} is not derivable from the active powpeg redeem script.`);
945
+ }
946
+ buildPegoutSimulation(outputScript, inputs, outputs, scriptSig) {
947
+ const transaction = new Transaction();
948
+ if (scriptSig) {
949
+ for (let i = 0; i < inputs; i++) {
950
+ transaction.addInput(Buffer.alloc(32), 0, void 0, scriptSig);
951
+ }
952
+ }
953
+ for (let i = 0; i < outputs; i++) {
954
+ transaction.addOutput(outputScript, 0);
955
+ }
956
+ return transaction;
957
+ }
958
+ /**
959
+ * Size the Bridge computes for a P2SH-P2WSH federation: the transaction is serialized without its
960
+ * inputs and a fixed script-sig size is added per input instead.
961
+ */
962
+ pegoutVSizeSegwit(redeemScript, threshold, outputScript, inputs, outputs) {
963
+ const baseSize = this.buildPegoutSimulation(outputScript, inputs, outputs).byteLength(false) + inputs * this.pegoutScriptSigSize;
964
+ const signingSize = threshold * inputs * this.pegoutDeployedSignatureSize;
965
+ const totalSize = baseSize + signingSize + inputs * redeemScript.length;
966
+ return Math.floor((totalSize + 3 * baseSize) / 4);
967
+ }
968
+ /**
969
+ * Size the Bridge computes for a federation that is not P2SH-P2WSH: plain serialized bytes, with the
970
+ * redeem script spent through each input's script sig and no witness discount.
971
+ */
972
+ pegoutVSizeNonSegwit(redeemScript, threshold, outputScript, inputs, outputs) {
973
+ const baseSize = this.buildPegoutSimulation(outputScript, inputs, outputs, redeemScript).byteLength(false);
974
+ return baseSize + threshold * inputs * this.pegoutDeployedSignatureSize;
975
+ }
976
+ /**
977
+ * Size the Bridge computes once RSKIP378 is active: every input is serialized, and its witness carries
978
+ * one signature per required signer plus the redeem script, weighted as per BIP141.
979
+ */
980
+ pegoutVSizeAfterRskip378(redeemScript, threshold, outputScript, inputs, outputs) {
981
+ const baseSize = this.buildPegoutSimulation(outputScript, inputs, outputs, Buffer.alloc(this.pegoutScriptSigSize)).byteLength(false);
982
+ const witnessSize = inputs * this.estimateSigningSizePerInput(redeemScript.length, threshold);
983
+ return Math.floor((4 * baseSize + witnessSize) / 4);
984
+ }
985
+ /**
986
+ * Virtual size of the transaction the Bridge would build for a regular peg-out, taken as the larger of
987
+ * what it computes today and what it will compute once RSKIP378 activates, so the derived minimum is
988
+ * never below the one the Bridge enforces under either rule.
989
+ */
990
+ simulatePegoutVSize(redeemScriptHex, threshold, federationAddress) {
991
+ const redeemScript = Buffer.from(remove0x(redeemScriptHex), "hex");
992
+ const { outputScript, isSegwit } = this.resolveFederationOutput(redeemScript, federationAddress);
993
+ const inputs = this.pegoutSimulationInputs;
994
+ const outputs = this.pegoutSimulationOutputs;
995
+ const deployed = isSegwit ? this.pegoutVSizeSegwit(redeemScript, threshold, outputScript, inputs, outputs) : this.pegoutVSizeNonSegwit(redeemScript, threshold, outputScript, inputs, outputs);
996
+ return Math.max(deployed, this.pegoutVSizeAfterRskip378(redeemScript, threshold, outputScript, inputs, outputs));
997
+ }
998
+ async getMinimumPegoutSatoshis() {
999
+ const [feePerKb, redeemScript, threshold, federationAddress] = await Promise.all([
1000
+ this.bridge.getFeePerKb(),
1001
+ this.bridge.getActivePowpegRedeemScript(),
1002
+ this.bridge.getFederationThreshold(),
1003
+ this.bridge.getFederationAddress()
1004
+ ]);
1005
+ const pegoutSize = BigInt(this.simulatePegoutVSize(redeemScript, threshold, federationAddress));
1006
+ const feeForPegout = feePerKb * pegoutSize / 1000n;
1007
+ const requiredFunds = feeForPegout + feeForPegout * this.pegoutFeeGapPercentage / 100n;
1008
+ const networkMinimum = this.minPegoutSatoshis[this.network];
1009
+ return requiredFunds > networkMinimum ? requiredFunds : networkMinimum;
1010
+ }
1011
+ assertAtLeastMinimumPegout(amountSatoshis, minimumSatoshis) {
1012
+ if (amountSatoshis < minimumSatoshis) {
1013
+ const minimumAmount = ethers3.utils.formatUnits(minimumSatoshis * this.weiPerSatoshi, 18);
1014
+ throw new AmountBelowMinError(`Minimum allowed amount is ${minimumAmount}.`);
1015
+ }
1016
+ }
1017
+ async validateMinimumPegoutAmount(amount) {
1018
+ const amountSatoshis = ethers3.utils.parseUnits(amount, 18).toBigInt() / this.weiPerSatoshi;
1019
+ this.assertAtLeastMinimumPegout(amountSatoshis, this.minPegoutSatoshis[this.network]);
1020
+ this.assertAtLeastMinimumPegout(amountSatoshis, await this.getMinimumPegoutSatoshis());
670
1021
  }
671
1022
  createPegoutTransaction(amount, fromAddress) {
672
1023
  const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
@@ -681,9 +1032,10 @@ var PowPegSDK = class {
681
1032
  * @param {string} amount - Amount to peg out, in RBTC (18 decimals).
682
1033
  * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address.
683
1034
  * @returns {Promise<PegoutFeeEstimation>} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei).
1035
+ * @throws {AmountBelowMinError} If `amount` is below the minimum the Bridge currently enforces, derived from its fee per kb and the active federation.
684
1036
  */
685
1037
  async estimatePegoutFees(amount, fromAddress = ethers3.constants.AddressZero) {
686
- this.validateMinimumPegoutAmount(amount);
1038
+ await this.validateMinimumPegoutAmount(amount);
687
1039
  const tx = this.createPegoutTransaction(amount, fromAddress);
688
1040
  const [gas, gasPrice, bitcoinFee] = await Promise.all([
689
1041
  this.rskProvider.estimateGas(tx),
@@ -703,31 +1055,74 @@ var PowPegSDK = class {
703
1055
  * @param {string} senderAccount - Rootstock address that will send the peg-out.
704
1056
  * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees.
705
1057
  * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`.
1058
+ * @throws {UnsupportedSenderError} If `senderAccount` is a contract account.
706
1059
  */
707
1060
  async createPegout(amount, senderAccount) {
708
1061
  const fees = await this.estimatePegoutFees(amount, senderAccount);
709
1062
  const amountBN = ethers3.utils.parseUnits(amount, 18).toBigInt();
710
- const balance = await this.rskProvider.getBalance(senderAccount);
1063
+ const [balance, senderCode] = await Promise.all([
1064
+ this.rskProvider.getBalance(senderAccount),
1065
+ this.rskProvider.getCode(senderAccount)
1066
+ ]);
1067
+ if (senderCode !== "0x") {
1068
+ throw new UnsupportedSenderError(`${senderAccount} is a contract account; the Bridge only releases BTC for peg-outs sent from an externally owned account.`);
1069
+ }
711
1070
  if (balance.lt(amountBN)) {
712
1071
  throw new NotEnoughFundsError(`Requested amount ${amountBN} is greater than current balance ${balance}.`);
713
1072
  }
714
1073
  const tx = this.createPegoutTransaction(amount, senderAccount);
715
1074
  return {
716
- tx,
1075
+ tx: { ...tx, chainId: this.rskNetworks[this.network].chainId },
717
1076
  rootstockFee: fees.rootstockFee,
718
1077
  bitcoinFee: fees.bitcoinFee
719
1078
  };
720
1079
  }
721
1080
  /**
722
1081
  * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
723
- * and waits for it to be mined on the SDK's RSK RPC node.
724
- * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request.
1082
+ * and waits for it to be mined.
1083
+ * @param {UnsignedPegout} tx - The peg-out transaction request, as returned by {@link createPegout}. Forwarded to the signer as given, so gas, nonce and fee fields set by the caller are honoured; only an absent chain id is filled in.
725
1084
  * @param {ethers.Signer} signer - Ethers signer used to send the transaction.
726
- * @returns The mined transaction receipt.
1085
+ * @returns The mined transaction receipt, if the signer's provider is set.
1086
+ * @throws {WrongNetworkError} If the transaction's chain id, or the signer's chain, doesn't match the network the SDK was configured for.
1087
+ * @throws {TransactionRevertedError} If the transaction was mined but reverted.
1088
+ * @throws {PegoutRejectedError} If the transaction was mined but the Bridge rejected and refunded the release request.
727
1089
  */
728
1090
  async signAndBroadcastPegout(tx, signer) {
729
- const { hash } = await signer.sendTransaction(tx);
730
- return this.rskProvider.waitForTransaction(hash);
1091
+ const expectedChainId = this.rskNetworks[this.network].chainId;
1092
+ const request = { ...tx, chainId: tx.chainId === void 0 ? expectedChainId : tx.chainId };
1093
+ assertTruthy2(
1094
+ typeof request.to === "string" && request.to.toLowerCase() === this.bridge.address.toLowerCase(),
1095
+ `A peg-out is a value transfer to the bridge at ${this.bridge.address}; this request is addressed to ${String(request.to)}.`
1096
+ );
1097
+ assertTruthy2(
1098
+ request.data === void 0 || request.data === "0x",
1099
+ "A peg-out carries no calldata; remove the data field from the request."
1100
+ );
1101
+ if (request.chainId !== expectedChainId) {
1102
+ throw new WrongNetworkError(`The transaction targets chain ${request.chainId}, but the SDK is configured for ${this.network} (chain ${expectedChainId}).`);
1103
+ }
1104
+ const signerChainId = await signer.getChainId();
1105
+ if (signerChainId !== expectedChainId) {
1106
+ throw new WrongNetworkError(`Signer is on chain ${signerChainId}, but the SDK is configured for ${this.network} (chain ${expectedChainId}).`);
1107
+ }
1108
+ const { hash } = await signer.sendTransaction(request);
1109
+ const receipt = await signer.provider?.waitForTransaction(hash);
1110
+ if (receipt) {
1111
+ if (receipt.status === 0) {
1112
+ throw new TransactionRevertedError(hash, receipt, `The peg-out transaction ${hash} was mined but reverted; no BTC release was requested.`);
1113
+ }
1114
+ const rejected = this.bridge.findRejectedPegout(receipt.logs ?? []);
1115
+ if (rejected) {
1116
+ const reason = this.pegoutRejectionReasons[RejectedPegoutReasons[rejected.reason]] ?? `the Bridge reported reason code ${rejected.reason}`;
1117
+ throw new PegoutRejectedError(
1118
+ rejected.reason,
1119
+ hash,
1120
+ rejected.amount,
1121
+ `The Bridge rejected the peg-out of ${rejected.amount} wei in transaction ${hash}: ${reason}.`
1122
+ );
1123
+ }
1124
+ }
1125
+ return receipt;
731
1126
  }
732
1127
  /**
733
1128
  * Fetches the current status of a peg-in or peg-out transaction from the configured API.
@@ -760,370 +1155,23 @@ var PowPegSDK = class {
760
1155
  return this.getUtxos(addressList);
761
1156
  }
762
1157
  };
763
-
764
- // src/bitcoin-signers/trezor/trezor.ts
765
- import TrezorConnect from "@trezor/connect-web";
766
- import { assertTruthy as assertTruthy2 } from "@rsksmart/bridges-core-sdk";
767
- import "bitcoinjs-lib";
768
- var TrezorSigner = class _TrezorSigner {
769
- constructor(network = "TEST", _addressType = "NATIVE SEGWIT") {
770
- this.network = network;
771
- this._addressType = _addressType;
772
- }
773
- bitcoinTxVersion = 1;
774
- addresses = /* @__PURE__ */ new Map();
775
- /**
776
- * Initializes the Trezor connection and returns a ready-to-use signer.
777
- * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
778
- * @param {Partial<Parameters<typeof TrezorConnect.init>[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call.
779
- * @returns {Promise<TrezorSigner>} The initialized signer.
780
- */
781
- static async init(network, initOptions) {
782
- await TrezorConnect.init({ manifest: { appUrl: "", email: "", appName: "" }, ...initOptions });
783
- return new _TrezorSigner(network);
784
- }
785
- /**
786
- * Disposes the current Trezor connection and re-initializes it.
787
- * @returns {Promise<TrezorSigner>} A freshly initialized signer for the default (`'TEST'`) network.
788
- */
789
- static async reinit() {
790
- TrezorConnect.dispose();
791
- return _TrezorSigner.init();
792
- }
793
- /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
794
- set addressType(addressType) {
795
- this._addressType = addressType;
796
- }
797
- get addressType() {
798
- return this._addressType;
799
- }
800
- getPathPurpose() {
801
- return supportedAddressTypes[this._addressType].path;
802
- }
803
- getPathCoin() {
804
- return networks[this.network].coin;
805
- }
806
- async getAddresses(bundleSize, change = false) {
807
- const addresses = [];
808
- const bundle = Array.from(
809
- { length: bundleSize },
810
- (_, i) => ({ path: `m/${this.getPathPurpose()}'/${this.getPathCoin()}'/0'/${change ? "1" : "0"}/${i}`, showOnTrezor: false, coin: this.network })
811
- );
812
- const result = await TrezorConnect.getAddress({ bundle });
813
- if (result.success) {
814
- result.payload.forEach(({ address: address2, path }) => {
815
- this.addresses.set(address2, path);
816
- addresses.push(address2);
817
- });
818
- }
819
- return addresses;
820
- }
821
- /**
822
- * @param {number} bundleSize - Number of change addresses to derive.
823
- * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Trezor device.
824
- */
825
- async getChangeAddresses(bundleSize) {
826
- return this.getAddresses(bundleSize, true);
827
- }
828
- /**
829
- * @param {number} bundleSize - Number of receive addresses to derive.
830
- * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Trezor device.
831
- */
832
- async getNonChangeAddresses(bundleSize) {
833
- return this.getAddresses(bundleSize);
834
- }
835
- getScriptType(address2) {
836
- const addressType = getAddressType(address2, this.network);
837
- switch (addressType) {
838
- case "SEGWIT":
839
- return "SPENDP2SHWITNESS";
840
- case "LEGACY":
841
- return "SPENDADDRESS";
842
- case "NATIVE SEGWIT":
843
- return "SPENDWITNESS";
844
- default:
845
- return "SPENDADDRESS";
846
- }
847
- }
848
- getInputs(utxos) {
849
- return utxos.map((utxo) => {
850
- return {
851
- address_n: this.addresses.get(utxo.address) ?? [],
852
- prev_hash: utxo.txid,
853
- prev_index: utxo.vout,
854
- script_type: this.getScriptType(utxo.address),
855
- amount: Number(utxo.amount)
856
- };
857
- });
858
- }
859
- getOutputScriptType(address2) {
860
- const addressType = getAddressType(address2, this.network);
861
- switch (addressType) {
862
- case "SEGWIT":
863
- return "PAYTOP2SHWITNESS";
864
- case "NATIVE SEGWIT":
865
- return "PAYTOWITNESS";
866
- default:
867
- return "PAYTOADDRESS";
868
- }
869
- }
870
- isChangePath(path) {
871
- return path.length === 5 && path[3] === 1;
872
- }
873
- getOutputs(psbt) {
874
- const lastIndex = psbt.txOutputs.length - 1;
875
- return psbt.txOutputs.map((output, index) => {
876
- if (output.value === 0 && !output.address) {
877
- return {
878
- amount: output.value,
879
- op_return_data: output.script.toString("hex").slice(4),
880
- script_type: "PAYTOOPRETURN"
881
- };
882
- }
883
- const path = output.address ? this.addresses.get(output.address) : void 0;
884
- if (index === lastIndex && index > 0 && output.address && path && this.isChangePath(path)) {
885
- return {
886
- address_n: path,
887
- script_type: this.getOutputScriptType(output.address),
888
- amount: output.value
889
- };
890
- }
891
- return {
892
- address: output.address ?? "",
893
- script_type: "PAYTOADDRESS",
894
- amount: output.value
895
- };
896
- });
897
- }
898
- /**
899
- * Signs the given PSBT's inputs/outputs on the Trezor device.
900
- * @param {Psbt} psbt - The PSBT to sign.
901
- * @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.
902
- * @returns {Promise<string>} The serialized signed transaction, or an empty string if signing didn't succeed.
903
- */
904
- async signTransaction(psbt, utxos) {
905
- assertTruthy2(utxos, "TrezorSigner.signTransaction requires utxos to look up input derivation paths");
906
- const inputs = this.getInputs(utxos);
907
- const outputs = this.getOutputs(psbt);
908
- const result = await TrezorConnect.signTransaction({
909
- coin: this.network,
910
- version: this.bitcoinTxVersion,
911
- inputs,
912
- outputs
913
- });
914
- if (result.success) {
915
- return result.payload.serializedTx;
916
- }
917
- return "";
918
- }
919
- };
920
-
921
- // src/bitcoin-signers/ledger/ledger.ts
922
- import Btc from "@ledgerhq/hw-app-btc";
923
- import TransportWebUSB from "@ledgerhq/hw-transport-webusb";
924
- import { assertTruthy as assertTruthy3 } from "@rsksmart/bridges-core-sdk";
925
- import { Transaction as Transaction2 } from "bitcoinjs-lib";
926
-
927
- // src/bitcoin-signers/ledger/ledger-transport.ts
928
- var LedgerTransportService = class {
929
- constructor(transport) {
930
- this.transport = transport;
931
- }
932
- queue = [];
933
- isProcessing = false;
934
- async processQueue() {
935
- if (this.isProcessing || this.queue.length === 0 || this.isDeviceBusy()) {
936
- return;
937
- }
938
- this.isProcessing = true;
939
- const item = this.queue.shift();
940
- if (!item) {
941
- this.isProcessing = false;
942
- return;
943
- }
944
- try {
945
- const result = await item.operation();
946
- item.resolve(result);
947
- } catch (error) {
948
- item.reject(error instanceof Error ? error : new Error(String(error)));
949
- } finally {
950
- this.isProcessing = false;
951
- this.processQueue();
952
- }
953
- }
954
- async enqueue(operation) {
955
- return new Promise((resolve, reject) => {
956
- this.queue.push({
957
- resolve,
958
- reject,
959
- operation
960
- });
961
- this.processQueue();
962
- });
963
- }
964
- isDeviceBusy() {
965
- return Boolean(this.transport._appAPIlock);
966
- }
967
- };
968
-
969
- // src/bitcoin-signers/ledger/ledger.ts
970
- var LedgerSigner = class _LedgerSigner {
971
- constructor(connection, transport, network, _addressType = "NATIVE SEGWIT") {
972
- this.connection = connection;
973
- this.transport = transport;
974
- this.network = network;
975
- this._addressType = _addressType;
976
- this.transportService = new LedgerTransportService(transport);
977
- }
978
- addresses = /* @__PURE__ */ new Map();
979
- transportService;
980
- /**
981
- * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer.
982
- * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`.
983
- * @returns {Promise<LedgerSigner>} The initialized signer.
984
- */
985
- static async init(network = "TEST") {
986
- const transport = await TransportWebUSB.create();
987
- const connection = new Btc({ transport, currency: networks[network].currency });
988
- return new _LedgerSigner(connection, transport, network);
989
- }
990
- /**
991
- * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation.
992
- * @returns {Promise<LedgerSigner>} A freshly initialized signer for the default (`'TEST'`) network.
993
- */
994
- async reinit() {
995
- return this.transportService.enqueue(async () => {
996
- await this.transport.close();
997
- return _LedgerSigner.init();
998
- });
999
- }
1000
- /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */
1001
- set addressType(addressType) {
1002
- this._addressType = addressType;
1003
- }
1004
- get addressType() {
1005
- return this._addressType;
1006
- }
1007
- getPathPurpose() {
1008
- return supportedAddressTypes[this._addressType].path;
1009
- }
1010
- getPathCoin() {
1011
- return networks[this.network].coin;
1012
- }
1013
- getAddressFormat() {
1014
- return supportedAddressTypes[this._addressType].format;
1015
- }
1016
- getXpubVersion() {
1017
- return networks[this.network].xpubVersion;
1018
- }
1019
- isSegwit() {
1020
- return this._addressType === "SEGWIT" || this._addressType === "NATIVE SEGWIT";
1021
- }
1022
- async getAddresses(bundleSize, change = false) {
1023
- return this.transportService.enqueue(async () => {
1024
- const addresses = [];
1025
- const basePath = `m/${this.getPathPurpose()}'/${this.getPathCoin()}'/0'/${change ? "1" : "0"}`;
1026
- const xpub = await this.connection.getWalletXpub({ path: basePath, xpubVersion: this.getXpubVersion() });
1027
- for (let i = 0; i < bundleSize; i++) {
1028
- const path = `${basePath}/${i}`;
1029
- const address2 = deriveAddress(xpub, i, this.addressType, this.network);
1030
- if (address2) {
1031
- addresses.push(address2);
1032
- this.addresses.set(address2, path);
1033
- }
1034
- }
1035
- return addresses;
1036
- });
1037
- }
1038
- /**
1039
- * @param {number} bundleSize - Number of change addresses to derive.
1040
- * @returns {Promise<string[]>} `bundleSize` change addresses derived from the Ledger device.
1041
- */
1042
- async getChangeAddresses(bundleSize) {
1043
- return this.getAddresses(bundleSize, true);
1044
- }
1045
- /**
1046
- * @param {number} bundleSize - Number of receive addresses to derive.
1047
- * @returns {Promise<string[]>} `bundleSize` receive (non-change) addresses derived from the Ledger device.
1048
- */
1049
- async getNonChangeAddresses(bundleSize) {
1050
- return this.getAddresses(bundleSize);
1051
- }
1052
- getInputs(inputs, transactions) {
1053
- return inputs.map((input, index) => {
1054
- const txHex = transactions[index];
1055
- const tx = Transaction2.fromHex(txHex);
1056
- const deserializedTx = this.connection.splitTransaction(txHex, tx.hasWitnesses());
1057
- return [deserializedTx, input.vout, void 0, void 0];
1058
- });
1059
- }
1060
- isChangePath(path) {
1061
- const segments = path.split("/");
1062
- return segments.length === 6 && segments[4] === "1";
1063
- }
1064
- getChangePath(psbt) {
1065
- if (psbt.txOutputs.length < 2) {
1066
- return void 0;
1067
- }
1068
- const lastOutput = psbt.txOutputs[psbt.txOutputs.length - 1];
1069
- if (!lastOutput.address) {
1070
- return void 0;
1071
- }
1072
- const path = this.addresses.get(lastOutput.address);
1073
- return path && this.isChangePath(path) ? path : void 0;
1074
- }
1075
- getOutputScriptHex(psbt) {
1076
- const outputs = psbt.txOutputs.map((output) => {
1077
- const amount = Buffer.alloc(8);
1078
- amount.writeBigUInt64LE(BigInt(output.value));
1079
- return {
1080
- script: output.script,
1081
- amount
1082
- };
1083
- });
1084
- return this.connection.serializeTransactionOutputs({ outputs }).toString("hex");
1085
- }
1086
- /**
1087
- * Signs the given PSBT on the Ledger device, queued behind any in-flight operation.
1088
- * @param {Psbt} psbt - The PSBT to sign.
1089
- * @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.
1090
- * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input.
1091
- * @returns {Promise<string>} The signed, serialized transaction.
1092
- */
1093
- async signTransaction(psbt, inputs, transactions) {
1094
- assertTruthy3(inputs, "LedgerSigner.signTransaction requires inputs to look up each UTXO's derived address path");
1095
- assertTruthy3(transactions, "LedgerSigner.signTransaction requires the raw hex transactions for each input");
1096
- return this.transportService.enqueue(async () => {
1097
- const ledgerInputs = this.getInputs(inputs, transactions);
1098
- const paths = inputs.map((input) => this.addresses.get(input.address)).filter((item) => !!item);
1099
- const outputScriptHex = this.getOutputScriptHex(psbt);
1100
- const changePath = this.getChangePath(psbt);
1101
- return this.connection.createPaymentTransaction({
1102
- inputs: ledgerInputs,
1103
- associatedKeysets: paths,
1104
- outputScriptHex,
1105
- // hw-app-btc throws if changePath matches no output, so omit it
1106
- // when the transaction has no device-derived change output
1107
- ...changePath ? { changePath } : {},
1108
- segwit: this.isSegwit(),
1109
- useTrustedInputForSegwit: this.isSegwit(),
1110
- additionals: this.getAddressFormat() === "bech32" ? ["bech32"] : []
1111
- });
1112
- });
1113
- }
1114
- };
1115
1158
  export {
1116
1159
  APIError,
1117
1160
  AmountBelowMinError,
1118
1161
  FederationAddressError,
1119
1162
  InvalidAddressError,
1120
1163
  InvalidFeeRateError,
1121
- LedgerSigner,
1164
+ Network,
1122
1165
  NotEnoughFundsError,
1123
1166
  PeginStatuses,
1167
+ PegoutRejectedError,
1124
1168
  PegoutStatuses,
1125
1169
  PowPegSDK,
1126
1170
  RejectedPegoutReasons,
1127
- TrezorSigner,
1128
- TxType
1171
+ SigningError,
1172
+ TransactionRevertedError,
1173
+ TxType,
1174
+ UnsupportedAddressTypeError,
1175
+ UnsupportedSenderError,
1176
+ WrongNetworkError
1129
1177
  };