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