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