@babylonlabs-io/ts-sdk 0.34.0 → 0.36.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 (78) hide show
  1. package/dist/{PayoutManager-DDnNB0mj.cjs → PayoutManager-BhJoQZsG.cjs} +2 -2
  2. package/dist/PayoutManager-BhJoQZsG.cjs.map +1 -0
  3. package/dist/{PayoutManager-C9XHKZ5j.js → PayoutManager-s_uH8Uuj.js} +2 -2
  4. package/dist/PayoutManager-s_uH8Uuj.js.map +1 -0
  5. package/dist/PeginManager-DF1oinIQ.js +1172 -0
  6. package/dist/PeginManager-DF1oinIQ.js.map +1 -0
  7. package/dist/PeginManager-cPQuJTB9.cjs +2 -0
  8. package/dist/PeginManager-cPQuJTB9.cjs.map +1 -0
  9. package/dist/{buildAndBroadcastRefund-C7hnNWbj.cjs → buildAndBroadcastRefund-BQ0CaL6Q.cjs} +2 -2
  10. package/dist/{buildAndBroadcastRefund-C7hnNWbj.cjs.map → buildAndBroadcastRefund-BQ0CaL6Q.cjs.map} +1 -1
  11. package/dist/{buildAndBroadcastRefund-B6fGRmvo.js → buildAndBroadcastRefund-DzX11N9S.js} +2 -2
  12. package/dist/{buildAndBroadcastRefund-B6fGRmvo.js.map → buildAndBroadcastRefund-DzX11N9S.js.map} +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +124 -123
  15. package/dist/sha2-BYVxyZzX.js +274 -0
  16. package/dist/{sha2-6wN58S6R.js.map → sha2-BYVxyZzX.js.map} +1 -1
  17. package/dist/sha2-DsrLC4NM.cjs +2 -0
  18. package/dist/{sha2-CsTynrfJ.cjs.map → sha2-DsrLC4NM.cjs.map} +1 -1
  19. package/dist/tbv/core/clients/index.cjs +1 -1
  20. package/dist/tbv/core/clients/index.js +1 -1
  21. package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts.map +1 -1
  22. package/dist/tbv/core/index.cjs +1 -1
  23. package/dist/tbv/core/index.js +134 -133
  24. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  25. package/dist/tbv/core/managers/index.cjs +1 -1
  26. package/dist/tbv/core/managers/index.js +2 -2
  27. package/dist/tbv/core/services/index.cjs +1 -1
  28. package/dist/tbv/core/services/index.js +2 -2
  29. package/dist/tbv/core/utils/eth/__tests__/waitForTransactionReceiptSmartAware.test.d.ts +2 -0
  30. package/dist/tbv/core/utils/eth/__tests__/waitForTransactionReceiptSmartAware.test.d.ts.map +1 -0
  31. package/dist/tbv/core/utils/eth/index.d.ts +2 -0
  32. package/dist/tbv/core/utils/eth/index.d.ts.map +1 -0
  33. package/dist/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.d.ts +18 -0
  34. package/dist/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.d.ts.map +1 -0
  35. package/dist/tbv/core/utils/index.cjs +1 -1
  36. package/dist/tbv/core/utils/index.d.ts +1 -0
  37. package/dist/tbv/core/utils/index.d.ts.map +1 -1
  38. package/dist/tbv/core/utils/index.js +14 -13
  39. package/dist/tbv/core/vault-secrets/__tests__/deriveVaultRoot.test.d.ts +1 -1
  40. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +4 -6
  41. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -1
  42. package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts +1 -1
  43. package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
  44. package/dist/tbv/core/vault-secrets/index.d.ts +1 -1
  45. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  46. package/dist/tbv/index.cjs +1 -1
  47. package/dist/tbv/index.js +134 -133
  48. package/dist/testing/index.cjs +1 -1
  49. package/dist/testing/index.js +1 -1
  50. package/dist/{vault-registry-reader-CqhD3Iyd.js → vault-registry-reader-Bz8uu0dh.js} +13 -12
  51. package/dist/vault-registry-reader-Bz8uu0dh.js.map +1 -0
  52. package/dist/{vault-registry-reader-Brkh1j7p.cjs → vault-registry-reader-Cufa-ZkW.cjs} +2 -2
  53. package/dist/vault-registry-reader-Cufa-ZkW.cjs.map +1 -0
  54. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js +217 -0
  55. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js.map +1 -0
  56. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs +2 -0
  57. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs.map +1 -0
  58. package/package.json +1 -2
  59. package/dist/PayoutManager-C9XHKZ5j.js.map +0 -1
  60. package/dist/PayoutManager-DDnNB0mj.cjs.map +0 -1
  61. package/dist/PeginManager-C8-I4gFH.js +0 -1280
  62. package/dist/PeginManager-C8-I4gFH.js.map +0 -1
  63. package/dist/PeginManager-D0TW9RET.cjs +0 -2
  64. package/dist/PeginManager-D0TW9RET.cjs.map +0 -1
  65. package/dist/psbtInputFields-2224j2ZY.js +0 -128
  66. package/dist/psbtInputFields-2224j2ZY.js.map +0 -1
  67. package/dist/psbtInputFields-B1lrwYzH.cjs +0 -2
  68. package/dist/psbtInputFields-B1lrwYzH.cjs.map +0 -1
  69. package/dist/sha2-6wN58S6R.js +0 -280
  70. package/dist/sha2-CsTynrfJ.cjs +0 -2
  71. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts +0 -8
  72. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts.map +0 -1
  73. package/dist/tbv/core/vault-secrets/expand.d.ts +0 -58
  74. package/dist/tbv/core/vault-secrets/expand.d.ts.map +0 -1
  75. package/dist/tbv/core/vault-secrets/info.d.ts +0 -55
  76. package/dist/tbv/core/vault-secrets/info.d.ts.map +0 -1
  77. package/dist/vault-registry-reader-Brkh1j7p.cjs.map +0 -1
  78. package/dist/vault-registry-reader-CqhD3Iyd.js.map +0 -1
