@btc-vision/transaction 1.0.86 → 1.0.87

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.
@@ -1,496 +1,498 @@
1
- import { Psbt, Transaction } from 'bitcoinjs-lib';
2
- import {
3
- IDeploymentParameters,
4
- IFundingTransactionParameters,
5
- IInteractionParameters,
6
- IUnwrapParameters,
7
- IWrapParameters,
8
- } from './interfaces/ITransactionParameters.js';
9
- import { FundingTransaction } from './builders/FundingTransaction.js';
10
- import { Output } from 'bitcoinjs-lib/src/transaction.js';
11
- import { UTXO } from '../utxo/interfaces/IUTXO.js';
12
- import { InteractionTransaction } from './builders/InteractionTransaction.js';
13
- import { DeploymentTransaction } from './builders/DeploymentTransaction.js';
14
- import { Address } from '@btc-vision/bsi-binary';
15
- import { wBTC } from '../metadata/contracts/wBTC.js';
16
- import { WrapTransaction } from './builders/WrapTransaction.js';
17
- import { PSBTTypes } from './psbt/PSBTTypes.js';
18
- import { VaultUTXOs } from './processor/PsbtTransaction.js';
19
- import { UnwrapSegwitTransaction } from './builders/UnwrapSegwitTransaction.js';
20
- import { UnwrapTransaction } from './builders/UnwrapTransaction.js';
21
- import { currentConsensus, currentConsensusConfig } from '../consensus/ConsensusConfig.js';
22
-
23
- export interface DeploymentResult {
24
- readonly transaction: [string, string];
25
-
26
- readonly contractAddress: Address;
27
- readonly p2trAddress: Address;
28
-
29
- readonly utxos: UTXO[];
30
- }
31
-
32
- export interface WrapResult {
33
- readonly transaction: [string, string];
34
- readonly vaultAddress: Address;
35
- readonly amount: bigint;
36
- readonly receiverAddress: Address;
37
- readonly utxos: UTXO[];
38
- }
39
-
40
- export interface UnwrapResult {
41
- readonly fundingTransaction: string;
42
- readonly psbt: string;
43
-
44
- /**
45
- * @description The fee refund or loss.
46
- * @description If the amount is negative, it means that the user has to pay the difference. The difference is deducted from the amount.
47
- * @description If the amount is positive, it means that the user will be refunded the difference.
48
- * @type {bigint}
49
- */
50
- readonly feeRefundOrLoss: bigint;
51
-
52
- readonly utxos: UTXO[];
53
- }
54
-
55
- export class TransactionFactory {
56
- constructor() {}
57
-
58
- /**
59
- * @description Generates the required transactions.
60
- * @returns {Promise<[string, string]>} - The signed transaction
61
- */
62
- public async signInteraction(
63
- interactionParameters: IInteractionParameters,
64
- ): Promise<[string, string, UTXO[]]> {
65
- if (!interactionParameters.to) {
66
- throw new Error('Field "to" not provided.');
67
- }
68
-
69
- if (!interactionParameters.from) {
70
- throw new Error('Field "from" not provided.');
71
- }
72
-
73
- const preTransaction: InteractionTransaction = new InteractionTransaction({
74
- ...interactionParameters,
75
- utxos: [interactionParameters.utxos[0]], // we simulate one input here.
76
- });
77
-
78
- // we don't sign that transaction, we just need the parameters.
79
-
80
- await preTransaction.generateTransactionMinimalSignatures();
81
-
82
- const parameters: IFundingTransactionParameters =
83
- await preTransaction.getFundingTransactionParameters();
84
-
85
- parameters.utxos = interactionParameters.utxos;
86
- parameters.amount = await preTransaction.estimateTransactionFees();
87
-
88
- const feeEstimationFundingTransaction = await this.createFundTransaction({ ...parameters });
89
- if (!feeEstimationFundingTransaction) {
90
- throw new Error('Could not sign funding transaction.');
91
- }
92
-
93
- parameters.estimatedFees = feeEstimationFundingTransaction.estimatedFees;
94
-
95
- const signedTransaction = await this.createFundTransaction(parameters);
96
- if (!signedTransaction) {
97
- throw new Error('Could not sign funding transaction.');
98
- }
99
-
100
- interactionParameters.utxos = this.getUTXOAsTransaction(
101
- signedTransaction.tx,
102
- interactionParameters.to,
103
- 0,
104
- );
105
-
106
- const newParams: IInteractionParameters = {
107
- ...interactionParameters,
108
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, interactionParameters.to, 0), // always 0
109
- randomBytes: preTransaction.getRndBytes(),
110
- nonWitnessUtxo: signedTransaction.tx.toBuffer(),
111
- estimatedFees: preTransaction.estimatedFees,
112
- };
113
-
114
- const finalTransaction: InteractionTransaction = new InteractionTransaction(newParams);
115
-
116
- // We have to regenerate using the new utxo
117
- const outTx: Transaction = await finalTransaction.signTransaction();
118
-
119
- return [
120
- signedTransaction.tx.toHex(),
121
- outTx.toHex(),
122
- this.getUTXOAsTransaction(signedTransaction.tx, interactionParameters.from, 1), // always 1
123
- ];
124
- }
125
-
126
- /**
127
- * @description Generates the required transactions.
128
- * @param {IDeploymentParameters} deploymentParameters - The deployment parameters
129
- * @returns {Promise<DeploymentResult>} - The signed transaction
130
- */
131
- public async signDeployment(
132
- deploymentParameters: IDeploymentParameters,
133
- ): Promise<DeploymentResult> {
134
- const preTransaction: DeploymentTransaction = new DeploymentTransaction(
135
- deploymentParameters,
136
- );
137
-
138
- // Initial generation
139
- await preTransaction.signTransaction();
140
-
141
- const parameters: IFundingTransactionParameters =
142
- await preTransaction.getFundingTransactionParameters();
143
-
144
- const fundingTransaction: FundingTransaction = new FundingTransaction(parameters);
145
- const signedTransaction: Transaction = await fundingTransaction.signTransaction();
146
- if (!signedTransaction) {
147
- throw new Error('Could not sign funding transaction.');
148
- }
149
-
150
- const out: Output = signedTransaction.outs[0];
151
- const newUtxo: UTXO = {
152
- transactionId: signedTransaction.getId(),
153
- outputIndex: 0, // always 0
154
- scriptPubKey: {
155
- hex: out.script.toString('hex'),
156
- address: preTransaction.getScriptAddress(),
157
- },
158
- value: BigInt(out.value),
159
- };
160
-
161
- const newParams: IDeploymentParameters = {
162
- ...deploymentParameters,
163
- utxos: [newUtxo],
164
- randomBytes: preTransaction.getRndBytes(),
165
- nonWitnessUtxo: signedTransaction.toBuffer(),
166
- };
167
-
168
- const finalTransaction: DeploymentTransaction = new DeploymentTransaction(newParams);
169
-
170
- // We have to regenerate using the new utxo
171
- const outTx: Transaction = await finalTransaction.signTransaction();
172
-
173
- const out2: Output = signedTransaction.outs[1];
174
- const refundUTXO: UTXO = {
175
- transactionId: signedTransaction.getId(),
176
- outputIndex: 1, // always 1
177
- scriptPubKey: {
178
- hex: out2.script.toString('hex'),
179
- address: deploymentParameters.from,
180
- },
181
- value: BigInt(out2.value),
182
- };
183
-
184
- return {
185
- transaction: [signedTransaction.toHex(), outTx.toHex()],
186
- contractAddress: finalTransaction.contractAddress,
187
- p2trAddress: finalTransaction.p2trAddress,
188
- utxos: [refundUTXO],
189
- };
190
- }
191
-
192
- /**
193
- * Basically it's fun to manage UTXOs.
194
- * @param {IWrapParameters} warpParameters - The wrap parameters
195
- * @returns {Promise<WrapResult>} - The signed transaction
196
- * @throws {Error} - If the transaction could not be signed
197
- */
198
- public async wrap(warpParameters: Omit<IWrapParameters, 'calldata'>): Promise<WrapResult> {
199
- if (warpParameters.amount < currentConsensusConfig.VAULT_MINIMUM_AMOUNT) {
200
- throw new Error(
201
- `Amount is too low. Minimum consolidation is ${currentConsensusConfig.VAULT_MINIMUM_AMOUNT} sat. Received ${warpParameters.amount} sat. Make sure that you cover the unwrap consolidation fees of ${currentConsensusConfig.UNWRAP_CONSOLIDATION_PREPAID_FEES_SAT}sat.`,
202
- );
203
- }
204
-
205
- const childTransactionRequiredValue: bigint =
206
- warpParameters.amount + currentConsensusConfig.UNWRAP_CONSOLIDATION_PREPAID_FEES_SAT;
207
-
208
- const wbtc: wBTC = new wBTC(warpParameters.network, warpParameters.chainId);
209
- const to = wbtc.getAddress();
210
- const fundingParameters: IFundingTransactionParameters = {
211
- ...warpParameters,
212
- amount: childTransactionRequiredValue,
213
- to: warpParameters.to ?? to,
214
- };
215
-
216
- const preFundingTransaction = await this.createFundTransaction(fundingParameters);
217
- warpParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
218
-
219
- const preTransaction: WrapTransaction = new WrapTransaction(warpParameters);
220
-
221
- // Initial generation
222
- await preTransaction.signTransaction();
223
-
224
- const parameters: IFundingTransactionParameters =
225
- await preTransaction.getFundingTransactionParameters();
226
-
227
- // We add the amount
228
- parameters.amount += childTransactionRequiredValue;
229
- parameters.utxos = fundingParameters.utxos;
230
-
231
- const signedTransaction = await this.createFundTransaction(parameters);
232
- if (!signedTransaction) {
233
- throw new Error('Could not sign funding transaction.');
234
- }
235
-
236
- const newParams: IWrapParameters = {
237
- ...warpParameters,
238
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
239
- randomBytes: preTransaction.getRndBytes(),
240
- nonWitnessUtxo: signedTransaction.tx.toBuffer(),
241
- };
242
-
243
- const finalTransaction: WrapTransaction = new WrapTransaction(newParams);
244
-
245
- // We have to regenerate using the new utxo
246
- const outTx: Transaction = await finalTransaction.signTransaction();
247
- return {
248
- transaction: [signedTransaction.tx.toHex(), outTx.toHex()],
249
- vaultAddress: finalTransaction.vault,
250
- amount: finalTransaction.amount,
251
- receiverAddress: finalTransaction.receiver,
252
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, warpParameters.from, 1),
253
- };
254
- }
255
-
256
- /**
257
- * Unwrap bitcoin.
258
- * @param {IUnwrapParameters} unwrapParameters - The unwrap parameters
259
- * @returns {Promise<UnwrapResult>} - The signed transaction
260
- * @throws {Error} - If the transaction could not be signed
261
- * @deprecated
262
- */
263
- public async unwrapSegwit(unwrapParameters: IUnwrapParameters): Promise<UnwrapResult> {
264
- console.error('The "unwrap" method is deprecated. Use unwrapTap instead.');
265
-
266
- const transaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction(unwrapParameters);
267
- await transaction.signTransaction();
268
-
269
- const to = transaction.toAddress();
270
- if (!to) throw new Error('To address is required');
271
-
272
- // Initial generation
273
- const estimatedGas = await transaction.estimateTransactionFees();
274
- const estimatedFees = transaction.preEstimateTransactionFees(
275
- BigInt(unwrapParameters.feeRate),
276
- this.calculateNumInputs(unwrapParameters.unwrapUTXOs),
277
- 2n,
278
- this.calculateNumSignatures(unwrapParameters.unwrapUTXOs),
279
- this.maxPubKeySize(unwrapParameters.unwrapUTXOs),
280
- );
281
-
282
- const fundingParameters: IFundingTransactionParameters = {
283
- ...unwrapParameters,
284
- amount: estimatedGas + estimatedFees,
285
- to: to,
286
- };
287
-
288
- const preFundingTransaction = await this.createFundTransaction(fundingParameters);
289
- unwrapParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
290
-
291
- const preTransaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction({
292
- ...unwrapParameters,
293
- randomBytes: transaction.getRndBytes(),
294
- });
295
-
296
- // Initial generation
297
- await preTransaction.signTransaction();
298
-
299
- const parameters: IFundingTransactionParameters =
300
- await preTransaction.getFundingTransactionParameters();
301
-
302
- parameters.utxos = fundingParameters.utxos;
303
- parameters.amount = (await preTransaction.estimateTransactionFees()) + estimatedFees;
304
-
305
- const signedTransaction = await this.createFundTransaction(parameters);
306
- if (!signedTransaction) {
307
- throw new Error('Could not sign funding transaction.');
308
- }
309
-
310
- const newParams: IUnwrapParameters = {
311
- ...unwrapParameters,
312
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
313
- randomBytes: preTransaction.getRndBytes(),
314
- nonWitnessUtxo: signedTransaction.tx.toBuffer(),
315
- };
316
-
317
- const finalTransaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction(newParams);
318
-
319
- // We have to regenerate using the new utxo
320
- const outTx: Psbt = await finalTransaction.signPSBT();
321
- const asBase64 = outTx.toBase64();
322
- const psbt = this.writePSBTHeader(PSBTTypes.UNWRAP, asBase64);
323
-
324
- return {
325
- fundingTransaction: signedTransaction.tx.toHex(),
326
- psbt: psbt,
327
- feeRefundOrLoss: estimatedFees,
328
- utxos: [],
329
- };
330
- }
331
-
332
- /**
333
- * Unwrap bitcoin via taproot.
334
- * @param {IUnwrapParameters} unwrapParameters - The unwrap parameters
335
- * @returns {Promise<UnwrapResult>} - The signed transaction
336
- * @throws {Error} - If the transaction could not be signed
337
- */
338
- public async unwrap(unwrapParameters: IUnwrapParameters): Promise<UnwrapResult> {
339
- if (!unwrapParameters.from) {
340
- throw new Error('Field "from" not provided.');
341
- }
342
-
343
- const transaction: UnwrapTransaction = new UnwrapTransaction(unwrapParameters);
344
- await transaction.signTransaction();
345
-
346
- const to = transaction.toAddress();
347
- if (!to) throw new Error('To address is required');
348
-
349
- // Initial generation
350
- const estimatedGas = await transaction.estimateTransactionFees();
351
- const fundingParameters: IFundingTransactionParameters = {
352
- ...unwrapParameters,
353
- amount: estimatedGas,
354
- to: to,
355
- };
356
-
357
- const preFundingTransaction = await this.createFundTransaction(fundingParameters);
358
- unwrapParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
359
-
360
- const preTransaction: UnwrapTransaction = new UnwrapTransaction({
361
- ...unwrapParameters,
362
- randomBytes: transaction.getRndBytes(),
363
- });
364
-
365
- // Initial generation
366
- await preTransaction.signTransaction();
367
-
368
- const parameters: IFundingTransactionParameters =
369
- await preTransaction.getFundingTransactionParameters();
370
-
371
- parameters.utxos = fundingParameters.utxos;
372
- parameters.amount = await preTransaction.estimateTransactionFees();
373
-
374
- const signedTransaction = await this.createFundTransaction(parameters);
375
- if (!signedTransaction) {
376
- throw new Error('Could not sign funding transaction.');
377
- }
378
-
379
- const newParams: IUnwrapParameters = {
380
- ...unwrapParameters,
381
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
382
- randomBytes: preTransaction.getRndBytes(),
383
- nonWitnessUtxo: signedTransaction.tx.toBuffer(),
384
- };
385
-
386
- const finalTransaction: UnwrapTransaction = new UnwrapTransaction(newParams);
387
-
388
- // We have to regenerate using the new utxo
389
- const outTx: Psbt = await finalTransaction.signPSBT();
390
- const asBase64 = outTx.toBase64();
391
- const psbt = this.writePSBTHeader(PSBTTypes.UNWRAP, asBase64);
392
-
393
- return {
394
- fundingTransaction: signedTransaction.tx.toHex(),
395
- psbt: psbt,
396
- feeRefundOrLoss: finalTransaction.getFeeLossOrRefund(),
397
- utxos: this.getUTXOAsTransaction(signedTransaction.tx, unwrapParameters.from, 1),
398
- };
399
- }
400
-
401
- /**
402
- * @description Creates a funding transaction.
403
- * @param {IFundingTransactionParameters} parameters - The funding transaction parameters
404
- * @returns {Promise<{ estimatedFees: bigint; tx: string }>} - The signed transaction
405
- */
406
- public async createBTCTransfer(parameters: IFundingTransactionParameters): Promise<{
407
- estimatedFees: bigint;
408
- tx: string;
409
- nextUTXOs: UTXO[];
410
- }> {
411
- if (!parameters.from) {
412
- throw new Error('Field "from" not provided.');
413
- }
414
-
415
- const resp = await this.createFundTransaction(parameters);
416
-
417
- return {
418
- estimatedFees: resp.estimatedFees,
419
- tx: resp.tx.toHex(),
420
- nextUTXOs: this.getUTXOAsTransaction(resp.tx, parameters.from, 1),
421
- };
422
- }
423
-
424
- private async createFundTransaction(parameters: IFundingTransactionParameters): Promise<{
425
- tx: Transaction;
426
- original: FundingTransaction;
427
- estimatedFees: bigint;
428
- }> {
429
- const fundingTransaction: FundingTransaction = new FundingTransaction(parameters);
430
- const signedTransaction: Transaction = await fundingTransaction.signTransaction();
431
- if (!signedTransaction) {
432
- throw new Error('Could not sign funding transaction.');
433
- }
434
-
435
- return {
436
- tx: signedTransaction,
437
- original: fundingTransaction,
438
- estimatedFees: await fundingTransaction.estimateTransactionFees(),
439
- };
440
- }
441
-
442
- private calculateNumSignatures(vault: VaultUTXOs[]): bigint {
443
- let numSignatures = 0n;
444
-
445
- for (const v of vault) {
446
- numSignatures += BigInt(v.minimum * v.utxos.length);
447
- }
448
-
449
- return numSignatures;
450
- }
451
-
452
- private calculateNumInputs(vault: VaultUTXOs[]): bigint {
453
- let numSignatures = 0n;
454
-
455
- for (const v of vault) {
456
- numSignatures += BigInt(v.utxos.length);
457
- }
458
-
459
- return numSignatures;
460
- }
461
-
462
- private maxPubKeySize(vault: VaultUTXOs[]): bigint {
463
- let size = 0;
464
-
465
- for (const v of vault) {
466
- size = Math.max(size, v.publicKeys.length);
467
- }
468
-
469
- return BigInt(size);
470
- }
471
-
472
- private writePSBTHeader(type: PSBTTypes, psbt: string): string {
473
- const buf = Buffer.from(psbt, 'base64');
474
-
475
- const header = Buffer.alloc(2);
476
- header.writeUInt8(type, 0);
477
- header.writeUInt8(currentConsensus, 1);
478
-
479
- return Buffer.concat([header, buf]).toString('hex');
480
- }
481
-
482
- private getUTXOAsTransaction(tx: Transaction, to: Address, index: number): UTXO[] {
483
- const out: Output = tx.outs[index];
484
- const newUtxo: UTXO = {
485
- transactionId: tx.getId(),
486
- outputIndex: index,
487
- scriptPubKey: {
488
- hex: out.script.toString('hex'),
489
- address: to,
490
- },
491
- value: BigInt(out.value),
492
- };
493
-
494
- return [newUtxo];
495
- }
496
- }
1
+ import { Psbt, Transaction } from 'bitcoinjs-lib';
2
+ import {
3
+ IDeploymentParameters,
4
+ IFundingTransactionParameters,
5
+ IInteractionParameters,
6
+ IUnwrapParameters,
7
+ IWrapParameters,
8
+ } from './interfaces/ITransactionParameters.js';
9
+ import { FundingTransaction } from './builders/FundingTransaction.js';
10
+ import { Output } from 'bitcoinjs-lib/src/transaction.js';
11
+ import { UTXO } from '../utxo/interfaces/IUTXO.js';
12
+ import { InteractionTransaction } from './builders/InteractionTransaction.js';
13
+ import { DeploymentTransaction } from './builders/DeploymentTransaction.js';
14
+ import { Address } from '@btc-vision/bsi-binary';
15
+ import { wBTC } from '../metadata/contracts/wBTC.js';
16
+ import { WrapTransaction } from './builders/WrapTransaction.js';
17
+ import { PSBTTypes } from './psbt/PSBTTypes.js';
18
+ import { VaultUTXOs } from './processor/PsbtTransaction.js';
19
+ import { UnwrapSegwitTransaction } from './builders/UnwrapSegwitTransaction.js';
20
+ import { UnwrapTransaction } from './builders/UnwrapTransaction.js';
21
+ import { currentConsensus, currentConsensusConfig } from '../consensus/ConsensusConfig.js';
22
+
23
+ export interface DeploymentResult {
24
+ readonly transaction: [string, string];
25
+
26
+ readonly contractAddress: Address;
27
+ readonly p2trAddress: Address;
28
+
29
+ readonly utxos: UTXO[];
30
+ }
31
+
32
+ export interface WrapResult {
33
+ readonly transaction: [string, string];
34
+ readonly vaultAddress: Address;
35
+ readonly amount: bigint;
36
+ readonly receiverAddress: Address;
37
+ readonly utxos: UTXO[];
38
+ }
39
+
40
+ export interface UnwrapResult {
41
+ readonly fundingTransaction: string;
42
+ readonly psbt: string;
43
+
44
+ /**
45
+ * @description The fee refund or loss.
46
+ * @description If the amount is negative, it means that the user has to pay the difference. The difference is deducted from the amount.
47
+ * @description If the amount is positive, it means that the user will be refunded the difference.
48
+ * @type {bigint}
49
+ */
50
+ readonly feeRefundOrLoss: bigint;
51
+
52
+ readonly utxos: UTXO[];
53
+ }
54
+
55
+ export class TransactionFactory {
56
+ constructor() {}
57
+
58
+ /**
59
+ * @description Generates the required transactions.
60
+ * @returns {Promise<[string, string]>} - The signed transaction
61
+ */
62
+ public async signInteraction(
63
+ interactionParameters: IInteractionParameters,
64
+ ): Promise<[string, string, UTXO[]]> {
65
+ if (!interactionParameters.to) {
66
+ throw new Error('Field "to" not provided.');
67
+ }
68
+
69
+ if (!interactionParameters.from) {
70
+ throw new Error('Field "from" not provided.');
71
+ }
72
+
73
+ const preTransaction: InteractionTransaction = new InteractionTransaction({
74
+ ...interactionParameters,
75
+ utxos: [interactionParameters.utxos[0]], // we simulate one input here.
76
+ });
77
+
78
+ // we don't sign that transaction, we just need the parameters.
79
+
80
+ await preTransaction.generateTransactionMinimalSignatures();
81
+
82
+ const parameters: IFundingTransactionParameters =
83
+ await preTransaction.getFundingTransactionParameters();
84
+
85
+ parameters.utxos = interactionParameters.utxos;
86
+ parameters.amount = await preTransaction.estimateTransactionFees();
87
+
88
+ const feeEstimationFundingTransaction = await this.createFundTransaction({ ...parameters });
89
+ if (!feeEstimationFundingTransaction) {
90
+ throw new Error('Could not sign funding transaction.');
91
+ }
92
+
93
+ parameters.estimatedFees = feeEstimationFundingTransaction.estimatedFees;
94
+
95
+ const signedTransaction = await this.createFundTransaction(parameters);
96
+ if (!signedTransaction) {
97
+ throw new Error('Could not sign funding transaction.');
98
+ }
99
+
100
+ interactionParameters.utxos = this.getUTXOAsTransaction(
101
+ signedTransaction.tx,
102
+ interactionParameters.to,
103
+ 0,
104
+ );
105
+
106
+ const newParams: IInteractionParameters = {
107
+ ...interactionParameters,
108
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, interactionParameters.to, 0), // always 0
109
+ randomBytes: preTransaction.getRndBytes(),
110
+ nonWitnessUtxo: signedTransaction.tx.toBuffer(),
111
+ estimatedFees: preTransaction.estimatedFees,
112
+ };
113
+
114
+ const finalTransaction: InteractionTransaction = new InteractionTransaction(newParams);
115
+
116
+ // We have to regenerate using the new utxo
117
+ const outTx: Transaction = await finalTransaction.signTransaction();
118
+
119
+ return [
120
+ signedTransaction.tx.toHex(),
121
+ outTx.toHex(),
122
+ this.getUTXOAsTransaction(signedTransaction.tx, interactionParameters.from, 1), // always 1
123
+ ];
124
+ }
125
+
126
+ /**
127
+ * @description Generates the required transactions.
128
+ * @param {IDeploymentParameters} deploymentParameters - The deployment parameters
129
+ * @returns {Promise<DeploymentResult>} - The signed transaction
130
+ */
131
+ public async signDeployment(
132
+ deploymentParameters: IDeploymentParameters,
133
+ ): Promise<DeploymentResult> {
134
+ const preTransaction: DeploymentTransaction = new DeploymentTransaction(
135
+ deploymentParameters,
136
+ );
137
+
138
+ // Initial generation
139
+ await preTransaction.signTransaction();
140
+
141
+ const parameters: IFundingTransactionParameters =
142
+ await preTransaction.getFundingTransactionParameters();
143
+
144
+ const fundingTransaction: FundingTransaction = new FundingTransaction(parameters);
145
+ const signedTransaction: Transaction = await fundingTransaction.signTransaction();
146
+ if (!signedTransaction) {
147
+ throw new Error('Could not sign funding transaction.');
148
+ }
149
+
150
+ const out: Output = signedTransaction.outs[0];
151
+ const newUtxo: UTXO = {
152
+ transactionId: signedTransaction.getId(),
153
+ outputIndex: 0, // always 0
154
+ scriptPubKey: {
155
+ hex: out.script.toString('hex'),
156
+ address: preTransaction.getScriptAddress(),
157
+ },
158
+ value: BigInt(out.value),
159
+ };
160
+
161
+ const newParams: IDeploymentParameters = {
162
+ ...deploymentParameters,
163
+ utxos: [newUtxo],
164
+ randomBytes: preTransaction.getRndBytes(),
165
+ nonWitnessUtxo: signedTransaction.toBuffer(),
166
+ };
167
+
168
+ const finalTransaction: DeploymentTransaction = new DeploymentTransaction(newParams);
169
+
170
+ // We have to regenerate using the new utxo
171
+ const outTx: Transaction = await finalTransaction.signTransaction();
172
+
173
+ const out2: Output = signedTransaction.outs[1];
174
+ const refundUTXO: UTXO = {
175
+ transactionId: signedTransaction.getId(),
176
+ outputIndex: 1, // always 1
177
+ scriptPubKey: {
178
+ hex: out2.script.toString('hex'),
179
+ address: deploymentParameters.from,
180
+ },
181
+ value: BigInt(out2.value),
182
+ };
183
+
184
+ return {
185
+ transaction: [signedTransaction.toHex(), outTx.toHex()],
186
+ contractAddress: finalTransaction.contractAddress,
187
+ p2trAddress: finalTransaction.p2trAddress,
188
+ utxos: [refundUTXO],
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Basically it's fun to manage UTXOs.
194
+ * @param {IWrapParameters} warpParameters - The wrap parameters
195
+ * @returns {Promise<WrapResult>} - The signed transaction
196
+ * @throws {Error} - If the transaction could not be signed
197
+ */
198
+ public async wrap(warpParameters: Omit<IWrapParameters, 'calldata'>): Promise<WrapResult> {
199
+ if (warpParameters.amount < currentConsensusConfig.VAULT_MINIMUM_AMOUNT) {
200
+ throw new Error(
201
+ `Amount is too low. Minimum consolidation is ${currentConsensusConfig.VAULT_MINIMUM_AMOUNT} sat. Received ${warpParameters.amount} sat. Make sure that you cover the unwrap consolidation fees of ${currentConsensusConfig.UNWRAP_CONSOLIDATION_PREPAID_FEES_SAT}sat.`,
202
+ );
203
+ }
204
+
205
+ const childTransactionRequiredValue: bigint =
206
+ warpParameters.amount + currentConsensusConfig.UNWRAP_CONSOLIDATION_PREPAID_FEES_SAT;
207
+
208
+ const wbtc: wBTC = new wBTC(warpParameters.network, warpParameters.chainId);
209
+ const to = wbtc.getAddress();
210
+ const fundingParameters: IFundingTransactionParameters = {
211
+ ...warpParameters,
212
+ amount: childTransactionRequiredValue,
213
+ to: warpParameters.to ?? to,
214
+ };
215
+
216
+ const preFundingTransaction = await this.createFundTransaction(fundingParameters);
217
+ warpParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
218
+
219
+ const preTransaction: WrapTransaction = new WrapTransaction(warpParameters);
220
+
221
+ // Initial generation
222
+ await preTransaction.signTransaction();
223
+
224
+ const parameters: IFundingTransactionParameters =
225
+ await preTransaction.getFundingTransactionParameters();
226
+
227
+ // We add the amount
228
+ parameters.amount += childTransactionRequiredValue;
229
+ parameters.utxos = fundingParameters.utxos;
230
+
231
+ const signedTransaction = await this.createFundTransaction(parameters);
232
+ if (!signedTransaction) {
233
+ throw new Error('Could not sign funding transaction.');
234
+ }
235
+
236
+ const newParams: IWrapParameters = {
237
+ ...warpParameters,
238
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
239
+ randomBytes: preTransaction.getRndBytes(),
240
+ nonWitnessUtxo: signedTransaction.tx.toBuffer(),
241
+ };
242
+
243
+ const finalTransaction: WrapTransaction = new WrapTransaction(newParams);
244
+
245
+ // We have to regenerate using the new utxo
246
+ const outTx: Transaction = await finalTransaction.signTransaction();
247
+ return {
248
+ transaction: [signedTransaction.tx.toHex(), outTx.toHex()],
249
+ vaultAddress: finalTransaction.vault,
250
+ amount: finalTransaction.amount,
251
+ receiverAddress: finalTransaction.receiver,
252
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, warpParameters.from, 1),
253
+ };
254
+ }
255
+
256
+ /**
257
+ * Unwrap bitcoin.
258
+ * @param {IUnwrapParameters} unwrapParameters - The unwrap parameters
259
+ * @returns {Promise<UnwrapResult>} - The signed transaction
260
+ * @throws {Error} - If the transaction could not be signed
261
+ * @deprecated
262
+ */
263
+ public async unwrapSegwit(unwrapParameters: IUnwrapParameters): Promise<UnwrapResult> {
264
+ console.error('The "unwrap" method is deprecated. Use unwrapTap instead.');
265
+
266
+ const transaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction(unwrapParameters);
267
+ await transaction.signTransaction();
268
+
269
+ const to = transaction.toAddress();
270
+ if (!to) throw new Error('To address is required');
271
+
272
+ // Initial generation
273
+ const estimatedGas = await transaction.estimateTransactionFees();
274
+ const estimatedFees = transaction.preEstimateTransactionFees(
275
+ BigInt(unwrapParameters.feeRate),
276
+ this.calculateNumInputs(unwrapParameters.unwrapUTXOs),
277
+ 2n,
278
+ this.calculateNumSignatures(unwrapParameters.unwrapUTXOs),
279
+ this.maxPubKeySize(unwrapParameters.unwrapUTXOs),
280
+ );
281
+
282
+ const fundingParameters: IFundingTransactionParameters = {
283
+ ...unwrapParameters,
284
+ amount: estimatedGas + estimatedFees,
285
+ to: to,
286
+ };
287
+
288
+ const preFundingTransaction = await this.createFundTransaction(fundingParameters);
289
+ unwrapParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
290
+
291
+ const preTransaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction({
292
+ ...unwrapParameters,
293
+ randomBytes: transaction.getRndBytes(),
294
+ });
295
+
296
+ // Initial generation
297
+ await preTransaction.signTransaction();
298
+
299
+ const parameters: IFundingTransactionParameters =
300
+ await preTransaction.getFundingTransactionParameters();
301
+
302
+ parameters.utxos = fundingParameters.utxos;
303
+ parameters.amount = (await preTransaction.estimateTransactionFees()) + estimatedFees;
304
+
305
+ const signedTransaction = await this.createFundTransaction(parameters);
306
+ if (!signedTransaction) {
307
+ throw new Error('Could not sign funding transaction.');
308
+ }
309
+
310
+ const newParams: IUnwrapParameters = {
311
+ ...unwrapParameters,
312
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
313
+ randomBytes: preTransaction.getRndBytes(),
314
+ nonWitnessUtxo: signedTransaction.tx.toBuffer(),
315
+ };
316
+
317
+ const finalTransaction: UnwrapSegwitTransaction = new UnwrapSegwitTransaction(newParams);
318
+
319
+ // We have to regenerate using the new utxo
320
+ const outTx: Psbt = await finalTransaction.signPSBT();
321
+ const asBase64 = outTx.toBase64();
322
+ const psbt = this.writePSBTHeader(PSBTTypes.UNWRAP, asBase64);
323
+
324
+ return {
325
+ fundingTransaction: signedTransaction.tx.toHex(),
326
+ psbt: psbt,
327
+ feeRefundOrLoss: estimatedFees,
328
+ utxos: [],
329
+ };
330
+ }
331
+
332
+ /**
333
+ * Unwrap bitcoin via taproot.
334
+ * @param {IUnwrapParameters} unwrapParameters - The unwrap parameters
335
+ * @returns {Promise<UnwrapResult>} - The signed transaction
336
+ * @throws {Error} - If the transaction could not be signed
337
+ */
338
+ public async unwrap(unwrapParameters: IUnwrapParameters): Promise<UnwrapResult> {
339
+ if (!unwrapParameters.from) {
340
+ throw new Error('Field "from" not provided.');
341
+ }
342
+
343
+ const transaction: UnwrapTransaction = new UnwrapTransaction(unwrapParameters);
344
+ await transaction.signTransaction();
345
+
346
+ const to = transaction.toAddress();
347
+ if (!to) throw new Error('To address is required');
348
+
349
+ // Initial generation
350
+ const estimatedGas = await transaction.estimateTransactionFees();
351
+ const fundingParameters: IFundingTransactionParameters = {
352
+ ...unwrapParameters,
353
+ amount: estimatedGas,
354
+ to: to,
355
+ };
356
+
357
+ const preFundingTransaction = await this.createFundTransaction(fundingParameters);
358
+ unwrapParameters.utxos = this.getUTXOAsTransaction(preFundingTransaction.tx, to, 0);
359
+
360
+ const preTransaction: UnwrapTransaction = new UnwrapTransaction({
361
+ ...unwrapParameters,
362
+ randomBytes: transaction.getRndBytes(),
363
+ });
364
+
365
+ // Initial generation
366
+ await preTransaction.signTransaction();
367
+
368
+ const parameters: IFundingTransactionParameters =
369
+ await preTransaction.getFundingTransactionParameters();
370
+
371
+ parameters.utxos = fundingParameters.utxos;
372
+ parameters.amount = await preTransaction.estimateTransactionFees();
373
+
374
+ const signedTransaction = await this.createFundTransaction(parameters);
375
+ if (!signedTransaction) {
376
+ throw new Error('Could not sign funding transaction.');
377
+ }
378
+
379
+ const newParams: IUnwrapParameters = {
380
+ ...unwrapParameters,
381
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, to, 0), // always 0
382
+ randomBytes: preTransaction.getRndBytes(),
383
+ nonWitnessUtxo: signedTransaction.tx.toBuffer(),
384
+ };
385
+
386
+ const finalTransaction: UnwrapTransaction = new UnwrapTransaction(newParams);
387
+
388
+ // We have to regenerate using the new utxo
389
+ const outTx: Psbt = await finalTransaction.signPSBT();
390
+ const asBase64 = outTx.toBase64();
391
+ const psbt = this.writePSBTHeader(PSBTTypes.UNWRAP, asBase64);
392
+
393
+ return {
394
+ fundingTransaction: signedTransaction.tx.toHex(),
395
+ psbt: psbt,
396
+ feeRefundOrLoss: finalTransaction.getFeeLossOrRefund(),
397
+ utxos: this.getUTXOAsTransaction(signedTransaction.tx, unwrapParameters.from, 1),
398
+ };
399
+ }
400
+
401
+ /**
402
+ * @description Creates a funding transaction.
403
+ * @param {IFundingTransactionParameters} parameters - The funding transaction parameters
404
+ * @returns {Promise<{ estimatedFees: bigint; tx: string }>} - The signed transaction
405
+ */
406
+ public async createBTCTransfer(parameters: IFundingTransactionParameters): Promise<{
407
+ estimatedFees: bigint;
408
+ tx: string;
409
+ nextUTXOs: UTXO[];
410
+ }> {
411
+ if (!parameters.from) {
412
+ throw new Error('Field "from" not provided.');
413
+ }
414
+
415
+ const resp = await this.createFundTransaction(parameters);
416
+
417
+ return {
418
+ estimatedFees: resp.estimatedFees,
419
+ tx: resp.tx.toHex(),
420
+ nextUTXOs: this.getUTXOAsTransaction(resp.tx, parameters.from, 1),
421
+ };
422
+ }
423
+
424
+ private async createFundTransaction(parameters: IFundingTransactionParameters): Promise<{
425
+ tx: Transaction;
426
+ original: FundingTransaction;
427
+ estimatedFees: bigint;
428
+ }> {
429
+ const fundingTransaction: FundingTransaction = new FundingTransaction(parameters);
430
+ const signedTransaction: Transaction = await fundingTransaction.signTransaction();
431
+ if (!signedTransaction) {
432
+ throw new Error('Could not sign funding transaction.');
433
+ }
434
+
435
+ return {
436
+ tx: signedTransaction,
437
+ original: fundingTransaction,
438
+ estimatedFees: await fundingTransaction.estimateTransactionFees(),
439
+ };
440
+ }
441
+
442
+ private calculateNumSignatures(vault: VaultUTXOs[]): bigint {
443
+ let numSignatures = 0n;
444
+
445
+ for (const v of vault) {
446
+ numSignatures += BigInt(v.minimum * v.utxos.length);
447
+ }
448
+
449
+ return numSignatures;
450
+ }
451
+
452
+ private calculateNumInputs(vault: VaultUTXOs[]): bigint {
453
+ let numSignatures = 0n;
454
+
455
+ for (const v of vault) {
456
+ numSignatures += BigInt(v.utxos.length);
457
+ }
458
+
459
+ return numSignatures;
460
+ }
461
+
462
+ private maxPubKeySize(vault: VaultUTXOs[]): bigint {
463
+ let size = 0;
464
+
465
+ for (const v of vault) {
466
+ size = Math.max(size, v.publicKeys.length);
467
+ }
468
+
469
+ return BigInt(size);
470
+ }
471
+
472
+ private writePSBTHeader(type: PSBTTypes, psbt: string): string {
473
+ const buf = Buffer.from(psbt, 'base64');
474
+
475
+ const header = Buffer.alloc(2);
476
+ header.writeUInt8(type, 0);
477
+ header.writeUInt8(currentConsensus, 1);
478
+
479
+ return Buffer.concat([header, buf]).toString('hex');
480
+ }
481
+
482
+ private getUTXOAsTransaction(tx: Transaction, to: Address, index: number): UTXO[] {
483
+ if (!tx.outs[index]) return [];
484
+
485
+ const out: Output = tx.outs[index];
486
+ const newUtxo: UTXO = {
487
+ transactionId: tx.getId(),
488
+ outputIndex: index,
489
+ scriptPubKey: {
490
+ hex: out.script.toString('hex'),
491
+ address: to,
492
+ },
493
+ value: BigInt(out.value),
494
+ };
495
+
496
+ return [newUtxo];
497
+ }
498
+ }