@babylonlabs-io/ts-sdk 0.68.0 → 0.69.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.
Files changed (79) hide show
  1. package/dist/PeginManager-DSFecw-w.js +1503 -0
  2. package/dist/PeginManager-DSFecw-w.js.map +1 -0
  3. package/dist/PeginManager-VM-jifLt.cjs +2 -0
  4. package/dist/PeginManager-VM-jifLt.cjs.map +1 -0
  5. package/dist/{batchPoll-Cjj1du0i.js → batchPoll-Bc_UKaTz.js} +2 -2
  6. package/dist/{batchPoll-Cjj1du0i.js.map → batchPoll-Bc_UKaTz.js.map} +1 -1
  7. package/dist/{batchPoll-REVZiE-M.cjs → batchPoll-C9cZ5usJ.cjs} +2 -2
  8. package/dist/{batchPoll-REVZiE-M.cjs.map → batchPoll-C9cZ5usJ.cjs.map} +1 -1
  9. package/dist/buildAndBroadcastRefund-CPPGvzXb.cjs +2 -0
  10. package/dist/buildAndBroadcastRefund-CPPGvzXb.cjs.map +1 -0
  11. package/dist/{buildAndBroadcastRefund-CpMDJ8up.js → buildAndBroadcastRefund-DY4ZZcFL.js} +3 -3
  12. package/dist/buildAndBroadcastRefund-DY4ZZcFL.js.map +1 -0
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +7 -7
  15. package/dist/{mempoolApi-_D-jvtj_.js → mempoolApi-71R_CNZa.js} +71 -69
  16. package/dist/mempoolApi-71R_CNZa.js.map +1 -0
  17. package/dist/mempoolApi-BJN9fGEd.cjs +2 -0
  18. package/dist/mempoolApi-BJN9fGEd.cjs.map +1 -0
  19. package/dist/signPsbtsWithFallback-C5cVgYhh.cjs +2 -0
  20. package/dist/signPsbtsWithFallback-C5cVgYhh.cjs.map +1 -0
  21. package/dist/{signPsbtsWithFallback-Bv79gLFe.js → signPsbtsWithFallback-DCZO2h6i.js} +84 -81
  22. package/dist/signPsbtsWithFallback-DCZO2h6i.js.map +1 -0
  23. package/dist/tbv/core/clients/index.cjs +1 -1
  24. package/dist/tbv/core/clients/index.js +2 -2
  25. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +9 -0
  26. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -1
  27. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +13 -0
  28. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -1
  29. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts +1 -0
  30. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts.map +1 -1
  31. package/dist/tbv/core/index.cjs +1 -1
  32. package/dist/tbv/core/index.js +7 -7
  33. package/dist/tbv/core/managers/PeginManager.d.ts +6 -0
  34. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  35. package/dist/tbv/core/managers/index.cjs +1 -1
  36. package/dist/tbv/core/managers/index.js +2 -2
  37. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts.map +1 -1
  38. package/dist/tbv/core/primitives/index.cjs +1 -1
  39. package/dist/tbv/core/primitives/index.js +1 -1
  40. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts +6 -5
  41. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts.map +1 -1
  42. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  43. package/dist/tbv/core/services/index.cjs +1 -1
  44. package/dist/tbv/core/services/index.js +2 -2
  45. package/dist/tbv/index.cjs +1 -1
  46. package/dist/tbv/index.js +7 -7
  47. package/dist/testing/MockBitcoinWallet.d.ts +1 -1
  48. package/dist/testing/MockBitcoinWallet.d.ts.map +1 -1
  49. package/dist/testing/index.cjs +1 -1
  50. package/dist/testing/index.cjs.map +1 -1
  51. package/dist/testing/index.js +66 -62
  52. package/dist/testing/index.js.map +1 -1
  53. package/dist/testing/signBip322P2wpkhWitness.d.ts +5 -0
  54. package/dist/testing/signBip322P2wpkhWitness.d.ts.map +1 -1
  55. package/dist/{toRefundInputs-9hv_6k0E.js → toRefundInputs-C012ZXcp.js} +3 -3
  56. package/dist/{toRefundInputs-9hv_6k0E.js.map → toRefundInputs-C012ZXcp.js.map} +1 -1
  57. package/dist/{toRefundInputs-D8sFs44p.cjs → toRefundInputs-DaxiTty9.cjs} +2 -2
  58. package/dist/{toRefundInputs-D8sFs44p.cjs.map → toRefundInputs-DaxiTty9.cjs.map} +1 -1
  59. package/dist/{verifyKeyPathSchnorrSignature-oGCUbjjZ.js → verifyKeyPathSchnorrSignature-C6Cmk0R1.js} +137 -128
  60. package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +1 -0
  61. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +2 -0
  62. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +1 -0
  63. package/package.json +1 -1
  64. package/dist/PeginManager--2R3T2S8.js +0 -1458
  65. package/dist/PeginManager--2R3T2S8.js.map +0 -1
  66. package/dist/PeginManager-CKWq8ouZ.cjs +0 -2
  67. package/dist/PeginManager-CKWq8ouZ.cjs.map +0 -1
  68. package/dist/buildAndBroadcastRefund-CpMDJ8up.js.map +0 -1
  69. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs +0 -2
  70. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs.map +0 -1
  71. package/dist/mempoolApi-EU1La9wk.cjs +0 -2
  72. package/dist/mempoolApi-EU1La9wk.cjs.map +0 -1
  73. package/dist/mempoolApi-_D-jvtj_.js.map +0 -1
  74. package/dist/signPsbtsWithFallback-Bv79gLFe.js.map +0 -1
  75. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs +0 -2
  76. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs.map +0 -1
  77. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs +0 -2
  78. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs.map +0 -1
  79. package/dist/verifyKeyPathSchnorrSignature-oGCUbjjZ.js.map +0 -1