@@ -0,0 +1,1172 @@
1
+ var Wt = Object.defineProperty;
2
+ var Lt = (n, t, e) => t in n ? Wt(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var y = (n, t, e) => Lt(n, typeof t != "symbol" ? t + "" : t, e);
4
+ import { s as tt, c as Tt, H as Ft, r as U, a as F, b as st, u as Mt, d as ot, e as rt, f as it, g as Xt } from "./sha2-BYVxyZzX.js";
5
+ import * as _t from "bitcoinjs-lib";
6
+ import { Transaction as Kt, Psbt as at } from "bitcoinjs-lib";
7
+ import { Buffer as q } from "buffer";
8
+ import { isAddressEqual as ct, encodeFunctionData as lt, zeroAddress as Dt } from "viem";
9
+ import { B as R } from "./BTCVaultRegistry.abi-DbJ5lsFJ.js";
10
+ import { h as A } from "./errors-CznAK5NB.js";
11
+ import { expandWotsSeed as zt, expandHashlockSecret as Gt, expandAuthAnchor as jt, deriveVaultId as ut } from "@babylonlabs-io/babylon-tbv-rust-wasm";
12
+ import { b as ht, a as qt, c as Zt, e as Qt, f as Yt } from "./peginInput-C2QPvuhR.js";
13
+ import { s as T, u as M, h as Z, e as I, p as Jt, g as dt, i as te } from "./bitcoin-B0S8SHCX.js";
14
+ import { c as ee } from "./signing-DaLvGwQe.js";
15
+ import { M as ft } from "./validation-CxqROCno.js";
16
+ import { c as ne } from "./PayoutManager-s_uH8Uuj.js";
17
+ import { s as se, c as K, d as oe, w as gt } from "./waitForTransactionReceiptSmartAware-Cj_DKm0G.js";
18
+ import { p as re, f as ie } from "./fundPeginTransaction-oV-dNJOU.js";
19
+ import { p as ae, f as ce } from "./mempoolApi-CAIge7Nj.js";
20
+ const N = /* @__PURE__ */ BigInt(2 ** 32 - 1), pt = /* @__PURE__ */ BigInt(32);
21
+ function le(n, t = !1) {
22
+ return t ? { h: Number(n & N), l: Number(n >> pt & N) } : { h: Number(n >> pt & N) | 0, l: Number(n & N) | 0 };
23
+ }
24
+ function ue(n, t = !1) {
25
+ const e = n.length;
26
+ let s = new Uint32Array(e), o = new Uint32Array(e);
27
+ for (let r = 0; r < e; r++) {
28
+ const { h: i, l: a } = le(n[r], t);
29
+ [s[r], o[r]] = [i, a];
30
+ }
31
+ return [s, o];
32
+ }
33
+ const he = (n, t, e) => n << e | t >>> 32 - e, de = (n, t, e) => t << e | n >>> 32 - e, fe = (n, t, e) => t << e - 32 | n >>> 64 - e, ge = (n, t, e) => n << e - 32 | t >>> 64 - e, pe = 106, me = 32, mt = 34;
34
+ function we(n, t, e) {
35
+ const s = T(n), o = _t.Transaction.fromHex(s);
36
+ if (o.outs.length <= t)
37
+ throw new Error(
38
+ `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${o.outs.length} outputs, expected at least ${t + 1} (vault outputs + OP_RETURN)`
39
+ );
40
+ const r = o.outs[t], i = r.script;
41
+ if (i.length !== mt || i[0] !== pe || i[1] !== me)
42
+ throw new Error(
43
+ `Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0, Math.min(2, i.length)).toString("hex")}; expected ${mt}-byte OP_RETURN + PUSH32 layout)`
44
+ );
45
+ const a = i.slice(2).toString("hex").toLowerCase();
46
+ if (a !== e.toLowerCase())
47
+ throw new Error(
48
+ `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${a}, expected ${e}`
49
+ );
50
+ if (r.value !== 0)
51
+ throw new Error(
52
+ `Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${r.value}; OP_RETURN outputs must be 0-value`
53
+ );
54
+ }
55
+ const C = 32, D = 32, Q = 36, vt = 32, X = 4, Pe = X + C + X + vt;
56
+ function Y(n, t, e) {
57
+ n[t] = e >>> 24 & 255, n[t + 1] = e >>> 16 & 255, n[t + 2] = e >>> 8 & 255, n[t + 3] = e & 255;
58
+ }
59
+ function be(n) {
60
+ if (n.txid.length !== D)
61
+ throw new Error(
62
+ `outpoint.txid must be exactly ${D} bytes, got ${n.txid.length}`
63
+ );
64
+ if (!Number.isInteger(n.vout) || n.vout < 0 || n.vout > 4294967295)
65
+ throw new Error(`outpoint.vout must be a u32, got ${n.vout}`);
66
+ const t = new Uint8Array(Q);
67
+ return t.set(n.txid, 0), Y(t, D, n.vout), t;
68
+ }
69
+ function wt(n, t) {
70
+ const e = Math.min(n.length, t.length);
71
+ for (let s = 0; s < e; s++)
72
+ if (n[s] !== t[s]) return n[s] - t[s];
73
+ return n.length - t.length;
74
+ }
75
+ function xe(n) {
76
+ if (n.length === 0)
77
+ throw new Error(
78
+ "buildFundingOutpointsCommitment: outpoints must be non-empty"
79
+ );
80
+ const t = n.map(be);
81
+ t.sort(wt);
82
+ for (let s = 1; s < t.length; s++)
83
+ if (wt(t[s - 1], t[s]) === 0)
84
+ throw new Error(
85
+ "buildFundingOutpointsCommitment: duplicate outpoint detected"
86
+ );
87
+ const e = new Uint8Array(t.length * Q);
88
+ for (let s = 0; s < t.length; s++)
89
+ e.set(t[s], s * Q);
90
+ return tt(e);
91
+ }
92
+ function ye(n) {
93
+ if (n.depositorBtcPubkey.length !== C)
94
+ throw new Error(
95
+ `vaultContext: depositorBtcPubkey must be exactly ${C} bytes, got ${n.depositorBtcPubkey.length}`
96
+ );
97
+ const t = xe(n.fundingOutpoints), e = new Uint8Array(Pe);
98
+ let s = 0;
99
+ return Y(e, s, C), s += X, e.set(n.depositorBtcPubkey, s), s += C, Y(e, s, vt), s += X, e.set(t, s), e;
100
+ }
101
+ const ke = "babylon-btc-vault", It = 32, Pt = It * 2, Ee = /^[0-9a-f]+$/;
102
+ async function Te(n, t) {
103
+ const e = ye(t), s = M(e), o = await n.deriveContextHash(ke, s);
104
+ if (typeof o != "string")
105
+ throw new Error(
106
+ `deriveVaultRoot: wallet must return a string, got ${typeof o}`
107
+ );
108
+ if (o.length !== Pt)
109
+ throw new Error(
110
+ `deriveVaultRoot: wallet must return a ${Pt}-character hex string (${It} bytes), got length ${o.length}`
111
+ );
112
+ if (!Ee.test(o))
113
+ throw new Error(
114
+ "deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters"
115
+ );
116
+ return Z(o);
117
+ }
118
+ const _e = /* @__PURE__ */ Uint8Array.from([
119
+ 7,
120
+ 4,
121
+ 13,
122
+ 1,
123
+ 10,
124
+ 6,
125
+ 15,
126
+ 3,
127
+ 12,
128
+ 0,
129
+ 9,
130
+ 5,
131
+ 2,
132
+ 14,
133
+ 11,
134
+ 8
135
+ ]), St = Uint8Array.from(new Array(16).fill(0).map((n, t) => t)), ve = St.map((n) => (9 * n + 5) % 16), Bt = /* @__PURE__ */ (() => {
136
+ const e = [[St], [ve]];
137
+ for (let s = 0; s < 4; s++)
138
+ for (let o of e)
139
+ o.push(o[s].map((r) => _e[r]));
140
+ return e;
141
+ })(), At = Bt[0], Ot = Bt[1], Rt = /* @__PURE__ */ [
142
+ [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
143
+ [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
144
+ [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
145
+ [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
146
+ [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
147
+ ].map((n) => Uint8Array.from(n)), Ie = /* @__PURE__ */ At.map((n, t) => n.map((e) => Rt[t][e])), Se = /* @__PURE__ */ Ot.map((n, t) => n.map((e) => Rt[t][e])), Be = /* @__PURE__ */ Uint32Array.from([
148
+ 0,
149
+ 1518500249,
150
+ 1859775393,
151
+ 2400959708,
152
+ 2840853838
153
+ ]), Ae = /* @__PURE__ */ Uint32Array.from([
154
+ 1352829926,
155
+ 1548603684,
156
+ 1836072691,
157
+ 2053994217,
158
+ 0
159
+ ]);
160
+ function bt(n, t, e, s) {
161
+ return n === 0 ? t ^ e ^ s : n === 1 ? t & e | ~t & s : n === 2 ? (t | ~e) ^ s : n === 3 ? t & s | e & ~s : t ^ (e | ~s);
162
+ }
163
+ const V = /* @__PURE__ */ new Uint32Array(16);
164
+ class Oe extends Ft {
165
+ constructor() {
166
+ super(64, 20, 8, !0);
167
+ y(this, "h0", 1732584193);
168
+ y(this, "h1", -271733879);
169
+ y(this, "h2", -1732584194);
170
+ y(this, "h3", 271733878);
171
+ y(this, "h4", -1009589776);
172
+ }
173
+ get() {
174
+ const { h0: e, h1: s, h2: o, h3: r, h4: i } = this;
175
+ return [e, s, o, r, i];
176
+ }
177
+ set(e, s, o, r, i) {
178
+ this.h0 = e | 0, this.h1 = s | 0, this.h2 = o | 0, this.h3 = r | 0, this.h4 = i | 0;
179
+ }
180
+ process(e, s) {
181
+ for (let h = 0; h < 16; h++, s += 4)
182
+ V[h] = e.getUint32(s, !0);
183
+ let o = this.h0 | 0, r = o, i = this.h1 | 0, a = i, c = this.h2 | 0, u = c, l = this.h3 | 0, m = l, w = this.h4 | 0, P = w;
184
+ for (let h = 0; h < 5; h++) {
185
+ const g = 4 - h, E = Be[h], S = Ae[h], f = At[h], x = Ot[h], d = Ie[h], k = Se[h];
186
+ for (let b = 0; b < 16; b++) {
187
+ const p = U(o + bt(h, i, c, l) + V[f[b]] + E, d[b]) + w | 0;
188
+ o = w, w = l, l = U(c, 10) | 0, c = i, i = p;
189
+ }
190
+ for (let b = 0; b < 16; b++) {
191
+ const p = U(r + bt(g, a, u, m) + V[x[b]] + S, k[b]) + P | 0;
192
+ r = P, P = m, m = U(u, 10) | 0, u = a, a = p;
193
+ }
194
+ }
195
+ this.set(this.h1 + c + m | 0, this.h2 + l + P | 0, this.h3 + w + r | 0, this.h4 + o + a | 0, this.h0 + i + u | 0);
196
+ }
197
+ roundClean() {
198
+ F(V);
199
+ }
200
+ destroy() {
201
+ this.destroyed = !0, F(this.buffer), this.set(0, 0, 0, 0, 0);
202
+ }
203
+ }
204
+ const Re = /* @__PURE__ */ Tt(() => new Oe()), He = BigInt(0), H = BigInt(1), $e = BigInt(2), Ce = BigInt(7), Ue = BigInt(256), Ne = BigInt(113), Ht = [], $t = [], Ct = [];
205
+ for (let n = 0, t = H, e = 1, s = 0; n < 24; n++) {
206
+ [e, s] = [s, (2 * e + 3 * s) % 5], Ht.push(2 * (5 * s + e)), $t.push((n + 1) * (n + 2) / 2 % 64);
207
+ let o = He;
208
+ for (let r = 0; r < 7; r++)
209
+ t = (t << H ^ (t >> Ce) * Ne) % Ue, t & $e && (o ^= H << (H << BigInt(r)) - H);
210
+ Ct.push(o);
211
+ }
212
+ const Ut = ue(Ct, !0), Ve = Ut[0], We = Ut[1], xt = (n, t, e) => e > 32 ? fe(n, t, e) : he(n, t, e), yt = (n, t, e) => e > 32 ? ge(n, t, e) : de(n, t, e);
213
+ function Le(n, t = 24) {
214
+ const e = new Uint32Array(10);
215
+ for (let s = 24 - t; s < 24; s++) {
216
+ for (let i = 0; i < 10; i++)
217
+ e[i] = n[i] ^ n[i + 10] ^ n[i + 20] ^ n[i + 30] ^ n[i + 40];
218
+ for (let i = 0; i < 10; i += 2) {
219
+ const a = (i + 8) % 10, c = (i + 2) % 10, u = e[c], l = e[c + 1], m = xt(u, l, 1) ^ e[a], w = yt(u, l, 1) ^ e[a + 1];
220
+ for (let P = 0; P < 50; P += 10)
221
+ n[i + P] ^= m, n[i + P + 1] ^= w;
222
+ }
223
+ let o = n[2], r = n[3];
224
+ for (let i = 0; i < 24; i++) {
225
+ const a = $t[i], c = xt(o, r, a), u = yt(o, r, a), l = Ht[i];
226
+ o = n[l], r = n[l + 1], n[l] = c, n[l + 1] = u;
227
+ }
228
+ for (let i = 0; i < 50; i += 10) {
229
+ for (let a = 0; a < 10; a++)
230
+ e[a] = n[i + a];
231
+ for (let a = 0; a < 10; a++)
232
+ n[i + a] ^= ~e[(a + 2) % 10] & e[(a + 4) % 10];
233
+ }
234
+ n[0] ^= Ve[s], n[1] ^= We[s];
235
+ }
236
+ F(e);
237
+ }
238
+ class et {
239
+ // NOTE: we accept arguments in bytes instead of bits here.
240
+ constructor(t, e, s, o = !1, r = 24) {
241
+ y(this, "state");
242
+ y(this, "pos", 0);
243
+ y(this, "posOut", 0);
244
+ y(this, "finished", !1);
245
+ y(this, "state32");
246
+ y(this, "destroyed", !1);
247
+ y(this, "blockLen");
248
+ y(this, "suffix");
249
+ y(this, "outputLen");
250
+ y(this, "enableXOF", !1);
251
+ y(this, "rounds");
252
+ if (this.blockLen = t, this.suffix = e, this.outputLen = s, this.enableXOF = o, this.rounds = r, st(s, "outputLen"), !(0 < t && t < 200))
253
+ throw new Error("only keccak-f1600 function is supported");
254
+ this.state = new Uint8Array(200), this.state32 = Mt(this.state);
255
+ }
256
+ clone() {
257
+ return this._cloneInto();
258
+ }
259
+ keccak() {
260
+ ot(this.state32), Le(this.state32, this.rounds), ot(this.state32), this.posOut = 0, this.pos = 0;
261
+ }
262
+ update(t) {
263
+ rt(this), it(t);
264
+ const { blockLen: e, state: s } = this, o = t.length;
265
+ for (let r = 0; r < o; ) {
266
+ const i = Math.min(e - this.pos, o - r);
267
+ for (let a = 0; a < i; a++)
268
+ s[this.pos++] ^= t[r++];
269
+ this.pos === e && this.keccak();
270
+ }
271
+ return this;
272
+ }
273
+ finish() {
274
+ if (this.finished)
275
+ return;
276
+ this.finished = !0;
277
+ const { state: t, suffix: e, pos: s, blockLen: o } = this;
278
+ t[s] ^= e, (e & 128) !== 0 && s === o - 1 && this.keccak(), t[o - 1] ^= 128, this.keccak();
279
+ }
280
+ writeInto(t) {
281
+ rt(this, !1), it(t), this.finish();
282
+ const e = this.state, { blockLen: s } = this;
283
+ for (let o = 0, r = t.length; o < r; ) {
284
+ this.posOut >= s && this.keccak();
285
+ const i = Math.min(s - this.posOut, r - o);
286
+ t.set(e.subarray(this.posOut, this.posOut + i), o), this.posOut += i, o += i;
287
+ }
288
+ return t;
289
+ }
290
+ xofInto(t) {
291
+ if (!this.enableXOF)
292
+ throw new Error("XOF is not possible for this instance");
293
+ return this.writeInto(t);
294
+ }
295
+ xof(t) {
296
+ return st(t), this.xofInto(new Uint8Array(t));
297
+ }
298
+ digestInto(t) {
299
+ if (Xt(t, this), this.finished)
300
+ throw new Error("digest() was already called");
301
+ return this.writeInto(t), this.destroy(), t;
302
+ }
303
+ digest() {
304
+ return this.digestInto(new Uint8Array(this.outputLen));
305
+ }
306
+ destroy() {
307
+ this.destroyed = !0, F(this.state);
308
+ }
309
+ _cloneInto(t) {
310
+ const { blockLen: e, suffix: s, outputLen: o, rounds: r, enableXOF: i } = this;
311
+ return t || (t = new et(e, s, o, i, r)), t.state32.set(this.state32), t.pos = this.pos, t.posOut = this.posOut, t.finished = this.finished, t.rounds = r, t.suffix = s, t.outputLen = o, t.enableXOF = i, t.destroyed = this.destroyed, t;
312
+ }
313
+ }
314
+ const Fe = (n, t, e, s = {}) => Tt(() => new et(t, n, e), s), Me = /* @__PURE__ */ Fe(1, 136, 32), kt = 64, _ = 20, J = 4, Nt = 2, Xe = 0, Ke = 1, W = [64, 64], De = (n) => Array.from(n).map((t) => t.toString(16).padStart(2, "0")).join("");
315
+ function nt(n) {
316
+ return Re(tt(n));
317
+ }
318
+ function Vt(n) {
319
+ return (1 << n) - 1;
320
+ }
321
+ function ze(n) {
322
+ let t = 1;
323
+ for (; t * t < n + 1; ) t++;
324
+ return Math.max(t, 2);
325
+ }
326
+ function Ge(n) {
327
+ const t = J, e = n * Vt(t);
328
+ return { d: t, n, checksum_radix: ze(e) };
329
+ }
330
+ function z(n, t) {
331
+ const e = [];
332
+ let s = t;
333
+ for (; s > 0; )
334
+ e.push(s & 255), s >>>= 8;
335
+ const o = new Uint8Array(n.length + e.length);
336
+ o.set(n);
337
+ for (let r = 0; r < e.length; r++)
338
+ o[n.length + r] = e[r];
339
+ return nt(o);
340
+ }
341
+ function G(n, t) {
342
+ let e = n;
343
+ for (let s = 0; s < t; s++)
344
+ e = nt(e);
345
+ return e;
346
+ }
347
+ function je(n, t) {
348
+ const e = Vt(t.d), s = t.checksum_radix - 1, o = Math.floor(t.n * e / t.checksum_radix), r = [];
349
+ for (let l = 0; l < t.n; l++) {
350
+ const m = z(n, l + Nt), w = G(m, e);
351
+ r.push(Array.from(w));
352
+ }
353
+ const i = z(
354
+ n,
355
+ Xe
356
+ ), a = G(
357
+ i,
358
+ s
359
+ ), c = z(
360
+ n,
361
+ Ke
362
+ ), u = G(
363
+ c,
364
+ o
365
+ );
366
+ return {
367
+ config: t,
368
+ message_terminals: r,
369
+ checksum_major_terminal: Array.from(u),
370
+ checksum_minor_terminal: Array.from(a)
371
+ };
372
+ }
373
+ async function qe(n) {
374
+ try {
375
+ if (n.length !== kt)
376
+ throw new Error(
377
+ `WOTS seed must be exactly ${kt} bytes, got ${n.length}`
378
+ );
379
+ const t = [];
380
+ for (let e = 0; e < W.length; e++) {
381
+ const s = W[e], o = Ge(s), r = new Uint8Array(n.length + 1);
382
+ r.set(n), r[n.length] = e;
383
+ const i = nt(r);
384
+ try {
385
+ const a = je(i, o);
386
+ if (a.config.d !== J)
387
+ throw new Error(
388
+ `Block ${e}: expected d=${J}, got d=${a.config.d}`
389
+ );
390
+ if (a.config.n !== s)
391
+ throw new Error(
392
+ `Block ${e}: expected n=${s}, got n=${a.config.n}`
393
+ );
394
+ if (a.message_terminals.length !== s)
395
+ throw new Error(
396
+ `Block ${e}: expected ${s} message terminals, got ${a.message_terminals.length}`
397
+ );
398
+ for (let c = 0; c < a.message_terminals.length; c++)
399
+ if (a.message_terminals[c].length !== _)
400
+ throw new Error(
401
+ `Block ${e} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`
402
+ );
403
+ if (a.checksum_minor_terminal.length !== _)
404
+ throw new Error(
405
+ `Block ${e} checksum_minor: expected ${_} bytes`
406
+ );
407
+ if (a.checksum_major_terminal.length !== _)
408
+ throw new Error(
409
+ `Block ${e} checksum_major: expected ${_} bytes`
410
+ );
411
+ t.push(a);
412
+ } finally {
413
+ r.fill(0), i.fill(0);
414
+ }
415
+ }
416
+ if (t.length !== W.length)
417
+ throw new Error(
418
+ `Expected ${W.length} blocks, got ${t.length}`
419
+ );
420
+ return t;
421
+ } finally {
422
+ n.fill(0);
423
+ }
424
+ }
425
+ function j(n, t, e) {
426
+ if (n.length !== _)
427
+ throw new Error(
428
+ `Block ${t} ${e}: expected ${_} bytes, got ${n.length}`
429
+ );
430
+ for (let s = 0; s < n.length; s++) {
431
+ const o = n[s];
432
+ if (!Number.isInteger(o) || o < 0 || o > 255)
433
+ throw new Error(
434
+ `Block ${t} ${e}[${s}]: invalid byte value ${o}`
435
+ );
436
+ }
437
+ }
438
+ function Ze(n) {
439
+ if (n.length === 0)
440
+ throw new Error("Public keys array must not be empty");
441
+ for (let r = 0; r < n.length; r++) {
442
+ const i = n[r];
443
+ j(i.checksum_minor_terminal, r, "checksum_minor_terminal"), j(i.checksum_major_terminal, r, "checksum_major_terminal");
444
+ for (let a = 0; a < i.message_terminals.length; a++)
445
+ j(i.message_terminals[a], r, `message_terminal[${a}]`);
446
+ }
447
+ let t = 0;
448
+ for (const r of n)
449
+ t += Nt + r.message_terminals.length;
450
+ const e = new Uint8Array(t * _);
451
+ let s = 0;
452
+ for (const r of n) {
453
+ e.set(r.checksum_minor_terminal, s), s += _, e.set(r.checksum_major_terminal, s), s += _;
454
+ for (const i of r.message_terminals)
455
+ e.set(i, s), s += _;
456
+ }
457
+ const o = Me(e);
458
+ return `0x${De(o)}`;
459
+ }
460
+ async function Qe(n, t) {
461
+ const e = [], s = [], o = [], r = [];
462
+ try {
463
+ for (let i = 0; i < t; i++) {
464
+ const a = await zt(n, i);
465
+ try {
466
+ const u = await qe(a);
467
+ e.push(u), s.push(Ze(u));
468
+ } finally {
469
+ a.fill(0);
470
+ }
471
+ const c = await Gt(n, i);
472
+ try {
473
+ const u = M(c);
474
+ o.push(u), r.push(ne(I(u)).slice(2));
475
+ } finally {
476
+ c.fill(0);
477
+ }
478
+ }
479
+ } finally {
480
+ n.fill(0);
481
+ }
482
+ return { perVaultWotsKeys: e, wotsPkHashes: s, htlcSecretHexes: o, hashlocks: r };
483
+ }
484
+ const Ye = /^0x[0-9a-f]+$/i, Je = /^[0-9a-f]+$/i, tn = /^[A-Za-z0-9+/]+={0,2}$/;
485
+ function $(n) {
486
+ if (typeof n != "string" || n.length === 0)
487
+ throw new Error("BTC wallet returned empty public key");
488
+ return Jt(n).toLowerCase();
489
+ }
490
+ function en(n) {
491
+ if (typeof n != "string" || n.length === 0)
492
+ throw new Error("BTC wallet returned empty BIP-322 signature");
493
+ if (n.startsWith("0x") || n.startsWith("0X")) {
494
+ if (!Ye.test(n) || n.length < 4 || n.length % 2 !== 0)
495
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
496
+ return n.toLowerCase();
497
+ }
498
+ if (Je.test(n)) {
499
+ if (n.length % 2 !== 0)
500
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
501
+ return `0x${n.toLowerCase()}`;
502
+ }
503
+ if (!tn.test(n) || n.length % 4 !== 0)
504
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
505
+ const t = q.from(n, "base64");
506
+ if (t.length === 0 || t.toString("base64") !== n)
507
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
508
+ return `0x${t.toString("hex")}`;
509
+ }
510
+ async function nn(n, t, e) {
511
+ if (typeof n.signPsbts == "function") {
512
+ const o = await n.signPsbts(t, e);
513
+ if (o.length !== t.length)
514
+ throw new Error(
515
+ `Expected ${t.length} signed PSBTs but received ${o.length}`
516
+ );
517
+ return o;
518
+ }
519
+ const s = [];
520
+ for (let o = 0; o < t.length; o++) {
521
+ const r = await n.signPsbt(t[o], e[o]);
522
+ s.push(r);
523
+ }
524
+ return s;
525
+ }
526
+ const sn = 0, L = "00".repeat(32);
527
+ function on(n, t, e, s) {
528
+ const o = e == null ? void 0 : e[`${n}:${t}`];
529
+ return o ? Promise.resolve({
530
+ txid: n,
531
+ vout: t,
532
+ value: o.value,
533
+ scriptPubKey: o.scriptPubKey
534
+ }) : ce(n, t, s);
535
+ }
536
+ const Et = 12e4;
537
+ class kn {
538
+ /**
539
+ * Creates a new PeginManager instance.
540
+ *
541
+ * @param config - Manager configuration including wallets and contract addresses
542
+ */
543
+ constructor(t) {
544
+ y(this, "config");
545
+ this.config = t;
546
+ }
547
+ /**
548
+ * Prepare a peg-in: sizing pass → vault-root derivation (one wallet
549
+ * popup) → per-vault WOTS / hashlock derivation → commit pass with
550
+ * batch PSBT signing (one popup). Returns broadcast-ready txs, the
551
+ * pubkey snapshot, and the sensitive derived material.
552
+ *
553
+ * @throws If the wallet rejects, insufficient funds, or an internal
554
+ * invariant violation.
555
+ */
556
+ async preparePegin(t) {
557
+ if (t.amounts.length === 0)
558
+ throw new Error("amounts must contain at least one entry");
559
+ const e = await this.config.btcWallet.getPublicKeyHex(), s = $(e), o = await this.prepareSizing(s, t), r = o.selectedUTXOs.map(
560
+ (g) => ({
561
+ txid: Z(g.txid),
562
+ vout: g.vout
563
+ })
564
+ ), i = await Te(this.config.btcWallet, {
565
+ depositorBtcPubkey: Z(s),
566
+ fundingOutpoints: r
567
+ });
568
+ let a, c;
569
+ try {
570
+ const g = await jt(i);
571
+ try {
572
+ a = M(g), c = M(tt(g));
573
+ } finally {
574
+ g.fill(0);
575
+ }
576
+ } catch (g) {
577
+ throw i.fill(0), g;
578
+ }
579
+ const u = await Qe(i, t.amounts.length), { perVaultWotsKeys: l, wotsPkHashes: m, htlcSecretHexes: w, hashlocks: P } = u, h = await this.preparePeginCommit({
580
+ depositorBtcPubkeyRaw: e,
581
+ depositorBtcPubkey: s,
582
+ hashlocks: P,
583
+ authAnchorHash: c,
584
+ sizing: o,
585
+ params: t
586
+ });
587
+ for (let g = 0; g < h.perVault.length; g++)
588
+ if (h.perVault[g].htlcVout !== g)
589
+ throw new Error(
590
+ `Internal invariant violation: htlcVout/index mismatch at vault ${g} (expected ${g}, got ${h.perVault[g].htlcVout})`
591
+ );
592
+ return we(
593
+ h.fundedPrePeginTxHex,
594
+ t.amounts.length,
595
+ c
596
+ ), {
597
+ transaction: {
598
+ ...h,
599
+ selectedUTXOs: o.selectedUTXOs,
600
+ fee: o.fee,
601
+ changeAmount: o.changeAmount
602
+ },
603
+ depositorBtcPubkey: s,
604
+ derivedSecrets: {
605
+ perVaultWotsKeys: l,
606
+ wotsPkHashes: m,
607
+ htlcSecretHexes: w,
608
+ authAnchorHex: a
609
+ }
610
+ };
611
+ }
612
+ /**
613
+ * Build unfunded Pre-PegIn + select UTXOs. No PSBT signing.
614
+ *
615
+ * Returns the full selection result (UTXOs, fee, changeAmount) so the
616
+ * commit pass funds the broadcast tx with the exact same set used to
617
+ * build the vault-context funding-outpoints commitment. Re-running
618
+ * `selectUtxosForPegin` in the commit pass would be deterministic given
619
+ * the same inputs, but threading the result through guarantees the
620
+ * domain separator structurally matches the funded tx inputs.
621
+ *
622
+ * Sizing runs before the wallet popup, so neither the real per-vault
623
+ * hashlocks nor the real `authAnchorHash` are known yet. Both slots
624
+ * are filled with a 32-byte placeholder; the commit pass swaps in the
625
+ * real values. Output budget is identical (32-byte push regardless of
626
+ * content), so UTXO selection is invariant under substitution.
627
+ */
628
+ async prepareSizing(t, e) {
629
+ const s = e.amounts.map(
630
+ () => L
631
+ ), o = e.vaultKeeperBtcPubkeys.length, r = await ht({
632
+ depositorPubkey: t,
633
+ vaultProviderPubkey: T(e.vaultProviderBtcPubkey),
634
+ vaultKeeperPubkeys: e.vaultKeeperBtcPubkeys.map(T),
635
+ universalChallengerPubkeys: e.universalChallengerBtcPubkeys.map(T),
636
+ hashlocks: s,
637
+ timelockRefund: e.timelockRefund,
638
+ pegInAmounts: e.amounts,
639
+ feeRate: e.protocolFeeRate,
640
+ numLocalChallengers: o,
641
+ councilQuorum: e.councilQuorum,
642
+ councilSize: e.councilSize,
643
+ network: this.config.btcNetwork,
644
+ authAnchorHash: L
645
+ }), i = se(
646
+ [...e.availableUTXOs],
647
+ r.totalOutputValue,
648
+ e.mempoolFeeRate,
649
+ re(
650
+ r.htlcValues.length,
651
+ L
652
+ )
653
+ );
654
+ return {
655
+ selectedUTXOs: i.selectedUTXOs,
656
+ fee: i.fee,
657
+ changeAmount: i.changeAmount
658
+ };
659
+ }
660
+ /** Build PegIn txs and batch-sign their inputs with real hashlocks. */
661
+ async preparePeginCommit(t) {
662
+ const {
663
+ depositorBtcPubkeyRaw: e,
664
+ depositorBtcPubkey: s,
665
+ hashlocks: o,
666
+ authAnchorHash: r,
667
+ sizing: i,
668
+ params: a
669
+ } = t, c = L.toLowerCase();
670
+ for (let p = 0; p < o.length; p++)
671
+ if (o[p].toLowerCase() === c)
672
+ throw new Error(
673
+ `preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${p} — internal substitution bug`
674
+ );
675
+ if (r.toLowerCase() === c)
676
+ throw new Error(
677
+ "preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug"
678
+ );
679
+ const u = T(a.vaultProviderBtcPubkey), l = a.vaultKeeperBtcPubkeys.map(T), m = a.universalChallengerBtcPubkeys.map(T), w = l.length, P = {
680
+ depositorPubkey: s,
681
+ vaultProviderPubkey: u,
682
+ vaultKeeperPubkeys: l,
683
+ universalChallengerPubkeys: m,
684
+ hashlocks: o,
685
+ timelockRefund: a.timelockRefund,
686
+ pegInAmounts: a.amounts,
687
+ feeRate: a.protocolFeeRate,
688
+ numLocalChallengers: w,
689
+ councilQuorum: a.councilQuorum,
690
+ councilSize: a.councilSize,
691
+ network: this.config.btcNetwork,
692
+ authAnchorHash: r
693
+ }, h = await ht(P), g = dt(this.config.btcNetwork), E = ie({
694
+ unfundedTxHex: h.psbtHex,
695
+ selectedUTXOs: i.selectedUTXOs,
696
+ changeAddress: a.changeAddress,
697
+ changeAmount: i.changeAmount,
698
+ network: g
699
+ }), S = T(K(E)), f = [], x = [], d = [];
700
+ for (let p = 0; p < o.length; p++) {
701
+ const v = await qt({
702
+ prePeginParams: P,
703
+ timelockPegin: a.timelockPegin,
704
+ fundedPrePeginTxHex: E,
705
+ htlcVout: p
706
+ }), B = await Zt({
707
+ peginTxHex: v.txHex,
708
+ fundedPrePeginTxHex: E,
709
+ depositorPubkey: s,
710
+ vaultProviderPubkey: u,
711
+ vaultKeeperPubkeys: l,
712
+ universalChallengerPubkeys: m,
713
+ hashlock: o[p],
714
+ timelockRefund: a.timelockRefund,
715
+ network: this.config.btcNetwork
716
+ });
717
+ f.push(v), x.push(B.psbtHex), d.push(
718
+ ee(e, 1)
719
+ );
720
+ }
721
+ const k = await nn(
722
+ this.config.btcWallet,
723
+ x,
724
+ d
725
+ ), b = [];
726
+ for (let p = 0; p < k.length; p++) {
727
+ const v = Qt(
728
+ k[p],
729
+ s
730
+ ), B = Yt(k[p]);
731
+ b.push({
732
+ htlcVout: p,
733
+ htlcValue: h.htlcValues[p],
734
+ peginTxHex: B,
735
+ peginTxid: f[p].txid,
736
+ peginInputSignature: v,
737
+ vaultScriptPubKey: f[p].vaultScriptPubKey
738
+ });
739
+ }
740
+ return {
741
+ fundedPrePeginTxHex: E,
742
+ prePeginTxid: S,
743
+ perVault: b
744
+ };
745
+ }
746
+ /**
747
+ * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
748
+ *
749
+ * This method:
750
+ * 1. Parses the funded transaction hex
751
+ * 2. Fetches UTXO data from mempool for each input
752
+ * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
753
+ * 4. Signs via btcWallet.signPsbt()
754
+ * 5. Finalizes and extracts the transaction
755
+ * 6. Broadcasts via mempool API
756
+ *
757
+ * @param params - Transaction hex and depositor public key
758
+ * @returns The broadcasted Bitcoin transaction ID
759
+ * @throws Error if signing or broadcasting fails
760
+ */
761
+ async signAndBroadcast(t) {
762
+ const { fundedPrePeginTxHex: e, depositorBtcPubkey: s } = t, o = e.startsWith("0x") ? e.slice(2) : e, r = Kt.fromHex(o);
763
+ if (r.ins.length === 0)
764
+ throw new Error("Transaction has no inputs");
765
+ const i = new at();
766
+ i.setVersion(r.version), i.setLocktime(r.locktime);
767
+ const a = q.from(
768
+ $(s),
769
+ "hex"
770
+ ), c = this.config.mempoolApiUrl, u = r.ins.map((f) => {
771
+ const x = q.from(f.hash).reverse().toString("hex"), d = f.index;
772
+ return on(x, d, t.localPrevouts, c).then(
773
+ (k) => ({ input: f, utxoData: k, txid: x, vout: d })
774
+ );
775
+ }), l = await Promise.all(u), m = l.reduce(
776
+ (f, x) => f + BigInt(x.utxoData.value),
777
+ 0n
778
+ ), w = r.outs.reduce(
779
+ (f, x) => f + BigInt(x.value),
780
+ 0n
781
+ );
782
+ if (m < w)
783
+ throw new Error(
784
+ `UTXO value mismatch: total input value (${m} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`
785
+ );
786
+ const P = m - w;
787
+ if (P > ft)
788
+ throw new Error(
789
+ `Implied transaction fee (${P} sat) exceeds maximum reasonable fee (${ft} sat). This may indicate manipulated UTXO data.`
790
+ );
791
+ for (const { input: f, utxoData: x, txid: d, vout: k } of l) {
792
+ const b = oe(
793
+ {
794
+ value: x.value,
795
+ scriptPubKey: x.scriptPubKey
796
+ },
797
+ a
798
+ );
799
+ i.addInput({
800
+ hash: f.hash,
801
+ index: f.index,
802
+ sequence: f.sequence,
803
+ ...b
804
+ });
805
+ }
806
+ for (const f of r.outs)
807
+ i.addOutput({
808
+ script: f.script,
809
+ value: f.value
810
+ });
811
+ const h = await this.config.btcWallet.signPsbt(i.toHex()), g = at.fromHex(h);
812
+ try {
813
+ g.finalizeAllInputs();
814
+ } catch (f) {
815
+ if (!g.data.inputs.every(
816
+ (d) => d.finalScriptWitness || d.finalScriptSig
817
+ ))
818
+ throw new Error(
819
+ `PSBT finalization failed and wallet did not auto-finalize: ${f}`
820
+ );
821
+ }
822
+ const E = g.extractTransaction().toHex();
823
+ return await ae(E, c);
824
+ }
825
+ /**
826
+ * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.
827
+ *
828
+ * This method:
829
+ * 1. Re-verifies the PopSignature against the currently connected ETH
830
+ * and BTC wallets — refuses to proceed if either has changed
831
+ * 2. Derives vault ID and checks if it already exists (pre-flight)
832
+ * 3. Encodes the contract call using viem
833
+ * 4. Estimates gas (catches contract errors early with proper revert
834
+ * reasons)
835
+ * 5. Sends transaction with pre-estimated gas via
836
+ * ethWallet.sendTransaction()
837
+ *
838
+ * The PopSignature must be obtained via
839
+ * {@link signProofOfPossession} before this call.
840
+ *
841
+ * @param params - Registration parameters including the PopSignature
842
+ * and the prepared Pre-PegIn / PegIn transactions
843
+ * @returns Result containing Ethereum transaction hash and vault ID
844
+ * @throws Error if the PopSignature does not match the connected wallets
845
+ * @throws Error if the vault already exists
846
+ * @throws Error if contract simulation fails (e.g., invalid signature,
847
+ * unauthorized)
848
+ */
849
+ async registerPeginOnChain(t) {
850
+ const {
851
+ unsignedPrePeginTx: e,
852
+ depositorSignedPeginTx: s,
853
+ vaultProvider: o,
854
+ hashlock: r,
855
+ htlcVout: i,
856
+ depositorPayoutBtcAddress: a,
857
+ depositorWotsPkHash: c,
858
+ popSignature: u
859
+ } = t;
860
+ if (!this.config.ethWallet.account)
861
+ throw new Error("Ethereum wallet account not found");
862
+ const l = this.config.ethWallet.account.address;
863
+ if (!ct(u.depositorEthAddress, l))
864
+ throw new Error(
865
+ `Proof of possession was signed for ${u.depositorEthAddress} but the Ethereum wallet is currently connected to ${l}. Reconnect the original account or call signProofOfPossession() again.`
866
+ );
867
+ await this.assertPopMatchesBtcWallet(u);
868
+ const m = u.btcPopSignature, w = I(u.depositorBtcPubkey), P = I(e), h = I(s), g = await this.resolvePayoutScriptPubKey(
869
+ a
870
+ ), E = K(h), S = await ut(
871
+ T(E),
872
+ T(l)
873
+ ), f = I(S);
874
+ if (await this.checkVaultExists(f))
875
+ throw new Error(
876
+ `Vault already exists (ID: ${f}, peginTxHash: ${E}). 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.`
877
+ );
878
+ const d = this.config.publicClient;
879
+ let k;
880
+ try {
881
+ k = await d.readContract({
882
+ address: this.config.vaultContracts.btcVaultRegistry,
883
+ abi: R,
884
+ functionName: "getPegInFee",
885
+ args: [o]
886
+ });
887
+ } catch (O) {
888
+ throw new Error(
889
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
890
+ { cause: O }
891
+ );
892
+ }
893
+ const b = lt({
894
+ abi: R,
895
+ functionName: "submitPeginRequest",
896
+ args: [
897
+ l,
898
+ w,
899
+ m,
900
+ P,
901
+ h,
902
+ o,
903
+ r,
904
+ i,
905
+ g,
906
+ c
907
+ ]
908
+ });
909
+ let p;
910
+ try {
911
+ p = await d.estimateGas({
912
+ to: this.config.vaultContracts.btcVaultRegistry,
913
+ data: b,
914
+ value: k,
915
+ account: this.config.ethWallet.account.address
916
+ });
917
+ } catch (O) {
918
+ A(O);
919
+ }
920
+ let v;
921
+ try {
922
+ v = await this.config.ethWallet.sendTransaction({
923
+ to: this.config.vaultContracts.btcVaultRegistry,
924
+ data: b,
925
+ value: k,
926
+ account: this.config.ethWallet.account,
927
+ chain: this.config.ethChain,
928
+ gas: p
929
+ });
930
+ } catch (O) {
931
+ A(O);
932
+ }
933
+ const B = await gt({
934
+ publicClient: d,
935
+ walletAddress: this.config.ethWallet.account.address,
936
+ hash: v,
937
+ timeout: Et
938
+ });
939
+ return B.status === "reverted" && A(
940
+ new Error(
941
+ `Transaction reverted. Hash: ${B.transactionHash}. Check the transaction on block explorer for details.`
942
+ )
943
+ ), {
944
+ ethTxHash: B.transactionHash,
945
+ vaultId: f,
946
+ peginTxHash: E
947
+ };
948
+ }
949
+ /**
950
+ * Register multiple pegins on Ethereum in a single transaction.
951
+ *
952
+ * Uses the contract's submitPeginRequestBatch() to submit all vault
953
+ * registrations atomically. All vaults must share the same vault provider.
954
+ * The PoP signature is signed once and included in each request.
955
+ *
956
+ * @param params - Batch registration parameters
957
+ * @returns Batch result with per-vault IDs and single ETH tx hash
958
+ */
959
+ async registerPeginBatchOnChain(t) {
960
+ const { vaultProvider: e, unsignedPrePeginTx: s, requests: o, popSignature: r } = t;
961
+ if (o.length === 0)
962
+ throw new Error("Batch pegin requires at least one request");
963
+ if (!this.config.ethWallet.account)
964
+ throw new Error("Ethereum wallet account not found");
965
+ const i = this.config.ethWallet.account.address;
966
+ if (!ct(r.depositorEthAddress, i))
967
+ throw new Error(
968
+ `Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`
969
+ );
970
+ await this.assertPopMatchesBtcWallet(r);
971
+ const a = r.btcPopSignature, c = [];
972
+ for (const d of o)
973
+ c.push(
974
+ await this.resolvePayoutScriptPubKey(d.depositorPayoutBtcAddress)
975
+ );
976
+ const u = [];
977
+ for (const d of o) {
978
+ const k = I(
979
+ d.depositorSignedPeginTx
980
+ ), b = K(k), p = await ut(
981
+ T(b),
982
+ T(i)
983
+ ), v = I(p);
984
+ if (await this.checkVaultExists(v))
985
+ throw new Error(
986
+ `Vault already exists (ID: ${v}, peginTxHash: ${b}). To create a new vault, use different UTXOs or a different amount.`
987
+ );
988
+ u.push({ vaultId: v, peginTxHash: b });
989
+ }
990
+ const l = this.config.publicClient;
991
+ let m;
992
+ try {
993
+ m = await l.readContract({
994
+ address: this.config.vaultContracts.btcVaultRegistry,
995
+ abi: R,
996
+ functionName: "getPegInFee",
997
+ args: [e]
998
+ });
999
+ } catch (d) {
1000
+ throw new Error(
1001
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
1002
+ { cause: d }
1003
+ );
1004
+ }
1005
+ const w = m * BigInt(o.length), P = I(
1006
+ r.depositorBtcPubkey
1007
+ ), h = I(s), g = o.map((d, k) => ({
1008
+ depositorBtcPubKey: P,
1009
+ btcPopSignature: a,
1010
+ unsignedPrePeginTx: h,
1011
+ depositorSignedPeginTx: I(
1012
+ d.depositorSignedPeginTx
1013
+ ),
1014
+ hashlock: d.hashlock,
1015
+ htlcVout: d.htlcVout,
1016
+ referralCode: sn,
1017
+ depositorPayoutBtcAddress: c[k],
1018
+ depositorWotsPkHash: d.depositorWotsPkHash
1019
+ })), E = lt({
1020
+ abi: R,
1021
+ functionName: "submitPeginRequestBatch",
1022
+ args: [i, e, g]
1023
+ });
1024
+ let S;
1025
+ try {
1026
+ S = await l.estimateGas({
1027
+ to: this.config.vaultContracts.btcVaultRegistry,
1028
+ data: E,
1029
+ value: w,
1030
+ account: this.config.ethWallet.account.address
1031
+ });
1032
+ } catch (d) {
1033
+ A(d);
1034
+ }
1035
+ let f;
1036
+ try {
1037
+ f = await this.config.ethWallet.sendTransaction({
1038
+ to: this.config.vaultContracts.btcVaultRegistry,
1039
+ data: E,
1040
+ value: w,
1041
+ account: this.config.ethWallet.account,
1042
+ chain: this.config.ethChain,
1043
+ gas: S
1044
+ });
1045
+ } catch (d) {
1046
+ A(d);
1047
+ }
1048
+ const x = await gt({
1049
+ publicClient: l,
1050
+ walletAddress: this.config.ethWallet.account.address,
1051
+ hash: f,
1052
+ timeout: Et
1053
+ });
1054
+ return x.status === "reverted" && A(
1055
+ new Error(
1056
+ `Batch transaction reverted. Hash: ${x.transactionHash}. Check the transaction on block explorer for details.`
1057
+ )
1058
+ ), {
1059
+ ethTxHash: x.transactionHash,
1060
+ vaults: u
1061
+ };
1062
+ }
1063
+ /**
1064
+ * Check if a vault already exists for a given vault ID.
1065
+ *
1066
+ * The contract returns a default struct (with `depositor === zeroAddress`)
1067
+ * when no vault is registered, so existence is signalled in the response,
1068
+ * not via a thrown error. RPC/network failures are propagated rather than
1069
+ * silently treated as "vault doesn't exist", which would otherwise let
1070
+ * downstream calls run with stale assumptions.
1071
+ *
1072
+ * @param vaultId - The Bitcoin transaction hash (vault ID)
1073
+ * @returns True if vault exists, false otherwise
1074
+ * @throws If the underlying RPC read fails
1075
+ */
1076
+ async checkVaultExists(t) {
1077
+ return (await this.config.publicClient.readContract({
1078
+ address: this.config.vaultContracts.btcVaultRegistry,
1079
+ abi: R,
1080
+ functionName: "getBtcVaultBasicInfo",
1081
+ args: [t]
1082
+ })).depositor !== Dt;
1083
+ }
1084
+ /**
1085
+ * Resolve the BTC payout address to a scriptPubKey hex for the contract.
1086
+ *
1087
+ * If a payout address is provided, converts it directly.
1088
+ * If omitted, uses the wallet's address and validates it against the
1089
+ * wallet's public key to guard against a compromised wallet provider.
1090
+ */
1091
+ async resolvePayoutScriptPubKey(t) {
1092
+ let e;
1093
+ if (t)
1094
+ e = t;
1095
+ else {
1096
+ e = await this.config.btcWallet.getAddress();
1097
+ const o = await this.config.btcWallet.getPublicKeyHex();
1098
+ if (!te(
1099
+ e,
1100
+ o,
1101
+ this.config.btcNetwork
1102
+ ))
1103
+ throw new Error(
1104
+ "The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit)."
1105
+ );
1106
+ }
1107
+ const s = dt(this.config.btcNetwork);
1108
+ try {
1109
+ return `0x${_t.address.toOutputScript(e, s).toString("hex")}`;
1110
+ } catch {
1111
+ throw new Error(
1112
+ `Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
1113
+ );
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Sign a BIP-322 BTC Proof-of-Possession binding the connected BTC
1118
+ * wallet to the connected ETH account for this chain and vault
1119
+ * registry. The returned {@link PopSignature} can be reused across
1120
+ * every register call in the same session.
1121
+ */
1122
+ async signProofOfPossession() {
1123
+ if (!this.config.ethWallet.account)
1124
+ throw new Error("Ethereum wallet account not found");
1125
+ const t = this.config.ethWallet.account.address, e = $(
1126
+ await this.config.btcWallet.getPublicKeyHex()
1127
+ ), s = this.config.vaultContracts.btcVaultRegistry, o = `${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`, r = await this.config.btcWallet.signMessage(
1128
+ o,
1129
+ "bip322-simple"
1130
+ );
1131
+ return {
1132
+ btcPopSignature: en(r),
1133
+ depositorEthAddress: t,
1134
+ depositorBtcPubkey: e
1135
+ };
1136
+ }
1137
+ async assertPopMatchesBtcWallet(t) {
1138
+ const e = $(
1139
+ await this.config.btcWallet.getPublicKeyHex()
1140
+ ), s = $(t.depositorBtcPubkey);
1141
+ if (e !== s)
1142
+ throw new Error(
1143
+ `Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${e}. Reconnect the original wallet or call signProofOfPossession() again.`
1144
+ );
1145
+ }
1146
+ /**
1147
+ * Gets the configured Bitcoin network.
1148
+ *
1149
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1150
+ */
1151
+ getNetwork() {
1152
+ return this.config.btcNetwork;
1153
+ }
1154
+ /**
1155
+ * Gets the configured BTCVaultRegistry contract address.
1156
+ *
1157
+ * @returns The Ethereum address of the BTCVaultRegistry contract
1158
+ */
1159
+ getVaultContractAddress() {
1160
+ return this.config.vaultContracts.btcVaultRegistry;
1161
+ }
1162
+ }
1163
+ export {
1164
+ kn as P,
1165
+ ke as V,
1166
+ ye as a,
1167
+ xe as b,
1168
+ Ze as c,
1169
+ qe as d,
1170
+ Te as e
1171
+ };
1172
+ //# sourceMappingURL=PeginManager-DF1oinIQ.js.map