@bitgo-beta/babylonlabs-io-btc-staking-ts 0.4.0-beta.0

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