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