@babylonlabs-io/ts-sdk 0.49.0 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1011 @@
1
+ var J = Object.defineProperty;
2
+ var Z = (e, r, t) => r in e ? J(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t;
3
+ var $ = (e, r, t) => Z(e, typeof r != "symbol" ? r + "" : r, t);
4
+ import { B as ee } from "./BTCVaultRegistry.abi-Chs4AFBj.js";
5
+ import { e as te, v as re, s as p, u as X, p as A, f as E } from "./bitcoin-B5aNKtsk.js";
6
+ import { v as ne, P as oe, f as ae } from "./PayoutManager-D26nGR-e.js";
7
+ import { D as w, c as se, a as ie, R as ue, d as z } from "./types-CQDRQvV-.js";
8
+ import { Transaction as C, Psbt as le } from "bitcoinjs-lib";
9
+ import { c as ce, d as V, e as N, f as H } from "./verifyScriptPathSchnorrSignature-CeZp6tMw.js";
10
+ import { c as he, a as de, b as pe } from "./noPayout-C1WCsqfd.js";
11
+ import { c as O } from "./signing-DaLvGwQe.js";
12
+ const ge = /^0x[0-9a-fA-F]{64}$/, fe = /^0x[0-9a-fA-F]{40}$/, me = /^0x([0-9a-fA-F]{2})*$/;
13
+ function B(e, r) {
14
+ if (e.length !== 66)
15
+ throw new Error(
16
+ `${r} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`
17
+ );
18
+ if (!ge.test(e))
19
+ throw new Error(
20
+ `${r} must contain only hex characters after the 0x prefix`
21
+ );
22
+ }
23
+ function Pe(e, r) {
24
+ if (!fe.test(e))
25
+ throw new Error(
26
+ `${r} must be a 20-byte 0x-prefixed hex address (42 chars)`
27
+ );
28
+ }
29
+ function be(e, r) {
30
+ if (!me.test(e))
31
+ throw new Error(
32
+ `${r} must be a 0x-prefixed hex string with an even number of hex chars`
33
+ );
34
+ }
35
+ async function st(e) {
36
+ const {
37
+ btcVaultRegistryAddress: r,
38
+ vaultId: t,
39
+ hashlock: n,
40
+ activationMetadata: s,
41
+ writeContract: u,
42
+ signal: a
43
+ } = e;
44
+ a == null || a.throwIfAborted(), Pe(r, "btcVaultRegistryAddress"), B(t, "vaultId");
45
+ const i = te(e.secret);
46
+ if (B(i, "secret"), n !== void 0 && (B(n, "hashlock"), !ne(i, n)))
47
+ throw new Error(
48
+ "Invalid secret: SHA256(secret) does not match the provided hashlock"
49
+ );
50
+ return be(s, "activationMetadata"), u({
51
+ address: r,
52
+ abi: ee,
53
+ functionName: "activateVaultWithSecret",
54
+ args: [t, i, s]
55
+ });
56
+ }
57
+ const ye = 1e4;
58
+ async function G(e) {
59
+ const {
60
+ statusReader: r,
61
+ peginTxid: t,
62
+ targetStatuses: n,
63
+ timeoutMs: s,
64
+ pollIntervalMs: u = ye,
65
+ signal: a
66
+ } = e, i = Date.now();
67
+ for (; ; ) {
68
+ if (a != null && a.aborted)
69
+ throw new Error(
70
+ `Polling aborted for pegin ${t.slice(0, 8)}… (target: ${[...n].join(", ")})`
71
+ );
72
+ if (Date.now() - i >= s)
73
+ throw new Error(
74
+ `Polling timeout after ${s}ms for pegin ${t.slice(0, 8)}… (target: ${[...n].join(", ")})`
75
+ );
76
+ try {
77
+ const o = await r.getPeginStatus(
78
+ { pegin_txid: t },
79
+ a
80
+ );
81
+ if (o.pegin_txid.toLowerCase() !== t.toLowerCase())
82
+ throw new Error(
83
+ `getPeginStatus returned status for pegin ${o.pegin_txid.slice(0, 8)}…, requested ${t.slice(0, 8)}…`
84
+ );
85
+ const l = o.status;
86
+ if (n.has(l) || l === w.ACTIVATED)
87
+ return l;
88
+ if (l === w.EXPIRED || se.has(l))
89
+ throw new Error(
90
+ `Pegin ${t.slice(0, 8)}… reached terminal status "${l}" while waiting for ${[...n].join(", ")}`
91
+ );
92
+ } catch (o) {
93
+ if (!(o instanceof ie && o.code === ue.PEGIN_NOT_FOUND))
94
+ throw o;
95
+ }
96
+ await new Promise((o, l) => {
97
+ const h = () => {
98
+ clearTimeout(c), l(
99
+ new Error(
100
+ `Polling aborted for pegin ${t.slice(0, 8)}… (target: ${[...n].join(", ")})`
101
+ )
102
+ );
103
+ }, c = setTimeout(() => {
104
+ a == null || a.removeEventListener("abort", h), o();
105
+ }, u);
106
+ a == null || a.addEventListener("abort", h, { once: !0 });
107
+ });
108
+ }
109
+ }
110
+ const we = 300 * 1e3, xe = /* @__PURE__ */ new Set([
111
+ w.PENDING_DEPOSITOR_WOTS_PK,
112
+ ...z
113
+ ]);
114
+ async function it(e) {
115
+ const {
116
+ statusReader: r,
117
+ wotsSubmitter: t,
118
+ peginTxid: n,
119
+ depositorPk: s,
120
+ wotsPublicKeys: u,
121
+ timeoutMs: a = we,
122
+ signal: i
123
+ } = e;
124
+ i == null || i.throwIfAborted();
125
+ const o = await G({
126
+ statusReader: r,
127
+ peginTxid: n,
128
+ targetStatuses: xe,
129
+ timeoutMs: a,
130
+ signal: i
131
+ });
132
+ z.has(o) || (i == null || i.throwIfAborted(), await t.submitDepositorWotsKey(
133
+ {
134
+ pegin_txid: n,
135
+ depositor_pk: s,
136
+ wots_public_keys: u
137
+ },
138
+ i
139
+ ));
140
+ }
141
+ const K = 1, ve = 1;
142
+ function Ee(e, r) {
143
+ const t = p(r).toLowerCase(), s = e.map((u) => p(u).toLowerCase()).filter((u) => u !== t);
144
+ if (s.length === 0)
145
+ throw new Error(
146
+ "Cannot derive localChallengers: vault keeper set is empty (or contains only the depositor)"
147
+ );
148
+ if (new Set(s).size !== s.length)
149
+ throw new Error(
150
+ "Cannot derive localChallengers: duplicate vaultKeeper key — signing context is misconfigured"
151
+ );
152
+ return s;
153
+ }
154
+ function Te(e, r, t) {
155
+ const n = t.map(
156
+ (c) => p(c).toLowerCase()
157
+ ), s = r.filter((c) => n.includes(c));
158
+ if (s.length > 0)
159
+ throw new Error(
160
+ `Cannot validate challenger set: vault keepers and universal challengers overlap (${s.join(", ")})`
161
+ );
162
+ const u = [...r, ...n], a = e.map(
163
+ (c) => p(c.challenger_pubkey).toLowerCase()
164
+ ), i = new Set(a);
165
+ if (i.size !== a.length)
166
+ throw new Error(
167
+ "Depositor graph contains duplicate challenger entries in challenger_presign_data"
168
+ );
169
+ const o = new Set(u), l = u.filter((c) => !i.has(c)), h = a.filter((c) => !o.has(c));
170
+ if (l.length > 0 || h.length > 0)
171
+ throw new Error(
172
+ "Depositor graph challenger set does not match expected (local ∪ universal)" + (l.length > 0 ? ` (missing: ${l.join(", ")})` : "") + (h.length > 0 ? ` (unexpected: ${h.join(", ")})` : "")
173
+ );
174
+ }
175
+ function ke(e, r) {
176
+ const t = e.ins[r];
177
+ return X(new Uint8Array(t.hash).slice().reverse());
178
+ }
179
+ function R(e, r, t, n, s) {
180
+ const u = e.ins[r];
181
+ if (u.index !== 0)
182
+ throw new Error(
183
+ `NoPayout (challenger ${s}) input ${r} expected to spend ${n} vout 0, got vout ${u.index}`
184
+ );
185
+ const a = t.getId(), i = ke(e, r);
186
+ if (i !== a)
187
+ throw new Error(
188
+ `NoPayout (challenger ${s}) input ${r} does not reference ${n} (expected txid ${a}, got ${i})`
189
+ );
190
+ }
191
+ async function _e(e, r, t) {
192
+ const n = [], s = [], u = [], a = Ee(
193
+ t.vaultKeeperBtcPubkeys,
194
+ t.depositorBtcPubkey
195
+ );
196
+ Te(
197
+ e.challenger_presign_data,
198
+ a,
199
+ t.universalChallengerBtcPubkeys
200
+ );
201
+ const i = await ce({
202
+ payoutTxHex: e.payout_tx.tx_hex,
203
+ peginTxHex: t.peginTxHex,
204
+ assertTxHex: e.assert_tx.tx_hex,
205
+ depositorBtcPubkey: t.depositorBtcPubkey,
206
+ vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
207
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
208
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
209
+ timelockPegin: t.timelockPegin,
210
+ network: t.network,
211
+ claimerBtcPubkey: t.depositorBtcPubkey,
212
+ registeredPayoutScriptPubKey: t.registeredPayoutScriptPubKey,
213
+ commissionBps: ve
214
+ });
215
+ n.push(i.psbtHex), s.push(
216
+ O(
217
+ r,
218
+ K
219
+ )
220
+ );
221
+ const o = p(t.depositorBtcPubkey), l = C.fromHex(
222
+ p(e.assert_tx.tx_hex)
223
+ );
224
+ for (const h of e.challenger_presign_data) {
225
+ const c = p(h.challenger_pubkey), d = n.length, P = await Se({
226
+ challenger: h,
227
+ challengerPubkey: c,
228
+ claimerPubkey: o,
229
+ localChallengers: a,
230
+ assertTxParsed: l,
231
+ ctx: t
232
+ });
233
+ n.push(P), s.push(
234
+ O(
235
+ r,
236
+ K
237
+ )
238
+ ), u.push({
239
+ challengerPubkey: c,
240
+ noPayoutIdx: d
241
+ });
242
+ }
243
+ return { psbtHexes: n, signOptions: s, challengerEntries: u };
244
+ }
245
+ async function Se(e) {
246
+ const {
247
+ challenger: r,
248
+ challengerPubkey: t,
249
+ claimerPubkey: n,
250
+ localChallengers: s,
251
+ assertTxParsed: u,
252
+ ctx: a
253
+ } = e;
254
+ he(
255
+ r.nopayout_tx.tx_hex,
256
+ t,
257
+ a.network
258
+ );
259
+ const i = C.fromHex(
260
+ p(r.nopayout_tx.tx_hex)
261
+ ), o = C.fromHex(
262
+ p(r.challenge_assert_x_tx.tx_hex)
263
+ ), l = C.fromHex(
264
+ p(r.challenge_assert_y_tx.tx_hex)
265
+ );
266
+ if (i.ins.length !== 3)
267
+ throw new Error(
268
+ `NoPayout (challenger ${t}) must have exactly 3 inputs, got ${i.ins.length}`
269
+ );
270
+ R(
271
+ i,
272
+ 0,
273
+ u,
274
+ "Assert",
275
+ t
276
+ ), R(
277
+ i,
278
+ 1,
279
+ o,
280
+ "ChallengeAssertX",
281
+ t
282
+ ), R(
283
+ i,
284
+ 2,
285
+ l,
286
+ "ChallengeAssertY",
287
+ t
288
+ );
289
+ const h = [
290
+ u.outs[0],
291
+ o.outs[0],
292
+ l.outs[0]
293
+ ].map((c) => ({
294
+ script_pubkey: X(new Uint8Array(c.script)),
295
+ value: c.value
296
+ }));
297
+ return de({
298
+ noPayoutTxHex: r.nopayout_tx.tx_hex,
299
+ challengerPubkey: t,
300
+ prevouts: h,
301
+ connectorParams: {
302
+ claimer: n,
303
+ localChallengers: s,
304
+ universalChallengers: a.universalChallengerBtcPubkeys,
305
+ timelockAssert: a.timelockAssert,
306
+ councilMembers: a.councilMembers,
307
+ councilQuorum: a.councilQuorum
308
+ }
309
+ });
310
+ }
311
+ function Ce(e, r, t) {
312
+ V(e[0]);
313
+ const s = N(
314
+ e[0].returnedPsbtHex,
315
+ t
316
+ );
317
+ H({
318
+ requestedPsbtHex: e[0].requestedPsbtHex,
319
+ signatureHex: s,
320
+ signerXOnlyPubkeyHex: t,
321
+ inputIndex: 0
322
+ });
323
+ const u = {};
324
+ for (const a of r) {
325
+ V(e[a.noPayoutIdx]);
326
+ const i = N(
327
+ e[a.noPayoutIdx].returnedPsbtHex,
328
+ t
329
+ );
330
+ H({
331
+ requestedPsbtHex: e[a.noPayoutIdx].requestedPsbtHex,
332
+ signatureHex: i,
333
+ signerXOnlyPubkeyHex: t,
334
+ inputIndex: 0
335
+ }), u[a.challengerPubkey] = {
336
+ nopayout_signature: i
337
+ };
338
+ }
339
+ return {
340
+ payout_signatures: {
341
+ payout_signature: s
342
+ },
343
+ per_challenger: u
344
+ };
345
+ }
346
+ async function Ae(e, r, t) {
347
+ if (typeof e.signPsbts == "function")
348
+ return e.signPsbts(r, t);
349
+ const n = [];
350
+ for (let s = 0; s < r.length; s++)
351
+ n.push(await e.signPsbt(r[s], t == null ? void 0 : t[s]));
352
+ return n;
353
+ }
354
+ async function $e(e) {
355
+ const { depositorGraph: r, btcWallet: t, signingContext: n } = e, s = await t.getPublicKeyHex(), { depositorPubkey: u } = re(
356
+ s,
357
+ p(n.depositorBtcPubkey)
358
+ ), { psbtHexes: a, signOptions: i, challengerEntries: o } = await _e(
359
+ r,
360
+ s,
361
+ n
362
+ ), l = await Ae(
363
+ t,
364
+ a,
365
+ i
366
+ );
367
+ if (l.length !== a.length)
368
+ throw new Error(
369
+ `Wallet returned ${l.length} signed PSBTs, expected ${a.length}`
370
+ );
371
+ const h = a.map((c, d) => ({
372
+ requestedPsbtHex: c,
373
+ returnedPsbtHex: l[d]
374
+ }));
375
+ return Ce(
376
+ h,
377
+ o,
378
+ u
379
+ );
380
+ }
381
+ const Be = 1200 * 1e3, q = /* @__PURE__ */ new Set([
382
+ w.PENDING_ACKS,
383
+ w.PENDING_ACTIVATION,
384
+ w.ACTIVATED_PENDING_BROADCAST,
385
+ w.ACTIVATED
386
+ ]), Re = /* @__PURE__ */ new Set([
387
+ w.PENDING_DEPOSITOR_SIGNATURES,
388
+ ...q
389
+ ]);
390
+ function Ie(e) {
391
+ return e.map((r) => ({
392
+ claimerPubkeyXOnly: A(r.claimer_pubkey),
393
+ payoutTxHex: r.payout_tx.tx_hex,
394
+ assertTxHex: r.assert_tx.tx_hex
395
+ }));
396
+ }
397
+ function _(e) {
398
+ return A(e).toLowerCase();
399
+ }
400
+ function Ve(e, r, t, n) {
401
+ const s = _(n), u = [
402
+ _(r),
403
+ ...t.map(_)
404
+ ], a = new Set(u);
405
+ if (a.size !== u.length)
406
+ throw new Error(
407
+ "Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key"
408
+ );
409
+ if (a.has(s))
410
+ throw new Error(
411
+ "Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set"
412
+ );
413
+ const i = e.map(
414
+ (d) => _(d.claimer_pubkey)
415
+ );
416
+ if (new Set(i).size !== i.length)
417
+ throw new Error(
418
+ "Presign response contains duplicate claimer entries"
419
+ );
420
+ const o = i.filter((d) => d !== s), l = new Set(o), h = u.filter((d) => !l.has(d)), c = o.filter((d) => !a.has(d));
421
+ if (h.length > 0 || c.length > 0)
422
+ throw new Error(
423
+ "Presign response claimer set does not match expected (vault provider ∪ vault keepers)" + (h.length > 0 ? ` (missing: ${h.join(", ")})` : "") + (c.length > 0 ? ` (unexpected: ${c.join(", ")})` : "")
424
+ );
425
+ }
426
+ function U(e, r) {
427
+ return {
428
+ payoutTxHex: e.payoutTxHex,
429
+ peginTxHex: r.peginTxHex,
430
+ assertTxHex: e.assertTxHex,
431
+ vaultProviderBtcPubkey: r.vaultProviderBtcPubkey,
432
+ vaultKeeperBtcPubkeys: r.vaultKeeperBtcPubkeys,
433
+ universalChallengerBtcPubkeys: r.universalChallengerBtcPubkeys,
434
+ depositorBtcPubkey: r.depositorBtcPubkey,
435
+ timelockPegin: r.timelockPegin,
436
+ registeredPayoutScriptPubKey: r.registeredPayoutScriptPubKey,
437
+ claimerBtcPubkey: e.claimerPubkeyXOnly,
438
+ commissionBps: r.commissionBps
439
+ };
440
+ }
441
+ async function Ne(e, r, t, n) {
442
+ const s = new oe({
443
+ network: r.network,
444
+ btcWallet: e
445
+ }), u = t.length;
446
+ n == null || n(0, u);
447
+ let a;
448
+ if (s.supportsBatchSigning())
449
+ a = (await s.signPayoutTransactionsBatch(
450
+ t.map((l) => U(l, r))
451
+ )).map((l) => l.payoutSignature);
452
+ else {
453
+ a = [];
454
+ for (let o = 0; o < t.length; o++) {
455
+ n == null || n(o, u);
456
+ const l = await s.signPayoutTransaction(
457
+ U(t[o], r)
458
+ );
459
+ a.push(l.signature);
460
+ }
461
+ }
462
+ const i = {};
463
+ for (let o = 0; o < t.length; o++)
464
+ i[t[o].claimerPubkeyXOnly] = {
465
+ payout_signature: a[o]
466
+ };
467
+ return n == null || n(u, u), i;
468
+ }
469
+ async function ut(e) {
470
+ const {
471
+ statusReader: r,
472
+ presignClient: t,
473
+ btcWallet: n,
474
+ peginTxid: s,
475
+ depositorPk: u,
476
+ signingContext: a,
477
+ timeoutMs: i = Be,
478
+ signal: o,
479
+ onProgress: l
480
+ } = e, h = await G({
481
+ statusReader: r,
482
+ peginTxid: s,
483
+ targetStatuses: Re,
484
+ timeoutMs: i,
485
+ signal: o
486
+ });
487
+ if (q.has(h))
488
+ return;
489
+ o == null || o.throwIfAborted();
490
+ const c = await t.requestDepositorPresignTransactions(
491
+ {
492
+ pegin_txid: s,
493
+ depositor_pk: u
494
+ },
495
+ o
496
+ );
497
+ o == null || o.throwIfAborted();
498
+ const d = _(u);
499
+ Ve(
500
+ c.txs,
501
+ a.vaultProviderBtcPubkey,
502
+ a.vaultKeeperBtcPubkeys,
503
+ u
504
+ );
505
+ const P = c.txs.filter(
506
+ (v) => _(v.claimer_pubkey) !== d
507
+ ), m = Ie(P), y = await Ne(
508
+ n,
509
+ a,
510
+ m,
511
+ l
512
+ );
513
+ o == null || o.throwIfAborted();
514
+ const x = await $e({
515
+ depositorGraph: c.depositor_graph,
516
+ btcWallet: n,
517
+ signingContext: {
518
+ peginTxHex: a.peginTxHex,
519
+ depositorBtcPubkey: u,
520
+ vaultProviderBtcPubkey: a.vaultProviderBtcPubkey,
521
+ vaultKeeperBtcPubkeys: a.vaultKeeperBtcPubkeys,
522
+ universalChallengerBtcPubkeys: a.universalChallengerBtcPubkeys,
523
+ timelockPegin: a.timelockPegin,
524
+ timelockAssert: a.timelockAssert,
525
+ councilMembers: a.councilMembers,
526
+ councilQuorum: a.councilQuorum,
527
+ network: a.network,
528
+ registeredPayoutScriptPubKey: a.registeredPayoutScriptPubKey
529
+ }
530
+ });
531
+ o == null || o.throwIfAborted();
532
+ const b = { ...y };
533
+ b[p(u)] = x.payout_signatures, await t.submitDepositorPresignatures(
534
+ {
535
+ pegin_txid: s,
536
+ depositor_pk: u,
537
+ signatures: b,
538
+ depositor_claimer_presignatures: x
539
+ },
540
+ o
541
+ );
542
+ }
543
+ function He(e) {
544
+ return /^[0-9a-fA-F]{64}$/.test(e);
545
+ }
546
+ function lt(e) {
547
+ const {
548
+ amountSats: r,
549
+ minDeposit: t,
550
+ maxDeposit: n,
551
+ btcBalance: s,
552
+ estimatedFeeSats: u,
553
+ depositorClaimValue: a
554
+ } = e;
555
+ return !(r <= 0n || r < t || n && n > 0n && r > n || u == null || a == null || r + u + a > s);
556
+ }
557
+ function ct(e, r, t) {
558
+ return e <= 0n ? {
559
+ valid: !1,
560
+ error: "Deposit amount must be greater than zero"
561
+ } : e < r ? {
562
+ valid: !1,
563
+ error: `Minimum deposit is ${E(r)} BTC`
564
+ } : t && t > 0n && e > t ? {
565
+ valid: !1,
566
+ error: `Maximum deposit is ${E(t)} BTC`
567
+ } : { valid: !0 };
568
+ }
569
+ function ht(e) {
570
+ const { amount: r, effectiveRemaining: t } = e;
571
+ return t === null ? { valid: !0 } : t === 0n ? {
572
+ valid: !1,
573
+ error: "Supply cap reached — deposits temporarily paused"
574
+ } : r > t ? {
575
+ valid: !1,
576
+ error: `Vault size exceeds remaining capacity (${E(t)} BTC)`
577
+ } : { valid: !0 };
578
+ }
579
+ function dt(e, r) {
580
+ if (!e || e.length === 0)
581
+ return {
582
+ valid: !1,
583
+ error: "At least one vault provider must be selected"
584
+ };
585
+ const t = r.map(
586
+ (s) => s.toLowerCase()
587
+ );
588
+ return e.filter(
589
+ (s) => !t.includes(s.toLowerCase())
590
+ ).length > 0 ? {
591
+ valid: !1,
592
+ error: "Invalid vault provider selected"
593
+ } : { valid: !0 };
594
+ }
595
+ function Oe(e, r, t) {
596
+ if (!e || e.length === 0)
597
+ return {
598
+ valid: !1,
599
+ error: "At least one vault amount required"
600
+ };
601
+ for (let n = 0; n < e.length; n++) {
602
+ const s = e[n];
603
+ if (s <= 0n)
604
+ return {
605
+ valid: !1,
606
+ error: `Vault ${n + 1} amount must be positive`
607
+ };
608
+ if (r && s < r)
609
+ return {
610
+ valid: !1,
611
+ error: `Vault ${n + 1} amount ${E(s)} BTC is below minimum deposit ${E(r)} BTC`
612
+ };
613
+ if (t && s > t)
614
+ return {
615
+ valid: !1,
616
+ error: `Vault ${n + 1} amount ${E(s)} BTC exceeds maximum deposit ${E(t)} BTC`
617
+ };
618
+ }
619
+ return { valid: !0 };
620
+ }
621
+ function De(e) {
622
+ const r = p(e);
623
+ return He(r) ? { valid: !0 } : {
624
+ valid: !1,
625
+ error: "Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"
626
+ };
627
+ }
628
+ function Ke(e) {
629
+ if (!e || e.length === 0)
630
+ throw new Error(
631
+ "No vault keepers available. The system requires at least one vault keeper to create a deposit."
632
+ );
633
+ }
634
+ function Ue(e) {
635
+ if (!e || e.length === 0)
636
+ throw new Error(
637
+ "No universal challengers available. The system requires at least one universal challenger to create a deposit."
638
+ );
639
+ }
640
+ function Fe(e) {
641
+ if (e.length === 0)
642
+ throw new Error("No spendable UTXOs available");
643
+ }
644
+ function pt(e) {
645
+ const {
646
+ vaultAmounts: r,
647
+ confirmedUTXOs: t,
648
+ vaultProviderBtcPubkey: n,
649
+ vaultKeeperBtcPubkeys: s,
650
+ universalChallengerBtcPubkeys: u,
651
+ minDeposit: a,
652
+ maxDeposit: i
653
+ } = e, o = Oe(
654
+ r,
655
+ a,
656
+ i
657
+ );
658
+ if (!o.valid)
659
+ throw new Error(o.error);
660
+ const l = De(n);
661
+ if (!l.valid)
662
+ throw new Error(l.error);
663
+ Ke(s), Ue(u), Fe(t);
664
+ }
665
+ async function gt(e) {
666
+ const {
667
+ vaultRegistryReader: r,
668
+ vaultKeeperReader: t,
669
+ universalChallengerReader: n,
670
+ vaultProviderEthAddress: s,
671
+ applicationEntryPoint: u,
672
+ expectedVaultProviderBtcPubkey: a,
673
+ expectedVaultKeeperBtcPubkeys: i,
674
+ expectedUniversalChallengerBtcPubkeys: o
675
+ } = e, [
676
+ l,
677
+ h,
678
+ c
679
+ ] = await Promise.all([
680
+ r.getVaultProviderBtcPubKey(s),
681
+ t.getCurrentVaultKeepersVersion(u),
682
+ n.getLatestUniversalChallengersVersion()
683
+ ]), [d, P] = await Promise.all([
684
+ t.getVaultKeepersByVersion(
685
+ u,
686
+ h
687
+ ),
688
+ n.getUniversalChallengersByVersion(
689
+ c
690
+ )
691
+ ]), m = (g) => A(g).toLowerCase(), y = (g) => g.map(m).sort();
692
+ if (m(a) !== l)
693
+ throw new Error(
694
+ `Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${s}. Refresh and try again.`
695
+ );
696
+ const b = y(i), v = y(
697
+ d.map((g) => g.btcPubKey)
698
+ );
699
+ if (b.length !== v.length || b.some((g, S) => g !== v[S]))
700
+ throw new Error(
701
+ `Vault keeper BTC pubkeys (v${h}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`
702
+ );
703
+ const T = y(o), k = y(
704
+ P.map((g) => g.btcPubKey)
705
+ );
706
+ if (T.length !== k.length || T.some((g, S) => g !== k[S]))
707
+ throw new Error(
708
+ `Universal challenger BTC pubkeys (v${c}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`
709
+ );
710
+ return {
711
+ vaultProviderBtcPubkeyXOnly: l,
712
+ vaultKeeperBtcPubkeysSorted: v,
713
+ universalChallengerBtcPubkeysSorted: k,
714
+ expectedAppVaultKeepersVersion: h,
715
+ expectedUniversalChallengersVersion: c
716
+ };
717
+ }
718
+ class j extends Error {
719
+ constructor(r) {
720
+ super(r), this.name = "RegisteredVaultVersionMismatchError";
721
+ }
722
+ }
723
+ function ft(e) {
724
+ return e instanceof j || e instanceof Error && e.name === "RegisteredVaultVersionMismatchError";
725
+ }
726
+ async function mt(e) {
727
+ const {
728
+ vaultRegistryReader: r,
729
+ vaultIds: t,
730
+ expectedOffchainParamsVersion: n,
731
+ expectedAppVaultKeepersVersion: s,
732
+ expectedUniversalChallengersVersion: u
733
+ } = e, a = await r.getProtocolInfoBatch(t), i = [];
734
+ if (a.forEach((o, l) => {
735
+ const h = t[l];
736
+ o.offchainParamsVersion !== n && i.push(
737
+ `vault ${h}: offchainParams expected v${n}, got v${o.offchainParamsVersion}`
738
+ ), o.appVaultKeepersVersion !== s && i.push(
739
+ `vault ${h}: appVaultKeepers expected v${s}, got v${o.appVaultKeepersVersion}`
740
+ ), o.universalChallengersVersion !== u && i.push(
741
+ `vault ${h}: universalChallengers expected v${u}, got v${o.universalChallengersVersion}`
742
+ );
743
+ }), i.length > 0)
744
+ throw new j(
745
+ `Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${i.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`
746
+ );
747
+ }
748
+ var Q = /* @__PURE__ */ ((e) => (e.CLAIM_EVENT_RECEIVED = "ClaimEventReceived", e.CLAIM_BROADCAST = "ClaimBroadcast", e.ASSERT_BROADCAST = "AssertBroadcast", e.PAYOUT_BROADCAST = "PayoutBroadcast", e.PAYOUT_BLOCKED = "PayoutBlocked", e))(Q || {});
749
+ const Me = /* @__PURE__ */ new Set([
750
+ "PayoutBroadcast",
751
+ "PayoutBlocked"
752
+ /* PAYOUT_BLOCKED */
753
+ ]);
754
+ function Pt(e) {
755
+ return Object.values(Q).includes(
756
+ e
757
+ );
758
+ }
759
+ function bt(e) {
760
+ return !!e && Me.has(e);
761
+ }
762
+ class Le extends Error {
763
+ constructor(t, n) {
764
+ super(`Refund not yet mature (BIP68 not final): ${n.message}`);
765
+ $(this, "vaultId");
766
+ $(this, "cause");
767
+ this.name = "BIP68NotMatureError", this.vaultId = t, this.cause = n;
768
+ }
769
+ }
770
+ const Xe = /^0x[0-9a-fA-F]{64}$/, ze = /^(?:0x)?(?:[0-9a-fA-F]{2})+$/, W = /^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/, Y = 160, F = 2e3, M = 10n, L = 100n;
771
+ function yt(e) {
772
+ if (!Number.isFinite(e) || e <= 0)
773
+ throw new Error(
774
+ `feeRateSatsVb must be a positive finite number, got ${e}`
775
+ );
776
+ return BigInt(Math.ceil(e * Y));
777
+ }
778
+ const Ge = 1, qe = /non-BIP68-final/i;
779
+ function D(e, r) {
780
+ if (e.length !== 66)
781
+ throw new Error(
782
+ `${r} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`
783
+ );
784
+ if (!Xe.test(e))
785
+ throw new Error(
786
+ `${r} must contain only hex characters after the 0x prefix`
787
+ );
788
+ }
789
+ function I(e, r) {
790
+ if (!Number.isInteger(e) || e < 0)
791
+ throw new Error(`${r} must be a non-negative integer, got ${e}`);
792
+ }
793
+ function je(e) {
794
+ if (D(e.hashlock, "hashlock"), !Number.isInteger(e.htlcVout) || e.htlcVout < 0)
795
+ throw new Error(
796
+ `htlcVout must be a non-negative integer, got ${e.htlcVout}`
797
+ );
798
+ if (!Array.isArray(e.batch) || e.batch.length === 0)
799
+ throw new Error("batch must be a non-empty array of HTLC entries");
800
+ if (e.htlcVout >= e.batch.length)
801
+ throw new Error(
802
+ `htlcVout ${e.htlcVout} is out of range for batch of size ${e.batch.length}`
803
+ );
804
+ for (let t = 0; t < e.batch.length; t++) {
805
+ const n = e.batch[t];
806
+ if (D(n.hashlock, `batch[${t}].hashlock`), !Number.isInteger(n.htlcVout) || n.htlcVout !== t)
807
+ throw new Error(
808
+ `batch[${t}].htlcVout must equal ${t} (contiguous vout-ordered vector), got ${n.htlcVout}`
809
+ );
810
+ if (typeof n.amount != "bigint" || n.amount <= 0n)
811
+ throw new Error(
812
+ `batch[${t}].amount must be a positive bigint, got ${n.amount}`
813
+ );
814
+ }
815
+ const r = e.batch[e.htlcVout];
816
+ if (r.hashlock.toLowerCase() !== e.hashlock.toLowerCase())
817
+ throw new Error(
818
+ `batch[${e.htlcVout}].hashlock (${r.hashlock}) does not match target hashlock (${e.hashlock})`
819
+ );
820
+ if (r.amount !== e.amount)
821
+ throw new Error(
822
+ `batch[${e.htlcVout}].amount (${r.amount}) does not match target amount (${e.amount})`
823
+ );
824
+ if (I(e.offchainParamsVersion, "offchainParamsVersion"), I(e.appVaultKeepersVersion, "appVaultKeepersVersion"), I(
825
+ e.universalChallengersVersion,
826
+ "universalChallengersVersion"
827
+ ), typeof e.unsignedPrePeginTxHex != "string" || e.unsignedPrePeginTxHex.length === 0)
828
+ throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");
829
+ if (!ze.test(e.unsignedPrePeginTxHex))
830
+ throw new Error(
831
+ "unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)"
832
+ );
833
+ if (!e.depositorBtcPubkey || !W.test(e.depositorBtcPubkey))
834
+ throw new Error(
835
+ "depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)"
836
+ );
837
+ if (typeof e.amount != "bigint" || e.amount <= 0n)
838
+ throw new Error(`amount must be a positive bigint, got ${e.amount}`);
839
+ }
840
+ function Qe(e) {
841
+ if (!e.vaultProviderPubkey || !W.test(e.vaultProviderPubkey))
842
+ throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");
843
+ if (e.vaultKeeperPubkeys.length === 0)
844
+ throw new Error("vaultKeeperPubkeys must be non-empty");
845
+ if (e.universalChallengerPubkeys.length === 0)
846
+ throw new Error("universalChallengerPubkeys must be non-empty");
847
+ if (!Number.isInteger(e.timelockRefund) || e.timelockRefund <= 0)
848
+ throw new Error(
849
+ `timelockRefund must be a positive integer, got ${e.timelockRefund}`
850
+ );
851
+ if (typeof e.feeRate != "bigint" || e.feeRate <= 0n)
852
+ throw new Error(
853
+ `protocol feeRate must be a positive bigint, got ${e.feeRate}`
854
+ );
855
+ if (typeof e.minPeginFeeRate != "bigint" || e.minPeginFeeRate <= 0n)
856
+ throw new Error(
857
+ `minPeginFeeRate must be a positive bigint, got ${e.minPeginFeeRate}`
858
+ );
859
+ if (!Number.isInteger(e.numLocalChallengers) || e.numLocalChallengers < 0)
860
+ throw new Error("numLocalChallengers must be a non-negative integer");
861
+ if (!Number.isInteger(e.councilQuorum) || !Number.isInteger(e.councilSize) || e.councilQuorum <= 0 || e.councilSize <= 0 || e.councilQuorum > e.councilSize)
862
+ throw new Error(
863
+ `councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`
864
+ );
865
+ }
866
+ function We(e) {
867
+ const r = le.fromHex(e);
868
+ try {
869
+ r.finalizeAllInputs();
870
+ } catch (t) {
871
+ const n = t instanceof Error ? t.message : String(t);
872
+ if (!n.includes("already finalized"))
873
+ throw new Error(`Failed to finalize refund PSBT: ${n}`);
874
+ }
875
+ return r.extractTransaction().toHex();
876
+ }
877
+ async function wt(e) {
878
+ const {
879
+ vaultId: r,
880
+ readVault: t,
881
+ readPrePeginContext: n,
882
+ feeRate: s,
883
+ signPsbt: u,
884
+ broadcastTx: a,
885
+ signal: i
886
+ } = e;
887
+ i == null || i.throwIfAborted(), D(r, "vaultId");
888
+ const o = await t();
889
+ je(o), i == null || i.throwIfAborted();
890
+ const l = await n(o);
891
+ if (Qe(l), i == null || i.throwIfAborted(), !Number.isFinite(s) || s <= 0)
892
+ throw new Error(`feeRate must be a positive number, got ${s}`);
893
+ if (s > F)
894
+ throw new Error(
895
+ `feeRate ${s} sat/vB exceeds refund safety cap ${F} sat/vB; refusing to sign refund.`
896
+ );
897
+ const h = BigInt(Math.ceil(s * Y)), c = o.amount * M / L;
898
+ if (h > c)
899
+ throw new Error(
900
+ `Refund fee ${h} sats exceeds the per-vault safety cap of ${c} sats (${M}/${L} of vault.amount=${o.amount}); refusing to sign refund.`
901
+ );
902
+ i == null || i.throwIfAborted();
903
+ const d = A(
904
+ o.depositorBtcPubkey
905
+ ), P = p(o.unsignedPrePeginTxHex), m = ae(P);
906
+ if (m !== void 0 && m.vout !== o.batch.length)
907
+ throw new Error(
908
+ `Auth-anchor OP_RETURN at vout ${m.vout} does not match batch size (${o.batch.length} HTLC outputs expect the anchor at vout ${o.batch.length}). Refund refused — sibling HTLC vector is incomplete.`
909
+ );
910
+ const y = m == null ? void 0 : m.hash;
911
+ let x;
912
+ try {
913
+ x = C.fromHex(P);
914
+ } catch (f) {
915
+ throw new Error(
916
+ `Failed to parse funded Pre-PegIn transaction hex: ${f instanceof Error ? f.message : String(f)}`
917
+ );
918
+ }
919
+ if (x.outs.length < o.batch.length)
920
+ throw new Error(
921
+ `Funded Pre-PegIn tx has ${x.outs.length} outputs but batch requires at least ${o.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`
922
+ );
923
+ const { psbtHex: b } = await pe({
924
+ prePeginParams: {
925
+ depositorPubkey: d,
926
+ vaultProviderPubkey: p(l.vaultProviderPubkey),
927
+ vaultKeeperPubkeys: l.vaultKeeperPubkeys.map(p),
928
+ universalChallengerPubkeys: l.universalChallengerPubkeys.map(p),
929
+ hashlocks: o.batch.map((f) => p(f.hashlock)),
930
+ timelockRefund: l.timelockRefund,
931
+ // `batch[i].amount` is the on-chain vault deposit (peg-in) amount, which
932
+ // is exactly what WASM's `pegInAmounts` expects — it re-adds the protocol
933
+ // reserve (`depositorClaimValue + minPeginFee`) internally when sizing the
934
+ // HTLC output. `buildRefundPsbt`'s value cross-check then binds the result
935
+ // to the funded tx bytes, refusing the refund if the template's HTLC value
936
+ // disagrees with the on-chain commitment.
937
+ pegInAmounts: o.batch.map((f) => f.amount),
938
+ feeRate: l.feeRate,
939
+ minPeginFeeRate: l.minPeginFeeRate,
940
+ numLocalChallengers: l.numLocalChallengers,
941
+ councilQuorum: l.councilQuorum,
942
+ councilSize: l.councilSize,
943
+ network: l.network,
944
+ authAnchorHash: y
945
+ },
946
+ fundedPrePeginTxHex: P,
947
+ htlcVout: o.htlcVout,
948
+ refundFee: h,
949
+ // buildRefundPsbt's top-level `hashlock` param is documented as "no 0x
950
+ // prefix" and flows into the WASM HTLC connector derivation; a prefixed
951
+ // value would derive the wrong refund script leaf and yield an
952
+ // unspendable PSBT. Match the `hashlocks` array handling above.
953
+ hashlock: p(o.hashlock)
954
+ });
955
+ i == null || i.throwIfAborted();
956
+ const v = O(
957
+ o.depositorBtcPubkey,
958
+ Ge
959
+ ), T = await u(b, v);
960
+ V({
961
+ requestedPsbtHex: b,
962
+ returnedPsbtHex: T
963
+ });
964
+ const k = 0, g = N(
965
+ T,
966
+ d,
967
+ k
968
+ );
969
+ H({
970
+ requestedPsbtHex: b,
971
+ signatureHex: g,
972
+ signerXOnlyPubkeyHex: d,
973
+ inputIndex: k
974
+ });
975
+ const S = We(T);
976
+ i == null || i.throwIfAborted();
977
+ try {
978
+ return await a(S);
979
+ } catch (f) {
980
+ throw f instanceof Error && qe.test(f.message) ? new Le(r, f) : f;
981
+ }
982
+ }
983
+ export {
984
+ Le as B,
985
+ Q as C,
986
+ j as R,
987
+ st as a,
988
+ $e as b,
989
+ ht as c,
990
+ dt as d,
991
+ Oe as e,
992
+ De as f,
993
+ pt as g,
994
+ gt as h,
995
+ lt as i,
996
+ ft as j,
997
+ mt as k,
998
+ Pt as l,
999
+ bt as m,
1000
+ wt as n,
1001
+ yt as o,
1002
+ L as p,
1003
+ M as q,
1004
+ ut as r,
1005
+ it as s,
1006
+ F as t,
1007
+ Y as u,
1008
+ ct as v,
1009
+ G as w
1010
+ };
1011
+ //# sourceMappingURL=buildAndBroadcastRefund-Bmz9WJuN.js.map