@bitgo-beta/babylonlabs-io-btc-staking-ts 0.0.0-semantic-release-managed

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.cjs ADDED
@@ -0,0 +1,2777 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key2 of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
16
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ BabylonBtcStakingManager: () => BabylonBtcStakingManager,
34
+ BitcoinScriptType: () => BitcoinScriptType,
35
+ ObservableStaking: () => ObservableStaking,
36
+ ObservableStakingScriptData: () => ObservableStakingScriptData,
37
+ Staking: () => Staking,
38
+ StakingScriptData: () => StakingScriptData,
39
+ buildStakingTransactionOutputs: () => buildStakingTransactionOutputs,
40
+ createCovenantWitness: () => createCovenantWitness,
41
+ deriveSlashingOutput: () => deriveSlashingOutput,
42
+ deriveStakingOutputInfo: () => deriveStakingOutputInfo,
43
+ deriveUnbondingOutputInfo: () => deriveUnbondingOutputInfo,
44
+ findInputUTXO: () => findInputUTXO,
45
+ findMatchingTxOutputIndex: () => findMatchingTxOutputIndex,
46
+ getBabylonParamByBtcHeight: () => getBabylonParamByBtcHeight,
47
+ getBabylonParamByVersion: () => getBabylonParamByVersion,
48
+ getPsbtInputFields: () => getPsbtInputFields,
49
+ getPublicKeyNoCoord: () => getPublicKeyNoCoord,
50
+ getScriptType: () => getScriptType,
51
+ getUnbondingTxStakerSignature: () => getUnbondingTxStakerSignature,
52
+ hasSlashing: () => hasSlashing,
53
+ initBTCCurve: () => initBTCCurve,
54
+ isNativeSegwit: () => isNativeSegwit,
55
+ isTaproot: () => isTaproot,
56
+ isValidBabylonAddress: () => isValidBabylonAddress,
57
+ isValidBitcoinAddress: () => isValidBitcoinAddress,
58
+ isValidNoCoordPublicKey: () => isValidNoCoordPublicKey,
59
+ slashEarlyUnbondedTransaction: () => slashEarlyUnbondedTransaction,
60
+ slashTimelockUnbondedTransaction: () => slashTimelockUnbondedTransaction,
61
+ stakingTransaction: () => stakingTransaction,
62
+ toBuffers: () => toBuffers,
63
+ transactionIdToHash: () => transactionIdToHash,
64
+ unbondingTransaction: () => unbondingTransaction,
65
+ validateParams: () => validateParams,
66
+ validateStakingTimelock: () => validateStakingTimelock,
67
+ validateStakingTxInputData: () => validateStakingTxInputData,
68
+ withdrawEarlyUnbondedTransaction: () => withdrawEarlyUnbondedTransaction,
69
+ withdrawSlashingTransaction: () => withdrawSlashingTransaction,
70
+ withdrawTimelockUnbondedTransaction: () => withdrawTimelockUnbondedTransaction
71
+ });
72
+ module.exports = __toCommonJS(src_exports);
73
+
74
+ // src/error/index.ts
75
+ var StakingError = class _StakingError extends Error {
76
+ constructor(code, message) {
77
+ super(message);
78
+ this.code = code;
79
+ }
80
+ // Static method to safely handle unknown errors
81
+ static fromUnknown(error, code, fallbackMsg) {
82
+ if (error instanceof _StakingError) {
83
+ return error;
84
+ }
85
+ if (error instanceof Error) {
86
+ return new _StakingError(code, error.message);
87
+ }
88
+ return new _StakingError(code, fallbackMsg);
89
+ }
90
+ };
91
+
92
+ // src/utils/btc.ts
93
+ var ecc = __toESM(require("@bitcoin-js/tiny-secp256k1-asmjs"), 1);
94
+ var import_bitcoinjs_lib = require("bitcoinjs-lib");
95
+
96
+ // src/constants/keys.ts
97
+ var NO_COORD_PK_BYTE_LENGTH = 32;
98
+
99
+ // src/utils/btc.ts
100
+ var initBTCCurve = () => {
101
+ (0, import_bitcoinjs_lib.initEccLib)(ecc);
102
+ };
103
+ var isValidBitcoinAddress = (btcAddress, network) => {
104
+ try {
105
+ return !!import_bitcoinjs_lib.address.toOutputScript(btcAddress, network);
106
+ } catch (error) {
107
+ return false;
108
+ }
109
+ };
110
+ var isTaproot = (taprootAddress, network) => {
111
+ try {
112
+ const decoded = import_bitcoinjs_lib.address.fromBech32(taprootAddress);
113
+ if (decoded.version !== 1) {
114
+ return false;
115
+ }
116
+ if (network.bech32 === import_bitcoinjs_lib.networks.bitcoin.bech32) {
117
+ return taprootAddress.startsWith("bc1p");
118
+ } else if (network.bech32 === import_bitcoinjs_lib.networks.testnet.bech32) {
119
+ return taprootAddress.startsWith("tb1p") || taprootAddress.startsWith("sb1p");
120
+ }
121
+ return false;
122
+ } catch (error) {
123
+ return false;
124
+ }
125
+ };
126
+ var isNativeSegwit = (segwitAddress, network) => {
127
+ try {
128
+ const decoded = import_bitcoinjs_lib.address.fromBech32(segwitAddress);
129
+ if (decoded.version !== 0) {
130
+ return false;
131
+ }
132
+ if (network.bech32 === import_bitcoinjs_lib.networks.bitcoin.bech32) {
133
+ return segwitAddress.startsWith("bc1q");
134
+ } else if (network.bech32 === import_bitcoinjs_lib.networks.testnet.bech32) {
135
+ return segwitAddress.startsWith("tb1q");
136
+ }
137
+ return false;
138
+ } catch (error) {
139
+ return false;
140
+ }
141
+ };
142
+ var isValidNoCoordPublicKey = (pkWithNoCoord) => {
143
+ try {
144
+ const keyBuffer = Buffer.from(pkWithNoCoord, "hex");
145
+ return validateNoCoordPublicKeyBuffer(keyBuffer);
146
+ } catch (error) {
147
+ return false;
148
+ }
149
+ };
150
+ var getPublicKeyNoCoord = (pkHex) => {
151
+ const publicKey = Buffer.from(pkHex, "hex");
152
+ const publicKeyNoCoordBuffer = publicKey.length === NO_COORD_PK_BYTE_LENGTH ? publicKey : publicKey.subarray(1, 33);
153
+ if (!validateNoCoordPublicKeyBuffer(publicKeyNoCoordBuffer)) {
154
+ throw new Error("Invalid public key without coordinate");
155
+ }
156
+ return publicKeyNoCoordBuffer.toString("hex");
157
+ };
158
+ var validateNoCoordPublicKeyBuffer = (pkBuffer) => {
159
+ if (pkBuffer.length !== NO_COORD_PK_BYTE_LENGTH) {
160
+ return false;
161
+ }
162
+ const compressedKeyEven = Buffer.concat([Buffer.from([2]), pkBuffer]);
163
+ const compressedKeyOdd = Buffer.concat([Buffer.from([3]), pkBuffer]);
164
+ return ecc.isPoint(compressedKeyEven) || ecc.isPoint(compressedKeyOdd);
165
+ };
166
+ var transactionIdToHash = (txId) => {
167
+ if (txId === "") {
168
+ throw new Error("Transaction id cannot be empty");
169
+ }
170
+ return Buffer.from(txId, "hex").reverse();
171
+ };
172
+
173
+ // src/utils/staking/index.ts
174
+ var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
175
+
176
+ // src/constants/internalPubkey.ts
177
+ var key = "0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0";
178
+ var internalPubkey = Buffer.from(key, "hex").subarray(1, 33);
179
+
180
+ // src/constants/unbonding.ts
181
+ var MIN_UNBONDING_OUTPUT_VALUE = 1e3;
182
+
183
+ // src/utils/staking/index.ts
184
+ var buildStakingTransactionOutputs = (scripts, network, amount) => {
185
+ const stakingOutputInfo = deriveStakingOutputInfo(scripts, network);
186
+ const transactionOutputs = [
187
+ {
188
+ scriptPubKey: stakingOutputInfo.scriptPubKey,
189
+ value: amount
190
+ }
191
+ ];
192
+ if (scripts.dataEmbedScript) {
193
+ transactionOutputs.push({
194
+ scriptPubKey: scripts.dataEmbedScript,
195
+ value: 0
196
+ });
197
+ }
198
+ return transactionOutputs;
199
+ };
200
+ var deriveStakingOutputInfo = (scripts, network) => {
201
+ const scriptTree = [
202
+ {
203
+ output: scripts.slashingScript
204
+ },
205
+ [{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
206
+ ];
207
+ const stakingOutput = import_bitcoinjs_lib2.payments.p2tr({
208
+ internalPubkey,
209
+ scriptTree,
210
+ network
211
+ });
212
+ if (!stakingOutput.address) {
213
+ throw new StakingError(
214
+ "INVALID_OUTPUT" /* INVALID_OUTPUT */,
215
+ "Failed to build staking output"
216
+ );
217
+ }
218
+ return {
219
+ outputAddress: stakingOutput.address,
220
+ scriptPubKey: import_bitcoinjs_lib2.address.toOutputScript(stakingOutput.address, network)
221
+ };
222
+ };
223
+ var deriveUnbondingOutputInfo = (scripts, network) => {
224
+ const outputScriptTree = [
225
+ {
226
+ output: scripts.slashingScript
227
+ },
228
+ { output: scripts.unbondingTimelockScript }
229
+ ];
230
+ const unbondingOutput = import_bitcoinjs_lib2.payments.p2tr({
231
+ internalPubkey,
232
+ scriptTree: outputScriptTree,
233
+ network
234
+ });
235
+ if (!unbondingOutput.address) {
236
+ throw new StakingError(
237
+ "INVALID_OUTPUT" /* INVALID_OUTPUT */,
238
+ "Failed to build unbonding output"
239
+ );
240
+ }
241
+ return {
242
+ outputAddress: unbondingOutput.address,
243
+ scriptPubKey: import_bitcoinjs_lib2.address.toOutputScript(unbondingOutput.address, network)
244
+ };
245
+ };
246
+ var deriveSlashingOutput = (scripts, network) => {
247
+ const slashingOutput = import_bitcoinjs_lib2.payments.p2tr({
248
+ internalPubkey,
249
+ scriptTree: { output: scripts.unbondingTimelockScript },
250
+ network
251
+ });
252
+ const slashingOutputAddress = slashingOutput.address;
253
+ if (!slashingOutputAddress) {
254
+ throw new StakingError(
255
+ "INVALID_OUTPUT" /* INVALID_OUTPUT */,
256
+ "Failed to build slashing output address"
257
+ );
258
+ }
259
+ return {
260
+ outputAddress: slashingOutputAddress,
261
+ scriptPubKey: import_bitcoinjs_lib2.address.toOutputScript(slashingOutputAddress, network)
262
+ };
263
+ };
264
+ var findMatchingTxOutputIndex = (tx, outputAddress, network) => {
265
+ const index = tx.outs.findIndex((output) => {
266
+ try {
267
+ return import_bitcoinjs_lib2.address.fromOutputScript(output.script, network) === outputAddress;
268
+ } catch (error) {
269
+ return false;
270
+ }
271
+ });
272
+ if (index === -1) {
273
+ throw new StakingError(
274
+ "INVALID_OUTPUT" /* INVALID_OUTPUT */,
275
+ `Matching output not found for address: ${outputAddress}`
276
+ );
277
+ }
278
+ return index;
279
+ };
280
+ var validateStakingTxInputData = (stakingAmountSat, timelock, params, inputUTXOs, feeRate) => {
281
+ if (stakingAmountSat < params.minStakingAmountSat || stakingAmountSat > params.maxStakingAmountSat) {
282
+ throw new StakingError(
283
+ "INVALID_INPUT" /* INVALID_INPUT */,
284
+ "Invalid staking amount"
285
+ );
286
+ }
287
+ if (timelock < params.minStakingTimeBlocks || timelock > params.maxStakingTimeBlocks) {
288
+ throw new StakingError("INVALID_INPUT" /* INVALID_INPUT */, "Invalid timelock");
289
+ }
290
+ if (inputUTXOs.length == 0) {
291
+ throw new StakingError(
292
+ "INVALID_INPUT" /* INVALID_INPUT */,
293
+ "No input UTXOs provided"
294
+ );
295
+ }
296
+ if (feeRate <= 0) {
297
+ throw new StakingError("INVALID_INPUT" /* INVALID_INPUT */, "Invalid fee rate");
298
+ }
299
+ };
300
+ var validateParams = (params) => {
301
+ if (params.covenantNoCoordPks.length == 0) {
302
+ throw new StakingError(
303
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
304
+ "Could not find any covenant public keys"
305
+ );
306
+ }
307
+ if (params.covenantNoCoordPks.length < params.covenantQuorum) {
308
+ throw new StakingError(
309
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
310
+ "Covenant public keys must be greater than or equal to the quorum"
311
+ );
312
+ }
313
+ params.covenantNoCoordPks.forEach((pk) => {
314
+ if (!isValidNoCoordPublicKey(pk)) {
315
+ throw new StakingError(
316
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
317
+ "Covenant public key should contains no coordinate"
318
+ );
319
+ }
320
+ });
321
+ if (params.unbondingTime <= 0) {
322
+ throw new StakingError(
323
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
324
+ "Unbonding time must be greater than 0"
325
+ );
326
+ }
327
+ if (params.unbondingFeeSat <= 0) {
328
+ throw new StakingError(
329
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
330
+ "Unbonding fee must be greater than 0"
331
+ );
332
+ }
333
+ if (params.maxStakingAmountSat < params.minStakingAmountSat) {
334
+ throw new StakingError(
335
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
336
+ "Max staking amount must be greater or equal to min staking amount"
337
+ );
338
+ }
339
+ if (params.minStakingAmountSat < params.unbondingFeeSat + MIN_UNBONDING_OUTPUT_VALUE) {
340
+ throw new StakingError(
341
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
342
+ `Min staking amount must be greater than unbonding fee plus ${MIN_UNBONDING_OUTPUT_VALUE}`
343
+ );
344
+ }
345
+ if (params.maxStakingTimeBlocks < params.minStakingTimeBlocks) {
346
+ throw new StakingError(
347
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
348
+ "Max staking time must be greater or equal to min staking time"
349
+ );
350
+ }
351
+ if (params.minStakingTimeBlocks <= 0) {
352
+ throw new StakingError(
353
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
354
+ "Min staking time must be greater than 0"
355
+ );
356
+ }
357
+ if (params.covenantQuorum <= 0) {
358
+ throw new StakingError(
359
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
360
+ "Covenant quorum must be greater than 0"
361
+ );
362
+ }
363
+ if (params.slashing) {
364
+ if (params.slashing.slashingRate <= 0) {
365
+ throw new StakingError(
366
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
367
+ "Slashing rate must be greater than 0"
368
+ );
369
+ }
370
+ if (params.slashing.slashingRate > 1) {
371
+ throw new StakingError(
372
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
373
+ "Slashing rate must be less or equal to 1"
374
+ );
375
+ }
376
+ if (params.slashing.slashingPkScriptHex.length == 0) {
377
+ throw new StakingError(
378
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
379
+ "Slashing public key script is missing"
380
+ );
381
+ }
382
+ if (params.slashing.minSlashingTxFeeSat <= 0) {
383
+ throw new StakingError(
384
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
385
+ "Minimum slashing transaction fee must be greater than 0"
386
+ );
387
+ }
388
+ }
389
+ };
390
+ var validateStakingTimelock = (stakingTimelock, params) => {
391
+ if (stakingTimelock < params.minStakingTimeBlocks || stakingTimelock > params.maxStakingTimeBlocks) {
392
+ throw new StakingError(
393
+ "INVALID_INPUT" /* INVALID_INPUT */,
394
+ "Staking transaction timelock is out of range"
395
+ );
396
+ }
397
+ };
398
+ var toBuffers = (inputs) => {
399
+ try {
400
+ return inputs.map((i) => Buffer.from(i, "hex"));
401
+ } catch (error) {
402
+ throw StakingError.fromUnknown(
403
+ error,
404
+ "INVALID_INPUT" /* INVALID_INPUT */,
405
+ "Cannot convert values to buffers"
406
+ );
407
+ }
408
+ };
409
+
410
+ // src/staking/psbt.ts
411
+ var import_bitcoinjs_lib4 = require("bitcoinjs-lib");
412
+
413
+ // src/constants/transaction.ts
414
+ var REDEEM_VERSION = 192;
415
+
416
+ // src/utils/utxo/findInputUTXO.ts
417
+ var findInputUTXO = (inputUTXOs, input) => {
418
+ const inputUTXO = inputUTXOs.find(
419
+ (u) => transactionIdToHash(u.txid).toString("hex") === input.hash.toString("hex") && u.vout === input.index
420
+ );
421
+ if (!inputUTXO) {
422
+ throw new Error(
423
+ `Input UTXO not found for txid: ${Buffer.from(input.hash).reverse().toString("hex")} and vout: ${input.index}`
424
+ );
425
+ }
426
+ return inputUTXO;
427
+ };
428
+
429
+ // src/utils/utxo/getScriptType.ts
430
+ var import_bitcoinjs_lib3 = require("bitcoinjs-lib");
431
+ var BitcoinScriptType = /* @__PURE__ */ ((BitcoinScriptType2) => {
432
+ BitcoinScriptType2["P2PKH"] = "pubkeyhash";
433
+ BitcoinScriptType2["P2SH"] = "scripthash";
434
+ BitcoinScriptType2["P2WPKH"] = "witnesspubkeyhash";
435
+ BitcoinScriptType2["P2WSH"] = "witnessscripthash";
436
+ BitcoinScriptType2["P2TR"] = "taproot";
437
+ return BitcoinScriptType2;
438
+ })(BitcoinScriptType || {});
439
+ var getScriptType = (script4) => {
440
+ try {
441
+ import_bitcoinjs_lib3.payments.p2pkh({ output: script4 });
442
+ return "pubkeyhash" /* P2PKH */;
443
+ } catch {
444
+ }
445
+ try {
446
+ import_bitcoinjs_lib3.payments.p2sh({ output: script4 });
447
+ return "scripthash" /* P2SH */;
448
+ } catch {
449
+ }
450
+ try {
451
+ import_bitcoinjs_lib3.payments.p2wpkh({ output: script4 });
452
+ return "witnesspubkeyhash" /* P2WPKH */;
453
+ } catch {
454
+ }
455
+ try {
456
+ import_bitcoinjs_lib3.payments.p2wsh({ output: script4 });
457
+ return "witnessscripthash" /* P2WSH */;
458
+ } catch {
459
+ }
460
+ try {
461
+ import_bitcoinjs_lib3.payments.p2tr({ output: script4 });
462
+ return "taproot" /* P2TR */;
463
+ } catch {
464
+ }
465
+ throw new Error("Unknown script type");
466
+ };
467
+
468
+ // src/utils/utxo/getPsbtInputFields.ts
469
+ var getPsbtInputFields = (utxo, publicKeyNoCoord) => {
470
+ const scriptPubKey = Buffer.from(utxo.scriptPubKey, "hex");
471
+ const type = getScriptType(scriptPubKey);
472
+ switch (type) {
473
+ case "pubkeyhash" /* P2PKH */: {
474
+ if (!utxo.rawTxHex) {
475
+ throw new Error("Missing rawTxHex for legacy P2PKH input");
476
+ }
477
+ return { nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex") };
478
+ }
479
+ case "scripthash" /* P2SH */: {
480
+ if (!utxo.rawTxHex) {
481
+ throw new Error("Missing rawTxHex for P2SH input");
482
+ }
483
+ if (!utxo.redeemScript) {
484
+ throw new Error("Missing redeemScript for P2SH input");
485
+ }
486
+ return {
487
+ nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
488
+ redeemScript: Buffer.from(utxo.redeemScript, "hex")
489
+ };
490
+ }
491
+ case "witnesspubkeyhash" /* P2WPKH */: {
492
+ return {
493
+ witnessUtxo: {
494
+ script: scriptPubKey,
495
+ value: utxo.value
496
+ }
497
+ };
498
+ }
499
+ case "witnessscripthash" /* P2WSH */: {
500
+ if (!utxo.witnessScript) {
501
+ throw new Error("Missing witnessScript for P2WSH input");
502
+ }
503
+ return {
504
+ witnessUtxo: {
505
+ script: scriptPubKey,
506
+ value: utxo.value
507
+ },
508
+ witnessScript: Buffer.from(utxo.witnessScript, "hex")
509
+ };
510
+ }
511
+ case "taproot" /* P2TR */: {
512
+ return {
513
+ witnessUtxo: {
514
+ script: scriptPubKey,
515
+ value: utxo.value
516
+ },
517
+ // this is needed only if the wallet is in taproot mode
518
+ ...publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }
519
+ };
520
+ }
521
+ default:
522
+ throw new Error(`Unsupported script type: ${type}`);
523
+ }
524
+ };
525
+
526
+ // src/staking/psbt.ts
527
+ var stakingPsbt = (stakingTx, network, inputUTXOs, publicKeyNoCoord) => {
528
+ if (publicKeyNoCoord && publicKeyNoCoord.length !== NO_COORD_PK_BYTE_LENGTH) {
529
+ throw new Error("Invalid public key");
530
+ }
531
+ const psbt = new import_bitcoinjs_lib4.Psbt({ network });
532
+ if (stakingTx.version !== void 0)
533
+ psbt.setVersion(stakingTx.version);
534
+ if (stakingTx.locktime !== void 0)
535
+ psbt.setLocktime(stakingTx.locktime);
536
+ stakingTx.ins.forEach((input) => {
537
+ const inputUTXO = findInputUTXO(inputUTXOs, input);
538
+ const psbtInputData = getPsbtInputFields(inputUTXO, publicKeyNoCoord);
539
+ psbt.addInput({
540
+ hash: input.hash,
541
+ index: input.index,
542
+ sequence: input.sequence,
543
+ ...psbtInputData
544
+ });
545
+ });
546
+ stakingTx.outs.forEach((o) => {
547
+ psbt.addOutput({ script: o.script, value: o.value });
548
+ });
549
+ return psbt;
550
+ };
551
+ var unbondingPsbt = (scripts, unbondingTx, stakingTx, network) => {
552
+ if (unbondingTx.outs.length !== 1) {
553
+ throw new Error("Unbonding transaction must have exactly one output");
554
+ }
555
+ if (unbondingTx.ins.length !== 1) {
556
+ throw new Error("Unbonding transaction must have exactly one input");
557
+ }
558
+ validateUnbondingOutput(scripts, unbondingTx, network);
559
+ const psbt = new import_bitcoinjs_lib4.Psbt({ network });
560
+ if (unbondingTx.version !== void 0) {
561
+ psbt.setVersion(unbondingTx.version);
562
+ }
563
+ if (unbondingTx.locktime !== void 0) {
564
+ psbt.setLocktime(unbondingTx.locktime);
565
+ }
566
+ const input = unbondingTx.ins[0];
567
+ const outputIndex = input.index;
568
+ const inputScriptTree = [
569
+ { output: scripts.slashingScript },
570
+ [{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
571
+ ];
572
+ const inputRedeem = {
573
+ output: scripts.unbondingScript,
574
+ redeemVersion: REDEEM_VERSION
575
+ };
576
+ const p2tr = import_bitcoinjs_lib4.payments.p2tr({
577
+ internalPubkey,
578
+ scriptTree: inputScriptTree,
579
+ redeem: inputRedeem,
580
+ network
581
+ });
582
+ const inputTapLeafScript = {
583
+ leafVersion: inputRedeem.redeemVersion,
584
+ script: inputRedeem.output,
585
+ controlBlock: p2tr.witness[p2tr.witness.length - 1]
586
+ };
587
+ psbt.addInput({
588
+ hash: input.hash,
589
+ index: input.index,
590
+ sequence: input.sequence,
591
+ tapInternalKey: internalPubkey,
592
+ witnessUtxo: {
593
+ value: stakingTx.outs[outputIndex].value,
594
+ script: stakingTx.outs[outputIndex].script
595
+ },
596
+ tapLeafScript: [inputTapLeafScript]
597
+ });
598
+ psbt.addOutput({
599
+ script: unbondingTx.outs[0].script,
600
+ value: unbondingTx.outs[0].value
601
+ });
602
+ return psbt;
603
+ };
604
+ var validateUnbondingOutput = (scripts, unbondingTx, network) => {
605
+ const unbondingOutputInfo = deriveUnbondingOutputInfo(scripts, network);
606
+ if (unbondingOutputInfo.scriptPubKey.toString("hex") !== unbondingTx.outs[0].script.toString("hex")) {
607
+ throw new Error(
608
+ "Unbonding output script does not match the expected script while building psbt"
609
+ );
610
+ }
611
+ };
612
+
613
+ // src/staking/stakingScript.ts
614
+ var import_bitcoinjs_lib5 = require("bitcoinjs-lib");
615
+ var MAGIC_BYTES_LEN = 4;
616
+ var StakingScriptData = class {
617
+ constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock) {
618
+ if (!stakerKey || !finalityProviderKeys || !covenantKeys || !covenantThreshold || !stakingTimelock || !unbondingTimelock) {
619
+ throw new Error("Missing required input values");
620
+ }
621
+ this.stakerKey = stakerKey;
622
+ this.finalityProviderKeys = finalityProviderKeys;
623
+ this.covenantKeys = covenantKeys;
624
+ this.covenantThreshold = covenantThreshold;
625
+ this.stakingTimeLock = stakingTimelock;
626
+ this.unbondingTimeLock = unbondingTimelock;
627
+ if (!this.validate()) {
628
+ throw new Error("Invalid script data provided");
629
+ }
630
+ }
631
+ /**
632
+ * Validates the staking script.
633
+ * @returns {boolean} Returns true if the staking script is valid, otherwise false.
634
+ */
635
+ validate() {
636
+ if (this.stakerKey.length != NO_COORD_PK_BYTE_LENGTH) {
637
+ return false;
638
+ }
639
+ if (this.finalityProviderKeys.some(
640
+ (finalityProviderKey) => finalityProviderKey.length != NO_COORD_PK_BYTE_LENGTH
641
+ )) {
642
+ return false;
643
+ }
644
+ if (this.covenantKeys.some((covenantKey) => covenantKey.length != NO_COORD_PK_BYTE_LENGTH)) {
645
+ return false;
646
+ }
647
+ const allPks = [
648
+ this.stakerKey,
649
+ ...this.finalityProviderKeys,
650
+ ...this.covenantKeys
651
+ ];
652
+ const allPksSet = new Set(allPks);
653
+ if (allPks.length !== allPksSet.size) {
654
+ return false;
655
+ }
656
+ if (this.covenantThreshold <= 0 || this.covenantThreshold > this.covenantKeys.length) {
657
+ return false;
658
+ }
659
+ if (this.stakingTimeLock <= 0 || this.stakingTimeLock > 65535) {
660
+ return false;
661
+ }
662
+ if (this.unbondingTimeLock <= 0 || this.unbondingTimeLock > 65535) {
663
+ return false;
664
+ }
665
+ return true;
666
+ }
667
+ // The staking script allows for multiple finality provider public keys
668
+ // to support (re)stake to multiple finality providers
669
+ // Covenant members are going to have multiple keys
670
+ /**
671
+ * Builds a timelock script.
672
+ * @param timelock - The timelock value to encode in the script.
673
+ * @returns {Buffer} containing the compiled timelock script.
674
+ */
675
+ buildTimelockScript(timelock) {
676
+ return import_bitcoinjs_lib5.script.compile([
677
+ this.stakerKey,
678
+ import_bitcoinjs_lib5.opcodes.OP_CHECKSIGVERIFY,
679
+ import_bitcoinjs_lib5.script.number.encode(timelock),
680
+ import_bitcoinjs_lib5.opcodes.OP_CHECKSEQUENCEVERIFY
681
+ ]);
682
+ }
683
+ /**
684
+ * Builds the staking timelock script.
685
+ * Only holder of private key for given pubKey can spend after relative lock time
686
+ * Creates the timelock script in the form:
687
+ * <stakerPubKey>
688
+ * OP_CHECKSIGVERIFY
689
+ * <stakingTimeBlocks>
690
+ * OP_CHECKSEQUENCEVERIFY
691
+ * @returns {Buffer} The staking timelock script.
692
+ */
693
+ buildStakingTimelockScript() {
694
+ return this.buildTimelockScript(this.stakingTimeLock);
695
+ }
696
+ /**
697
+ * Builds the unbonding timelock script.
698
+ * Creates the unbonding timelock script in the form:
699
+ * <stakerPubKey>
700
+ * OP_CHECKSIGVERIFY
701
+ * <unbondingTimeBlocks>
702
+ * OP_CHECKSEQUENCEVERIFY
703
+ * @returns {Buffer} The unbonding timelock script.
704
+ */
705
+ buildUnbondingTimelockScript() {
706
+ return this.buildTimelockScript(this.unbondingTimeLock);
707
+ }
708
+ /**
709
+ * Builds the unbonding script in the form:
710
+ * buildSingleKeyScript(stakerPk, true) ||
711
+ * buildMultiKeyScript(covenantPks, covenantThreshold, false)
712
+ * || means combining the scripts
713
+ * @returns {Buffer} The unbonding script.
714
+ */
715
+ buildUnbondingScript() {
716
+ return Buffer.concat([
717
+ this.buildSingleKeyScript(this.stakerKey, true),
718
+ this.buildMultiKeyScript(
719
+ this.covenantKeys,
720
+ this.covenantThreshold,
721
+ false
722
+ )
723
+ ]);
724
+ }
725
+ /**
726
+ * Builds the slashing script for staking in the form:
727
+ * buildSingleKeyScript(stakerPk, true) ||
728
+ * buildMultiKeyScript(finalityProviderPKs, 1, true) ||
729
+ * buildMultiKeyScript(covenantPks, covenantThreshold, false)
730
+ * || means combining the scripts
731
+ * The slashing script is a combination of single-key and multi-key scripts.
732
+ * The single-key script is used for staker key verification.
733
+ * The multi-key script is used for finality provider key verification and covenant key verification.
734
+ * @returns {Buffer} The slashing script as a Buffer.
735
+ */
736
+ buildSlashingScript() {
737
+ return Buffer.concat([
738
+ this.buildSingleKeyScript(this.stakerKey, true),
739
+ this.buildMultiKeyScript(
740
+ this.finalityProviderKeys,
741
+ // The threshold is always 1 as we only need one
742
+ // finalityProvider signature to perform slashing
743
+ // (only one finalityProvider performs an offence)
744
+ 1,
745
+ // OP_VERIFY/OP_CHECKSIGVERIFY is added at the end
746
+ true
747
+ ),
748
+ this.buildMultiKeyScript(
749
+ this.covenantKeys,
750
+ this.covenantThreshold,
751
+ // No need to add verify since covenants are at the end of the script
752
+ false
753
+ )
754
+ ]);
755
+ }
756
+ /**
757
+ * Builds the staking scripts.
758
+ * @returns {StakingScripts} The staking scripts.
759
+ */
760
+ buildScripts() {
761
+ return {
762
+ timelockScript: this.buildStakingTimelockScript(),
763
+ unbondingScript: this.buildUnbondingScript(),
764
+ slashingScript: this.buildSlashingScript(),
765
+ unbondingTimelockScript: this.buildUnbondingTimelockScript()
766
+ };
767
+ }
768
+ // buildSingleKeyScript and buildMultiKeyScript allow us to reuse functionality
769
+ // for creating Bitcoin scripts for the unbonding script and the slashing script
770
+ /**
771
+ * Builds a single key script in the form:
772
+ * buildSingleKeyScript creates a single key script
773
+ * <pk> OP_CHECKSIGVERIFY (if withVerify is true)
774
+ * <pk> OP_CHECKSIG (if withVerify is false)
775
+ * @param pk - The public key buffer.
776
+ * @param withVerify - A boolean indicating whether to include the OP_CHECKSIGVERIFY opcode.
777
+ * @returns The compiled script buffer.
778
+ */
779
+ buildSingleKeyScript(pk, withVerify) {
780
+ if (pk.length != NO_COORD_PK_BYTE_LENGTH) {
781
+ throw new Error("Invalid key length");
782
+ }
783
+ return import_bitcoinjs_lib5.script.compile([
784
+ pk,
785
+ withVerify ? import_bitcoinjs_lib5.opcodes.OP_CHECKSIGVERIFY : import_bitcoinjs_lib5.opcodes.OP_CHECKSIG
786
+ ]);
787
+ }
788
+ /**
789
+ * Builds a multi-key script in the form:
790
+ * <pk1> OP_CHEKCSIG <pk2> OP_CHECKSIGADD <pk3> OP_CHECKSIGADD ... <pkN> OP_CHECKSIGADD <threshold> OP_NUMEQUAL
791
+ * <withVerify -> OP_NUMEQUALVERIFY>
792
+ * It validates whether provided keys are unique and the threshold is not greater than number of keys
793
+ * If there is only one key provided it will return single key sig script
794
+ * @param pks - An array of public keys.
795
+ * @param threshold - The required number of valid signers.
796
+ * @param withVerify - A boolean indicating whether to include the OP_VERIFY opcode.
797
+ * @returns The compiled multi-key script as a Buffer.
798
+ * @throws {Error} If no keys are provided, if the required number of valid signers is greater than the number of provided keys, or if duplicate keys are provided.
799
+ */
800
+ buildMultiKeyScript(pks, threshold, withVerify) {
801
+ if (!pks || pks.length === 0) {
802
+ throw new Error("No keys provided");
803
+ }
804
+ if (pks.some((pk) => pk.length != NO_COORD_PK_BYTE_LENGTH)) {
805
+ throw new Error("Invalid key length");
806
+ }
807
+ if (threshold > pks.length) {
808
+ throw new Error(
809
+ "Required number of valid signers is greater than number of provided keys"
810
+ );
811
+ }
812
+ if (pks.length === 1) {
813
+ return this.buildSingleKeyScript(pks[0], withVerify);
814
+ }
815
+ const sortedPks = [...pks].sort(Buffer.compare);
816
+ for (let i = 0; i < sortedPks.length - 1; ++i) {
817
+ if (sortedPks[i].equals(sortedPks[i + 1])) {
818
+ throw new Error("Duplicate keys provided");
819
+ }
820
+ }
821
+ const scriptElements = [sortedPks[0], import_bitcoinjs_lib5.opcodes.OP_CHECKSIG];
822
+ for (let i = 1; i < sortedPks.length; i++) {
823
+ scriptElements.push(sortedPks[i]);
824
+ scriptElements.push(import_bitcoinjs_lib5.opcodes.OP_CHECKSIGADD);
825
+ }
826
+ scriptElements.push(import_bitcoinjs_lib5.script.number.encode(threshold));
827
+ if (withVerify) {
828
+ scriptElements.push(import_bitcoinjs_lib5.opcodes.OP_NUMEQUALVERIFY);
829
+ } else {
830
+ scriptElements.push(import_bitcoinjs_lib5.opcodes.OP_NUMEQUAL);
831
+ }
832
+ return import_bitcoinjs_lib5.script.compile(scriptElements);
833
+ }
834
+ };
835
+
836
+ // src/staking/transactions.ts
837
+ var import_bitcoinjs_lib8 = require("bitcoinjs-lib");
838
+
839
+ // src/constants/dustSat.ts
840
+ var BTC_DUST_SAT = 546;
841
+
842
+ // src/utils/fee/index.ts
843
+ var import_bitcoinjs_lib7 = require("bitcoinjs-lib");
844
+
845
+ // src/constants/fee.ts
846
+ var DEFAULT_INPUT_SIZE = 180;
847
+ var P2WPKH_INPUT_SIZE = 68;
848
+ var P2TR_INPUT_SIZE = 58;
849
+ var TX_BUFFER_SIZE_OVERHEAD = 11;
850
+ var LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;
851
+ var MAX_NON_LEGACY_OUTPUT_SIZE = 43;
852
+ var WITHDRAW_TX_BUFFER_SIZE = 17;
853
+ var WALLET_RELAY_FEE_RATE_THRESHOLD = 2;
854
+ var OP_RETURN_OUTPUT_VALUE_SIZE = 8;
855
+ var OP_RETURN_VALUE_SERIALIZE_SIZE = 1;
856
+
857
+ // src/utils/fee/utils.ts
858
+ var import_bitcoinjs_lib6 = require("bitcoinjs-lib");
859
+ var isOP_RETURN = (script4) => {
860
+ const decompiled = import_bitcoinjs_lib6.script.decompile(script4);
861
+ return !!decompiled && decompiled[0] === import_bitcoinjs_lib6.opcodes.OP_RETURN;
862
+ };
863
+ var getInputSizeByScript = (script4) => {
864
+ try {
865
+ const { address: p2wpkhAddress } = import_bitcoinjs_lib6.payments.p2wpkh({
866
+ output: script4
867
+ });
868
+ if (p2wpkhAddress) {
869
+ return P2WPKH_INPUT_SIZE;
870
+ }
871
+ } catch (error) {
872
+ }
873
+ try {
874
+ const { address: p2trAddress } = import_bitcoinjs_lib6.payments.p2tr({
875
+ output: script4
876
+ });
877
+ if (p2trAddress) {
878
+ return P2TR_INPUT_SIZE;
879
+ }
880
+ } catch (error) {
881
+ }
882
+ return DEFAULT_INPUT_SIZE;
883
+ };
884
+ var getEstimatedChangeOutputSize = () => {
885
+ return MAX_NON_LEGACY_OUTPUT_SIZE;
886
+ };
887
+ var inputValueSum = (inputUTXOs) => {
888
+ return inputUTXOs.reduce((acc, utxo) => acc + utxo.value, 0);
889
+ };
890
+
891
+ // src/utils/fee/index.ts
892
+ var getStakingTxInputUTXOsAndFees = (availableUTXOs, stakingAmount, feeRate, outputs) => {
893
+ if (availableUTXOs.length === 0) {
894
+ throw new Error("Insufficient funds");
895
+ }
896
+ const validUTXOs = availableUTXOs.filter((utxo) => {
897
+ const script4 = Buffer.from(utxo.scriptPubKey, "hex");
898
+ return !!import_bitcoinjs_lib7.script.decompile(script4);
899
+ });
900
+ if (validUTXOs.length === 0) {
901
+ throw new Error("Insufficient funds: no valid UTXOs available for staking");
902
+ }
903
+ const sortedUTXOs = validUTXOs.sort((a, b) => b.value - a.value);
904
+ const selectedUTXOs = [];
905
+ let accumulatedValue = 0;
906
+ let estimatedFee = 0;
907
+ for (const utxo of sortedUTXOs) {
908
+ selectedUTXOs.push(utxo);
909
+ accumulatedValue += utxo.value;
910
+ const estimatedSize = getEstimatedSize(selectedUTXOs, outputs);
911
+ estimatedFee = estimatedSize * feeRate + rateBasedTxBufferFee(feeRate);
912
+ if (accumulatedValue - (stakingAmount + estimatedFee) > BTC_DUST_SAT) {
913
+ estimatedFee += getEstimatedChangeOutputSize() * feeRate;
914
+ }
915
+ if (accumulatedValue >= stakingAmount + estimatedFee) {
916
+ break;
917
+ }
918
+ }
919
+ if (accumulatedValue < stakingAmount + estimatedFee) {
920
+ throw new Error(
921
+ "Insufficient funds: unable to gather enough UTXOs to cover the staking amount and fees"
922
+ );
923
+ }
924
+ return {
925
+ selectedUTXOs,
926
+ fee: estimatedFee
927
+ };
928
+ };
929
+ var getWithdrawTxFee = (feeRate) => {
930
+ const inputSize = P2TR_INPUT_SIZE;
931
+ const outputSize = getEstimatedChangeOutputSize();
932
+ return feeRate * (inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD + WITHDRAW_TX_BUFFER_SIZE) + rateBasedTxBufferFee(feeRate);
933
+ };
934
+ var getEstimatedSize = (inputUtxos, outputs) => {
935
+ const inputSize = inputUtxos.reduce((acc, u) => {
936
+ const script4 = Buffer.from(u.scriptPubKey, "hex");
937
+ const decompiledScript = import_bitcoinjs_lib7.script.decompile(script4);
938
+ if (!decompiledScript) {
939
+ return acc;
940
+ }
941
+ return acc + getInputSizeByScript(script4);
942
+ }, 0);
943
+ const outputSize = outputs.reduce((acc, output) => {
944
+ if (isOP_RETURN(output.scriptPubKey)) {
945
+ return acc + output.scriptPubKey.length + OP_RETURN_OUTPUT_VALUE_SIZE + OP_RETURN_VALUE_SERIALIZE_SIZE;
946
+ }
947
+ return acc + MAX_NON_LEGACY_OUTPUT_SIZE;
948
+ }, 0);
949
+ return inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;
950
+ };
951
+ var rateBasedTxBufferFee = (feeRate) => {
952
+ return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER : 0;
953
+ };
954
+
955
+ // src/constants/psbt.ts
956
+ var NON_RBF_SEQUENCE = 4294967295;
957
+ var TRANSACTION_VERSION = 2;
958
+
959
+ // src/staking/transactions.ts
960
+ var BTC_LOCKTIME_HEIGHT_TIME_CUTOFF = 5e8;
961
+ var BTC_SLASHING_FRACTION_DIGITS = 4;
962
+ function stakingTransaction(scripts, amount, changeAddress, inputUTXOs, network, feeRate, lockHeight) {
963
+ if (amount <= 0 || feeRate <= 0) {
964
+ throw new Error("Amount and fee rate must be bigger than 0");
965
+ }
966
+ if (!isValidBitcoinAddress(changeAddress, network)) {
967
+ throw new Error("Invalid change address");
968
+ }
969
+ const stakingOutputs = buildStakingTransactionOutputs(scripts, network, amount);
970
+ const { selectedUTXOs, fee } = getStakingTxInputUTXOsAndFees(
971
+ inputUTXOs,
972
+ amount,
973
+ feeRate,
974
+ stakingOutputs
975
+ );
976
+ const tx = new import_bitcoinjs_lib8.Transaction();
977
+ tx.version = TRANSACTION_VERSION;
978
+ for (let i = 0; i < selectedUTXOs.length; ++i) {
979
+ const input = selectedUTXOs[i];
980
+ tx.addInput(
981
+ transactionIdToHash(input.txid),
982
+ input.vout,
983
+ NON_RBF_SEQUENCE
984
+ );
985
+ }
986
+ stakingOutputs.forEach((o) => {
987
+ tx.addOutput(o.scriptPubKey, o.value);
988
+ });
989
+ const inputsSum = inputValueSum(selectedUTXOs);
990
+ if (inputsSum - (amount + fee) > BTC_DUST_SAT) {
991
+ tx.addOutput(
992
+ import_bitcoinjs_lib8.address.toOutputScript(changeAddress, network),
993
+ inputsSum - (amount + fee)
994
+ );
995
+ }
996
+ if (lockHeight) {
997
+ if (lockHeight >= BTC_LOCKTIME_HEIGHT_TIME_CUTOFF) {
998
+ throw new Error("Invalid lock height");
999
+ }
1000
+ tx.locktime = lockHeight;
1001
+ }
1002
+ return {
1003
+ transaction: tx,
1004
+ fee
1005
+ };
1006
+ }
1007
+ function withdrawEarlyUnbondedTransaction(scripts, unbondingTx, withdrawalAddress, network, feeRate) {
1008
+ const scriptTree = [
1009
+ {
1010
+ output: scripts.slashingScript
1011
+ },
1012
+ { output: scripts.unbondingTimelockScript }
1013
+ ];
1014
+ return withdrawalTransaction(
1015
+ {
1016
+ timelockScript: scripts.unbondingTimelockScript
1017
+ },
1018
+ scriptTree,
1019
+ unbondingTx,
1020
+ withdrawalAddress,
1021
+ network,
1022
+ feeRate,
1023
+ 0
1024
+ // unbonding always has a single output
1025
+ );
1026
+ }
1027
+ function withdrawTimelockUnbondedTransaction(scripts, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
1028
+ const scriptTree = [
1029
+ {
1030
+ output: scripts.slashingScript
1031
+ },
1032
+ [{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
1033
+ ];
1034
+ return withdrawalTransaction(
1035
+ scripts,
1036
+ scriptTree,
1037
+ tx,
1038
+ withdrawalAddress,
1039
+ network,
1040
+ feeRate,
1041
+ outputIndex
1042
+ );
1043
+ }
1044
+ function withdrawSlashingTransaction(scripts, slashingTx, withdrawalAddress, network, feeRate, outputIndex) {
1045
+ const scriptTree = { output: scripts.unbondingTimelockScript };
1046
+ return withdrawalTransaction(
1047
+ {
1048
+ timelockScript: scripts.unbondingTimelockScript
1049
+ },
1050
+ scriptTree,
1051
+ slashingTx,
1052
+ withdrawalAddress,
1053
+ network,
1054
+ feeRate,
1055
+ outputIndex
1056
+ );
1057
+ }
1058
+ function withdrawalTransaction(scripts, scriptTree, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
1059
+ if (feeRate <= 0) {
1060
+ throw new Error("Withdrawal feeRate must be bigger than 0");
1061
+ }
1062
+ if (outputIndex < 0) {
1063
+ throw new Error("Output index must be bigger or equal to 0");
1064
+ }
1065
+ const timePosition = 2;
1066
+ const decompiled = import_bitcoinjs_lib8.script.decompile(scripts.timelockScript);
1067
+ if (!decompiled) {
1068
+ throw new Error("Timelock script is not valid");
1069
+ }
1070
+ let timelock = 0;
1071
+ if (typeof decompiled[timePosition] !== "number") {
1072
+ const timeBuffer = decompiled[timePosition];
1073
+ timelock = import_bitcoinjs_lib8.script.number.decode(timeBuffer);
1074
+ } else {
1075
+ const wrap = decompiled[timePosition] % 16;
1076
+ timelock = wrap === 0 ? 16 : wrap;
1077
+ }
1078
+ const redeem = {
1079
+ output: scripts.timelockScript,
1080
+ redeemVersion: REDEEM_VERSION
1081
+ };
1082
+ const p2tr = import_bitcoinjs_lib8.payments.p2tr({
1083
+ internalPubkey,
1084
+ scriptTree,
1085
+ redeem,
1086
+ network
1087
+ });
1088
+ const tapLeafScript = {
1089
+ leafVersion: redeem.redeemVersion,
1090
+ script: redeem.output,
1091
+ controlBlock: p2tr.witness[p2tr.witness.length - 1]
1092
+ };
1093
+ const psbt = new import_bitcoinjs_lib8.Psbt({ network });
1094
+ psbt.setVersion(TRANSACTION_VERSION);
1095
+ psbt.addInput({
1096
+ hash: tx.getHash(),
1097
+ index: outputIndex,
1098
+ tapInternalKey: internalPubkey,
1099
+ witnessUtxo: {
1100
+ value: tx.outs[outputIndex].value,
1101
+ script: tx.outs[outputIndex].script
1102
+ },
1103
+ tapLeafScript: [tapLeafScript],
1104
+ sequence: timelock
1105
+ });
1106
+ const estimatedFee = getWithdrawTxFee(feeRate);
1107
+ const outputValue = tx.outs[outputIndex].value - estimatedFee;
1108
+ if (outputValue < 0) {
1109
+ throw new Error(
1110
+ "Not enough funds to cover the fee for withdrawal transaction"
1111
+ );
1112
+ }
1113
+ if (outputValue < BTC_DUST_SAT) {
1114
+ throw new Error("Output value is less than dust limit");
1115
+ }
1116
+ psbt.addOutput({
1117
+ address: withdrawalAddress,
1118
+ value: outputValue
1119
+ });
1120
+ psbt.setLocktime(0);
1121
+ return {
1122
+ psbt,
1123
+ fee: estimatedFee
1124
+ };
1125
+ }
1126
+ function slashTimelockUnbondedTransaction(scripts, stakingTransaction2, slashingPkScriptHex, slashingRate, minimumFee, network, outputIndex = 0) {
1127
+ const slashingScriptTree = [
1128
+ {
1129
+ output: scripts.slashingScript
1130
+ },
1131
+ [{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
1132
+ ];
1133
+ return slashingTransaction(
1134
+ {
1135
+ unbondingTimelockScript: scripts.unbondingTimelockScript,
1136
+ slashingScript: scripts.slashingScript
1137
+ },
1138
+ slashingScriptTree,
1139
+ stakingTransaction2,
1140
+ slashingPkScriptHex,
1141
+ slashingRate,
1142
+ minimumFee,
1143
+ network,
1144
+ outputIndex
1145
+ );
1146
+ }
1147
+ function slashEarlyUnbondedTransaction(scripts, unbondingTx, slashingPkScriptHex, slashingRate, minimumSlashingFee, network) {
1148
+ const unbondingScriptTree = [
1149
+ {
1150
+ output: scripts.slashingScript
1151
+ },
1152
+ {
1153
+ output: scripts.unbondingTimelockScript
1154
+ }
1155
+ ];
1156
+ return slashingTransaction(
1157
+ {
1158
+ unbondingTimelockScript: scripts.unbondingTimelockScript,
1159
+ slashingScript: scripts.slashingScript
1160
+ },
1161
+ unbondingScriptTree,
1162
+ unbondingTx,
1163
+ slashingPkScriptHex,
1164
+ slashingRate,
1165
+ minimumSlashingFee,
1166
+ network,
1167
+ 0
1168
+ // unbonding always has a single output
1169
+ );
1170
+ }
1171
+ function slashingTransaction(scripts, scriptTree, transaction, slashingPkScriptHex, slashingRate, minimumFee, network, outputIndex = 0) {
1172
+ if (slashingRate <= 0 || slashingRate >= 1) {
1173
+ throw new Error("Slashing rate must be between 0 and 1");
1174
+ }
1175
+ slashingRate = parseFloat(slashingRate.toFixed(BTC_SLASHING_FRACTION_DIGITS));
1176
+ if (minimumFee <= 0 || !Number.isInteger(minimumFee)) {
1177
+ throw new Error("Minimum fee must be a positve integer");
1178
+ }
1179
+ if (outputIndex < 0 || !Number.isInteger(outputIndex)) {
1180
+ throw new Error("Output index must be an integer bigger or equal to 0");
1181
+ }
1182
+ if (!transaction.outs[outputIndex]) {
1183
+ throw new Error("Output index is out of range");
1184
+ }
1185
+ const redeem = {
1186
+ output: scripts.slashingScript,
1187
+ redeemVersion: REDEEM_VERSION
1188
+ };
1189
+ const p2tr = import_bitcoinjs_lib8.payments.p2tr({
1190
+ internalPubkey,
1191
+ scriptTree,
1192
+ redeem,
1193
+ network
1194
+ });
1195
+ const tapLeafScript = {
1196
+ leafVersion: redeem.redeemVersion,
1197
+ script: redeem.output,
1198
+ controlBlock: p2tr.witness[p2tr.witness.length - 1]
1199
+ };
1200
+ const stakingAmount = transaction.outs[outputIndex].value;
1201
+ const slashingAmount = Math.round(stakingAmount * slashingRate);
1202
+ const slashingOutput = Buffer.from(slashingPkScriptHex, "hex");
1203
+ if (import_bitcoinjs_lib8.opcodes.OP_RETURN != slashingOutput[0]) {
1204
+ if (slashingAmount <= BTC_DUST_SAT) {
1205
+ throw new Error("Slashing amount is less than dust limit");
1206
+ }
1207
+ }
1208
+ const userFunds = stakingAmount - slashingAmount - minimumFee;
1209
+ if (userFunds <= BTC_DUST_SAT) {
1210
+ throw new Error("User funds are less than dust limit");
1211
+ }
1212
+ const psbt = new import_bitcoinjs_lib8.Psbt({ network });
1213
+ psbt.setVersion(TRANSACTION_VERSION);
1214
+ psbt.addInput({
1215
+ hash: transaction.getHash(),
1216
+ index: outputIndex,
1217
+ tapInternalKey: internalPubkey,
1218
+ witnessUtxo: {
1219
+ value: stakingAmount,
1220
+ script: transaction.outs[outputIndex].script
1221
+ },
1222
+ tapLeafScript: [tapLeafScript],
1223
+ // not RBF-able
1224
+ sequence: NON_RBF_SEQUENCE
1225
+ });
1226
+ psbt.addOutput({
1227
+ script: slashingOutput,
1228
+ value: slashingAmount
1229
+ });
1230
+ const changeOutput = import_bitcoinjs_lib8.payments.p2tr({
1231
+ internalPubkey,
1232
+ scriptTree: { output: scripts.unbondingTimelockScript },
1233
+ network
1234
+ });
1235
+ psbt.addOutput({
1236
+ address: changeOutput.address,
1237
+ value: userFunds
1238
+ });
1239
+ psbt.setLocktime(0);
1240
+ return { psbt };
1241
+ }
1242
+ function unbondingTransaction(scripts, stakingTx, unbondingFee, network, outputIndex = 0) {
1243
+ if (unbondingFee <= 0) {
1244
+ throw new Error("Unbonding fee must be bigger than 0");
1245
+ }
1246
+ if (outputIndex < 0) {
1247
+ throw new Error("Output index must be bigger or equal to 0");
1248
+ }
1249
+ const tx = new import_bitcoinjs_lib8.Transaction();
1250
+ tx.version = TRANSACTION_VERSION;
1251
+ tx.addInput(
1252
+ stakingTx.getHash(),
1253
+ outputIndex,
1254
+ NON_RBF_SEQUENCE
1255
+ // not RBF-able
1256
+ );
1257
+ const unbondingOutputInfo = deriveUnbondingOutputInfo(scripts, network);
1258
+ const outputValue = stakingTx.outs[outputIndex].value - unbondingFee;
1259
+ if (outputValue < BTC_DUST_SAT) {
1260
+ throw new Error("Output value is less than dust limit for unbonding transaction");
1261
+ }
1262
+ if (!unbondingOutputInfo.outputAddress) {
1263
+ throw new Error("Unbonding output address is not defined");
1264
+ }
1265
+ tx.addOutput(
1266
+ unbondingOutputInfo.scriptPubKey,
1267
+ outputValue
1268
+ );
1269
+ tx.locktime = 0;
1270
+ return {
1271
+ transaction: tx,
1272
+ fee: unbondingFee
1273
+ };
1274
+ }
1275
+ var createCovenantWitness = (originalWitness, paramsCovenants, covenantSigs, covenantQuorum) => {
1276
+ if (covenantSigs.length < covenantQuorum) {
1277
+ throw new Error(
1278
+ `Not enough covenant signatures. Required: ${covenantQuorum}, got: ${covenantSigs.length}`
1279
+ );
1280
+ }
1281
+ for (const sig of covenantSigs) {
1282
+ const btcPkHexBuf = Buffer.from(sig.btcPkHex, "hex");
1283
+ if (!paramsCovenants.some((covenant) => covenant.equals(btcPkHexBuf))) {
1284
+ throw new Error(
1285
+ `Covenant signature public key ${sig.btcPkHex} not found in params covenants`
1286
+ );
1287
+ }
1288
+ }
1289
+ const covenantSigsBuffers = covenantSigs.slice(0, covenantQuorum).map((sig) => ({
1290
+ btcPkHex: Buffer.from(sig.btcPkHex, "hex"),
1291
+ sigHex: Buffer.from(sig.sigHex, "hex")
1292
+ }));
1293
+ const paramsCovenantsSorted = [...paramsCovenants].sort(Buffer.compare).reverse();
1294
+ const composedCovenantSigs = paramsCovenantsSorted.map((covenant) => {
1295
+ const covenantSig = covenantSigsBuffers.find(
1296
+ (sig) => sig.btcPkHex.compare(covenant) === 0
1297
+ );
1298
+ return covenantSig?.sigHex || Buffer.alloc(0);
1299
+ });
1300
+ return [...composedCovenantSigs, ...originalWitness];
1301
+ };
1302
+
1303
+ // src/staking/index.ts
1304
+ var Staking = class {
1305
+ constructor(network, stakerInfo, params, finalityProviderPksNoCoordHex, stakingTimelock) {
1306
+ if (!isValidBitcoinAddress(stakerInfo.address, network)) {
1307
+ throw new StakingError(
1308
+ "INVALID_INPUT" /* INVALID_INPUT */,
1309
+ "Invalid staker bitcoin address"
1310
+ );
1311
+ }
1312
+ if (!isValidNoCoordPublicKey(stakerInfo.publicKeyNoCoordHex)) {
1313
+ throw new StakingError(
1314
+ "INVALID_INPUT" /* INVALID_INPUT */,
1315
+ "Invalid staker public key"
1316
+ );
1317
+ }
1318
+ if (finalityProviderPksNoCoordHex.length === 0 || !finalityProviderPksNoCoordHex.every(isValidNoCoordPublicKey)) {
1319
+ throw new StakingError(
1320
+ "INVALID_INPUT" /* INVALID_INPUT */,
1321
+ "Invalid finality providers public keys"
1322
+ );
1323
+ }
1324
+ validateParams(params);
1325
+ validateStakingTimelock(stakingTimelock, params);
1326
+ this.network = network;
1327
+ this.stakerInfo = stakerInfo;
1328
+ this.params = params;
1329
+ this.finalityProviderPksNoCoordHex = finalityProviderPksNoCoordHex;
1330
+ this.stakingTimelock = stakingTimelock;
1331
+ }
1332
+ /**
1333
+ * buildScripts builds the staking scripts for the staking transaction.
1334
+ * Note: different staking types may have different scripts.
1335
+ * e.g the observable staking script has a data embed script.
1336
+ *
1337
+ * @returns {StakingScripts} - The staking scripts.
1338
+ */
1339
+ buildScripts() {
1340
+ const { covenantQuorum, covenantNoCoordPks, unbondingTime } = this.params;
1341
+ let stakingScriptData;
1342
+ try {
1343
+ stakingScriptData = new StakingScriptData(
1344
+ Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex"),
1345
+ this.finalityProviderPksNoCoordHex.map((pk) => Buffer.from(pk, "hex")),
1346
+ toBuffers(covenantNoCoordPks),
1347
+ covenantQuorum,
1348
+ this.stakingTimelock,
1349
+ unbondingTime
1350
+ );
1351
+ } catch (error) {
1352
+ throw StakingError.fromUnknown(
1353
+ error,
1354
+ "SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
1355
+ "Cannot build staking script data"
1356
+ );
1357
+ }
1358
+ let scripts;
1359
+ try {
1360
+ scripts = stakingScriptData.buildScripts();
1361
+ } catch (error) {
1362
+ throw StakingError.fromUnknown(
1363
+ error,
1364
+ "SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
1365
+ "Cannot build staking scripts"
1366
+ );
1367
+ }
1368
+ return scripts;
1369
+ }
1370
+ /**
1371
+ * Create a staking transaction for staking.
1372
+ *
1373
+ * @param {number} stakingAmountSat - The amount to stake in satoshis.
1374
+ * @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
1375
+ * transaction.
1376
+ * @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
1377
+ * @returns {TransactionResult} - An object containing the unsigned
1378
+ * transaction, and fee
1379
+ * @throws {StakingError} - If the transaction cannot be built
1380
+ */
1381
+ createStakingTransaction(stakingAmountSat, inputUTXOs, feeRate) {
1382
+ validateStakingTxInputData(
1383
+ stakingAmountSat,
1384
+ this.stakingTimelock,
1385
+ this.params,
1386
+ inputUTXOs,
1387
+ feeRate
1388
+ );
1389
+ const scripts = this.buildScripts();
1390
+ try {
1391
+ const { transaction, fee } = stakingTransaction(
1392
+ scripts,
1393
+ stakingAmountSat,
1394
+ this.stakerInfo.address,
1395
+ inputUTXOs,
1396
+ this.network,
1397
+ feeRate
1398
+ );
1399
+ return {
1400
+ transaction,
1401
+ fee
1402
+ };
1403
+ } catch (error) {
1404
+ throw StakingError.fromUnknown(
1405
+ error,
1406
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1407
+ "Cannot build unsigned staking transaction"
1408
+ );
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Create a staking psbt based on the existing staking transaction.
1413
+ *
1414
+ * @param {Transaction} stakingTx - The staking transaction.
1415
+ * @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
1416
+ * transaction. The UTXOs that were used to create the staking transaction should
1417
+ * be included in this array.
1418
+ * @returns {Psbt} - The psbt.
1419
+ */
1420
+ toStakingPsbt(stakingTx, inputUTXOs) {
1421
+ const scripts = this.buildScripts();
1422
+ const stakingOutputInfo = deriveStakingOutputInfo(scripts, this.network);
1423
+ findMatchingTxOutputIndex(
1424
+ stakingTx,
1425
+ stakingOutputInfo.outputAddress,
1426
+ this.network
1427
+ );
1428
+ return stakingPsbt(
1429
+ stakingTx,
1430
+ this.network,
1431
+ inputUTXOs,
1432
+ isTaproot(this.stakerInfo.address, this.network) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
1433
+ );
1434
+ }
1435
+ /**
1436
+ * Create an unbonding transaction for staking.
1437
+ *
1438
+ * @param {Transaction} stakingTx - The staking transaction to unbond.
1439
+ * @returns {TransactionResult} - An object containing the unsigned
1440
+ * transaction, and fee
1441
+ * @throws {StakingError} - If the transaction cannot be built
1442
+ */
1443
+ createUnbondingTransaction(stakingTx) {
1444
+ const scripts = this.buildScripts();
1445
+ const { outputAddress } = deriveStakingOutputInfo(scripts, this.network);
1446
+ const stakingOutputIndex = findMatchingTxOutputIndex(
1447
+ stakingTx,
1448
+ outputAddress,
1449
+ this.network
1450
+ );
1451
+ try {
1452
+ const { transaction } = unbondingTransaction(
1453
+ scripts,
1454
+ stakingTx,
1455
+ this.params.unbondingFeeSat,
1456
+ this.network,
1457
+ stakingOutputIndex
1458
+ );
1459
+ return {
1460
+ transaction,
1461
+ fee: this.params.unbondingFeeSat
1462
+ };
1463
+ } catch (error) {
1464
+ throw StakingError.fromUnknown(
1465
+ error,
1466
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1467
+ "Cannot build the unbonding transaction"
1468
+ );
1469
+ }
1470
+ }
1471
+ /**
1472
+ * Create an unbonding psbt based on the existing unbonding transaction and
1473
+ * staking transaction.
1474
+ *
1475
+ * @param {Transaction} unbondingTx - The unbonding transaction.
1476
+ * @param {Transaction} stakingTx - The staking transaction.
1477
+ *
1478
+ * @returns {Psbt} - The psbt.
1479
+ */
1480
+ toUnbondingPsbt(unbondingTx, stakingTx) {
1481
+ return unbondingPsbt(
1482
+ this.buildScripts(),
1483
+ unbondingTx,
1484
+ stakingTx,
1485
+ this.network
1486
+ );
1487
+ }
1488
+ /**
1489
+ * Creates a withdrawal transaction that spends from an unbonding or slashing
1490
+ * transaction. The timelock on the input transaction must have expired before
1491
+ * this withdrawal can be valid.
1492
+ *
1493
+ * @param {Transaction} earlyUnbondedTx - The unbonding or slashing
1494
+ * transaction to withdraw from
1495
+ * @param {number} feeRate - Fee rate in satoshis per byte for the withdrawal
1496
+ * transaction
1497
+ * @returns {PsbtResult} - Contains the unsigned PSBT and fee amount
1498
+ * @throws {StakingError} - If the input transaction is invalid or withdrawal
1499
+ * transaction cannot be built
1500
+ */
1501
+ createWithdrawEarlyUnbondedTransaction(earlyUnbondedTx, feeRate) {
1502
+ const scripts = this.buildScripts();
1503
+ try {
1504
+ return withdrawEarlyUnbondedTransaction(
1505
+ scripts,
1506
+ earlyUnbondedTx,
1507
+ this.stakerInfo.address,
1508
+ this.network,
1509
+ feeRate
1510
+ );
1511
+ } catch (error) {
1512
+ throw StakingError.fromUnknown(
1513
+ error,
1514
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1515
+ "Cannot build unsigned withdraw early unbonded transaction"
1516
+ );
1517
+ }
1518
+ }
1519
+ /**
1520
+ * Create a withdrawal psbt that spends a naturally expired staking
1521
+ * transaction.
1522
+ *
1523
+ * @param {Transaction} stakingTx - The staking transaction to withdraw from.
1524
+ * @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
1525
+ * @returns {PsbtResult} - An object containing the unsigned psbt and fee
1526
+ * @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
1527
+ */
1528
+ createWithdrawStakingExpiredPsbt(stakingTx, feeRate) {
1529
+ const scripts = this.buildScripts();
1530
+ const { outputAddress } = deriveStakingOutputInfo(scripts, this.network);
1531
+ const stakingOutputIndex = findMatchingTxOutputIndex(
1532
+ stakingTx,
1533
+ outputAddress,
1534
+ this.network
1535
+ );
1536
+ try {
1537
+ return withdrawTimelockUnbondedTransaction(
1538
+ scripts,
1539
+ stakingTx,
1540
+ this.stakerInfo.address,
1541
+ this.network,
1542
+ feeRate,
1543
+ stakingOutputIndex
1544
+ );
1545
+ } catch (error) {
1546
+ throw StakingError.fromUnknown(
1547
+ error,
1548
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1549
+ "Cannot build unsigned timelock unbonded transaction"
1550
+ );
1551
+ }
1552
+ }
1553
+ /**
1554
+ * Create a slashing psbt spending from the staking output.
1555
+ *
1556
+ * @param {Transaction} stakingTx - The staking transaction to slash.
1557
+ * @returns {PsbtResult} - An object containing the unsigned psbt and fee
1558
+ * @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
1559
+ */
1560
+ createStakingOutputSlashingPsbt(stakingTx) {
1561
+ if (!this.params.slashing) {
1562
+ throw new StakingError(
1563
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
1564
+ "Slashing parameters are missing"
1565
+ );
1566
+ }
1567
+ const scripts = this.buildScripts();
1568
+ const { outputAddress } = deriveStakingOutputInfo(scripts, this.network);
1569
+ const stakingOutputIndex = findMatchingTxOutputIndex(
1570
+ stakingTx,
1571
+ outputAddress,
1572
+ this.network
1573
+ );
1574
+ try {
1575
+ const { psbt } = slashTimelockUnbondedTransaction(
1576
+ scripts,
1577
+ stakingTx,
1578
+ this.params.slashing.slashingPkScriptHex,
1579
+ this.params.slashing.slashingRate,
1580
+ this.params.slashing.minSlashingTxFeeSat,
1581
+ this.network,
1582
+ stakingOutputIndex
1583
+ );
1584
+ return {
1585
+ psbt,
1586
+ fee: this.params.slashing.minSlashingTxFeeSat
1587
+ };
1588
+ } catch (error) {
1589
+ throw StakingError.fromUnknown(
1590
+ error,
1591
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1592
+ "Cannot build the slash timelock unbonded transaction"
1593
+ );
1594
+ }
1595
+ }
1596
+ /**
1597
+ * Create a slashing psbt for an unbonding output.
1598
+ *
1599
+ * @param {Transaction} unbondingTx - The unbonding transaction to slash.
1600
+ * @returns {PsbtResult} - An object containing the unsigned psbt and fee
1601
+ * @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
1602
+ */
1603
+ createUnbondingOutputSlashingPsbt(unbondingTx) {
1604
+ if (!this.params.slashing) {
1605
+ throw new StakingError(
1606
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
1607
+ "Slashing parameters are missing"
1608
+ );
1609
+ }
1610
+ const scripts = this.buildScripts();
1611
+ try {
1612
+ const { psbt } = slashEarlyUnbondedTransaction(
1613
+ scripts,
1614
+ unbondingTx,
1615
+ this.params.slashing.slashingPkScriptHex,
1616
+ this.params.slashing.slashingRate,
1617
+ this.params.slashing.minSlashingTxFeeSat,
1618
+ this.network
1619
+ );
1620
+ return {
1621
+ psbt,
1622
+ fee: this.params.slashing.minSlashingTxFeeSat
1623
+ };
1624
+ } catch (error) {
1625
+ throw StakingError.fromUnknown(
1626
+ error,
1627
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1628
+ "Cannot build the slash early unbonded transaction"
1629
+ );
1630
+ }
1631
+ }
1632
+ /**
1633
+ * Create a withdraw slashing psbt that spends a slashing transaction from the
1634
+ * staking output.
1635
+ *
1636
+ * @param {Transaction} slashingTx - The slashing transaction.
1637
+ * @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
1638
+ * @returns {PsbtResult} - An object containing the unsigned psbt and fee
1639
+ * @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
1640
+ */
1641
+ createWithdrawSlashingPsbt(slashingTx, feeRate) {
1642
+ const scripts = this.buildScripts();
1643
+ const slashingOutputInfo = deriveSlashingOutput(scripts, this.network);
1644
+ const slashingOutputIndex = findMatchingTxOutputIndex(
1645
+ slashingTx,
1646
+ slashingOutputInfo.outputAddress,
1647
+ this.network
1648
+ );
1649
+ try {
1650
+ return withdrawSlashingTransaction(
1651
+ scripts,
1652
+ slashingTx,
1653
+ this.stakerInfo.address,
1654
+ this.network,
1655
+ feeRate,
1656
+ slashingOutputIndex
1657
+ );
1658
+ } catch (error) {
1659
+ throw StakingError.fromUnknown(
1660
+ error,
1661
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
1662
+ "Cannot build withdraw slashing transaction"
1663
+ );
1664
+ }
1665
+ }
1666
+ };
1667
+
1668
+ // src/staking/manager.ts
1669
+ var import_babylon_proto_ts = require("@babylonlabs-io/babylon-proto-ts");
1670
+ var import_pop = require("@babylonlabs-io/babylon-proto-ts/dist/generated/babylon/btcstaking/v1/pop");
1671
+ var import_bitcoinjs_lib9 = require("bitcoinjs-lib");
1672
+
1673
+ // src/constants/registry.ts
1674
+ var BABYLON_REGISTRY_TYPE_URLS = {
1675
+ MsgCreateBTCDelegation: "/babylon.btcstaking.v1.MsgCreateBTCDelegation"
1676
+ };
1677
+
1678
+ // src/utils/index.ts
1679
+ var reverseBuffer = (buffer) => {
1680
+ const clonedBuffer = new Uint8Array(buffer);
1681
+ if (clonedBuffer.length < 1)
1682
+ return clonedBuffer;
1683
+ for (let i = 0, j = clonedBuffer.length - 1; i < clonedBuffer.length / 2; i++, j--) {
1684
+ let tmp = clonedBuffer[i];
1685
+ clonedBuffer[i] = clonedBuffer[j];
1686
+ clonedBuffer[j] = tmp;
1687
+ }
1688
+ return clonedBuffer;
1689
+ };
1690
+
1691
+ // src/utils/babylon.ts
1692
+ var import_encoding = require("@cosmjs/encoding");
1693
+ var isValidBabylonAddress = (address4) => {
1694
+ try {
1695
+ const { prefix } = (0, import_encoding.fromBech32)(address4);
1696
+ return prefix === "bbn";
1697
+ } catch (error) {
1698
+ return false;
1699
+ }
1700
+ };
1701
+
1702
+ // src/utils/staking/param.ts
1703
+ var getBabylonParamByBtcHeight = (height, babylonParamsVersions) => {
1704
+ const sortedParams = [...babylonParamsVersions].sort(
1705
+ (a, b) => b.btcActivationHeight - a.btcActivationHeight
1706
+ );
1707
+ const params = sortedParams.find(
1708
+ (p) => height >= p.btcActivationHeight
1709
+ );
1710
+ if (!params)
1711
+ throw new Error(`Babylon params not found for height ${height}`);
1712
+ return params;
1713
+ };
1714
+ var getBabylonParamByVersion = (version, babylonParams) => {
1715
+ const params = babylonParams.find((p) => p.version === version);
1716
+ if (!params)
1717
+ throw new Error(`Babylon params not found for version ${version}`);
1718
+ return params;
1719
+ };
1720
+
1721
+ // src/staking/manager.ts
1722
+ var BabylonBtcStakingManager = class {
1723
+ constructor(network, stakingParams, btcProvider, babylonProvider, ee) {
1724
+ this.network = network;
1725
+ this.stakingParams = stakingParams;
1726
+ this.btcProvider = btcProvider;
1727
+ this.babylonProvider = babylonProvider;
1728
+ this.ee = ee;
1729
+ this.network = network;
1730
+ if (stakingParams.length === 0) {
1731
+ throw new Error("No staking parameters provided");
1732
+ }
1733
+ this.stakingParams = stakingParams;
1734
+ }
1735
+ /**
1736
+ * Creates a signed Pre-Staking Registration transaction that is ready to be
1737
+ * sent to the Babylon chain.
1738
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
1739
+ * and the no-coord public key in hex format.
1740
+ * @param stakingInput - The staking inputs.
1741
+ * @param babylonBtcTipHeight - The Babylon BTC tip height.
1742
+ * @param inputUTXOs - The UTXOs that will be used to pay for the staking
1743
+ * transaction.
1744
+ * @param feeRate - The fee rate in satoshis per byte. Typical value for the
1745
+ * fee rate is above 1. If the fee rate is too low, the transaction will not
1746
+ * be included in a block.
1747
+ * @param babylonAddress - The Babylon bech32 encoded address of the staker.
1748
+ * @returns The signed babylon pre-staking registration transaction in base64
1749
+ * format.
1750
+ */
1751
+ async preStakeRegistrationBabylonTransaction(stakerBtcInfo, stakingInput, babylonBtcTipHeight, inputUTXOs, feeRate, babylonAddress) {
1752
+ if (babylonBtcTipHeight === 0) {
1753
+ throw new Error("Babylon BTC tip height cannot be 0");
1754
+ }
1755
+ if (inputUTXOs.length === 0) {
1756
+ throw new Error("No input UTXOs provided");
1757
+ }
1758
+ if (!isValidBabylonAddress(babylonAddress)) {
1759
+ throw new Error("Invalid Babylon address");
1760
+ }
1761
+ const params = getBabylonParamByBtcHeight(
1762
+ babylonBtcTipHeight,
1763
+ this.stakingParams
1764
+ );
1765
+ const staking = new Staking(
1766
+ this.network,
1767
+ stakerBtcInfo,
1768
+ params,
1769
+ stakingInput.finalityProviderPksNoCoordHex,
1770
+ stakingInput.stakingTimelock
1771
+ );
1772
+ const { transaction } = staking.createStakingTransaction(
1773
+ stakingInput.stakingAmountSat,
1774
+ inputUTXOs,
1775
+ feeRate
1776
+ );
1777
+ const msg = await this.createBtcDelegationMsg(
1778
+ "delegation:create",
1779
+ staking,
1780
+ stakingInput,
1781
+ transaction,
1782
+ babylonAddress,
1783
+ stakerBtcInfo,
1784
+ params
1785
+ );
1786
+ this.ee?.emit("delegation:create", {
1787
+ type: "create-btc-delegation-msg"
1788
+ });
1789
+ return {
1790
+ signedBabylonTx: await this.babylonProvider.signTransaction(msg),
1791
+ stakingTx: transaction
1792
+ };
1793
+ }
1794
+ /**
1795
+ * Creates a signed post-staking registration transaction that is ready to be
1796
+ * sent to the Babylon chain. This is used when a staking transaction is
1797
+ * already created and included in a BTC block and we want to register it on
1798
+ * the Babylon chain.
1799
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
1800
+ * and the no-coord public key in hex format.
1801
+ * @param stakingTx - The staking transaction.
1802
+ * @param stakingTxHeight - The BTC height in which the staking transaction
1803
+ * is included.
1804
+ * @param stakingInput - The staking inputs.
1805
+ * @param inclusionProof - Merkle Proof of Inclusion: Verifies transaction
1806
+ * inclusion in a Bitcoin block that is k-deep.
1807
+ * @param babylonAddress - The Babylon bech32 encoded address of the staker.
1808
+ * @returns The signed babylon transaction in base64 format.
1809
+ */
1810
+ async postStakeRegistrationBabylonTransaction(stakerBtcInfo, stakingTx, stakingTxHeight, stakingInput, inclusionProof, babylonAddress) {
1811
+ const params = getBabylonParamByBtcHeight(
1812
+ stakingTxHeight,
1813
+ this.stakingParams
1814
+ );
1815
+ if (!isValidBabylonAddress(babylonAddress)) {
1816
+ throw new Error("Invalid Babylon address");
1817
+ }
1818
+ const stakingInstance = new Staking(
1819
+ this.network,
1820
+ stakerBtcInfo,
1821
+ params,
1822
+ stakingInput.finalityProviderPksNoCoordHex,
1823
+ stakingInput.stakingTimelock
1824
+ );
1825
+ const scripts = stakingInstance.buildScripts();
1826
+ const stakingOutputInfo = deriveStakingOutputInfo(scripts, this.network);
1827
+ findMatchingTxOutputIndex(
1828
+ stakingTx,
1829
+ stakingOutputInfo.outputAddress,
1830
+ this.network
1831
+ );
1832
+ const delegationMsg = await this.createBtcDelegationMsg(
1833
+ "delegation:register",
1834
+ stakingInstance,
1835
+ stakingInput,
1836
+ stakingTx,
1837
+ babylonAddress,
1838
+ stakerBtcInfo,
1839
+ params,
1840
+ this.getInclusionProof(inclusionProof)
1841
+ );
1842
+ this.ee?.emit("delegation:register", {
1843
+ type: "create-btc-delegation-msg"
1844
+ });
1845
+ return {
1846
+ signedBabylonTx: await this.babylonProvider.signTransaction(delegationMsg)
1847
+ };
1848
+ }
1849
+ /**
1850
+ * Estimates the BTC fee required for staking.
1851
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
1852
+ * and the no-coord public key in hex format.
1853
+ * @param babylonBtcTipHeight - The BTC tip height recorded on the Babylon
1854
+ * chain.
1855
+ * @param stakingInput - The staking inputs.
1856
+ * @param inputUTXOs - The UTXOs that will be used to pay for the staking
1857
+ * transaction.
1858
+ * @param feeRate - The fee rate in satoshis per byte. Typical value for the
1859
+ * fee rate is above 1. If the fee rate is too low, the transaction will not
1860
+ * be included in a block.
1861
+ * @returns The estimated BTC fee in satoshis.
1862
+ */
1863
+ estimateBtcStakingFee(stakerBtcInfo, babylonBtcTipHeight, stakingInput, inputUTXOs, feeRate) {
1864
+ if (babylonBtcTipHeight === 0) {
1865
+ throw new Error("Babylon BTC tip height cannot be 0");
1866
+ }
1867
+ const params = getBabylonParamByBtcHeight(
1868
+ babylonBtcTipHeight,
1869
+ this.stakingParams
1870
+ );
1871
+ const staking = new Staking(
1872
+ this.network,
1873
+ stakerBtcInfo,
1874
+ params,
1875
+ stakingInput.finalityProviderPksNoCoordHex,
1876
+ stakingInput.stakingTimelock
1877
+ );
1878
+ const { fee: stakingFee } = staking.createStakingTransaction(
1879
+ stakingInput.stakingAmountSat,
1880
+ inputUTXOs,
1881
+ feeRate
1882
+ );
1883
+ return stakingFee;
1884
+ }
1885
+ /**
1886
+ * Creates a signed staking transaction that is ready to be sent to the BTC
1887
+ * network.
1888
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
1889
+ * and the no-coord public key in hex format.
1890
+ * @param stakingInput - The staking inputs.
1891
+ * @param unsignedStakingTx - The unsigned staking transaction.
1892
+ * @param inputUTXOs - The UTXOs that will be used to pay for the staking
1893
+ * transaction.
1894
+ * @param stakingParamsVersion - The params version that was used to create the
1895
+ * delegation in Babylon chain
1896
+ * @returns The signed staking transaction.
1897
+ */
1898
+ async createSignedBtcStakingTransaction(stakerBtcInfo, stakingInput, unsignedStakingTx, inputUTXOs, stakingParamsVersion) {
1899
+ const params = getBabylonParamByVersion(
1900
+ stakingParamsVersion,
1901
+ this.stakingParams
1902
+ );
1903
+ if (inputUTXOs.length === 0) {
1904
+ throw new Error("No input UTXOs provided");
1905
+ }
1906
+ const staking = new Staking(
1907
+ this.network,
1908
+ stakerBtcInfo,
1909
+ params,
1910
+ stakingInput.finalityProviderPksNoCoordHex,
1911
+ stakingInput.stakingTimelock
1912
+ );
1913
+ const stakingPsbt2 = staking.toStakingPsbt(unsignedStakingTx, inputUTXOs);
1914
+ const contracts = [
1915
+ {
1916
+ id: "babylon:staking" /* STAKING */,
1917
+ params: {
1918
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
1919
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
1920
+ covenantPks: params.covenantNoCoordPks,
1921
+ covenantThreshold: params.covenantQuorum,
1922
+ minUnbondingTime: params.unbondingTime,
1923
+ stakingDuration: stakingInput.stakingTimelock
1924
+ }
1925
+ }
1926
+ ];
1927
+ this.ee?.emit("delegation:stake", {
1928
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
1929
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
1930
+ covenantPks: params.covenantNoCoordPks,
1931
+ covenantThreshold: params.covenantQuorum,
1932
+ unbondingTimeBlocks: params.unbondingTime,
1933
+ stakingDuration: stakingInput.stakingTimelock,
1934
+ type: "staking"
1935
+ });
1936
+ const signedStakingPsbtHex = await this.btcProvider.signPsbt(
1937
+ stakingPsbt2.toHex(),
1938
+ {
1939
+ contracts,
1940
+ action: {
1941
+ name: "sign-btc-staking-transaction" /* SIGN_BTC_STAKING_TRANSACTION */
1942
+ }
1943
+ }
1944
+ );
1945
+ return import_bitcoinjs_lib9.Psbt.fromHex(signedStakingPsbtHex).extractTransaction();
1946
+ }
1947
+ /**
1948
+ * Creates a partial signed unbonding transaction that is only signed by the
1949
+ * staker. In order to complete the unbonding transaction, the covenant
1950
+ * unbonding signatures need to be added to the transaction before sending it
1951
+ * to the BTC network.
1952
+ * NOTE: This method should only be used for Babylon phase-1 unbonding.
1953
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
1954
+ * and the no-coord public key in hex format.
1955
+ * @param stakingInput - The staking inputs.
1956
+ * @param stakingParamsVersion - The params version that was used to create the
1957
+ * delegation in Babylon chain
1958
+ * @param stakingTx - The staking transaction.
1959
+ * @returns The partial signed unbonding transaction and its fee.
1960
+ */
1961
+ async createPartialSignedBtcUnbondingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx) {
1962
+ const params = getBabylonParamByVersion(
1963
+ stakingParamsVersion,
1964
+ this.stakingParams
1965
+ );
1966
+ const staking = new Staking(
1967
+ this.network,
1968
+ stakerBtcInfo,
1969
+ params,
1970
+ stakingInput.finalityProviderPksNoCoordHex,
1971
+ stakingInput.stakingTimelock
1972
+ );
1973
+ const { transaction: unbondingTx, fee } = staking.createUnbondingTransaction(stakingTx);
1974
+ const psbt = staking.toUnbondingPsbt(unbondingTx, stakingTx);
1975
+ const contracts = [
1976
+ {
1977
+ id: "babylon:staking" /* STAKING */,
1978
+ params: {
1979
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
1980
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
1981
+ covenantPks: params.covenantNoCoordPks,
1982
+ covenantThreshold: params.covenantQuorum,
1983
+ minUnbondingTime: params.unbondingTime,
1984
+ stakingDuration: stakingInput.stakingTimelock
1985
+ }
1986
+ },
1987
+ {
1988
+ id: "babylon:unbonding" /* UNBONDING */,
1989
+ params: {
1990
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
1991
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
1992
+ covenantPks: params.covenantNoCoordPks,
1993
+ covenantThreshold: params.covenantQuorum,
1994
+ unbondingTimeBlocks: params.unbondingTime,
1995
+ unbondingFeeSat: params.unbondingFeeSat
1996
+ }
1997
+ }
1998
+ ];
1999
+ this.ee?.emit("delegation:unbond", {
2000
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2001
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
2002
+ covenantPks: params.covenantNoCoordPks,
2003
+ covenantThreshold: params.covenantQuorum,
2004
+ stakingDuration: stakingInput.stakingTimelock,
2005
+ unbondingTimeBlocks: params.unbondingTime,
2006
+ unbondingFeeSat: params.unbondingFeeSat,
2007
+ type: "unbonding"
2008
+ });
2009
+ const signedUnbondingPsbtHex = await this.btcProvider.signPsbt(
2010
+ psbt.toHex(),
2011
+ {
2012
+ contracts,
2013
+ action: {
2014
+ name: "sign-btc-unbonding-transaction" /* SIGN_BTC_UNBONDING_TRANSACTION */
2015
+ }
2016
+ }
2017
+ );
2018
+ const signedUnbondingTx = import_bitcoinjs_lib9.Psbt.fromHex(
2019
+ signedUnbondingPsbtHex
2020
+ ).extractTransaction();
2021
+ return {
2022
+ transaction: signedUnbondingTx,
2023
+ fee
2024
+ };
2025
+ }
2026
+ /**
2027
+ * Creates a signed unbonding transaction that is ready to be sent to the BTC
2028
+ * network.
2029
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
2030
+ * and the no-coord public key in hex format.
2031
+ * @param stakingInput - The staking inputs.
2032
+ * @param stakingParamsVersion - The params version that was used to create the
2033
+ * delegation in Babylon chain
2034
+ * @param stakingTx - The staking transaction.
2035
+ * @param unsignedUnbondingTx - The unsigned unbonding transaction.
2036
+ * @param covenantUnbondingSignatures - The covenant unbonding signatures.
2037
+ * It can be retrieved from the Babylon chain or API.
2038
+ * @returns The signed unbonding transaction and its fee.
2039
+ */
2040
+ async createSignedBtcUnbondingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx, unsignedUnbondingTx, covenantUnbondingSignatures) {
2041
+ const params = getBabylonParamByVersion(
2042
+ stakingParamsVersion,
2043
+ this.stakingParams
2044
+ );
2045
+ const { transaction: signedUnbondingTx, fee } = await this.createPartialSignedBtcUnbondingTransaction(
2046
+ stakerBtcInfo,
2047
+ stakingInput,
2048
+ stakingParamsVersion,
2049
+ stakingTx
2050
+ );
2051
+ if (signedUnbondingTx.getId() !== unsignedUnbondingTx.getId()) {
2052
+ throw new Error(
2053
+ "Unbonding transaction hash does not match the computed hash"
2054
+ );
2055
+ }
2056
+ const covenantBuffers = params.covenantNoCoordPks.map(
2057
+ (covenant) => Buffer.from(covenant, "hex")
2058
+ );
2059
+ const witness = createCovenantWitness(
2060
+ // Since unbonding transactions always have a single input and output,
2061
+ // we expect exactly one signature in TaprootScriptSpendSig when the
2062
+ // signing is successful
2063
+ signedUnbondingTx.ins[0].witness,
2064
+ covenantBuffers,
2065
+ covenantUnbondingSignatures,
2066
+ params.covenantQuorum
2067
+ );
2068
+ signedUnbondingTx.ins[0].witness = witness;
2069
+ return {
2070
+ transaction: signedUnbondingTx,
2071
+ fee
2072
+ };
2073
+ }
2074
+ /**
2075
+ * Creates a signed withdrawal transaction on the unbodning output expiry path
2076
+ * that is ready to be sent to the BTC network.
2077
+ * @param stakingInput - The staking inputs.
2078
+ * @param stakingParamsVersion - The params version that was used to create the
2079
+ * delegation in Babylon chain
2080
+ * @param earlyUnbondingTx - The early unbonding transaction.
2081
+ * @param feeRate - The fee rate in satoshis per byte. Typical value for the
2082
+ * fee rate is above 1. If the fee rate is too low, the transaction will not
2083
+ * be included in a block.
2084
+ * @returns The signed withdrawal transaction and its fee.
2085
+ */
2086
+ async createSignedBtcWithdrawEarlyUnbondedTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, earlyUnbondingTx, feeRate) {
2087
+ const params = getBabylonParamByVersion(
2088
+ stakingParamsVersion,
2089
+ this.stakingParams
2090
+ );
2091
+ const staking = new Staking(
2092
+ this.network,
2093
+ stakerBtcInfo,
2094
+ params,
2095
+ stakingInput.finalityProviderPksNoCoordHex,
2096
+ stakingInput.stakingTimelock
2097
+ );
2098
+ const { psbt: unbondingPsbt2, fee } = staking.createWithdrawEarlyUnbondedTransaction(earlyUnbondingTx, feeRate);
2099
+ const contracts = [
2100
+ {
2101
+ id: "babylon:withdraw" /* WITHDRAW */,
2102
+ params: {
2103
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2104
+ timelockBlocks: params.unbondingTime
2105
+ }
2106
+ }
2107
+ ];
2108
+ this.ee?.emit("delegation:withdraw", {
2109
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2110
+ timelockBlocks: params.unbondingTime,
2111
+ type: "early-unbonded"
2112
+ });
2113
+ const signedWithdrawalPsbtHex = await this.btcProvider.signPsbt(
2114
+ unbondingPsbt2.toHex(),
2115
+ {
2116
+ contracts,
2117
+ action: {
2118
+ name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
2119
+ }
2120
+ }
2121
+ );
2122
+ return {
2123
+ transaction: import_bitcoinjs_lib9.Psbt.fromHex(signedWithdrawalPsbtHex).extractTransaction(),
2124
+ fee
2125
+ };
2126
+ }
2127
+ /**
2128
+ * Creates a signed withdrawal transaction on the staking output expiry path
2129
+ * that is ready to be sent to the BTC network.
2130
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
2131
+ * and the no-coord public key in hex format.
2132
+ * @param stakingInput - The staking inputs.
2133
+ * @param stakingParamsVersion - The params version that was used to create the
2134
+ * delegation in Babylon chain
2135
+ * @param stakingTx - The staking transaction.
2136
+ * @param feeRate - The fee rate in satoshis per byte. Typical value for the
2137
+ * fee rate is above 1. If the fee rate is too low, the transaction will not
2138
+ * be included in a block.
2139
+ * @returns The signed withdrawal transaction and its fee.
2140
+ */
2141
+ async createSignedBtcWithdrawStakingExpiredTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx, feeRate) {
2142
+ const params = getBabylonParamByVersion(
2143
+ stakingParamsVersion,
2144
+ this.stakingParams
2145
+ );
2146
+ const staking = new Staking(
2147
+ this.network,
2148
+ stakerBtcInfo,
2149
+ params,
2150
+ stakingInput.finalityProviderPksNoCoordHex,
2151
+ stakingInput.stakingTimelock
2152
+ );
2153
+ const { psbt, fee } = staking.createWithdrawStakingExpiredPsbt(
2154
+ stakingTx,
2155
+ feeRate
2156
+ );
2157
+ const contracts = [
2158
+ {
2159
+ id: "babylon:withdraw" /* WITHDRAW */,
2160
+ params: {
2161
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2162
+ timelockBlocks: stakingInput.stakingTimelock
2163
+ }
2164
+ }
2165
+ ];
2166
+ this.ee?.emit("delegation:withdraw", {
2167
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2168
+ timelockBlocks: stakingInput.stakingTimelock,
2169
+ type: "staking-expired"
2170
+ });
2171
+ const signedWithdrawalPsbtHex = await this.btcProvider.signPsbt(
2172
+ psbt.toHex(),
2173
+ {
2174
+ contracts,
2175
+ action: {
2176
+ name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
2177
+ }
2178
+ }
2179
+ );
2180
+ return {
2181
+ transaction: import_bitcoinjs_lib9.Psbt.fromHex(signedWithdrawalPsbtHex).extractTransaction(),
2182
+ fee
2183
+ };
2184
+ }
2185
+ /**
2186
+ * Creates a signed withdrawal transaction for the expired slashing output that
2187
+ * is ready to be sent to the BTC network.
2188
+ * @param stakerBtcInfo - The staker BTC info which includes the BTC address
2189
+ * and the no-coord public key in hex format.
2190
+ * @param stakingInput - The staking inputs.
2191
+ * @param stakingParamsVersion - The params version that was used to create the
2192
+ * delegation in Babylon chain
2193
+ * @param slashingTx - The slashing transaction.
2194
+ * @param feeRate - The fee rate in satoshis per byte. Typical value for the
2195
+ * fee rate is above 1. If the fee rate is too low, the transaction will not
2196
+ * be included in a block.
2197
+ * @returns The signed withdrawal transaction and its fee.
2198
+ */
2199
+ async createSignedBtcWithdrawSlashingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, slashingTx, feeRate) {
2200
+ const params = getBabylonParamByVersion(
2201
+ stakingParamsVersion,
2202
+ this.stakingParams
2203
+ );
2204
+ const staking = new Staking(
2205
+ this.network,
2206
+ stakerBtcInfo,
2207
+ params,
2208
+ stakingInput.finalityProviderPksNoCoordHex,
2209
+ stakingInput.stakingTimelock
2210
+ );
2211
+ const { psbt, fee } = staking.createWithdrawSlashingPsbt(
2212
+ slashingTx,
2213
+ feeRate
2214
+ );
2215
+ const contracts = [
2216
+ {
2217
+ id: "babylon:withdraw" /* WITHDRAW */,
2218
+ params: {
2219
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2220
+ timelockBlocks: params.unbondingTime
2221
+ }
2222
+ }
2223
+ ];
2224
+ this.ee?.emit("delegation:withdraw", {
2225
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2226
+ timelockBlocks: params.unbondingTime,
2227
+ type: "slashing"
2228
+ });
2229
+ const signedWithrawSlashingPsbtHex = await this.btcProvider.signPsbt(
2230
+ psbt.toHex(),
2231
+ {
2232
+ contracts,
2233
+ action: {
2234
+ name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
2235
+ }
2236
+ }
2237
+ );
2238
+ return {
2239
+ transaction: import_bitcoinjs_lib9.Psbt.fromHex(
2240
+ signedWithrawSlashingPsbtHex
2241
+ ).extractTransaction(),
2242
+ fee
2243
+ };
2244
+ }
2245
+ /**
2246
+ * Creates a proof of possession for the staker based on ECDSA signature.
2247
+ * @param bech32Address - The staker's bech32 address.
2248
+ * @returns The proof of possession.
2249
+ */
2250
+ async createProofOfPossession(channel, bech32Address, stakerBtcAddress) {
2251
+ let sigType = import_pop.BTCSigType.ECDSA;
2252
+ if (isTaproot(stakerBtcAddress, this.network) || isNativeSegwit(stakerBtcAddress, this.network)) {
2253
+ sigType = import_pop.BTCSigType.BIP322;
2254
+ }
2255
+ this.ee?.emit(channel, {
2256
+ bech32Address,
2257
+ type: "proof-of-possession"
2258
+ });
2259
+ const signedBabylonAddress = await this.btcProvider.signMessage(
2260
+ bech32Address,
2261
+ sigType === import_pop.BTCSigType.BIP322 ? "bip322-simple" : "ecdsa"
2262
+ );
2263
+ let btcSig;
2264
+ if (sigType === import_pop.BTCSigType.BIP322) {
2265
+ const bip322Sig = import_pop.BIP322Sig.fromPartial({
2266
+ address: stakerBtcAddress,
2267
+ sig: Buffer.from(signedBabylonAddress, "base64")
2268
+ });
2269
+ btcSig = import_pop.BIP322Sig.encode(bip322Sig).finish();
2270
+ } else {
2271
+ btcSig = Buffer.from(signedBabylonAddress, "base64");
2272
+ }
2273
+ return {
2274
+ btcSigType: sigType,
2275
+ btcSig
2276
+ };
2277
+ }
2278
+ /**
2279
+ * Creates the unbonding, slashing, and unbonding slashing transactions and
2280
+ * PSBTs.
2281
+ * @param stakingInstance - The staking instance.
2282
+ * @param stakingTx - The staking transaction.
2283
+ * @returns The unbonding, slashing, and unbonding slashing transactions and
2284
+ * PSBTs.
2285
+ */
2286
+ async createDelegationTransactionsAndPsbts(stakingInstance, stakingTx) {
2287
+ const { transaction: unbondingTx } = stakingInstance.createUnbondingTransaction(stakingTx);
2288
+ const { psbt: slashingPsbt } = stakingInstance.createStakingOutputSlashingPsbt(stakingTx);
2289
+ const { psbt: unbondingSlashingPsbt } = stakingInstance.createUnbondingOutputSlashingPsbt(unbondingTx);
2290
+ return {
2291
+ unbondingTx,
2292
+ slashingPsbt,
2293
+ unbondingSlashingPsbt
2294
+ };
2295
+ }
2296
+ /**
2297
+ * Creates a protobuf message for the BTC delegation.
2298
+ * @param channel - The event channel to emit the message on.
2299
+ * @param stakingInstance - The staking instance.
2300
+ * @param stakingInput - The staking inputs.
2301
+ * @param stakingTx - The staking transaction.
2302
+ * @param bech32Address - The staker's babylon chain bech32 address
2303
+ * @param stakerBtcInfo - The staker's BTC information such as address and
2304
+ * public key
2305
+ * @param params - The staking parameters.
2306
+ * @param inclusionProof - The inclusion proof of the staking transaction.
2307
+ * @returns The protobuf message.
2308
+ */
2309
+ async createBtcDelegationMsg(channel, stakingInstance, stakingInput, stakingTx, bech32Address, stakerBtcInfo, params, inclusionProof) {
2310
+ if (!params.slashing) {
2311
+ throw new StakingError(
2312
+ "INVALID_PARAMS" /* INVALID_PARAMS */,
2313
+ "Slashing parameters are required for creating delegation message"
2314
+ );
2315
+ }
2316
+ const { unbondingTx, slashingPsbt, unbondingSlashingPsbt } = await this.createDelegationTransactionsAndPsbts(
2317
+ stakingInstance,
2318
+ stakingTx
2319
+ );
2320
+ const slashingContracts = [
2321
+ {
2322
+ id: "babylon:staking" /* STAKING */,
2323
+ params: {
2324
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2325
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
2326
+ covenantPks: params.covenantNoCoordPks,
2327
+ covenantThreshold: params.covenantQuorum,
2328
+ minUnbondingTime: params.unbondingTime,
2329
+ stakingDuration: stakingInput.stakingTimelock
2330
+ }
2331
+ },
2332
+ {
2333
+ id: "babylon:slashing" /* SLASHING */,
2334
+ params: {
2335
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2336
+ unbondingTimeBlocks: params.unbondingTime,
2337
+ slashingFeeSat: params.slashing.minSlashingTxFeeSat
2338
+ }
2339
+ },
2340
+ {
2341
+ id: "babylon:slashing-burn" /* SLASHING_BURN */,
2342
+ params: {
2343
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2344
+ slashingPkScriptHex: params.slashing.slashingPkScriptHex
2345
+ }
2346
+ }
2347
+ ];
2348
+ this.ee?.emit(channel, {
2349
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2350
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
2351
+ covenantPks: params.covenantNoCoordPks,
2352
+ covenantThreshold: params.covenantQuorum,
2353
+ unbondingTimeBlocks: params.unbondingTime,
2354
+ stakingDuration: stakingInput.stakingTimelock,
2355
+ slashingFeeSat: params.slashing.minSlashingTxFeeSat,
2356
+ slashingPkScriptHex: params.slashing.slashingPkScriptHex,
2357
+ type: "staking-slashing"
2358
+ });
2359
+ const signedSlashingPsbtHex = await this.btcProvider.signPsbt(
2360
+ slashingPsbt.toHex(),
2361
+ {
2362
+ contracts: slashingContracts,
2363
+ action: {
2364
+ name: "sign-btc-slashing-transaction" /* SIGN_BTC_SLASHING_TRANSACTION */
2365
+ }
2366
+ }
2367
+ );
2368
+ const signedSlashingTx = import_bitcoinjs_lib9.Psbt.fromHex(
2369
+ signedSlashingPsbtHex
2370
+ ).extractTransaction();
2371
+ const slashingSig = extractFirstSchnorrSignatureFromTransaction(signedSlashingTx);
2372
+ if (!slashingSig) {
2373
+ throw new Error("No signature found in the staking output slashing PSBT");
2374
+ }
2375
+ const unbondingSlashingContracts = [
2376
+ {
2377
+ id: "babylon:unbonding" /* UNBONDING */,
2378
+ params: {
2379
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2380
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
2381
+ covenantPks: params.covenantNoCoordPks,
2382
+ covenantThreshold: params.covenantQuorum,
2383
+ unbondingTimeBlocks: params.unbondingTime,
2384
+ unbondingFeeSat: params.unbondingFeeSat
2385
+ }
2386
+ },
2387
+ {
2388
+ id: "babylon:slashing" /* SLASHING */,
2389
+ params: {
2390
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2391
+ unbondingTimeBlocks: params.unbondingTime,
2392
+ slashingFeeSat: params.slashing.minSlashingTxFeeSat
2393
+ }
2394
+ },
2395
+ {
2396
+ id: "babylon:slashing-burn" /* SLASHING_BURN */,
2397
+ params: {
2398
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2399
+ slashingPkScriptHex: params.slashing.slashingPkScriptHex
2400
+ }
2401
+ }
2402
+ ];
2403
+ this.ee?.emit(channel, {
2404
+ stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
2405
+ finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
2406
+ covenantPks: params.covenantNoCoordPks,
2407
+ covenantThreshold: params.covenantQuorum,
2408
+ unbondingTimeBlocks: params.unbondingTime,
2409
+ unbondingFeeSat: params.unbondingFeeSat,
2410
+ slashingFeeSat: params.slashing.minSlashingTxFeeSat,
2411
+ slashingPkScriptHex: params.slashing.slashingPkScriptHex,
2412
+ type: "unbonding-slashing"
2413
+ });
2414
+ const signedUnbondingSlashingPsbtHex = await this.btcProvider.signPsbt(
2415
+ unbondingSlashingPsbt.toHex(),
2416
+ {
2417
+ contracts: unbondingSlashingContracts,
2418
+ action: {
2419
+ name: "sign-btc-unbonding-slashing-transaction" /* SIGN_BTC_UNBONDING_SLASHING_TRANSACTION */
2420
+ }
2421
+ }
2422
+ );
2423
+ const signedUnbondingSlashingTx = import_bitcoinjs_lib9.Psbt.fromHex(
2424
+ signedUnbondingSlashingPsbtHex
2425
+ ).extractTransaction();
2426
+ const unbondingSignatures = extractFirstSchnorrSignatureFromTransaction(
2427
+ signedUnbondingSlashingTx
2428
+ );
2429
+ if (!unbondingSignatures) {
2430
+ throw new Error(
2431
+ "No signature found in the unbonding output slashing PSBT"
2432
+ );
2433
+ }
2434
+ const proofOfPossession = await this.createProofOfPossession(
2435
+ channel,
2436
+ bech32Address,
2437
+ stakerBtcInfo.address
2438
+ );
2439
+ const msg = import_babylon_proto_ts.btcstakingtx.MsgCreateBTCDelegation.fromPartial({
2440
+ stakerAddr: bech32Address,
2441
+ pop: proofOfPossession,
2442
+ btcPk: Uint8Array.from(
2443
+ Buffer.from(stakerBtcInfo.publicKeyNoCoordHex, "hex")
2444
+ ),
2445
+ fpBtcPkList: stakingInput.finalityProviderPksNoCoordHex.map(
2446
+ (pk) => Uint8Array.from(Buffer.from(pk, "hex"))
2447
+ ),
2448
+ stakingTime: stakingInput.stakingTimelock,
2449
+ stakingValue: stakingInput.stakingAmountSat,
2450
+ stakingTx: Uint8Array.from(stakingTx.toBuffer()),
2451
+ slashingTx: Uint8Array.from(
2452
+ Buffer.from(clearTxSignatures(signedSlashingTx).toHex(), "hex")
2453
+ ),
2454
+ delegatorSlashingSig: Uint8Array.from(slashingSig),
2455
+ unbondingTime: params.unbondingTime,
2456
+ unbondingTx: Uint8Array.from(unbondingTx.toBuffer()),
2457
+ unbondingValue: stakingInput.stakingAmountSat - params.unbondingFeeSat,
2458
+ unbondingSlashingTx: Uint8Array.from(
2459
+ Buffer.from(
2460
+ clearTxSignatures(signedUnbondingSlashingTx).toHex(),
2461
+ "hex"
2462
+ )
2463
+ ),
2464
+ delegatorUnbondingSlashingSig: Uint8Array.from(unbondingSignatures),
2465
+ stakingTxInclusionProof: inclusionProof
2466
+ });
2467
+ return {
2468
+ typeUrl: BABYLON_REGISTRY_TYPE_URLS.MsgCreateBTCDelegation,
2469
+ value: msg
2470
+ };
2471
+ }
2472
+ /**
2473
+ * Gets the inclusion proof for the staking transaction.
2474
+ * See the type `InclusionProof` for more information
2475
+ * @param inclusionProof - The inclusion proof.
2476
+ * @returns The inclusion proof.
2477
+ */
2478
+ getInclusionProof(inclusionProof) {
2479
+ const { pos, merkle, blockHashHex } = inclusionProof;
2480
+ const proofHex = deriveMerkleProof(merkle);
2481
+ const hash = reverseBuffer(
2482
+ Uint8Array.from(Buffer.from(blockHashHex, "hex"))
2483
+ );
2484
+ const inclusionProofKey = import_babylon_proto_ts.btccheckpoint.TransactionKey.fromPartial({
2485
+ index: pos,
2486
+ hash
2487
+ });
2488
+ return import_babylon_proto_ts.btcstaking.InclusionProof.fromPartial({
2489
+ key: inclusionProofKey,
2490
+ proof: Uint8Array.from(Buffer.from(proofHex, "hex"))
2491
+ });
2492
+ }
2493
+ };
2494
+ var extractFirstSchnorrSignatureFromTransaction = (singedTransaction) => {
2495
+ for (const input of singedTransaction.ins) {
2496
+ if (input.witness && input.witness.length > 0) {
2497
+ const schnorrSignature = input.witness[0];
2498
+ if (schnorrSignature.length === 64) {
2499
+ return schnorrSignature;
2500
+ }
2501
+ }
2502
+ }
2503
+ return void 0;
2504
+ };
2505
+ var clearTxSignatures = (tx) => {
2506
+ tx.ins.forEach((input) => {
2507
+ input.script = Buffer.alloc(0);
2508
+ input.witness = [];
2509
+ });
2510
+ return tx;
2511
+ };
2512
+ var deriveMerkleProof = (merkle) => {
2513
+ const proofHex = merkle.reduce((acc, m) => {
2514
+ return acc + Buffer.from(m, "hex").reverse().toString("hex");
2515
+ }, "");
2516
+ return proofHex;
2517
+ };
2518
+ var getUnbondingTxStakerSignature = (unbondingTx) => {
2519
+ try {
2520
+ return unbondingTx.ins[0].witness[0].toString("hex");
2521
+ } catch (error) {
2522
+ throw StakingError.fromUnknown(
2523
+ error,
2524
+ "INVALID_INPUT" /* INVALID_INPUT */,
2525
+ "Failed to get staker signature"
2526
+ );
2527
+ }
2528
+ };
2529
+
2530
+ // src/staking/observable/observableStakingScript.ts
2531
+ var import_bitcoinjs_lib10 = require("bitcoinjs-lib");
2532
+ var ObservableStakingScriptData = class extends StakingScriptData {
2533
+ constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock, magicBytes) {
2534
+ super(
2535
+ stakerKey,
2536
+ finalityProviderKeys,
2537
+ covenantKeys,
2538
+ covenantThreshold,
2539
+ stakingTimelock,
2540
+ unbondingTimelock
2541
+ );
2542
+ if (!magicBytes) {
2543
+ throw new Error("Missing required input values");
2544
+ }
2545
+ if (magicBytes.length != MAGIC_BYTES_LEN) {
2546
+ throw new Error("Invalid script data provided");
2547
+ }
2548
+ this.magicBytes = magicBytes;
2549
+ }
2550
+ /**
2551
+ * Builds a data embed script for staking in the form:
2552
+ * OP_RETURN || <serializedStakingData>
2553
+ * where serializedStakingData is the concatenation of:
2554
+ * MagicBytes || Version || StakerPublicKey || FinalityProviderPublicKey || StakingTimeLock
2555
+ * Note: Only a single finality provider key is supported for now in phase 1
2556
+ * @throws {Error} If the number of finality provider keys is not equal to 1.
2557
+ * @returns {Buffer} The compiled data embed script.
2558
+ */
2559
+ buildDataEmbedScript() {
2560
+ if (this.finalityProviderKeys.length != 1) {
2561
+ throw new Error("Only a single finality provider key is supported");
2562
+ }
2563
+ const version = Buffer.alloc(1);
2564
+ version.writeUInt8(0);
2565
+ const stakingTimeLock = Buffer.alloc(2);
2566
+ stakingTimeLock.writeUInt16BE(this.stakingTimeLock);
2567
+ const serializedStakingData = Buffer.concat([
2568
+ this.magicBytes,
2569
+ version,
2570
+ this.stakerKey,
2571
+ this.finalityProviderKeys[0],
2572
+ stakingTimeLock
2573
+ ]);
2574
+ return import_bitcoinjs_lib10.script.compile([import_bitcoinjs_lib10.opcodes.OP_RETURN, serializedStakingData]);
2575
+ }
2576
+ /**
2577
+ * Builds the staking scripts.
2578
+ * @returns {ObservableStakingScripts} The staking scripts that can be used to stake.
2579
+ * contains the timelockScript, unbondingScript, slashingScript,
2580
+ * unbondingTimelockScript, and dataEmbedScript.
2581
+ * @throws {Error} If script data is invalid.
2582
+ */
2583
+ buildScripts() {
2584
+ const scripts = super.buildScripts();
2585
+ return {
2586
+ ...scripts,
2587
+ dataEmbedScript: this.buildDataEmbedScript()
2588
+ };
2589
+ }
2590
+ };
2591
+
2592
+ // src/staking/observable/index.ts
2593
+ var ObservableStaking = class extends Staking {
2594
+ constructor(network, stakerInfo, params, finalityProviderPksNoCoordHex, stakingTimelock) {
2595
+ super(
2596
+ network,
2597
+ stakerInfo,
2598
+ params,
2599
+ finalityProviderPksNoCoordHex,
2600
+ stakingTimelock
2601
+ );
2602
+ if (!params.tag) {
2603
+ throw new StakingError(
2604
+ "INVALID_INPUT" /* INVALID_INPUT */,
2605
+ "Observable staking parameters must include tag"
2606
+ );
2607
+ }
2608
+ if (!params.btcActivationHeight) {
2609
+ throw new StakingError(
2610
+ "INVALID_INPUT" /* INVALID_INPUT */,
2611
+ "Observable staking parameters must include a positive activation height"
2612
+ );
2613
+ }
2614
+ if (finalityProviderPksNoCoordHex.length !== 1) {
2615
+ throw new StakingError(
2616
+ "INVALID_INPUT" /* INVALID_INPUT */,
2617
+ "Observable staking requires exactly one finality provider public key"
2618
+ );
2619
+ }
2620
+ this.params = params;
2621
+ }
2622
+ /**
2623
+ * Build the staking scripts for observable staking.
2624
+ * This method overwrites the base method to include the OP_RETURN tag based
2625
+ * on the tag provided in the parameters.
2626
+ *
2627
+ * @returns {ObservableStakingScripts} - The staking scripts for observable staking.
2628
+ * @throws {StakingError} - If the scripts cannot be built.
2629
+ */
2630
+ buildScripts() {
2631
+ const { covenantQuorum, covenantNoCoordPks, unbondingTime, tag } = this.params;
2632
+ let stakingScriptData;
2633
+ try {
2634
+ stakingScriptData = new ObservableStakingScriptData(
2635
+ Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex"),
2636
+ this.finalityProviderPksNoCoordHex.map((pk) => Buffer.from(pk, "hex")),
2637
+ toBuffers(covenantNoCoordPks),
2638
+ covenantQuorum,
2639
+ this.stakingTimelock,
2640
+ unbondingTime,
2641
+ Buffer.from(tag, "hex")
2642
+ );
2643
+ } catch (error) {
2644
+ throw StakingError.fromUnknown(
2645
+ error,
2646
+ "SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
2647
+ "Cannot build staking script data"
2648
+ );
2649
+ }
2650
+ let scripts;
2651
+ try {
2652
+ scripts = stakingScriptData.buildScripts();
2653
+ } catch (error) {
2654
+ throw StakingError.fromUnknown(
2655
+ error,
2656
+ "SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
2657
+ "Cannot build staking scripts"
2658
+ );
2659
+ }
2660
+ return scripts;
2661
+ }
2662
+ /**
2663
+ * Create a staking transaction for observable staking.
2664
+ * This overwrites the method from the Staking class with the addtion
2665
+ * of the
2666
+ * 1. OP_RETURN tag in the staking scripts
2667
+ * 2. lockHeight parameter
2668
+ *
2669
+ * @param {number} stakingAmountSat - The amount to stake in satoshis.
2670
+ * @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
2671
+ * transaction.
2672
+ * @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
2673
+ * @returns {TransactionResult} - An object containing the unsigned transaction,
2674
+ * and fee
2675
+ */
2676
+ createStakingTransaction(stakingAmountSat, inputUTXOs, feeRate) {
2677
+ validateStakingTxInputData(
2678
+ stakingAmountSat,
2679
+ this.stakingTimelock,
2680
+ this.params,
2681
+ inputUTXOs,
2682
+ feeRate
2683
+ );
2684
+ const scripts = this.buildScripts();
2685
+ try {
2686
+ const { transaction, fee } = stakingTransaction(
2687
+ scripts,
2688
+ stakingAmountSat,
2689
+ this.stakerInfo.address,
2690
+ inputUTXOs,
2691
+ this.network,
2692
+ feeRate,
2693
+ // `lockHeight` is exclusive of the provided value.
2694
+ // For example, if a Bitcoin height of X is provided,
2695
+ // the transaction will be included starting from height X+1.
2696
+ // https://learnmeabitcoin.com/technical/transaction/locktime/
2697
+ this.params.btcActivationHeight - 1
2698
+ );
2699
+ return {
2700
+ transaction,
2701
+ fee
2702
+ };
2703
+ } catch (error) {
2704
+ throw StakingError.fromUnknown(
2705
+ error,
2706
+ "BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
2707
+ "Cannot build unsigned staking transaction"
2708
+ );
2709
+ }
2710
+ }
2711
+ /**
2712
+ * Create a staking psbt for observable staking.
2713
+ *
2714
+ * @param {Transaction} stakingTx - The staking transaction.
2715
+ * @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
2716
+ * transaction.
2717
+ * @returns {Psbt} - The psbt.
2718
+ */
2719
+ toStakingPsbt(stakingTx, inputUTXOs) {
2720
+ return stakingPsbt(
2721
+ stakingTx,
2722
+ this.network,
2723
+ inputUTXOs,
2724
+ isTaproot(
2725
+ this.stakerInfo.address,
2726
+ this.network
2727
+ ) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
2728
+ );
2729
+ }
2730
+ };
2731
+
2732
+ // src/types/params.ts
2733
+ function hasSlashing(params) {
2734
+ return params.slashing !== void 0;
2735
+ }
2736
+ // Annotate the CommonJS export names for ESM import in node:
2737
+ 0 && (module.exports = {
2738
+ BabylonBtcStakingManager,
2739
+ BitcoinScriptType,
2740
+ ObservableStaking,
2741
+ ObservableStakingScriptData,
2742
+ Staking,
2743
+ StakingScriptData,
2744
+ buildStakingTransactionOutputs,
2745
+ createCovenantWitness,
2746
+ deriveSlashingOutput,
2747
+ deriveStakingOutputInfo,
2748
+ deriveUnbondingOutputInfo,
2749
+ findInputUTXO,
2750
+ findMatchingTxOutputIndex,
2751
+ getBabylonParamByBtcHeight,
2752
+ getBabylonParamByVersion,
2753
+ getPsbtInputFields,
2754
+ getPublicKeyNoCoord,
2755
+ getScriptType,
2756
+ getUnbondingTxStakerSignature,
2757
+ hasSlashing,
2758
+ initBTCCurve,
2759
+ isNativeSegwit,
2760
+ isTaproot,
2761
+ isValidBabylonAddress,
2762
+ isValidBitcoinAddress,
2763
+ isValidNoCoordPublicKey,
2764
+ slashEarlyUnbondedTransaction,
2765
+ slashTimelockUnbondedTransaction,
2766
+ stakingTransaction,
2767
+ toBuffers,
2768
+ transactionIdToHash,
2769
+ unbondingTransaction,
2770
+ validateParams,
2771
+ validateStakingTimelock,
2772
+ validateStakingTxInputData,
2773
+ withdrawEarlyUnbondedTransaction,
2774
+ withdrawSlashingTransaction,
2775
+ withdrawTimelockUnbondedTransaction
2776
+ });
2777
+ //# sourceMappingURL=index.cjs.map