@@ -0,0 +1,1503 @@
1
+ var Ge = Object.defineProperty;
2
+ var qe = (s, e, t) => e in s ? Ge(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
3
+ var x = (s, e, t) => qe(s, typeof e != "symbol" ? e + "" : e, t);
4
+ import { c as _e, H as Ye, r as W, a as K, b as ae, u as ze, d as ce, e as le, f as ue, g as je, s as Se } from "./sha2-BYVxyZzX.js";
5
+ import * as Ce from "bitcoinjs-lib";
6
+ import { Transaction as Ae, Psbt as he } from "bitcoinjs-lib";
7
+ import { Buffer as O } from "buffer";
8
+ import { isAddressEqual as de, encodeFunctionData as ee, zeroAddress as Qe } from "viem";
9
+ import { B as H } from "./BTCVaultRegistry.abi-CJwWI2EO.js";
10
+ import { h as R } from "./errors-Blc-JWnI.js";
11
+ import { expandWotsSeed as Ze, expandHashlockSecret as Je, expandAuthAnchor as et, deriveVaultId as pe } from "@babylonlabs-io/babylon-tbv-rust-wasm";
12
+ import { a as fe, b as tt, f as ge, g as st } from "./verifyScriptPathSchnorrSignature-Dy9gF5RF.js";
13
+ import { d as ot, b as nt, e as rt, f as it, c as at } from "./verifyKeyPathSchnorrSignature-C6Cmk0R1.js";
14
+ import { p as ct, h as te, u as se, e as A, i as me, s as k, k as Pe, X as lt } from "./bitcoin-Ch_jxnDa.js";
15
+ import { c as ut } from "./signing-DaLvGwQe.js";
16
+ import { M as be } from "./validation-Dj3dqYtl.js";
17
+ import { p as ht, d as Ie } from "./parseFundingOutpoints-CO-f6IHK.js";
18
+ import { c as dt, s as F, r as pt, b as ft, d as gt } from "./signPsbtsWithFallback-DCZO2h6i.js";
19
+ import { s as mt, f as q, i as Pt, w as we } from "./waitForTransactionReceiptSmartAware-lobLm0q0.js";
20
+ import { p as bt, f as wt } from "./fundPeginTransaction-B2wyjqp0.js";
21
+ import { M as X, B as yt } from "./constants-GjWXdaqV.js";
22
+ import { l as xt, P as kt, m as Et, n as Tt, p as vt, V as Bt, i as _t } from "./mempoolApi-71R_CNZa.js";
23
+ import * as St from "@bitcoin-js/tiny-secp256k1-asmjs";
24
+ const D = /* @__PURE__ */ BigInt(2 ** 32 - 1), ye = /* @__PURE__ */ BigInt(32);
25
+ function Ct(s, e = !1) {
26
+ return e ? { h: Number(s & D), l: Number(s >> ye & D) } : { h: Number(s >> ye & D) | 0, l: Number(s & D) | 0 };
27
+ }
28
+ function At(s, e = !1) {
29
+ const t = s.length;
30
+ let o = new Uint32Array(t), i = new Uint32Array(t);
31
+ for (let n = 0; n < t; n++) {
32
+ const { h: r, l: a } = Ct(s[n], e);
33
+ [o[n], i[n]] = [r, a];
34
+ }
35
+ return [o, i];
36
+ }
37
+ const It = (s, e, t) => s << t | e >>> 32 - t, Ht = (s, e, t) => e << t | s >>> 32 - t, Rt = (s, e, t) => e << t - 32 | s >>> 64 - t, $t = (s, e, t) => s << t - 32 | e >>> 64 - t, Ot = 64;
38
+ function Vt(s) {
39
+ const e = s.prepeginTxid.toLowerCase();
40
+ if (!/^[0-9a-f]+$/.test(e) || e.length !== Ot)
41
+ throw new Error(
42
+ `buildDepositTerms: prepeginTxid must be 64 hex chars, got "${s.prepeginTxid}"`
43
+ );
44
+ if (s.peginAmounts.length === 0)
45
+ throw new Error("buildDepositTerms: at least one pegin amount is required");
46
+ if (s.timelockPegin <= 0 || s.timelockAssert <= 0 || s.timelockRefund <= 0)
47
+ throw new Error("buildDepositTerms: timelocks must be positive");
48
+ if (!Number.isInteger(s.maxAcceptableCommissionBps) || s.maxAcceptableCommissionBps < 0 || s.maxAcceptableCommissionBps >= X)
49
+ throw new Error(
50
+ `buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${X}), got ${s.maxAcceptableCommissionBps}`
51
+ );
52
+ const t = BigInt(yt), o = s.peginAmounts.map(
53
+ (i, n) => ({
54
+ htlcVout: n,
55
+ vaultProviderBtcPubkey: s.vaultProviderBtcPubkey,
56
+ peginAmount: i,
57
+ // Ceiling, not quote: floor(peginAmount * maxAcceptableBps / 10_000) —
58
+ // the same bound the registration calldata enforces on-chain, so any
59
+ // stamped commission the contract admits stays under it (firmware
60
+ // >= c8db53e checks the payout commission output <= this value).
61
+ commissionFee: i * BigInt(s.maxAcceptableCommissionBps) / t,
62
+ depositorClaimValue: s.depositorClaimValue,
63
+ peginMaxFee: s.peginMaxFee
64
+ })
65
+ );
66
+ return {
67
+ vaultCoreVersion: s.vaultCoreVersion,
68
+ protocolFeeRate: s.protocolFeeRate,
69
+ timelockPegin: s.timelockPegin,
70
+ timelockAssert: s.timelockAssert,
71
+ timelockRefund: s.timelockRefund,
72
+ prepeginTxid: e,
73
+ prepeginMaxFee: s.prepeginMaxFee,
74
+ vaultKeeperBtcPubkeys: [...s.vaultKeeperBtcPubkeys],
75
+ universalChallengerBtcPubkeys: [...s.universalChallengerBtcPubkeys],
76
+ vaults: o
77
+ };
78
+ }
79
+ const oe = 25, He = 9999;
80
+ function Y(s) {
81
+ if (!Number.isInteger(s) || s < 0 || s >= X)
82
+ throw new Error(
83
+ `Quoted commissionBps must be an integer in [0, ${X}), got ${s}`
84
+ );
85
+ return Math.min(
86
+ s + oe,
87
+ He
88
+ );
89
+ }
90
+ const Ft = /^0x[0-9a-f]+$/i, Mt = /^[0-9a-f]+$/i, Wt = /^[A-Za-z0-9+/]+={0,2}$/;
91
+ function $(s) {
92
+ if (typeof s != "string" || s.length === 0)
93
+ throw new Error("BTC wallet returned empty public key");
94
+ return ct(s).toLowerCase();
95
+ }
96
+ function Dt(s) {
97
+ if (typeof s != "string" || s.length === 0)
98
+ throw new Error("BTC wallet returned empty BIP-322 signature");
99
+ if (s.startsWith("0x") || s.startsWith("0X")) {
100
+ if (!Ft.test(s) || s.length < 4 || s.length % 2 !== 0)
101
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
102
+ return s.toLowerCase();
103
+ }
104
+ if (Mt.test(s)) {
105
+ if (s.length % 2 !== 0)
106
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
107
+ return `0x${s.toLowerCase()}`;
108
+ }
109
+ if (!Wt.test(s) || s.length % 4 !== 0)
110
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
111
+ const e = O.from(s, "base64");
112
+ if (e.length === 0 || e.toString("base64") !== s)
113
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
114
+ return `0x${e.toString("hex")}`;
115
+ }
116
+ async function Nt(s) {
117
+ const { wallet: e, depositTerms: t, fundedPrePeginTxHex: o, depositorBtcPubkey: i } = s, n = typeof e.approveDepositTerms == "function" ? e.approveDepositTerms : void 0;
118
+ if (!n && !t)
119
+ return;
120
+ const r = o.startsWith("0x") ? o.slice(2) : o, c = Ae.fromHex(r).getId();
121
+ if (t && t.prepeginTxid.replace(/^0x/, "").toLowerCase() !== c)
122
+ throw new Error(
123
+ `Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${t.prepeginTxid}, but this transaction is ${c}.`
124
+ );
125
+ if (!n)
126
+ return;
127
+ if (!t)
128
+ throw new Error(
129
+ "This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild."
130
+ );
131
+ if (typeof e.deriveContextHash != "function")
132
+ throw new Error(
133
+ "A deposit-approval wallet must also implement deriveContextHash, but this one does not."
134
+ );
135
+ if (typeof e.holdsApprovedDepositTerms == "function") {
136
+ let g = !1;
137
+ try {
138
+ g = await e.holdsApprovedDepositTerms(t);
139
+ } catch {
140
+ }
141
+ if (g)
142
+ return;
143
+ }
144
+ typeof e.validateDepositTerms == "function" && await e.validateDepositTerms(t);
145
+ const h = ht(o);
146
+ (await Ie(
147
+ { deriveContextHash: e.deriveContextHash.bind(e) },
148
+ {
149
+ depositorBtcPubkey: te(
150
+ $(i)
151
+ ),
152
+ fundingOutpoints: h
153
+ }
154
+ )).fill(0), await n.call(e, t);
155
+ }
156
+ const Ut = /* @__PURE__ */ Uint8Array.from([
157
+ 7,
158
+ 4,
159
+ 13,
160
+ 1,
161
+ 10,
162
+ 6,
163
+ 15,
164
+ 3,
165
+ 12,
166
+ 0,
167
+ 9,
168
+ 5,
169
+ 2,
170
+ 14,
171
+ 11,
172
+ 8
173
+ ]), Re = Uint8Array.from(new Array(16).fill(0).map((s, e) => e)), Lt = Re.map((s) => (9 * s + 5) % 16), $e = /* @__PURE__ */ (() => {
174
+ const t = [[Re], [Lt]];
175
+ for (let o = 0; o < 4; o++)
176
+ for (let i of t)
177
+ i.push(i[o].map((n) => Ut[n]));
178
+ return t;
179
+ })(), Oe = $e[0], Ve = $e[1], Fe = /* @__PURE__ */ [
180
+ [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
181
+ [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
182
+ [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
183
+ [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
184
+ [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
185
+ ].map((s) => Uint8Array.from(s)), Kt = /* @__PURE__ */ Oe.map((s, e) => s.map((t) => Fe[e][t])), Xt = /* @__PURE__ */ Ve.map((s, e) => s.map((t) => Fe[e][t])), Gt = /* @__PURE__ */ Uint32Array.from([
186
+ 0,
187
+ 1518500249,
188
+ 1859775393,
189
+ 2400959708,
190
+ 2840853838
191
+ ]), qt = /* @__PURE__ */ Uint32Array.from([
192
+ 1352829926,
193
+ 1548603684,
194
+ 1836072691,
195
+ 2053994217,
196
+ 0
197
+ ]);
198
+ function xe(s, e, t, o) {
199
+ return s === 0 ? e ^ t ^ o : s === 1 ? e & t | ~e & o : s === 2 ? (e | ~t) ^ o : s === 3 ? e & o | t & ~o : e ^ (t | ~o);
200
+ }
201
+ const N = /* @__PURE__ */ new Uint32Array(16);
202
+ class Yt extends Ye {
203
+ constructor() {
204
+ super(64, 20, 8, !0);
205
+ x(this, "h0", 1732584193);
206
+ x(this, "h1", -271733879);
207
+ x(this, "h2", -1732584194);
208
+ x(this, "h3", 271733878);
209
+ x(this, "h4", -1009589776);
210
+ }
211
+ get() {
212
+ const { h0: t, h1: o, h2: i, h3: n, h4: r } = this;
213
+ return [t, o, i, n, r];
214
+ }
215
+ set(t, o, i, n, r) {
216
+ this.h0 = t | 0, this.h1 = o | 0, this.h2 = i | 0, this.h3 = n | 0, this.h4 = r | 0;
217
+ }
218
+ process(t, o) {
219
+ for (let l = 0; l < 16; l++, o += 4)
220
+ N[l] = t.getUint32(o, !0);
221
+ let i = this.h0 | 0, n = i, r = this.h1 | 0, a = r, c = this.h2 | 0, h = c, d = this.h3 | 0, g = d, P = this.h4 | 0, b = P;
222
+ for (let l = 0; l < 5; l++) {
223
+ const T = 4 - l, E = Gt[l], p = qt[l], B = Oe[l], S = Ve[l], f = Kt[l], w = Xt[l];
224
+ for (let u = 0; u < 16; u++) {
225
+ const y = W(i + xe(l, r, c, d) + N[B[u]] + E, f[u]) + P | 0;
226
+ i = P, P = d, d = W(c, 10) | 0, c = r, r = y;
227
+ }
228
+ for (let u = 0; u < 16; u++) {
229
+ const y = W(n + xe(T, a, h, g) + N[S[u]] + p, w[u]) + b | 0;
230
+ n = b, b = g, g = W(h, 10) | 0, h = a, a = y;
231
+ }
232
+ }
233
+ this.set(this.h1 + c + g | 0, this.h2 + d + b | 0, this.h3 + P + n | 0, this.h4 + i + a | 0, this.h0 + r + h | 0);
234
+ }
235
+ roundClean() {
236
+ K(N);
237
+ }
238
+ destroy() {
239
+ this.destroyed = !0, K(this.buffer), this.set(0, 0, 0, 0, 0);
240
+ }
241
+ }
242
+ const zt = /* @__PURE__ */ _e(() => new Yt()), jt = BigInt(0), M = BigInt(1), Qt = BigInt(2), Zt = BigInt(7), Jt = BigInt(256), es = BigInt(113), Me = [], We = [], De = [];
243
+ for (let s = 0, e = M, t = 1, o = 0; s < 24; s++) {
244
+ [t, o] = [o, (2 * t + 3 * o) % 5], Me.push(2 * (5 * o + t)), We.push((s + 1) * (s + 2) / 2 % 64);
245
+ let i = jt;
246
+ for (let n = 0; n < 7; n++)
247
+ e = (e << M ^ (e >> Zt) * es) % Jt, e & Qt && (i ^= M << (M << BigInt(n)) - M);
248
+ De.push(i);
249
+ }
250
+ const Ne = At(De, !0), ts = Ne[0], ss = Ne[1], ke = (s, e, t) => t > 32 ? Rt(s, e, t) : It(s, e, t), Ee = (s, e, t) => t > 32 ? $t(s, e, t) : Ht(s, e, t);
251
+ function os(s, e = 24) {
252
+ const t = new Uint32Array(10);
253
+ for (let o = 24 - e; o < 24; o++) {
254
+ for (let r = 0; r < 10; r++)
255
+ t[r] = s[r] ^ s[r + 10] ^ s[r + 20] ^ s[r + 30] ^ s[r + 40];
256
+ for (let r = 0; r < 10; r += 2) {
257
+ const a = (r + 8) % 10, c = (r + 2) % 10, h = t[c], d = t[c + 1], g = ke(h, d, 1) ^ t[a], P = Ee(h, d, 1) ^ t[a + 1];
258
+ for (let b = 0; b < 50; b += 10)
259
+ s[r + b] ^= g, s[r + b + 1] ^= P;
260
+ }
261
+ let i = s[2], n = s[3];
262
+ for (let r = 0; r < 24; r++) {
263
+ const a = We[r], c = ke(i, n, a), h = Ee(i, n, a), d = Me[r];
264
+ i = s[d], n = s[d + 1], s[d] = c, s[d + 1] = h;
265
+ }
266
+ for (let r = 0; r < 50; r += 10) {
267
+ for (let a = 0; a < 10; a++)
268
+ t[a] = s[r + a];
269
+ for (let a = 0; a < 10; a++)
270
+ s[r + a] ^= ~t[(a + 2) % 10] & t[(a + 4) % 10];
271
+ }
272
+ s[0] ^= ts[o], s[1] ^= ss[o];
273
+ }
274
+ K(t);
275
+ }
276
+ class re {
277
+ // NOTE: we accept arguments in bytes instead of bits here.
278
+ constructor(e, t, o, i = !1, n = 24) {
279
+ x(this, "state");
280
+ x(this, "pos", 0);
281
+ x(this, "posOut", 0);
282
+ x(this, "finished", !1);
283
+ x(this, "state32");
284
+ x(this, "destroyed", !1);
285
+ x(this, "blockLen");
286
+ x(this, "suffix");
287
+ x(this, "outputLen");
288
+ x(this, "enableXOF", !1);
289
+ x(this, "rounds");
290
+ if (this.blockLen = e, this.suffix = t, this.outputLen = o, this.enableXOF = i, this.rounds = n, ae(o, "outputLen"), !(0 < e && e < 200))
291
+ throw new Error("only keccak-f1600 function is supported");
292
+ this.state = new Uint8Array(200), this.state32 = ze(this.state);
293
+ }
294
+ clone() {
295
+ return this._cloneInto();
296
+ }
297
+ keccak() {
298
+ ce(this.state32), os(this.state32, this.rounds), ce(this.state32), this.posOut = 0, this.pos = 0;
299
+ }
300
+ update(e) {
301
+ le(this), ue(e);
302
+ const { blockLen: t, state: o } = this, i = e.length;
303
+ for (let n = 0; n < i; ) {
304
+ const r = Math.min(t - this.pos, i - n);
305
+ for (let a = 0; a < r; a++)
306
+ o[this.pos++] ^= e[n++];
307
+ this.pos === t && this.keccak();
308
+ }
309
+ return this;
310
+ }
311
+ finish() {
312
+ if (this.finished)
313
+ return;
314
+ this.finished = !0;
315
+ const { state: e, suffix: t, pos: o, blockLen: i } = this;
316
+ e[o] ^= t, (t & 128) !== 0 && o === i - 1 && this.keccak(), e[i - 1] ^= 128, this.keccak();
317
+ }
318
+ writeInto(e) {
319
+ le(this, !1), ue(e), this.finish();
320
+ const t = this.state, { blockLen: o } = this;
321
+ for (let i = 0, n = e.length; i < n; ) {
322
+ this.posOut >= o && this.keccak();
323
+ const r = Math.min(o - this.posOut, n - i);
324
+ e.set(t.subarray(this.posOut, this.posOut + r), i), this.posOut += r, i += r;
325
+ }
326
+ return e;
327
+ }
328
+ xofInto(e) {
329
+ if (!this.enableXOF)
330
+ throw new Error("XOF is not possible for this instance");
331
+ return this.writeInto(e);
332
+ }
333
+ xof(e) {
334
+ return ae(e), this.xofInto(new Uint8Array(e));
335
+ }
336
+ digestInto(e) {
337
+ if (je(e, this), this.finished)
338
+ throw new Error("digest() was already called");
339
+ return this.writeInto(e), this.destroy(), e;
340
+ }
341
+ digest() {
342
+ return this.digestInto(new Uint8Array(this.outputLen));
343
+ }
344
+ destroy() {
345
+ this.destroyed = !0, K(this.state);
346
+ }
347
+ _cloneInto(e) {
348
+ const { blockLen: t, suffix: o, outputLen: i, rounds: n, enableXOF: r } = this;
349
+ return e || (e = new re(t, o, i, r, n)), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = n, e.suffix = o, e.outputLen = i, e.enableXOF = r, e.destroyed = this.destroyed, e;
350
+ }
351
+ }
352
+ const ns = (s, e, t, o = {}) => _e(() => new re(e, s, t), o), rs = /* @__PURE__ */ ns(1, 136, 32), Te = 64, _ = 20, ne = 4, Ue = 2, is = 0, as = 1, U = [64, 64], cs = (s) => Array.from(s).map((e) => e.toString(16).padStart(2, "0")).join("");
353
+ function ie(s) {
354
+ return zt(Se(s));
355
+ }
356
+ function Le(s) {
357
+ return (1 << s) - 1;
358
+ }
359
+ function ls(s) {
360
+ let e = 1;
361
+ for (; e * e < s + 1; ) e++;
362
+ return Math.max(e, 2);
363
+ }
364
+ function us(s) {
365
+ const e = ne, t = s * Le(e);
366
+ return { d: e, n: s, checksum_radix: ls(t) };
367
+ }
368
+ function z(s, e) {
369
+ const t = [];
370
+ let o = e;
371
+ for (; o > 0; )
372
+ t.push(o & 255), o >>>= 8;
373
+ const i = new Uint8Array(s.length + t.length);
374
+ i.set(s);
375
+ for (let n = 0; n < t.length; n++)
376
+ i[s.length + n] = t[n];
377
+ return ie(i);
378
+ }
379
+ function j(s, e) {
380
+ let t = s;
381
+ for (let o = 0; o < e; o++)
382
+ t = ie(t);
383
+ return t;
384
+ }
385
+ function hs(s, e) {
386
+ const t = Le(e.d), o = e.checksum_radix - 1, i = Math.floor(e.n * t / e.checksum_radix), n = [];
387
+ for (let d = 0; d < e.n; d++) {
388
+ const g = z(s, d + Ue), P = j(g, t);
389
+ n.push(Array.from(P));
390
+ }
391
+ const r = z(
392
+ s,
393
+ is
394
+ ), a = j(
395
+ r,
396
+ o
397
+ ), c = z(
398
+ s,
399
+ as
400
+ ), h = j(
401
+ c,
402
+ i
403
+ );
404
+ return {
405
+ config: e,
406
+ message_terminals: n,
407
+ checksum_major_terminal: Array.from(h),
408
+ checksum_minor_terminal: Array.from(a)
409
+ };
410
+ }
411
+ async function ds(s) {
412
+ try {
413
+ if (s.length !== Te)
414
+ throw new Error(
415
+ `WOTS seed must be exactly ${Te} bytes, got ${s.length}`
416
+ );
417
+ const e = [];
418
+ for (let t = 0; t < U.length; t++) {
419
+ const o = U[t], i = us(o), n = new Uint8Array(s.length + 1);
420
+ n.set(s), n[s.length] = t;
421
+ const r = ie(n);
422
+ try {
423
+ const a = hs(r, i);
424
+ if (a.config.d !== ne)
425
+ throw new Error(
426
+ `Block ${t}: expected d=${ne}, got d=${a.config.d}`
427
+ );
428
+ if (a.config.n !== o)
429
+ throw new Error(
430
+ `Block ${t}: expected n=${o}, got n=${a.config.n}`
431
+ );
432
+ if (a.message_terminals.length !== o)
433
+ throw new Error(
434
+ `Block ${t}: expected ${o} message terminals, got ${a.message_terminals.length}`
435
+ );
436
+ for (let c = 0; c < a.message_terminals.length; c++)
437
+ if (a.message_terminals[c].length !== _)
438
+ throw new Error(
439
+ `Block ${t} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`
440
+ );
441
+ if (a.checksum_minor_terminal.length !== _)
442
+ throw new Error(
443
+ `Block ${t} checksum_minor: expected ${_} bytes`
444
+ );
445
+ if (a.checksum_major_terminal.length !== _)
446
+ throw new Error(
447
+ `Block ${t} checksum_major: expected ${_} bytes`
448
+ );
449
+ e.push(a);
450
+ } finally {
451
+ n.fill(0), r.fill(0);
452
+ }
453
+ }
454
+ if (e.length !== U.length)
455
+ throw new Error(
456
+ `Expected ${U.length} blocks, got ${e.length}`
457
+ );
458
+ return e;
459
+ } finally {
460
+ s.fill(0);
461
+ }
462
+ }
463
+ function Q(s, e, t) {
464
+ if (s.length !== _)
465
+ throw new Error(
466
+ `Block ${e} ${t}: expected ${_} bytes, got ${s.length}`
467
+ );
468
+ for (let o = 0; o < s.length; o++) {
469
+ const i = s[o];
470
+ if (!Number.isInteger(i) || i < 0 || i > 255)
471
+ throw new Error(
472
+ `Block ${e} ${t}[${o}]: invalid byte value ${i}`
473
+ );
474
+ }
475
+ }
476
+ function ps(s) {
477
+ if (s.length === 0)
478
+ throw new Error("Public keys array must not be empty");
479
+ for (let n = 0; n < s.length; n++) {
480
+ const r = s[n];
481
+ Q(r.checksum_minor_terminal, n, "checksum_minor_terminal"), Q(r.checksum_major_terminal, n, "checksum_major_terminal");
482
+ for (let a = 0; a < r.message_terminals.length; a++)
483
+ Q(r.message_terminals[a], n, `message_terminal[${a}]`);
484
+ }
485
+ let e = 0;
486
+ for (const n of s)
487
+ e += Ue + n.message_terminals.length;
488
+ const t = new Uint8Array(e * _);
489
+ let o = 0;
490
+ for (const n of s) {
491
+ t.set(n.checksum_minor_terminal, o), o += _, t.set(n.checksum_major_terminal, o), o += _;
492
+ for (const r of n.message_terminals)
493
+ t.set(r, o), o += _;
494
+ }
495
+ const i = rs(t);
496
+ return `0x${cs(i)}`;
497
+ }
498
+ async function fs(s, e) {
499
+ const t = [], o = [], i = [], n = [];
500
+ try {
501
+ for (let r = 0; r < e; r++) {
502
+ const a = await Ze(s, r);
503
+ try {
504
+ const h = await ds(a);
505
+ t.push(h), o.push(ps(h));
506
+ } finally {
507
+ a.fill(0);
508
+ }
509
+ const c = await Je(s, r);
510
+ try {
511
+ const h = se(c);
512
+ i.push(h), n.push(dt(A(h)).slice(2));
513
+ } finally {
514
+ c.fill(0);
515
+ }
516
+ }
517
+ } finally {
518
+ s.fill(0);
519
+ }
520
+ return { perVaultWotsKeys: t, wotsPkHashes: o, htlcSecretHexes: i, hashlocks: n };
521
+ }
522
+ const gs = 1, ms = 2, Ps = 33, bs = 2, ws = 3, ys = 1, L = 64, xs = 0, Z = 1, ve = /^[0-9a-f]{64}$/i, ks = /^(?:[0-9a-f]{2})+$/;
523
+ function Es(s) {
524
+ const e = s.slice(2);
525
+ if (!ks.test(e))
526
+ throw new Error(
527
+ "proof of possession witness is not even-length lowercase hex"
528
+ );
529
+ return ot(
530
+ Uint8Array.from(O.from(e, "hex")),
531
+ "proof of possession witness"
532
+ );
533
+ }
534
+ function Ts(s, e, t) {
535
+ var i;
536
+ const o = Es(t);
537
+ if (o.length === gs) {
538
+ const [n] = o;
539
+ let r, a;
540
+ if (n.length === L)
541
+ r = n, a = xs;
542
+ else if (n.length === L + 1 && n[L] === Z)
543
+ r = n.subarray(0, L), a = Z;
544
+ else
545
+ throw new Error(
546
+ "proof of possession witness item must be a 64-byte Schnorr signature (or 65 bytes ending in 0x01)"
547
+ );
548
+ if (!ve.test(e))
549
+ throw new Error(
550
+ `depositor public key must be bare 64-char x-only hex, got "${e}"`
551
+ );
552
+ const c = Uint8Array.from(O.from(e, "hex"));
553
+ if (!xt(s, c, r, a))
554
+ throw new Error(
555
+ "proof of possession signature does not verify against the depositor key"
556
+ );
557
+ return { kind: "p2tr-verified" };
558
+ }
559
+ if (o.length === ms) {
560
+ if (!ve.test(e))
561
+ throw new Error(
562
+ `depositor public key must be bare 64-char x-only hex, got "${e}"`
563
+ );
564
+ const [n, r] = o;
565
+ if (r.length !== Ps || r[0] !== bs && r[0] !== ws)
566
+ throw new Error(
567
+ `proof of possession P2WPKH witness item 1 is not a compressed public key (${r.length} bytes, prefix 0x${((i = r[0]) == null ? void 0 : i.toString(16)) ?? "none"})`
568
+ );
569
+ if (!St.isPointCompressed(r))
570
+ throw new Error(
571
+ "proof of possession P2WPKH witness pubkey is not a valid secp256k1 point"
572
+ );
573
+ const a = O.from(
574
+ r.subarray(ys)
575
+ ).toString("hex");
576
+ if (a !== e.toLowerCase())
577
+ throw new Error(
578
+ `proof of possession witness pubkey does not match the depositor key: witness carries ${a}, expected ${e}`
579
+ );
580
+ if (n.length < kt || n.length > Et)
581
+ throw new Error(
582
+ `proof of possession signature is ${n.length} bytes; vault ingestion accepts only 71/72-byte DER signatures with a sighash byte — try a different account or a Taproot address`
583
+ );
584
+ if (n[n.length - 1] !== Z)
585
+ throw new Error(
586
+ `proof of possession P2WPKH signature must end in a SIGHASH_ALL (0x01) byte, got 0x${n[n.length - 1].toString(16)}`
587
+ );
588
+ if (!Tt(s, r, n))
589
+ throw new Error(
590
+ "proof of possession signature does not verify against the depositor key"
591
+ );
592
+ return { kind: "p2wpkh-verified" };
593
+ }
594
+ throw new Error(
595
+ `proof of possession witness has ${o.length} items; expected 1 (P2TR) or 2 (P2WPKH)`
596
+ );
597
+ }
598
+ const Ke = 0, J = "00".repeat(32), vs = "00".repeat(32);
599
+ function Bs(s, e) {
600
+ const t = {
601
+ bitcoin: "bc",
602
+ testnet: "tb",
603
+ signet: "tb",
604
+ regtest: "bcrt"
605
+ };
606
+ try {
607
+ const o = Ce.address.fromBech32(s);
608
+ return o.prefix === t[e] && o.version === 0 && o.data.length === 20;
609
+ } catch {
610
+ return !1;
611
+ }
612
+ }
613
+ function _s(s, e, t, o) {
614
+ const i = t == null ? void 0 : t[`${s}:${e}`];
615
+ return i ? Promise.resolve({
616
+ txid: s,
617
+ vout: e,
618
+ value: i.value,
619
+ scriptPubKey: i.scriptPubKey
620
+ }) : _t(s, e, o);
621
+ }
622
+ const Be = 12e4;
623
+ class Js {
624
+ /**
625
+ * Creates a new PeginManager instance.
626
+ *
627
+ * @param config - Manager configuration including wallets and contract addresses
628
+ */
629
+ constructor(e) {
630
+ x(this, "config");
631
+ this.config = e;
632
+ }
633
+ /**
634
+ * Prepare a peg-in: sizing pass → vault-root derivation (one wallet
635
+ * popup) → per-vault WOTS / hashlock derivation → commit pass with
636
+ * PSBT signing (signPsbt for a single vault, one batch popup for a
637
+ * split). Returns broadcast-ready txs, the pubkey snapshot, and the
638
+ * sensitive derived material.
639
+ *
640
+ * @throws If the wallet rejects, insufficient funds, or an internal
641
+ * invariant violation.
642
+ */
643
+ async preparePegin(e) {
644
+ if (e.amounts.length === 0)
645
+ throw new Error("amounts must contain at least one entry");
646
+ const t = await this.config.btcWallet.getPublicKeyHex(), o = $(t);
647
+ if (F(this.config.btcWallet)) {
648
+ const p = (await pt(this.config.btcWallet)).trim();
649
+ if (e.changeAddress.trim() !== p)
650
+ throw new Error(
651
+ `Pre-PegIn changeAddress "${e.changeAddress}" is not the approval wallet's change address ("${p}"). Refusing to build a tx the signing device would reject.`
652
+ );
653
+ } else if (!me(
654
+ e.changeAddress,
655
+ t,
656
+ this.config.btcNetwork
657
+ ))
658
+ throw new Error(
659
+ `Pre-PegIn changeAddress "${e.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`
660
+ );
661
+ const i = await this.prepareSizing(o, e);
662
+ if (F(this.config.btcWallet)) {
663
+ const { validateDepositTerms: p } = this.config.btcWallet;
664
+ typeof p == "function" && await p.call(
665
+ this.config.btcWallet,
666
+ this.buildPeginDepositTerms({
667
+ params: e,
668
+ prepeginTxid: vs,
669
+ prepeginMaxFee: i.fee,
670
+ depositorClaimValue: i.depositorClaimValue,
671
+ peginMaxFee: i.minPeginFee
672
+ })
673
+ );
674
+ }
675
+ const n = i.selectedUTXOs.map(
676
+ (p) => ({
677
+ txid: te(p.txid),
678
+ vout: p.vout
679
+ })
680
+ ), r = await Ie(this.config.btcWallet, {
681
+ depositorBtcPubkey: te(o),
682
+ fundingOutpoints: n
683
+ });
684
+ let a, c;
685
+ try {
686
+ const p = await et(r);
687
+ try {
688
+ a = se(p), c = se(Se(p));
689
+ } finally {
690
+ p.fill(0);
691
+ }
692
+ } catch (p) {
693
+ throw r.fill(0), p;
694
+ }
695
+ const h = await fs(r, e.amounts.length), { perVaultWotsKeys: d, wotsPkHashes: g, htlcSecretHexes: P, hashlocks: b } = h, l = await this.preparePeginCommit({
696
+ depositorBtcPubkeyRaw: t,
697
+ depositorBtcPubkey: o,
698
+ hashlocks: b,
699
+ authAnchorHash: c,
700
+ sizing: i,
701
+ params: e
702
+ });
703
+ for (let p = 0; p < l.perVault.length; p++)
704
+ if (l.perVault[p].htlcVout !== p)
705
+ throw new Error(
706
+ `Internal invariant violation: htlcVout/index mismatch at vault ${p} (expected ${p}, got ${l.perVault[p].htlcVout})`
707
+ );
708
+ ft(
709
+ l.fundedPrePeginTxHex,
710
+ e.amounts.length,
711
+ c
712
+ );
713
+ const { depositTerms: T, ...E } = l;
714
+ return {
715
+ transaction: {
716
+ ...E,
717
+ selectedUTXOs: i.selectedUTXOs,
718
+ fee: i.fee,
719
+ changeAmount: i.changeAmount
720
+ },
721
+ depositorBtcPubkey: o,
722
+ derivedSecrets: {
723
+ perVaultWotsKeys: d,
724
+ wotsPkHashes: g,
725
+ htlcSecretHexes: P,
726
+ authAnchorHex: a
727
+ },
728
+ depositTerms: T
729
+ };
730
+ }
731
+ /**
732
+ * Build unfunded Pre-PegIn + select UTXOs. No PSBT signing.
733
+ *
734
+ * Returns the full selection result (UTXOs, fee, changeAmount) so the
735
+ * commit pass funds the broadcast tx with the exact same set used to
736
+ * build the vault-context funding-outpoints commitment. Re-running
737
+ * `selectUtxosForPegin` in the commit pass would be deterministic given
738
+ * the same inputs, but threading the result through guarantees the
739
+ * domain separator structurally matches the funded tx inputs.
740
+ *
741
+ * Sizing runs before the wallet popup, so neither the real per-vault
742
+ * hashlocks nor the real `authAnchorHash` are known yet. Both slots
743
+ * are filled with a 32-byte placeholder; the commit pass swaps in the
744
+ * real values. Output budget is identical (32-byte push regardless of
745
+ * content), so UTXO selection is invariant under substitution.
746
+ */
747
+ async prepareSizing(e, t) {
748
+ const o = t.amounts.map(
749
+ () => J
750
+ ), i = t.vaultKeeperBtcPubkeys.length, n = await fe({
751
+ vaultCoreVersion: t.vaultCoreVersion,
752
+ depositorPubkey: e,
753
+ vaultProviderPubkey: k(t.vaultProviderBtcPubkey),
754
+ vaultKeeperPubkeys: t.vaultKeeperBtcPubkeys.map(k),
755
+ universalChallengerPubkeys: t.universalChallengerBtcPubkeys.map(k),
756
+ hashlocks: o,
757
+ timelockRefund: t.timelockRefund,
758
+ pegInAmounts: t.amounts,
759
+ feeRate: t.protocolFeeRate,
760
+ minPeginFeeRate: t.minPeginFeeRate,
761
+ numLocalChallengers: i,
762
+ councilQuorum: t.councilQuorum,
763
+ councilSize: t.councilSize,
764
+ network: this.config.btcNetwork,
765
+ authAnchorHash: J
766
+ }), r = mt(
767
+ [...t.availableUTXOs],
768
+ n.totalOutputValue,
769
+ t.mempoolFeeRate,
770
+ bt(n.htlcValues.length, !0)
771
+ );
772
+ return {
773
+ selectedUTXOs: r.selectedUTXOs,
774
+ fee: r.fee,
775
+ changeAmount: r.changeAmount,
776
+ depositorClaimValue: n.depositorClaimValue,
777
+ minPeginFee: n.minPeginFee
778
+ };
779
+ }
780
+ /**
781
+ * One projection for both the provisional (pre-derive, placeholder-txid)
782
+ * terms and the final approved terms, so the fields the pre-check validated
783
+ * cannot drift from the fields the device later displays (#2110 T4).
784
+ */
785
+ buildPeginDepositTerms(e) {
786
+ const { params: t } = e;
787
+ return Vt({
788
+ vaultCoreVersion: t.vaultCoreVersion,
789
+ protocolFeeRate: t.protocolFeeRate,
790
+ timelockPegin: t.timelockPegin,
791
+ timelockAssert: t.timelockAssert,
792
+ timelockRefund: t.timelockRefund,
793
+ prepeginTxid: e.prepeginTxid,
794
+ prepeginMaxFee: e.prepeginMaxFee,
795
+ vaultProviderBtcPubkey: k(t.vaultProviderBtcPubkey),
796
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys.map(k),
797
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys.map(k),
798
+ maxAcceptableCommissionBps: Y(
799
+ t.commissionBps
800
+ ),
801
+ peginAmounts: t.amounts,
802
+ depositorClaimValue: e.depositorClaimValue,
803
+ peginMaxFee: e.peginMaxFee
804
+ });
805
+ }
806
+ /** Build PegIn txs and batch-sign their inputs with real hashlocks. */
807
+ async preparePeginCommit(e) {
808
+ const {
809
+ depositorBtcPubkeyRaw: t,
810
+ depositorBtcPubkey: o,
811
+ hashlocks: i,
812
+ authAnchorHash: n,
813
+ sizing: r,
814
+ params: a
815
+ } = e, c = J.toLowerCase();
816
+ for (let m = 0; m < i.length; m++)
817
+ if (i[m].toLowerCase() === c)
818
+ throw new Error(
819
+ `preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${m} — internal substitution bug`
820
+ );
821
+ if (n.toLowerCase() === c)
822
+ throw new Error(
823
+ "preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug"
824
+ );
825
+ const h = k(
826
+ a.vaultProviderBtcPubkey
827
+ ), d = a.vaultKeeperBtcPubkeys.map(k), g = a.universalChallengerBtcPubkeys.map(k), P = d.length, b = {
828
+ vaultCoreVersion: a.vaultCoreVersion,
829
+ depositorPubkey: o,
830
+ vaultProviderPubkey: h,
831
+ vaultKeeperPubkeys: d,
832
+ universalChallengerPubkeys: g,
833
+ hashlocks: i,
834
+ timelockRefund: a.timelockRefund,
835
+ pegInAmounts: a.amounts,
836
+ feeRate: a.protocolFeeRate,
837
+ minPeginFeeRate: a.minPeginFeeRate,
838
+ numLocalChallengers: P,
839
+ councilQuorum: a.councilQuorum,
840
+ councilSize: a.councilSize,
841
+ network: this.config.btcNetwork,
842
+ authAnchorHash: n
843
+ }, l = await fe(b);
844
+ if (l.depositorClaimValue !== r.depositorClaimValue || l.minPeginFee !== r.minPeginFee)
845
+ throw new Error(
846
+ `Pre-PegIn sizing/commit divergence: depositorClaimValue ${r.depositorClaimValue} -> ${l.depositorClaimValue}, minPeginFee ${r.minPeginFee} -> ${l.minPeginFee}. The provisional deposit terms validated before derivation would not match the terms sent for approval; refusing to continue.`
847
+ );
848
+ const T = Pe(this.config.btcNetwork), E = wt({
849
+ unfundedTxHex: l.psbtHex,
850
+ selectedUTXOs: r.selectedUTXOs,
851
+ changeAddress: a.changeAddress,
852
+ changeAmount: r.changeAmount,
853
+ network: T
854
+ }), p = r.selectedUTXOs.reduce((m, v) => m + BigInt(v.value), 0n) - l.totalOutputValue - r.changeAmount;
855
+ if (p !== r.fee)
856
+ throw new Error(
857
+ `Pre-PegIn funded fee ${p} does not match the sizing-pass fee ${r.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`
858
+ );
859
+ const B = k(
860
+ q(E)
861
+ ), S = [], f = [], w = [];
862
+ for (let m = 0; m < i.length; m++) {
863
+ const v = await tt({
864
+ prePeginParams: b,
865
+ timelockPegin: a.timelockPegin,
866
+ fundedPrePeginTxHex: E,
867
+ htlcVout: m
868
+ }), I = await nt({
869
+ vaultCoreVersion: a.vaultCoreVersion,
870
+ peginTxHex: v.txHex,
871
+ fundedPrePeginTxHex: E,
872
+ depositorPubkey: o,
873
+ vaultProviderPubkey: h,
874
+ vaultKeeperPubkeys: d,
875
+ universalChallengerPubkeys: g,
876
+ hashlock: i[m],
877
+ timelockRefund: a.timelockRefund,
878
+ network: this.config.btcNetwork
879
+ });
880
+ S.push(v), f.push(I.psbtHex), w.push(
881
+ ut(t, 1)
882
+ );
883
+ }
884
+ const u = this.buildPeginDepositTerms({
885
+ params: a,
886
+ prepeginTxid: B,
887
+ prepeginMaxFee: r.fee,
888
+ depositorClaimValue: l.depositorClaimValue,
889
+ peginMaxFee: l.minPeginFee
890
+ });
891
+ F(this.config.btcWallet) && await this.config.btcWallet.approveDepositTerms(u);
892
+ const y = await gt(
893
+ this.config.btcWallet,
894
+ f,
895
+ w
896
+ ), C = [];
897
+ for (let m = 0; m < y.length; m++) {
898
+ ge({
899
+ requestedPsbtHex: f[m],
900
+ returnedPsbtHex: y[m]
901
+ });
902
+ const v = rt(
903
+ y[m],
904
+ o
905
+ );
906
+ st({
907
+ requestedPsbtHex: f[m],
908
+ signatureHex: v,
909
+ signerXOnlyPubkeyHex: o,
910
+ inputIndex: 0
911
+ });
912
+ const I = it(y[m]);
913
+ C.push({
914
+ htlcVout: m,
915
+ htlcValue: l.htlcValues[m],
916
+ peginTxHex: I,
917
+ peginTxid: S[m].txid,
918
+ peginInputSignature: v,
919
+ vaultScriptPubKey: S[m].vaultScriptPubKey
920
+ });
921
+ }
922
+ return {
923
+ fundedPrePeginTxHex: E,
924
+ prePeginTxid: B,
925
+ perVault: C,
926
+ depositTerms: u
927
+ };
928
+ }
929
+ /**
930
+ * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
931
+ *
932
+ * This method:
933
+ * 1. Parses the funded transaction hex
934
+ * 2. Fetches UTXO data from mempool for each input
935
+ * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
936
+ * 4. Signs via btcWallet.signPsbt()
937
+ * 5. Finalizes and extracts the transaction
938
+ * 6. Broadcasts via mempool API
939
+ *
940
+ * IMPORTANT — this method does NOT gate on Ethereum finality. Committing
941
+ * BTC to the HTLC while the peg-in registration is still reorg-exposed can
942
+ * strand the deposit: the vault record disappears from the chain while the
943
+ * BTC stays locked until the HTLC refund timelock. Callers must await
944
+ * `waitForPeginRegistrationDepth` for the registered vault(s) before calling
945
+ * this. The gate is not applied here because the params carry no vault ID —
946
+ * adding one would be a breaking signature change.
947
+ *
948
+ * @param params - Transaction hex and depositor public key
949
+ * @returns The broadcasted Bitcoin transaction ID
950
+ * @throws Error if signing or broadcasting fails
951
+ */
952
+ async signAndBroadcast(e) {
953
+ const { fundedPrePeginTxHex: t, depositorBtcPubkey: o } = e, i = t.startsWith("0x") ? t.slice(2) : t, n = Ae.fromHex(i);
954
+ if (n.ins.length === 0)
955
+ throw new Error("Transaction has no inputs");
956
+ const r = new he();
957
+ r.setVersion(n.version), r.setLocktime(n.locktime);
958
+ const a = O.from(
959
+ $(o),
960
+ "hex"
961
+ ), c = this.config.mempoolApiUrl, h = n.ins.map((f) => {
962
+ const w = O.from(f.hash).reverse().toString("hex"), u = f.index;
963
+ return _s(w, u, e.localPrevouts, c).then(
964
+ (y) => ({ input: f, utxoData: y, txid: w, vout: u })
965
+ );
966
+ }), d = await Promise.all(h), g = d.reduce(
967
+ (f, w) => f + BigInt(w.utxoData.value),
968
+ 0n
969
+ ), P = n.outs.reduce(
970
+ (f, w) => f + BigInt(w.value),
971
+ 0n
972
+ );
973
+ if (g < P)
974
+ throw new Error(
975
+ `UTXO value mismatch: total input value (${g} sat) is less than total output value (${P} sat). This may indicate the mempool API returned manipulated UTXO data.`
976
+ );
977
+ const b = g - P;
978
+ if (b > be)
979
+ throw new Error(
980
+ `Implied transaction fee (${b} sat) exceeds maximum reasonable fee (${be} sat). This may indicate manipulated UTXO data.`
981
+ );
982
+ for (const { input: f, utxoData: w, txid: u, vout: y } of d) {
983
+ const C = Pt(
984
+ {
985
+ value: w.value,
986
+ scriptPubKey: w.scriptPubKey
987
+ },
988
+ a
989
+ );
990
+ r.addInput({
991
+ hash: f.hash,
992
+ index: f.index,
993
+ sequence: f.sequence,
994
+ ...C
995
+ });
996
+ }
997
+ for (const f of n.outs)
998
+ r.addOutput({
999
+ script: f.script,
1000
+ value: f.value
1001
+ });
1002
+ await Nt({
1003
+ wallet: this.config.btcWallet,
1004
+ depositTerms: e.depositTerms,
1005
+ fundedPrePeginTxHex: t,
1006
+ depositorBtcPubkey: o
1007
+ });
1008
+ const l = r.toHex(), T = await this.config.btcWallet.signPsbt(l);
1009
+ ge({
1010
+ requestedPsbtHex: l,
1011
+ returnedPsbtHex: T
1012
+ });
1013
+ const E = at({
1014
+ requestedPsbtHex: l,
1015
+ returnedPsbtHex: T
1016
+ });
1017
+ if (F(this.config.btcWallet) && E !== r.data.inputs.length)
1018
+ throw new Error(
1019
+ `Key-path verification covered ${E} of ${r.data.inputs.length} Pre-PegIn inputs; an approval wallet signs every input key-path, so the unverified ones must not be broadcast.`
1020
+ );
1021
+ const p = he.fromHex(T);
1022
+ try {
1023
+ p.finalizeAllInputs();
1024
+ } catch (f) {
1025
+ if (!p.data.inputs.every(
1026
+ (u) => u.finalScriptWitness || u.finalScriptSig
1027
+ ))
1028
+ throw new Error(
1029
+ `PSBT finalization failed and wallet did not auto-finalize: ${f}`
1030
+ );
1031
+ }
1032
+ const B = p.extractTransaction().toHex();
1033
+ return await vt(B, c);
1034
+ }
1035
+ /**
1036
+ * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.
1037
+ *
1038
+ * This method:
1039
+ * 1. Re-verifies the PopSignature against the currently connected ETH
1040
+ * and BTC wallets — refuses to proceed if either has changed
1041
+ * 2. Derives vault ID and checks if it already exists (pre-flight)
1042
+ * 3. Encodes the contract call using viem
1043
+ * 4. Estimates gas (catches contract errors early with proper revert
1044
+ * reasons)
1045
+ * 5. Sends transaction with pre-estimated gas via
1046
+ * ethWallet.sendTransaction()
1047
+ *
1048
+ * The PopSignature must be obtained via
1049
+ * {@link signProofOfPossession} before this call.
1050
+ *
1051
+ * @param params - Registration parameters including the PopSignature
1052
+ * and the prepared Pre-PegIn / PegIn transactions
1053
+ * @returns Result containing Ethereum transaction hash and vault ID
1054
+ * @throws Error if the PopSignature does not match the connected wallets
1055
+ * @throws Error if the vault already exists
1056
+ * @throws Error if contract simulation fails (e.g., invalid signature,
1057
+ * unauthorized)
1058
+ */
1059
+ async registerPeginOnChain(e) {
1060
+ const {
1061
+ unsignedPrePeginTx: t,
1062
+ depositorSignedPeginTx: o,
1063
+ vaultProvider: i,
1064
+ hashlock: n,
1065
+ htlcVout: r,
1066
+ depositorPayoutBtcAddress: a,
1067
+ depositorWotsPkHash: c,
1068
+ popSignature: h
1069
+ } = e;
1070
+ if (!this.config.ethWallet.account)
1071
+ throw new Error("Ethereum wallet account not found");
1072
+ const d = this.config.ethWallet.account.address;
1073
+ if (!de(h.depositorEthAddress, d))
1074
+ throw new Error(
1075
+ `Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${d}. Reconnect the original account or call signProofOfPossession() again.`
1076
+ );
1077
+ const g = await this.assertPopMatchesBtcWallet(h), P = h.btcPopSignature, b = A(
1078
+ h.depositorBtcPubkey
1079
+ ), l = A(t), T = A(o), E = a ?? await this.config.btcWallet.getAddress(), p = this.resolvePayoutScriptPubKey(
1080
+ g,
1081
+ E
1082
+ ), B = q(T), S = await pe(
1083
+ k(B),
1084
+ k(d)
1085
+ ), f = A(S);
1086
+ if (await this.checkVaultExists(f))
1087
+ throw new Error(
1088
+ `Vault already exists (ID: ${f}, peginTxHash: ${B}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`
1089
+ );
1090
+ const u = this.config.publicClient;
1091
+ let y;
1092
+ try {
1093
+ y = await u.readContract({
1094
+ address: this.config.vaultContracts.btcVaultRegistry,
1095
+ abi: H,
1096
+ functionName: "getPegInFee",
1097
+ args: [i]
1098
+ });
1099
+ } catch (V) {
1100
+ throw new Error(
1101
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
1102
+ { cause: V }
1103
+ );
1104
+ }
1105
+ const C = await this.resolveMaxAcceptableCommissionBps(
1106
+ i,
1107
+ e.quotedCommissionBps
1108
+ ), m = ee({
1109
+ abi: H,
1110
+ functionName: "submitPeginRequest",
1111
+ args: [
1112
+ d,
1113
+ b,
1114
+ P,
1115
+ l,
1116
+ T,
1117
+ i,
1118
+ C,
1119
+ n,
1120
+ r,
1121
+ p,
1122
+ c
1123
+ ]
1124
+ });
1125
+ let v;
1126
+ try {
1127
+ v = await u.estimateGas({
1128
+ to: this.config.vaultContracts.btcVaultRegistry,
1129
+ data: m,
1130
+ value: y,
1131
+ account: this.config.ethWallet.account.address
1132
+ });
1133
+ } catch (V) {
1134
+ R(V);
1135
+ }
1136
+ let I;
1137
+ try {
1138
+ I = await this.config.ethWallet.sendTransaction({
1139
+ to: this.config.vaultContracts.btcVaultRegistry,
1140
+ data: m,
1141
+ value: y,
1142
+ account: this.config.ethWallet.account,
1143
+ chain: this.config.ethChain,
1144
+ gas: v
1145
+ });
1146
+ } catch (V) {
1147
+ R(V);
1148
+ }
1149
+ const G = await we({
1150
+ publicClient: u,
1151
+ walletAddress: this.config.ethWallet.account.address,
1152
+ hash: I,
1153
+ timeout: Be
1154
+ });
1155
+ return G.status === "reverted" && R(
1156
+ new Error(
1157
+ `Transaction reverted. Hash: ${G.transactionHash}. Check the transaction on block explorer for details.`
1158
+ )
1159
+ ), {
1160
+ ethTxHash: G.transactionHash,
1161
+ vaultId: f,
1162
+ peginTxHash: B
1163
+ };
1164
+ }
1165
+ /**
1166
+ * Register multiple pegins on Ethereum in a single transaction.
1167
+ *
1168
+ * Uses the contract's submitPeginRequestBatch() to submit all vault
1169
+ * registrations atomically. All vaults must share the same vault provider.
1170
+ * The PoP signature is signed once and included in each request.
1171
+ *
1172
+ * @param params - Batch registration parameters
1173
+ * @returns Batch result with per-vault IDs and single ETH tx hash
1174
+ */
1175
+ async registerPeginBatchOnChain(e) {
1176
+ const { vaultProvider: t, unsignedPrePeginTx: o, requests: i, popSignature: n } = e;
1177
+ if (i.length === 0)
1178
+ throw new Error("Batch pegin requires at least one request");
1179
+ if (!this.config.ethWallet.account)
1180
+ throw new Error("Ethereum wallet account not found");
1181
+ const r = this.config.ethWallet.account.address;
1182
+ if (!de(n.depositorEthAddress, r))
1183
+ throw new Error(
1184
+ `Proof of possession was signed for ${n.depositorEthAddress} but the Ethereum wallet is currently connected to ${r}. Reconnect the original account or call signProofOfPossession() again.`
1185
+ );
1186
+ const a = await this.assertPopMatchesBtcWallet(n), c = n.btcPopSignature, h = i.map(
1187
+ (u) => this.resolvePayoutScriptPubKey(
1188
+ a,
1189
+ u.depositorPayoutBtcAddress
1190
+ )
1191
+ ), d = [];
1192
+ for (const u of i) {
1193
+ const y = A(
1194
+ u.depositorSignedPeginTx
1195
+ ), C = q(y), m = await pe(
1196
+ k(C),
1197
+ k(r)
1198
+ ), v = A(m);
1199
+ if (await this.checkVaultExists(v))
1200
+ throw new Error(
1201
+ `Vault already exists (ID: ${v}, peginTxHash: ${C}). To create a new vault, use different UTXOs or a different amount.`
1202
+ );
1203
+ d.push({ vaultId: v, peginTxHash: C });
1204
+ }
1205
+ const g = this.config.publicClient;
1206
+ let P;
1207
+ try {
1208
+ P = await g.readContract({
1209
+ address: this.config.vaultContracts.btcVaultRegistry,
1210
+ abi: H,
1211
+ functionName: "getPegInFee",
1212
+ args: [t]
1213
+ });
1214
+ } catch (u) {
1215
+ throw new Error(
1216
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
1217
+ { cause: u }
1218
+ );
1219
+ }
1220
+ const b = P * BigInt(i.length), l = await this.resolveMaxAcceptableCommissionBps(
1221
+ t,
1222
+ e.quotedCommissionBps
1223
+ ), T = A(
1224
+ n.depositorBtcPubkey
1225
+ ), E = A(o), p = i.map((u, y) => ({
1226
+ depositorBtcPubKey: T,
1227
+ btcPopSignature: c,
1228
+ unsignedPrePeginTx: E,
1229
+ depositorSignedPeginTx: A(
1230
+ u.depositorSignedPeginTx
1231
+ ),
1232
+ hashlock: u.hashlock,
1233
+ htlcVout: u.htlcVout,
1234
+ referralCode: Ke,
1235
+ depositorPayoutBtcAddress: h[y],
1236
+ depositorWotsPkHash: u.depositorWotsPkHash
1237
+ })), B = ee({
1238
+ abi: H,
1239
+ functionName: "submitPeginRequestBatch",
1240
+ args: [
1241
+ r,
1242
+ t,
1243
+ l,
1244
+ p
1245
+ ]
1246
+ });
1247
+ let S;
1248
+ try {
1249
+ S = await g.estimateGas({
1250
+ to: this.config.vaultContracts.btcVaultRegistry,
1251
+ data: B,
1252
+ value: b,
1253
+ account: this.config.ethWallet.account.address
1254
+ });
1255
+ } catch (u) {
1256
+ R(u);
1257
+ }
1258
+ let f;
1259
+ try {
1260
+ f = await this.config.ethWallet.sendTransaction({
1261
+ to: this.config.vaultContracts.btcVaultRegistry,
1262
+ data: B,
1263
+ value: b,
1264
+ account: this.config.ethWallet.account,
1265
+ chain: this.config.ethChain,
1266
+ gas: S
1267
+ });
1268
+ } catch (u) {
1269
+ R(u);
1270
+ }
1271
+ const w = await we({
1272
+ publicClient: g,
1273
+ walletAddress: this.config.ethWallet.account.address,
1274
+ hash: f,
1275
+ timeout: Be
1276
+ });
1277
+ return w.status === "reverted" && R(
1278
+ new Error(
1279
+ `Batch transaction reverted. Hash: ${w.transactionHash}. Check the transaction on block explorer for details.`
1280
+ )
1281
+ ), {
1282
+ ethTxHash: w.transactionHash,
1283
+ vaults: d
1284
+ };
1285
+ }
1286
+ // Anchor to quoted+headroom when supplied (refuse if chain drifted past it);
1287
+ // otherwise fall back to chain-current+headroom — see #1691.
1288
+ async resolveMaxAcceptableCommissionBps(e, t) {
1289
+ if (t === void 0 && F(this.config.btcWallet))
1290
+ throw new Error(
1291
+ "quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote."
1292
+ );
1293
+ let o;
1294
+ try {
1295
+ o = await new Bt(
1296
+ this.config.publicClient,
1297
+ this.config.vaultContracts.btcVaultRegistry
1298
+ ).getVaultProviderCommission(e);
1299
+ } catch (i) {
1300
+ throw new Error(
1301
+ "Failed to query vault provider commission from the contract. Please check your network connection and that the contract address is correct.",
1302
+ { cause: i }
1303
+ );
1304
+ }
1305
+ if (t !== void 0) {
1306
+ if (o > t + oe)
1307
+ throw new Error(
1308
+ `Vault provider commission changed since quote: quoted ${t} bps, chain currently reports ${o} bps (allowed drift ${oe} bps). Please refresh to see the new commission and try again.`
1309
+ );
1310
+ return Y(t);
1311
+ }
1312
+ return Y(o);
1313
+ }
1314
+ /**
1315
+ * Check if a vault already exists for a given vault ID.
1316
+ *
1317
+ * The contract returns a default struct (with `depositor === zeroAddress`)
1318
+ * when no vault is registered, so existence is signalled in the response,
1319
+ * not via a thrown error. RPC/network failures are propagated rather than
1320
+ * silently treated as "vault doesn't exist", which would otherwise let
1321
+ * downstream calls run with stale assumptions.
1322
+ *
1323
+ * @param vaultId - The Bitcoin transaction hash (vault ID)
1324
+ * @returns True if vault exists, false otherwise
1325
+ * @throws If the underlying RPC read fails
1326
+ */
1327
+ async checkVaultExists(e) {
1328
+ return (await this.config.publicClient.readContract({
1329
+ address: this.config.vaultContracts.btcVaultRegistry,
1330
+ abi: H,
1331
+ functionName: "getBtcVaultBasicInfo",
1332
+ args: [e]
1333
+ })).depositor !== Qe;
1334
+ }
1335
+ /**
1336
+ * Resolve the BTC scriptPubKey to register as the depositor's payout sink.
1337
+ *
1338
+ * `address` is validated against the verified depositor pubkey, sourced
1339
+ * from `assertPopMatchesBtcWallet`'s return value rather than
1340
+ * `popSignature.depositorBtcPubkey` (which is x-only, parity stripped).
1341
+ * For wallets that expose a compressed key this preserves y-parity end to
1342
+ * end. For Taproot wallets that only expose an x-only key, the helper
1343
+ * itself fails closed for P2WPKH — the parity is unknowable, so the
1344
+ * payout sink must be a P2TR address derived from that same x.
1345
+ *
1346
+ * The helper does not call into the wallet so the batch path can resolve
1347
+ * many requests without any extra adapter reads. Threat closed: a
1348
+ * state-race or stale FE state that lets a non-wallet address reach the
1349
+ * on-chain payout-script registration.
1350
+ */
1351
+ resolvePayoutScriptPubKey(e, t) {
1352
+ if (!me(
1353
+ t,
1354
+ e,
1355
+ this.config.btcNetwork
1356
+ ))
1357
+ throw k(e).length === lt && Bs(t, this.config.btcNetwork) ? new Error(
1358
+ `BTC payout address "${t}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`
1359
+ ) : new Error(
1360
+ `BTC payout address "${t}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`
1361
+ );
1362
+ const o = Pe(this.config.btcNetwork);
1363
+ try {
1364
+ return `0x${Ce.address.toOutputScript(t, o).toString("hex")}`;
1365
+ } catch {
1366
+ throw new Error(
1367
+ `Invalid BTC payout address: "${t}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
1368
+ );
1369
+ }
1370
+ }
1371
+ /**
1372
+ * Sign a BIP-322 BTC Proof-of-Possession binding the connected BTC
1373
+ * wallet to the connected ETH account for this chain and vault
1374
+ * registry. The returned {@link PopSignature} can be reused across
1375
+ * every register call in the same session.
1376
+ *
1377
+ * The witness is verified against the depositor key before it is
1378
+ * returned — Schnorr for one-item (P2TR), ECDSA over the BIP-322
1379
+ * P2WPKH virtual transaction for two-item — see {@link verifyPopWitness}.
1380
+ *
1381
+ * @throws If the wallet returns a malformed witness or a signature that
1382
+ * does not verify.
1383
+ */
1384
+ async signProofOfPossession() {
1385
+ if (!this.config.ethWallet.account)
1386
+ throw new Error("Ethereum wallet account not found");
1387
+ const e = this.config.ethWallet.account.address, t = $(
1388
+ await this.config.btcWallet.getPublicKeyHex()
1389
+ ), o = this.config.vaultContracts.btcVaultRegistry, i = `${e.toLowerCase()}:${this.config.ethChain.id}:pegin:${o.toLowerCase()}`, n = await this.config.btcWallet.signMessage(
1390
+ i,
1391
+ "bip322-simple"
1392
+ ), r = Dt(n);
1393
+ return Ts(
1394
+ new TextEncoder().encode(i),
1395
+ t,
1396
+ r
1397
+ ), { btcPopSignature: r, depositorEthAddress: e, depositorBtcPubkey: t };
1398
+ }
1399
+ /**
1400
+ * Confirm the connected BTC wallet still matches the PoP it produced, and
1401
+ * return the wallet's *raw* pubkey hex (parity-preserving form, as the
1402
+ * wallet adapter returns it). The raw form is required by callers that
1403
+ * validate Native SegWit / P2WPKH addresses, since P2WPKH is derived from
1404
+ * a parity-bearing compressed key — an x-only form would let an attacker
1405
+ * substitute the opposite-parity P2WPKH address.
1406
+ */
1407
+ async assertPopMatchesBtcWallet(e) {
1408
+ const t = await this.config.btcWallet.getPublicKeyHex(), o = $(t), i = $(e.depositorBtcPubkey);
1409
+ if (o !== i)
1410
+ throw new Error(
1411
+ `Proof of possession was signed with BTC pubkey ${i} but the BTC wallet is currently connected to ${o}. Reconnect the original wallet or call signProofOfPossession() again.`
1412
+ );
1413
+ return t;
1414
+ }
1415
+ /**
1416
+ * Gets the configured Bitcoin network.
1417
+ *
1418
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1419
+ */
1420
+ getNetwork() {
1421
+ return this.config.btcNetwork;
1422
+ }
1423
+ /**
1424
+ * Gets the configured BTCVaultRegistry contract address.
1425
+ *
1426
+ * @returns The Ethereum address of the BTCVaultRegistry contract
1427
+ */
1428
+ getVaultContractAddress() {
1429
+ return this.config.vaultContracts.btcVaultRegistry;
1430
+ }
1431
+ }
1432
+ const Ss = 80, Cs = 250, As = 300, Is = 22, Xe = "ab";
1433
+ function Hs(s, e) {
1434
+ const t = Xe.repeat(As), o = k(s).toLowerCase(), i = e.toString(16).padStart(8, "0"), n = `${o}${i}`, r = t.slice(n.length);
1435
+ return `0x${n}${r}`;
1436
+ }
1437
+ function Rs(s, e) {
1438
+ const t = (o) => `0x${Xe.repeat(o)}`;
1439
+ return {
1440
+ depositorBtcPubKey: t(32),
1441
+ btcPopSignature: t(Ss),
1442
+ unsignedPrePeginTx: t(Cs),
1443
+ depositorSignedPeginTx: Hs(
1444
+ s,
1445
+ e
1446
+ ),
1447
+ hashlock: t(32),
1448
+ htlcVout: e,
1449
+ referralCode: Ke,
1450
+ depositorPayoutBtcAddress: t(Is),
1451
+ depositorWotsPkHash: t(32)
1452
+ };
1453
+ }
1454
+ async function eo(s) {
1455
+ const {
1456
+ publicClient: e,
1457
+ btcVaultRegistry: t,
1458
+ depositorEthAddress: o,
1459
+ vaultProvider: i,
1460
+ batchSize: n
1461
+ } = s;
1462
+ if (n <= 0)
1463
+ throw new Error(
1464
+ `estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${n})`
1465
+ );
1466
+ const a = await e.readContract({
1467
+ address: t,
1468
+ abi: H,
1469
+ functionName: "getPegInFee",
1470
+ args: [i]
1471
+ }) * BigInt(n), c = Array.from(
1472
+ { length: n },
1473
+ (d, g) => Rs(o, g)
1474
+ ), h = ee({
1475
+ abi: H,
1476
+ functionName: "submitPeginRequestBatch",
1477
+ args: [
1478
+ o,
1479
+ i,
1480
+ He,
1481
+ c
1482
+ ]
1483
+ });
1484
+ return e.estimateGas({
1485
+ to: t,
1486
+ data: h,
1487
+ value: a,
1488
+ account: o
1489
+ });
1490
+ }
1491
+ export {
1492
+ oe as C,
1493
+ He as M,
1494
+ Js as P,
1495
+ Y as a,
1496
+ Vt as b,
1497
+ ps as c,
1498
+ ds as d,
1499
+ eo as e,
1500
+ Nt as f,
1501
+ fs as g
1502
+ };
1503
+ //# sourceMappingURL=PeginManager-DSFecw-w.js.map