@babylonlabs-io/ts-sdk 0.16.2 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/challengeAssert-D_k_ADgP.cjs +2 -0
  2. package/dist/challengeAssert-D_k_ADgP.cjs.map +1 -0
  3. package/dist/challengeAssert-k5_LWUtO.js +362 -0
  4. package/dist/challengeAssert-k5_LWUtO.js.map +1 -0
  5. package/dist/constants-EiyZkXce.cjs +2 -0
  6. package/dist/constants-EiyZkXce.cjs.map +1 -0
  7. package/dist/constants-Q7v2O7Ps.js +155 -0
  8. package/dist/constants-Q7v2O7Ps.js.map +1 -0
  9. package/dist/errors-DKLboMnq.cjs +2 -0
  10. package/dist/errors-DKLboMnq.cjs.map +1 -0
  11. package/dist/errors-KY63mgWT.js +1510 -0
  12. package/dist/errors-KY63mgWT.js.map +1 -0
  13. package/dist/fundPeginTransaction-DpwnDslW.js +50 -0
  14. package/dist/fundPeginTransaction-DpwnDslW.js.map +1 -0
  15. package/dist/fundPeginTransaction-EbrZzlrh.cjs +2 -0
  16. package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +1 -0
  17. package/dist/index-D3z3SZAj.cjs +2 -0
  18. package/dist/index-D3z3SZAj.cjs.map +1 -0
  19. package/dist/index-Dw7FAwne.js +913 -0
  20. package/dist/index-Dw7FAwne.js.map +1 -0
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +98 -74
  23. package/dist/index.js.map +1 -1
  24. package/dist/payout-Ce9vSs9e.js +164 -0
  25. package/dist/payout-Ce9vSs9e.js.map +1 -0
  26. package/dist/payout-CfsDnjKI.cjs +2 -0
  27. package/dist/payout-CfsDnjKI.cjs.map +1 -0
  28. package/dist/psbtInputFields-C0nKn_GD.cjs +2 -0
  29. package/dist/psbtInputFields-C0nKn_GD.cjs.map +1 -0
  30. package/dist/psbtInputFields-DO0ELwiv.js +116 -0
  31. package/dist/psbtInputFields-DO0ELwiv.js.map +1 -0
  32. package/dist/signAndSubmitPayouts-CAOEAQp9.js +490 -0
  33. package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +1 -0
  34. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +2 -0
  35. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +1 -0
  36. package/dist/signing-Deg5lCoC.cjs +2 -0
  37. package/dist/signing-Deg5lCoC.cjs.map +1 -0
  38. package/dist/signing-Drwr3bXB.js +16 -0
  39. package/dist/signing-Drwr3bXB.js.map +1 -0
  40. package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts +2 -0
  41. package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts.map +1 -0
  42. package/dist/tbv/core/clients/eth/index.d.ts +3 -0
  43. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -0
  44. package/dist/tbv/core/clients/eth/types.d.ts +37 -0
  45. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -0
  46. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +20 -0
  47. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -0
  48. package/dist/tbv/core/clients/index.cjs +2 -0
  49. package/dist/tbv/core/clients/index.cjs.map +1 -0
  50. package/dist/tbv/core/clients/index.d.ts +2 -0
  51. package/dist/tbv/core/clients/index.d.ts.map +1 -1
  52. package/dist/tbv/core/clients/index.js +26 -0
  53. package/dist/tbv/core/clients/index.js.map +1 -0
  54. package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts +2 -0
  55. package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts.map +1 -0
  56. package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts +2 -0
  57. package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts.map +1 -0
  58. package/dist/tbv/core/clients/vault-provider/api.d.ts +53 -0
  59. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -0
  60. package/dist/tbv/core/clients/vault-provider/index.d.ts +7 -0
  61. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -0
  62. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +90 -0
  63. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -0
  64. package/dist/tbv/core/clients/vault-provider/types.d.ts +256 -0
  65. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -0
  66. package/dist/tbv/core/clients/vault-provider/validators.d.ts +30 -0
  67. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -0
  68. package/dist/tbv/core/index.cjs +1 -1
  69. package/dist/tbv/core/index.d.ts +1 -0
  70. package/dist/tbv/core/index.d.ts.map +1 -1
  71. package/dist/tbv/core/index.js +97 -73
  72. package/dist/tbv/core/index.js.map +1 -1
  73. package/dist/tbv/core/primitives/index.cjs +1 -1
  74. package/dist/tbv/core/primitives/index.d.ts +8 -0
  75. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  76. package/dist/tbv/core/primitives/index.js +26 -24
  77. package/dist/tbv/core/primitives/index.js.map +1 -1
  78. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts +2 -0
  79. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts.map +1 -0
  80. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.test.d.ts +2 -0
  81. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.test.d.ts.map +1 -0
  82. package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts +2 -0
  83. package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts.map +1 -0
  84. package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts +2 -0
  85. package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts.map +1 -0
  86. package/dist/tbv/core/services/deposit/index.d.ts +10 -0
  87. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -0
  88. package/dist/tbv/core/services/deposit/interfaces.d.ts +21 -0
  89. package/dist/tbv/core/services/deposit/interfaces.d.ts.map +1 -0
  90. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts +55 -0
  91. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +1 -0
  92. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +21 -0
  93. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -0
  94. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts +25 -0
  95. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts.map +1 -0
  96. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts +24 -0
  97. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -0
  98. package/dist/tbv/core/services/index.cjs +2 -0
  99. package/dist/tbv/core/services/index.cjs.map +1 -0
  100. package/dist/tbv/core/services/index.d.ts +10 -0
  101. package/dist/tbv/core/services/index.d.ts.map +1 -0
  102. package/dist/tbv/core/services/index.js +8 -0
  103. package/dist/tbv/core/services/index.js.map +1 -0
  104. package/dist/tbv/core/utils/index.cjs +2 -0
  105. package/dist/tbv/core/utils/index.cjs.map +1 -0
  106. package/dist/tbv/core/utils/index.js +30 -0
  107. package/dist/tbv/core/utils/index.js.map +1 -0
  108. package/dist/tbv/index.cjs +1 -1
  109. package/dist/tbv/index.js +97 -73
  110. package/dist/tbv/index.js.map +1 -1
  111. package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +28 -18
  112. package/dist/tbv/integrations/aave/clients/spoke.d.ts +2 -2
  113. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
  114. package/dist/tbv/integrations/aave/constants.d.ts +7 -0
  115. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  116. package/dist/tbv/integrations/aave/index.cjs +1 -1
  117. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  118. package/dist/tbv/integrations/aave/index.d.ts +2 -2
  119. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  120. package/dist/tbv/integrations/aave/index.js +124 -120
  121. package/dist/tbv/integrations/aave/index.js.map +1 -1
  122. package/dist/tbv/integrations/aave/types.d.ts +4 -6
  123. package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
  124. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts +10 -1
  125. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts.map +1 -1
  126. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts +0 -1
  127. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts.map +1 -1
  128. package/dist/tbv/integrations/aave/utils/index.d.ts +1 -1
  129. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  130. package/dist/types-D1rYwwCu.js +235 -0
  131. package/dist/types-D1rYwwCu.js.map +1 -0
  132. package/dist/types-DEWiqXYp.cjs +2 -0
  133. package/dist/types-DEWiqXYp.cjs.map +1 -0
  134. package/package.json +11 -1
  135. package/dist/challengeAssert-CTajvPAY.cjs +0 -2
  136. package/dist/challengeAssert-CTajvPAY.cjs.map +0 -1
  137. package/dist/challengeAssert-DtrQLG0c.js +0 -711
  138. package/dist/challengeAssert-DtrQLG0c.js.map +0 -1
  139. package/dist/errors-BeFfs5_J.js +0 -2250
  140. package/dist/errors-BeFfs5_J.js.map +0 -1
  141. package/dist/errors-CAFiRPYI.cjs +0 -2
  142. package/dist/errors-CAFiRPYI.cjs.map +0 -1
@@ -1,2250 +0,0 @@
1
- var fe = Object.defineProperty;
2
- var pe = (e, t, n) => t in e ? fe(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var p = (e, t, n) => pe(e, typeof t != "symbol" ? t + "" : t, n);
4
- import * as be from "bitcoinjs-lib";
5
- import { script as ge, Transaction as xt, Psbt as kt } from "bitcoinjs-lib";
6
- import { Buffer as W } from "buffer";
7
- import { createPublicClient as lt, http as ht, encodeFunctionData as Ht, zeroAddress as ye } from "viem";
8
- import { P as xe, y as we, D as Xt, M as It, B as me, T as Pe, u as B, b as Te, A as ve, G as Et, E as ke, a as He, d as Ie, e as Ee, f as Be, s as U, q as Se, x as Bt, h as St, i as At, r as Ae } from "./challengeAssert-DtrQLG0c.js";
9
- import { deriveVaultId as Ut } from "@babylonlabs-io/babylon-tbv-rust-wasm";
10
- function Ue(e, t, n, s) {
11
- if (!Number.isInteger(s) || s < 1)
12
- throw new Error(
13
- `Invalid numOutputs: expected a positive integer, got ${s}`
14
- );
15
- if (e.length === 0)
16
- throw new Error("Insufficient funds: no UTXOs available");
17
- const o = e.filter((l) => {
18
- const h = W.from(l.scriptPubKey, "hex");
19
- return !!ge.decompile(h);
20
- });
21
- if (o.length === 0)
22
- throw new Error(
23
- "Insufficient funds: no valid UTXOs available (all have invalid scripts)"
24
- );
25
- const r = [...o].sort((l, h) => h.value - l.value), i = [];
26
- let a = 0n, c = 0n;
27
- for (const l of r) {
28
- i.push(l), a += BigInt(l.value);
29
- const h = i.length * xe, u = s * It, d = h + u + Pe;
30
- if (c = BigInt(Math.ceil(d * n)) + BigInt(we(n)), a - t - c > Xt) {
31
- const b = BigInt(
32
- Math.ceil(It * n)
33
- );
34
- c += b;
35
- }
36
- if (a >= t + c) {
37
- const b = a - t - c;
38
- return {
39
- selectedUTXOs: i,
40
- totalValue: a,
41
- fee: c,
42
- changeAmount: b
43
- };
44
- }
45
- }
46
- throw new Error(
47
- `Insufficient funds: need ${t + c} sats (${t} pegin + ${c} fee), have ${a} sats`
48
- );
49
- }
50
- function Qn(e) {
51
- return e > Xt;
52
- }
53
- function Yn() {
54
- return me;
55
- }
56
- function dt(e) {
57
- const t = e.startsWith("0x") ? e.slice(2) : e;
58
- return `0x${xt.fromHex(t).getId()}`;
59
- }
60
- var ot = /* @__PURE__ */ ((e) => (e.P2PKH = "P2PKH", e.P2SH = "P2SH", e.P2WPKH = "P2WPKH", e.P2WSH = "P2WSH", e.P2TR = "P2TR", e.UNKNOWN = "UNKNOWN", e))(ot || {});
61
- function Fe(e) {
62
- const t = e.length;
63
- return t === 25 && e[0] === 118 && // OP_DUP
64
- e[1] === 169 && // OP_HASH160
65
- e[2] === 20 && // Push 20 bytes
66
- e[23] === 136 && // OP_EQUALVERIFY
67
- e[24] === 172 ? "P2PKH" : t === 23 && e[0] === 169 && // OP_HASH160
68
- e[1] === 20 && // Push 20 bytes
69
- e[22] === 135 ? "P2SH" : t === 22 && e[0] === 0 && // OP_0
70
- e[1] === 20 ? "P2WPKH" : t === 34 && e[0] === 0 && // OP_0
71
- e[1] === 32 ? "P2WSH" : t === 34 && e[0] === 81 && // OP_1
72
- e[1] === 32 ? "P2TR" : "UNKNOWN";
73
- }
74
- function Ce(e, t) {
75
- const n = W.from(e.scriptPubKey, "hex"), s = Fe(n);
76
- switch (s) {
77
- case ot.P2WPKH:
78
- return {
79
- witnessUtxo: {
80
- script: n,
81
- value: e.value
82
- }
83
- };
84
- case ot.P2WSH: {
85
- if (!e.witnessScript)
86
- throw new Error("Missing witnessScript for P2WSH input");
87
- return {
88
- witnessUtxo: {
89
- script: n,
90
- value: e.value
91
- },
92
- witnessScript: W.from(e.witnessScript, "hex")
93
- };
94
- }
95
- case ot.P2TR: {
96
- if (t && t.length !== 32)
97
- throw new Error(
98
- `Invalid tapInternalKey length: expected 32 bytes, got ${t.length}`
99
- );
100
- return {
101
- witnessUtxo: {
102
- script: n,
103
- value: e.value
104
- },
105
- // tapInternalKey is needed for Taproot signing
106
- ...t && { tapInternalKey: t }
107
- };
108
- }
109
- default:
110
- throw new Error(`Unsupported script type: ${s}`);
111
- }
112
- }
113
- function gt(e, t) {
114
- if (!Number.isInteger(t) || t < 1)
115
- throw new Error(`inputCount must be a positive integer, got ${t}`);
116
- return {
117
- autoFinalized: !1,
118
- signInputs: Array.from({ length: t }, (n, s) => ({
119
- index: s,
120
- publicKey: e,
121
- disableTweakSigner: !0
122
- }))
123
- };
124
- }
125
- const $e = 21e6 * 1e8, Ft = 3e4;
126
- async function at(e, t) {
127
- const n = new AbortController(), s = setTimeout(
128
- () => n.abort(),
129
- Ft
130
- ), o = [n.signal, t == null ? void 0 : t.signal].filter(
131
- Boolean
132
- );
133
- try {
134
- return await fetch(e, {
135
- ...t,
136
- signal: AbortSignal.any(o)
137
- });
138
- } catch (r) {
139
- throw clearTimeout(s), r != null && typeof r == "object" && "name" in r && r.name === "AbortError" ? new Error(
140
- `Mempool API request timed out after ${Ft}ms: ${e}`
141
- ) : r;
142
- }
143
- }
144
- const qt = 1e4;
145
- function Gt(e) {
146
- return Number.isInteger(e) && e > 0 && e <= $e;
147
- }
148
- function Oe(e) {
149
- return Number.isInteger(e) && e > 0 && e <= qt;
150
- }
151
- function jt(e, t) {
152
- return !Number.isInteger(e) || e < 0 ? !1 : t === void 0 || e < t;
153
- }
154
- const Le = {
155
- mainnet: "https://mempool.space/api",
156
- testnet: "https://mempool.space/testnet/api",
157
- signet: "https://mempool.space/signet/api"
158
- };
159
- async function it(e, t) {
160
- try {
161
- const n = await at(e, t);
162
- if (!n.ok) {
163
- const o = await n.text();
164
- throw new Error(
165
- `Mempool API error (${n.status}): ${o || n.statusText}`
166
- );
167
- }
168
- const s = n.headers.get("content-type");
169
- return s != null && s.includes("application/json") ? await n.json() : await n.text();
170
- } catch (n) {
171
- throw n instanceof Error ? new Error(`Failed to fetch from mempool API: ${n.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
172
- }
173
- }
174
- async function _e(e, t) {
175
- try {
176
- const n = await at(`${t}/tx`, {
177
- method: "POST",
178
- body: e,
179
- headers: {
180
- "Content-Type": "text/plain"
181
- }
182
- });
183
- if (!n.ok) {
184
- const o = await n.text();
185
- let r;
186
- try {
187
- r = JSON.parse(o).message;
188
- } catch {
189
- r = o;
190
- }
191
- throw new Error(
192
- r || `Failed to broadcast transaction: ${n.statusText}`
193
- );
194
- }
195
- return await n.text();
196
- } catch (n) {
197
- throw n instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${n.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
198
- }
199
- }
200
- async function Re(e, t) {
201
- return it(`${t}/tx/${e}`);
202
- }
203
- async function ts(e, t) {
204
- try {
205
- const n = await at(`${t}/tx/${e}/hex`);
206
- if (!n.ok) {
207
- const s = await n.text();
208
- throw new Error(
209
- `Mempool API error (${n.status}): ${s || n.statusText}`
210
- );
211
- }
212
- return await n.text();
213
- } catch (n) {
214
- throw n instanceof Error ? new Error(`Failed to get transaction hex for ${e}: ${n.message}`) : new Error(`Failed to get transaction hex for ${e}: Unknown error`);
215
- }
216
- }
217
- async function We(e, t, n) {
218
- const s = await Re(e, n);
219
- if (!jt(t, s.vout.length))
220
- throw new Error(
221
- `Invalid vout ${t} for transaction ${e} (has ${s.vout.length} outputs)`
222
- );
223
- const o = s.vout[t];
224
- if (!Gt(o.value))
225
- throw new Error(`Invalid UTXO value ${o.value} for ${e}:${t}`);
226
- return {
227
- txid: e,
228
- vout: t,
229
- value: o.value,
230
- scriptPubKey: o.scriptpubkey
231
- };
232
- }
233
- async function es(e, t) {
234
- try {
235
- const n = await it(`${t}/address/${e}/utxo`), s = await it(`${t}/v1/validate-address/${e}`);
236
- if (!s.isvalid)
237
- throw new Error(
238
- `Invalid Bitcoin address: ${e}. Mempool API validation failed.`
239
- );
240
- for (const r of n) {
241
- if (!jt(r.vout))
242
- throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);
243
- if (!Gt(r.value))
244
- throw new Error(
245
- `Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`
246
- );
247
- }
248
- return n.sort((r, i) => i.value - r.value).map((r) => ({
249
- txid: r.txid,
250
- vout: r.vout,
251
- value: r.value,
252
- scriptPubKey: s.scriptPubKey,
253
- confirmed: r.status.confirmed
254
- }));
255
- } catch (n) {
256
- throw n instanceof Error ? new Error(
257
- `Failed to get UTXOs for address ${e}: ${n.message}`
258
- ) : new Error(
259
- `Failed to get UTXOs for address ${e}: Unknown error`
260
- );
261
- }
262
- }
263
- function ns(e) {
264
- return Le[e];
265
- }
266
- async function ss(e, t) {
267
- return it(`${t}/address/${e}/txs`);
268
- }
269
- async function os(e) {
270
- const t = await at(`${e}/v1/fees/recommended`);
271
- if (!t.ok)
272
- throw new Error(
273
- `Failed to fetch network fees: ${t.status} ${t.statusText}`
274
- );
275
- const n = await t.json(), s = [
276
- "fastestFee",
277
- "halfHourFee",
278
- "hourFee",
279
- "economyFee",
280
- "minimumFee"
281
- ];
282
- for (const o of s)
283
- if (!Oe(n[o]))
284
- throw new Error(
285
- `Invalid fee rate ${o}=${n[o]} from mempool API: expected a positive number ≤ ${qt}`
286
- );
287
- if (n.minimumFee > n.economyFee || n.economyFee > n.hourFee || n.hourFee > n.halfHourFee || n.halfHourFee > n.fastestFee)
288
- throw new Error(
289
- `Fee rate ordering violation from mempool API: expected minimumFee (${n.minimumFee}) <= economyFee (${n.economyFee}) <= hourFee (${n.hourFee}) <= halfHourFee (${n.halfHourFee}) <= fastestFee (${n.fastestFee}).`
290
- );
291
- return n;
292
- }
293
- const j = [
294
- {
295
- type: "function",
296
- name: "submitPeginRequest",
297
- inputs: [
298
- {
299
- name: "depositor",
300
- type: "address",
301
- internalType: "address"
302
- },
303
- {
304
- name: "depositorBtcPubKey",
305
- type: "bytes32",
306
- internalType: "bytes32"
307
- },
308
- {
309
- name: "btcPopSignature",
310
- type: "bytes",
311
- internalType: "bytes"
312
- },
313
- {
314
- name: "unsignedPrePeginTx",
315
- type: "bytes",
316
- internalType: "bytes"
317
- },
318
- {
319
- name: "depositorSignedPeginTx",
320
- type: "bytes",
321
- internalType: "bytes"
322
- },
323
- {
324
- name: "vaultProvider",
325
- type: "address",
326
- internalType: "address"
327
- },
328
- {
329
- name: "hashlock",
330
- type: "bytes32",
331
- internalType: "bytes32"
332
- },
333
- {
334
- name: "htlcVout",
335
- type: "uint8",
336
- internalType: "uint8"
337
- },
338
- {
339
- name: "depositorPayoutBtcAddress",
340
- type: "bytes",
341
- internalType: "bytes"
342
- },
343
- {
344
- name: "depositorWotsPkHash",
345
- type: "bytes32",
346
- internalType: "bytes32"
347
- }
348
- ],
349
- outputs: [
350
- {
351
- name: "",
352
- type: "bytes32",
353
- internalType: "bytes32"
354
- }
355
- ],
356
- stateMutability: "payable"
357
- },
358
- {
359
- type: "function",
360
- name: "submitPeginRequest",
361
- inputs: [
362
- {
363
- name: "depositor",
364
- type: "address",
365
- internalType: "address"
366
- },
367
- {
368
- name: "depositorBtcPubKey",
369
- type: "bytes32",
370
- internalType: "bytes32"
371
- },
372
- {
373
- name: "btcPopSignature",
374
- type: "bytes",
375
- internalType: "bytes"
376
- },
377
- {
378
- name: "unsignedPrePeginTx",
379
- type: "bytes",
380
- internalType: "bytes"
381
- },
382
- {
383
- name: "depositorSignedPeginTx",
384
- type: "bytes",
385
- internalType: "bytes"
386
- },
387
- {
388
- name: "vaultProvider",
389
- type: "address",
390
- internalType: "address"
391
- },
392
- {
393
- name: "hashlock",
394
- type: "bytes32",
395
- internalType: "bytes32"
396
- },
397
- {
398
- name: "htlcVout",
399
- type: "uint8",
400
- internalType: "uint8"
401
- },
402
- {
403
- name: "referralCode",
404
- type: "uint32",
405
- internalType: "uint32"
406
- },
407
- {
408
- name: "depositorPayoutBtcAddress",
409
- type: "bytes",
410
- internalType: "bytes"
411
- },
412
- {
413
- name: "depositorWotsPkHash",
414
- type: "bytes32",
415
- internalType: "bytes32"
416
- }
417
- ],
418
- outputs: [
419
- {
420
- name: "",
421
- type: "bytes32",
422
- internalType: "bytes32"
423
- }
424
- ],
425
- stateMutability: "payable"
426
- },
427
- {
428
- type: "function",
429
- name: "submitPeginRequestBatch",
430
- inputs: [
431
- { name: "depositor", type: "address", internalType: "address" },
432
- { name: "vaultProvider", type: "address", internalType: "address" },
433
- {
434
- name: "requests",
435
- type: "tuple[]",
436
- internalType: "struct IBTCVaultRegistry.BatchPeginRequest[]",
437
- components: [
438
- { name: "depositorBtcPubKey", type: "bytes32", internalType: "bytes32" },
439
- { name: "btcPopSignature", type: "bytes", internalType: "bytes" },
440
- { name: "unsignedPrePeginTx", type: "bytes", internalType: "bytes" },
441
- { name: "depositorSignedPeginTx", type: "bytes", internalType: "bytes" },
442
- { name: "hashlock", type: "bytes32", internalType: "bytes32" },
443
- { name: "htlcVout", type: "uint8", internalType: "uint8" },
444
- { name: "referralCode", type: "uint32", internalType: "uint32" },
445
- { name: "depositorPayoutBtcAddress", type: "bytes", internalType: "bytes" },
446
- { name: "depositorWotsPkHash", type: "bytes32", internalType: "bytes32" }
447
- ]
448
- }
449
- ],
450
- outputs: [
451
- { name: "vaultIds", type: "bytes32[]", internalType: "bytes32[]" }
452
- ],
453
- stateMutability: "payable"
454
- },
455
- {
456
- type: "function",
457
- name: "activateVaultWithSecret",
458
- inputs: [
459
- {
460
- name: "vaultId",
461
- type: "bytes32",
462
- internalType: "bytes32"
463
- },
464
- {
465
- name: "s",
466
- type: "bytes32",
467
- internalType: "bytes32"
468
- },
469
- {
470
- name: "activationMetadata",
471
- type: "bytes",
472
- internalType: "bytes"
473
- }
474
- ],
475
- outputs: [],
476
- stateMutability: "nonpayable"
477
- },
478
- {
479
- type: "function",
480
- name: "getPegInFee",
481
- inputs: [
482
- {
483
- name: "vaultProvider",
484
- type: "address",
485
- internalType: "address"
486
- }
487
- ],
488
- outputs: [
489
- {
490
- name: "totalFee",
491
- type: "uint256",
492
- internalType: "uint256"
493
- }
494
- ],
495
- stateMutability: "view"
496
- },
497
- {
498
- type: "function",
499
- name: "getBtcVaultBasicInfo",
500
- inputs: [
501
- {
502
- name: "vaultId",
503
- type: "bytes32",
504
- internalType: "bytes32"
505
- }
506
- ],
507
- outputs: [
508
- { name: "depositor", type: "address", internalType: "address" },
509
- { name: "depositorBtcPubKey", type: "bytes32", internalType: "bytes32" },
510
- { name: "amount", type: "uint256", internalType: "uint256" },
511
- { name: "vaultProvider", type: "address", internalType: "address" },
512
- { name: "status", type: "uint8", internalType: "enum IBTCVaultRegistry.BTCVaultStatus" },
513
- { name: "applicationEntryPoint", type: "address", internalType: "address" },
514
- { name: "createdAt", type: "uint256", internalType: "uint256" }
515
- ],
516
- stateMutability: "view"
517
- },
518
- {
519
- type: "error",
520
- name: "InvalidPeginFee",
521
- inputs: [
522
- {
523
- name: "provided",
524
- type: "uint256",
525
- internalType: "uint256"
526
- },
527
- {
528
- name: "required",
529
- type: "uint256",
530
- internalType: "uint256"
531
- }
532
- ]
533
- },
534
- {
535
- type: "error",
536
- name: "InvalidSecret",
537
- inputs: []
538
- },
539
- {
540
- type: "error",
541
- name: "ActivationDeadlineExpired",
542
- inputs: []
543
- },
544
- {
545
- type: "error",
546
- name: "InvalidHashlock",
547
- inputs: []
548
- },
549
- {
550
- type: "error",
551
- name: "DuplicateHashlock",
552
- inputs: []
553
- },
554
- {
555
- type: "error",
556
- name: "CapExceeded",
557
- inputs: []
558
- },
559
- {
560
- type: "error",
561
- name: "InvalidOutputIndex",
562
- inputs: []
563
- },
564
- {
565
- type: "error",
566
- name: "PeginSignaturesIncomplete",
567
- inputs: []
568
- }
569
- ], q = {
570
- // VaultAlreadyExists()
571
- "0x04aabf33": "Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.",
572
- // ScriptPubKeyMismatch() - taproot output doesn't match expected script
573
- "0x4fec082d": "Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.",
574
- // InvalidBTCProofOfPossession()
575
- "0x6cc363a5": "Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.",
576
- // InvalidBTCPublicKey()
577
- "0x6c3f2bf6": "Invalid BTC public key: The Bitcoin public key format is invalid.",
578
- // InvalidAmount()
579
- "0x2c5211c6": "Invalid amount: The deposit amount is invalid or below the minimum required.",
580
- // ApplicationNotRegistered()
581
- "0x0405f772": "Application not registered: The application controller is not registered in the system.",
582
- // InvalidProviderStatus()
583
- "0x24e165cc": "Invalid provider status: The vault provider is not in a valid state to accept deposits.",
584
- // ZeroAddress()
585
- "0xd92e233d": "Zero address: One of the required addresses is the zero address.",
586
- // BtcKeyMismatch()
587
- "0x65aa7007": "BTC key mismatch: The Bitcoin public key does not match the expected key.",
588
- // Unauthorized()
589
- "0x82b42900": "Unauthorized: You must be the depositor or vault provider to submit this transaction.",
590
- // InvalidSignature() - common signature verification error
591
- "0x8baa579f": "Invalid signature: The BTC proof of possession signature could not be verified.",
592
- // InvalidBtcTransaction()
593
- "0x2f9d01e9": "Invalid BTC transaction: The Bitcoin transaction format is invalid.",
594
- // VaultProviderNotRegistered()
595
- "0x5a3c6b3e": "Vault provider not registered: The selected vault provider is not registered.",
596
- // InvalidPeginFee(uint256,uint256)
597
- "0x979f4518": "Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction."
598
- };
599
- function wt(e) {
600
- if (!e || typeof e != "object") return;
601
- const t = e;
602
- if (typeof t.data == "string" && t.data.startsWith("0x"))
603
- return t.data;
604
- if (typeof t.details == "string" && t.details.startsWith("0x"))
605
- return t.details;
606
- let n = t.cause, s = 0;
607
- const o = 5;
608
- for (; n && typeof n == "object" && s < o; ) {
609
- const a = n;
610
- if (typeof a.data == "string" && a.data.startsWith("0x"))
611
- return a.data;
612
- n = a.cause, s++;
613
- }
614
- const i = (typeof t.message == "string" ? t.message : "").match(/\b(0x[a-fA-F0-9]{8})\b/);
615
- if (i)
616
- return i[1];
617
- }
618
- function rs(e) {
619
- const t = wt(e);
620
- if (t) {
621
- const n = t.substring(0, 10);
622
- return q[t] ?? q[n];
623
- }
624
- }
625
- function is(e) {
626
- const t = wt(e);
627
- if (t === void 0) return !1;
628
- const n = t.substring(0, 10);
629
- return t in q || n in q;
630
- }
631
- function K(e) {
632
- console.error("[Contract Error] Raw error:", e);
633
- const t = wt(e);
634
- if (console.error("[Contract Error] Extracted error data:", t), t) {
635
- const s = t.substring(0, 10), o = q[t] ?? q[s];
636
- if (o)
637
- throw console.error("[Contract Error] Known error:", o), new Error(o);
638
- }
639
- const n = (e == null ? void 0 : e.message) || "";
640
- if (n.includes("gas limit too high") || n.includes("21000000") || n.includes("Internal JSON-RPC error")) {
641
- const s = t ? ` (error code: ${t})` : "";
642
- throw console.error(
643
- "[Contract Error] Transaction rejected. Error code:",
644
- t,
645
- "Message:",
646
- n
647
- ), new Error(
648
- `Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`
649
- );
650
- }
651
- throw e instanceof Error ? (console.error("[Contract Error] Unhandled error:", e.message), e) : new Error(`Contract call failed: ${String(e)}`);
652
- }
653
- const Ve = 0;
654
- function De(e, t, n, s) {
655
- const o = n == null ? void 0 : n[`${e}:${t}`];
656
- return o ? Promise.resolve({
657
- txid: e,
658
- vout: t,
659
- value: o.value,
660
- scriptPubKey: o.scriptPubKey
661
- }) : We(e, t, s);
662
- }
663
- const Ct = 12e4;
664
- class as {
665
- /**
666
- * Creates a new PeginManager instance.
667
- *
668
- * @param config - Manager configuration including wallets and contract addresses
669
- */
670
- constructor(t) {
671
- p(this, "config");
672
- this.config = t;
673
- }
674
- /**
675
- * Prepares a peg-in by building the Pre-PegIn HTLC transaction,
676
- * funding it, constructing the PegIn transaction, and signing the PegIn input.
677
- *
678
- * This method orchestrates the following steps:
679
- * 1. Get depositor BTC public key from wallet
680
- * 2. Build unfunded Pre-PegIn transaction (HTLC output) using primitives
681
- * 3. Select UTXOs to cover the HTLC value
682
- * 4. Fund the Pre-PegIn transaction
683
- * 5. Derive the PegIn transaction from the funded Pre-PegIn txid
684
- * 6. Build PSBT for signing the PegIn input (HTLC leaf 0)
685
- * 7. Sign via BTC wallet and extract depositor signature
686
- *
687
- * The returned `fundedPrePeginTxHex` is funded but unsigned (inputs unsigned).
688
- * Use `signAndBroadcast()` AFTER registering on Ethereum to broadcast it.
689
- *
690
- * @param params - Pegin parameters including amount, HTLC params, UTXOs
691
- * @returns Pegin result with funded Pre-PegIn tx, signed PegIn input, and signatures
692
- * @throws Error if wallet operations fail or insufficient funds
693
- */
694
- async preparePegin(t) {
695
- const n = await this.config.btcWallet.getPublicKeyHex(), s = n.length === 66 ? n.slice(2) : n, o = B(t.vaultProviderBtcPubkey), r = t.vaultKeeperBtcPubkeys.map(B), i = t.universalChallengerBtcPubkeys.map(B);
696
- if (t.hashlocks.length !== t.amounts.length)
697
- throw new Error(
698
- `hashlocks.length (${t.hashlocks.length}) must equal amounts.length (${t.amounts.length})`
699
- );
700
- if (t.hashlocks.length === 0)
701
- throw new Error("hashlocks must contain at least one entry");
702
- const a = r.length, c = {
703
- depositorPubkey: s,
704
- vaultProviderPubkey: o,
705
- vaultKeeperPubkeys: r,
706
- universalChallengerPubkeys: i,
707
- hashlocks: t.hashlocks,
708
- timelockRefund: t.timelockRefund,
709
- pegInAmounts: t.amounts,
710
- feeRate: t.protocolFeeRate,
711
- numLocalChallengers: a,
712
- councilQuorum: t.councilQuorum,
713
- councilSize: t.councilSize,
714
- network: this.config.btcNetwork
715
- }, l = await Te(c), h = Ue(
716
- [...t.availableUTXOs],
717
- l.totalOutputValue,
718
- t.mempoolFeeRate,
719
- ve(l.htlcValues.length)
720
- ), u = Et(this.config.btcNetwork), d = ke({
721
- unfundedTxHex: l.psbtHex,
722
- selectedUTXOs: h.selectedUTXOs,
723
- changeAddress: t.changeAddress,
724
- changeAmount: h.changeAmount,
725
- network: u
726
- }), y = B(dt(d)), b = [], x = [], P = [];
727
- for (let f = 0; f < t.hashlocks.length; f++) {
728
- const w = await He({
729
- prePeginParams: c,
730
- timelockPegin: t.timelockPegin,
731
- fundedPrePeginTxHex: d,
732
- htlcVout: f
733
- }), v = await Ie({
734
- peginTxHex: w.txHex,
735
- fundedPrePeginTxHex: d,
736
- depositorPubkey: s,
737
- vaultProviderPubkey: o,
738
- vaultKeeperPubkeys: r,
739
- universalChallengerPubkeys: i,
740
- hashlock: t.hashlocks[f],
741
- timelockRefund: t.timelockRefund,
742
- network: this.config.btcNetwork
743
- });
744
- b.push(w), x.push(v.psbtHex), P.push(
745
- gt(n, 1)
746
- );
747
- }
748
- const m = await this.signPsbtsWithFallback(
749
- x,
750
- P
751
- ), g = [];
752
- for (let f = 0; f < m.length; f++) {
753
- const w = Ee(
754
- m[f],
755
- s
756
- ), v = Be(m[f]);
757
- g.push({
758
- htlcVout: f,
759
- htlcValue: l.htlcValues[f],
760
- peginTxHex: v,
761
- peginTxid: b[f].txid,
762
- peginInputSignature: w,
763
- vaultScriptPubKey: b[f].vaultScriptPubKey
764
- });
765
- }
766
- return {
767
- fundedPrePeginTxHex: d,
768
- prePeginTxid: y,
769
- unsignedPrePeginTxHex: l.psbtHex,
770
- perVault: g,
771
- selectedUTXOs: h.selectedUTXOs,
772
- fee: h.fee,
773
- changeAmount: h.changeAmount
774
- };
775
- }
776
- /**
777
- * Signs multiple PSBTs using batch signing if available, falling back to sequential signing.
778
- *
779
- * Wallets that support native batch signing (e.g. UniSat) will sign all PSBTs
780
- * in a single interaction. Others (e.g. Ledger, AppKit) implement signPsbts
781
- * by looping signPsbt internally, so the UX depends on the wallet adapter.
782
- */
783
- async signPsbtsWithFallback(t, n) {
784
- if (typeof this.config.btcWallet.signPsbts == "function") {
785
- const o = await this.config.btcWallet.signPsbts(
786
- t,
787
- n
788
- );
789
- if (o.length !== t.length)
790
- throw new Error(
791
- `Expected ${t.length} signed PSBTs but received ${o.length}`
792
- );
793
- return o;
794
- }
795
- const s = [];
796
- for (let o = 0; o < t.length; o++) {
797
- const r = await this.config.btcWallet.signPsbt(
798
- t[o],
799
- n[o]
800
- );
801
- s.push(r);
802
- }
803
- return s;
804
- }
805
- /**
806
- * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
807
- *
808
- * This method:
809
- * 1. Parses the funded transaction hex
810
- * 2. Fetches UTXO data from mempool for each input
811
- * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
812
- * 4. Signs via btcWallet.signPsbt()
813
- * 5. Finalizes and extracts the transaction
814
- * 6. Broadcasts via mempool API
815
- *
816
- * @param params - Transaction hex and depositor public key
817
- * @returns The broadcasted Bitcoin transaction ID
818
- * @throws Error if signing or broadcasting fails
819
- */
820
- async signAndBroadcast(t) {
821
- const { fundedPrePeginTxHex: n, depositorBtcPubkey: s } = t, o = n.startsWith("0x") ? n.slice(2) : n, r = xt.fromHex(o);
822
- if (r.ins.length === 0)
823
- throw new Error("Transaction has no inputs");
824
- const i = new kt();
825
- i.setVersion(r.version), i.setLocktime(r.locktime);
826
- const a = s.startsWith("0x") ? s.slice(2) : s;
827
- if (a.length !== 64 || !/^[0-9a-fA-F]+$/.test(a))
828
- throw new Error(
829
- "Invalid depositorBtcPubkey: expected 64 hex characters (x-only pubkey)"
830
- );
831
- const c = W.from(a, "hex");
832
- if (c.length !== 32)
833
- throw new Error(
834
- `Invalid depositorBtcPubkey length: expected 32 bytes, got ${c.length}`
835
- );
836
- const l = this.config.mempoolApiUrl, h = r.ins.map((g) => {
837
- const f = W.from(g.hash).reverse().toString("hex"), w = g.index;
838
- return De(f, w, t.localPrevouts, l).then(
839
- (v) => ({ input: g, utxoData: v, txid: f, vout: w })
840
- );
841
- }), u = await Promise.all(h), d = u.reduce(
842
- (g, f) => g + BigInt(f.utxoData.value),
843
- 0n
844
- ), y = r.outs.reduce(
845
- (g, f) => g + BigInt(f.value),
846
- 0n
847
- );
848
- if (d < y)
849
- throw new Error(
850
- `UTXO value mismatch: total input value (${d} sat) is less than total output value (${y} sat). This may indicate the mempool API returned manipulated UTXO data.`
851
- );
852
- for (const { input: g, utxoData: f, txid: w, vout: v } of u) {
853
- const T = Ce(
854
- {
855
- value: f.value,
856
- scriptPubKey: f.scriptPubKey
857
- },
858
- c
859
- );
860
- i.addInput({
861
- hash: g.hash,
862
- index: g.index,
863
- sequence: g.sequence,
864
- ...T
865
- });
866
- }
867
- for (const g of r.outs)
868
- i.addOutput({
869
- script: g.script,
870
- value: g.value
871
- });
872
- const b = await this.config.btcWallet.signPsbt(i.toHex()), x = kt.fromHex(b);
873
- try {
874
- x.finalizeAllInputs();
875
- } catch (g) {
876
- if (!x.data.inputs.every(
877
- (w) => w.finalScriptWitness || w.finalScriptSig
878
- ))
879
- throw new Error(
880
- `PSBT finalization failed and wallet did not auto-finalize: ${g}`
881
- );
882
- }
883
- const P = x.extractTransaction().toHex();
884
- return await _e(P, l);
885
- }
886
- /**
887
- * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.
888
- *
889
- * This method:
890
- * 1. Gets depositor ETH address from wallet
891
- * 2. Creates proof of possession (BTC signature of ETH address)
892
- * 3. Checks if vault already exists (pre-flight check)
893
- * 4. Encodes the contract call using viem
894
- * 5. Estimates gas (catches contract errors early with proper revert reasons)
895
- * 6. Sends transaction with pre-estimated gas via ethWallet.sendTransaction()
896
- *
897
- * @param params - Registration parameters including BTC pubkey and unsigned tx
898
- * @returns Result containing Ethereum transaction hash and vault ID
899
- * @throws Error if signing or transaction fails
900
- * @throws Error if vault already exists
901
- * @throws Error if contract simulation fails (e.g., invalid signature, unauthorized)
902
- */
903
- async registerPeginOnChain(t) {
904
- const {
905
- depositorBtcPubkey: n,
906
- unsignedPrePeginTx: s,
907
- depositorSignedPeginTx: o,
908
- vaultProvider: r,
909
- hashlock: i,
910
- htlcVout: a,
911
- onPopSigned: c,
912
- depositorPayoutBtcAddress: l,
913
- depositorWotsPkHash: h,
914
- preSignedBtcPopSignature: u
915
- } = t;
916
- if (!this.config.ethWallet.account)
917
- throw new Error("Ethereum wallet account not found");
918
- const d = this.config.ethWallet.account.address, y = await this.resolvePopSignature(
919
- d,
920
- u
921
- );
922
- c && await c();
923
- const b = U(n), x = U(s), P = U(o), m = await this.resolvePayoutScriptPubKey(
924
- l
925
- ), g = dt(P), f = await Ut(
926
- B(g),
927
- B(d)
928
- ), w = U(f);
929
- if (await this.checkVaultExists(w))
930
- throw new Error(
931
- `Vault already exists (ID: ${w}, peginTxHash: ${g}). 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.`
932
- );
933
- const T = lt({
934
- chain: this.config.ethChain,
935
- transport: ht()
936
- });
937
- let H;
938
- try {
939
- H = await T.readContract({
940
- address: this.config.vaultContracts.btcVaultRegistry,
941
- abi: j,
942
- functionName: "getPegInFee",
943
- args: [r]
944
- });
945
- } catch {
946
- throw new Error(
947
- "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct."
948
- );
949
- }
950
- const I = Ht({
951
- abi: j,
952
- functionName: "submitPeginRequest",
953
- args: [
954
- d,
955
- b,
956
- y,
957
- x,
958
- P,
959
- r,
960
- i,
961
- a,
962
- m,
963
- h
964
- ]
965
- });
966
- let E;
967
- try {
968
- E = await T.estimateGas({
969
- to: this.config.vaultContracts.btcVaultRegistry,
970
- data: I,
971
- value: H,
972
- account: this.config.ethWallet.account.address
973
- });
974
- } catch ($) {
975
- K($);
976
- }
977
- let C;
978
- try {
979
- C = await this.config.ethWallet.sendTransaction({
980
- to: this.config.vaultContracts.btcVaultRegistry,
981
- data: I,
982
- value: H,
983
- account: this.config.ethWallet.account,
984
- chain: this.config.ethChain,
985
- gas: E
986
- });
987
- } catch ($) {
988
- K($);
989
- }
990
- const M = await T.waitForTransactionReceipt({
991
- hash: C,
992
- timeout: Ct
993
- });
994
- return M.status === "reverted" && K(
995
- new Error(
996
- `Transaction reverted. Hash: ${C}. Check the transaction on block explorer for details.`
997
- )
998
- ), {
999
- ethTxHash: M.transactionHash,
1000
- vaultId: w,
1001
- peginTxHash: g,
1002
- btcPopSignature: y
1003
- };
1004
- }
1005
- /**
1006
- * Register multiple pegins on Ethereum in a single transaction.
1007
- *
1008
- * Uses the contract's submitPeginRequestBatch() to submit all vault
1009
- * registrations atomically. All vaults must share the same vault provider.
1010
- * The PoP signature is signed once and included in each request.
1011
- *
1012
- * @param params - Batch registration parameters
1013
- * @returns Batch result with per-vault IDs and single ETH tx hash
1014
- */
1015
- async registerPeginBatchOnChain(t) {
1016
- const { vaultProvider: n, requests: s, preSignedBtcPopSignature: o, onPopSigned: r } = t;
1017
- if (s.length === 0)
1018
- throw new Error("Batch pegin requires at least one request");
1019
- if (!this.config.ethWallet.account)
1020
- throw new Error("Ethereum wallet account not found");
1021
- const i = this.config.ethWallet.account.address, a = await this.resolvePopSignature(
1022
- i,
1023
- o
1024
- );
1025
- r && await r();
1026
- const c = [];
1027
- for (const g of s)
1028
- c.push(
1029
- await this.resolvePayoutScriptPubKey(g.depositorPayoutBtcAddress)
1030
- );
1031
- const l = [];
1032
- for (const g of s) {
1033
- const f = U(
1034
- g.depositorSignedPeginTx
1035
- ), w = dt(f), v = await Ut(
1036
- B(w),
1037
- B(i)
1038
- ), T = U(v);
1039
- if (await this.checkVaultExists(T))
1040
- throw new Error(
1041
- `Vault already exists (ID: ${T}, peginTxHash: ${w}). To create a new vault, use different UTXOs or a different amount.`
1042
- );
1043
- l.push({ vaultId: T, peginTxHash: w });
1044
- }
1045
- const h = lt({
1046
- chain: this.config.ethChain,
1047
- transport: ht()
1048
- });
1049
- let u;
1050
- try {
1051
- u = await h.readContract({
1052
- address: this.config.vaultContracts.btcVaultRegistry,
1053
- abi: j,
1054
- functionName: "getPegInFee",
1055
- args: [n]
1056
- });
1057
- } catch {
1058
- throw new Error(
1059
- "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct."
1060
- );
1061
- }
1062
- const d = u * BigInt(s.length), y = s.map((g, f) => ({
1063
- depositorBtcPubKey: U(g.depositorBtcPubkey),
1064
- btcPopSignature: a,
1065
- unsignedPrePeginTx: U(g.unsignedPrePeginTx),
1066
- depositorSignedPeginTx: U(
1067
- g.depositorSignedPeginTx
1068
- ),
1069
- hashlock: g.hashlock,
1070
- htlcVout: g.htlcVout,
1071
- referralCode: Ve,
1072
- depositorPayoutBtcAddress: c[f],
1073
- depositorWotsPkHash: g.depositorWotsPkHash
1074
- })), b = Ht({
1075
- abi: j,
1076
- functionName: "submitPeginRequestBatch",
1077
- args: [i, n, y]
1078
- });
1079
- let x;
1080
- try {
1081
- x = await h.estimateGas({
1082
- to: this.config.vaultContracts.btcVaultRegistry,
1083
- data: b,
1084
- value: d,
1085
- account: this.config.ethWallet.account.address
1086
- });
1087
- } catch (g) {
1088
- K(g);
1089
- }
1090
- let P;
1091
- try {
1092
- P = await this.config.ethWallet.sendTransaction({
1093
- to: this.config.vaultContracts.btcVaultRegistry,
1094
- data: b,
1095
- value: d,
1096
- account: this.config.ethWallet.account,
1097
- chain: this.config.ethChain,
1098
- gas: x
1099
- });
1100
- } catch (g) {
1101
- K(g);
1102
- }
1103
- const m = await h.waitForTransactionReceipt({
1104
- hash: P,
1105
- timeout: Ct
1106
- });
1107
- return m.status === "reverted" && K(
1108
- new Error(
1109
- `Batch transaction reverted. Hash: ${P}. Check the transaction on block explorer for details.`
1110
- )
1111
- ), {
1112
- ethTxHash: m.transactionHash,
1113
- vaults: l,
1114
- btcPopSignature: a
1115
- };
1116
- }
1117
- /**
1118
- * Check if a vault already exists for a given vault ID.
1119
- *
1120
- * @param vaultId - The Bitcoin transaction hash (vault ID)
1121
- * @returns True if vault exists, false otherwise
1122
- */
1123
- async checkVaultExists(t) {
1124
- try {
1125
- return (await lt({
1126
- chain: this.config.ethChain,
1127
- transport: ht()
1128
- }).readContract({
1129
- address: this.config.vaultContracts.btcVaultRegistry,
1130
- abi: j,
1131
- functionName: "getBtcVaultBasicInfo",
1132
- args: [t]
1133
- }))[0] !== ye;
1134
- } catch {
1135
- return !1;
1136
- }
1137
- }
1138
- /**
1139
- * Resolve the BTC payout address to a scriptPubKey hex for the contract.
1140
- *
1141
- * If a payout address is provided, converts it directly.
1142
- * If omitted, uses the wallet's address and validates it against the
1143
- * wallet's public key to guard against a compromised wallet provider.
1144
- */
1145
- async resolvePayoutScriptPubKey(t) {
1146
- let n;
1147
- if (t)
1148
- n = t;
1149
- else {
1150
- n = await this.config.btcWallet.getAddress();
1151
- const o = await this.config.btcWallet.getPublicKeyHex();
1152
- if (!Se(
1153
- n,
1154
- o,
1155
- this.config.btcNetwork
1156
- ))
1157
- throw new Error(
1158
- "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)."
1159
- );
1160
- }
1161
- const s = Et(this.config.btcNetwork);
1162
- try {
1163
- return `0x${be.address.toOutputScript(n, s).toString("hex")}`;
1164
- } catch {
1165
- throw new Error(
1166
- `Invalid BTC payout address: "${n}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
1167
- );
1168
- }
1169
- }
1170
- /**
1171
- * Resolve or create a BTC Proof-of-Possession signature.
1172
- *
1173
- * Reuses a pre-signed signature when provided (e.g. multi-vault deposits),
1174
- * otherwise signs a BIP-322 message with the BTC wallet.
1175
- */
1176
- async resolvePopSignature(t, n) {
1177
- if (n)
1178
- return n;
1179
- const s = this.config.vaultContracts.btcVaultRegistry, o = `${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`, r = await this.config.btcWallet.signMessage(
1180
- o,
1181
- "bip322-simple"
1182
- );
1183
- return r.startsWith("0x") ? r : `0x${W.from(r, "base64").toString("hex")}`;
1184
- }
1185
- /**
1186
- * Gets the configured Bitcoin network.
1187
- *
1188
- * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1189
- */
1190
- getNetwork() {
1191
- return this.config.btcNetwork;
1192
- }
1193
- /**
1194
- * Gets the configured BTCVaultRegistry contract address.
1195
- *
1196
- * @returns The Ethereum address of the BTCVaultRegistry contract
1197
- */
1198
- getVaultContractAddress() {
1199
- return this.config.vaultContracts.btcVaultRegistry;
1200
- }
1201
- }
1202
- class cs {
1203
- /**
1204
- * Creates a new PayoutManager instance.
1205
- *
1206
- * @param config - Manager configuration including wallet
1207
- */
1208
- constructor(t) {
1209
- p(this, "config");
1210
- this.config = t;
1211
- }
1212
- /**
1213
- * Signs a Payout transaction and extracts the Schnorr signature.
1214
- *
1215
- * Flow:
1216
- * 1. Vault provider submits Claim transaction
1217
- * 2. Claimer submits Assert transaction to prove validity
1218
- * 3. Payout can be executed (references Assert tx)
1219
- *
1220
- * This method orchestrates the following steps:
1221
- * 1. Get wallet's public key and convert to x-only format
1222
- * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)
1223
- * 3. Build unsigned PSBT using primitives
1224
- * 4. Sign PSBT via btcWallet.signPsbt()
1225
- * 5. Extract 64-byte Schnorr signature using primitives
1226
- *
1227
- * The returned signature can be submitted to the vault provider API.
1228
- *
1229
- * @param params - Payout signing parameters
1230
- * @returns Signature result with 64-byte Schnorr signature and depositor pubkey
1231
- * @throws Error if wallet pubkey doesn't match depositor pubkey
1232
- * @throws Error if wallet operations fail or signature extraction fails
1233
- */
1234
- async signPayoutTransaction(t) {
1235
- this.validatePayoutOutputs(
1236
- t.payoutTxHex,
1237
- t.registeredPayoutScriptPubKey
1238
- );
1239
- const n = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: s } = Bt(
1240
- n,
1241
- t.depositorBtcPubkey
1242
- ), o = await St({
1243
- payoutTxHex: t.payoutTxHex,
1244
- peginTxHex: t.peginTxHex,
1245
- assertTxHex: t.assertTxHex,
1246
- depositorBtcPubkey: s,
1247
- vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
1248
- vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
1249
- universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
1250
- timelockPegin: t.timelockPegin,
1251
- network: this.config.network
1252
- }), r = await this.config.btcWallet.signPsbt(
1253
- o.psbtHex,
1254
- gt(n, 1)
1255
- );
1256
- return {
1257
- signature: At(r, s),
1258
- depositorBtcPubkey: s
1259
- };
1260
- }
1261
- /**
1262
- * Gets the configured Bitcoin network.
1263
- *
1264
- * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1265
- */
1266
- getNetwork() {
1267
- return this.config.network;
1268
- }
1269
- /**
1270
- * Checks if the wallet supports batch signing (signPsbts).
1271
- *
1272
- * @returns true if batch signing is supported
1273
- */
1274
- supportsBatchSigning() {
1275
- return typeof this.config.btcWallet.signPsbts == "function";
1276
- }
1277
- /**
1278
- * Batch signs multiple payout transactions (1 per claimer).
1279
- * This allows signing all transactions with a single wallet interaction.
1280
- *
1281
- * @param transactions - Array of payout params to sign
1282
- * @returns Array of signature results matching input order
1283
- * @throws Error if wallet doesn't support batch signing
1284
- * @throws Error if any signing operation fails
1285
- */
1286
- async signPayoutTransactionsBatch(t) {
1287
- if (!this.supportsBatchSigning())
1288
- throw new Error(
1289
- "Wallet does not support batch signing (signPsbts method not available)"
1290
- );
1291
- const n = await this.config.btcWallet.getPublicKeyHex(), s = [], o = [], r = [];
1292
- for (const c of t) {
1293
- this.validatePayoutOutputs(
1294
- c.payoutTxHex,
1295
- c.registeredPayoutScriptPubKey
1296
- );
1297
- const { depositorPubkey: l } = Bt(
1298
- n,
1299
- c.depositorBtcPubkey
1300
- );
1301
- r.push(l);
1302
- const h = await St({
1303
- payoutTxHex: c.payoutTxHex,
1304
- peginTxHex: c.peginTxHex,
1305
- assertTxHex: c.assertTxHex,
1306
- depositorBtcPubkey: l,
1307
- vaultProviderBtcPubkey: c.vaultProviderBtcPubkey,
1308
- vaultKeeperBtcPubkeys: c.vaultKeeperBtcPubkeys,
1309
- universalChallengerBtcPubkeys: c.universalChallengerBtcPubkeys,
1310
- timelockPegin: c.timelockPegin,
1311
- network: this.config.network
1312
- });
1313
- s.push(h.psbtHex), o.push(gt(n, 1));
1314
- }
1315
- const i = await this.config.btcWallet.signPsbts(
1316
- s,
1317
- o
1318
- );
1319
- if (i.length !== t.length)
1320
- throw new Error(
1321
- `Expected ${t.length} signed PSBTs but received ${i.length}`
1322
- );
1323
- const a = [];
1324
- for (let c = 0; c < t.length; c++) {
1325
- const l = r[c], h = At(
1326
- i[c],
1327
- l
1328
- );
1329
- a.push({
1330
- payoutSignature: h,
1331
- depositorBtcPubkey: l
1332
- });
1333
- }
1334
- return a;
1335
- }
1336
- /**
1337
- * Validates that the payout transaction's largest output pays to the
1338
- * registered depositor payout address (scriptPubKey).
1339
- *
1340
- * This prevents two attack vectors from a malicious vault provider:
1341
- * 1. Substituting a completely different payout address
1342
- * 2. Including a dust output to the correct address while routing
1343
- * the actual funds to an attacker-controlled address
1344
- *
1345
- * @param payoutTxHex - Raw payout transaction hex
1346
- * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)
1347
- * @throws Error if scriptPubKey is invalid hex
1348
- * @throws Error if the largest output does not pay to the registered address
1349
- */
1350
- validatePayoutOutputs(t, n) {
1351
- if (!Ae(n))
1352
- throw new Error(
1353
- "Invalid registeredPayoutScriptPubKey: not valid hex"
1354
- );
1355
- const s = W.from(
1356
- B(n),
1357
- "hex"
1358
- ), o = xt.fromHex(B(t));
1359
- if (o.outs.length === 0)
1360
- throw new Error("Payout transaction has no outputs");
1361
- if (!o.outs.reduce(
1362
- (i, a) => a.value > i.value ? a : i
1363
- ).script.equals(s))
1364
- throw new Error(
1365
- "Payout transaction does not pay to the registered depositor payout address"
1366
- );
1367
- }
1368
- }
1369
- function Me(e) {
1370
- return e instanceof Uint8Array || ArrayBuffer.isView(e) && e.constructor.name === "Uint8Array";
1371
- }
1372
- function V(e, t = "") {
1373
- if (!Number.isSafeInteger(e) || e < 0) {
1374
- const n = t && `"${t}" `;
1375
- throw new Error(`${n}expected integer >= 0, got ${e}`);
1376
- }
1377
- }
1378
- function D(e, t, n = "") {
1379
- const s = Me(e), o = e == null ? void 0 : e.length, r = t !== void 0;
1380
- if (!s || r && o !== t) {
1381
- const i = n && `"${n}" `, a = r ? ` of length ${t}` : "", c = s ? `length=${o}` : `type=${typeof e}`;
1382
- throw new Error(i + "expected Uint8Array" + a + ", got " + c);
1383
- }
1384
- return e;
1385
- }
1386
- function zt(e) {
1387
- if (typeof e != "function" || typeof e.create != "function")
1388
- throw new Error("Hash must wrapped by utils.createHasher");
1389
- V(e.outputLen), V(e.blockLen);
1390
- }
1391
- function G(e, t = !0) {
1392
- if (e.destroyed)
1393
- throw new Error("Hash instance has been destroyed");
1394
- if (t && e.finished)
1395
- throw new Error("Hash#digest() has already been called");
1396
- }
1397
- function Zt(e, t) {
1398
- D(e, void 0, "digestInto() output");
1399
- const n = t.outputLen;
1400
- if (e.length < n)
1401
- throw new Error('"digestInto() output" expected to be of length >=' + n);
1402
- }
1403
- function Ke(e) {
1404
- return new Uint32Array(e.buffer, e.byteOffset, Math.floor(e.byteLength / 4));
1405
- }
1406
- function S(...e) {
1407
- for (let t = 0; t < e.length; t++)
1408
- e[t].fill(0);
1409
- }
1410
- function rt(e) {
1411
- return new DataView(e.buffer, e.byteOffset, e.byteLength);
1412
- }
1413
- function A(e, t) {
1414
- return e << 32 - t | e >>> t;
1415
- }
1416
- function J(e, t) {
1417
- return e << t | e >>> 32 - t >>> 0;
1418
- }
1419
- const Ne = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
1420
- function Xe(e) {
1421
- return e << 24 & 4278190080 | e << 8 & 16711680 | e >>> 8 & 65280 | e >>> 24 & 255;
1422
- }
1423
- function qe(e) {
1424
- for (let t = 0; t < e.length; t++)
1425
- e[t] = Xe(e[t]);
1426
- return e;
1427
- }
1428
- const $t = Ne ? (e) => e : qe;
1429
- function Ge(e) {
1430
- if (typeof e != "string")
1431
- throw new Error("string expected");
1432
- return new Uint8Array(new TextEncoder().encode(e));
1433
- }
1434
- function Ot(e, t = "") {
1435
- return typeof e == "string" ? Ge(e) : D(e, void 0, t);
1436
- }
1437
- function je(e, t) {
1438
- if (t !== void 0 && {}.toString.call(t) !== "[object Object]")
1439
- throw new Error("options must be object or undefined");
1440
- return Object.assign(e, t);
1441
- }
1442
- function ct(e, t = {}) {
1443
- const n = (o, r) => e(r).update(o).digest(), s = e(void 0);
1444
- return n.outputLen = s.outputLen, n.blockLen = s.blockLen, n.create = (o) => e(o), Object.assign(n, t), Object.freeze(n);
1445
- }
1446
- const Jt = (e) => ({
1447
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, e])
1448
- });
1449
- class Qt {
1450
- constructor(t, n) {
1451
- p(this, "oHash");
1452
- p(this, "iHash");
1453
- p(this, "blockLen");
1454
- p(this, "outputLen");
1455
- p(this, "finished", !1);
1456
- p(this, "destroyed", !1);
1457
- if (zt(t), D(n, void 0, "key"), this.iHash = t.create(), typeof this.iHash.update != "function")
1458
- throw new Error("Expected instance of class which extends utils.Hash");
1459
- this.blockLen = this.iHash.blockLen, this.outputLen = this.iHash.outputLen;
1460
- const s = this.blockLen, o = new Uint8Array(s);
1461
- o.set(n.length > s ? t.create().update(n).digest() : n);
1462
- for (let r = 0; r < o.length; r++)
1463
- o[r] ^= 54;
1464
- this.iHash.update(o), this.oHash = t.create();
1465
- for (let r = 0; r < o.length; r++)
1466
- o[r] ^= 106;
1467
- this.oHash.update(o), S(o);
1468
- }
1469
- update(t) {
1470
- return G(this), this.iHash.update(t), this;
1471
- }
1472
- digestInto(t) {
1473
- G(this), D(t, this.outputLen, "output"), this.finished = !0, this.iHash.digestInto(t), this.oHash.update(t), this.oHash.digestInto(t), this.destroy();
1474
- }
1475
- digest() {
1476
- const t = new Uint8Array(this.oHash.outputLen);
1477
- return this.digestInto(t), t;
1478
- }
1479
- _cloneInto(t) {
1480
- t || (t = Object.create(Object.getPrototypeOf(this), {}));
1481
- const { oHash: n, iHash: s, finished: o, destroyed: r, blockLen: i, outputLen: a } = this;
1482
- 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;
1483
- }
1484
- clone() {
1485
- return this._cloneInto();
1486
- }
1487
- destroy() {
1488
- this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
1489
- }
1490
- }
1491
- const mt = (e, t, n) => new Qt(e, t).update(n).digest();
1492
- mt.create = (e, t) => new Qt(e, t);
1493
- function ze(e, t, n) {
1494
- return e & t ^ ~e & n;
1495
- }
1496
- function Ze(e, t, n) {
1497
- return e & t ^ e & n ^ t & n;
1498
- }
1499
- class Pt {
1500
- constructor(t, n, s, o) {
1501
- p(this, "blockLen");
1502
- p(this, "outputLen");
1503
- p(this, "padOffset");
1504
- p(this, "isLE");
1505
- // For partial updates less than block size
1506
- p(this, "buffer");
1507
- p(this, "view");
1508
- p(this, "finished", !1);
1509
- p(this, "length", 0);
1510
- p(this, "pos", 0);
1511
- p(this, "destroyed", !1);
1512
- this.blockLen = t, this.outputLen = n, this.padOffset = s, this.isLE = o, this.buffer = new Uint8Array(t), this.view = rt(this.buffer);
1513
- }
1514
- update(t) {
1515
- G(this), D(t);
1516
- const { view: n, buffer: s, blockLen: o } = this, r = t.length;
1517
- for (let i = 0; i < r; ) {
1518
- const a = Math.min(o - this.pos, r - i);
1519
- if (a === o) {
1520
- const c = rt(t);
1521
- for (; o <= r - i; i += o)
1522
- this.process(c, i);
1523
- continue;
1524
- }
1525
- s.set(t.subarray(i, i + a), this.pos), this.pos += a, i += a, this.pos === o && (this.process(n, 0), this.pos = 0);
1526
- }
1527
- return this.length += t.length, this.roundClean(), this;
1528
- }
1529
- digestInto(t) {
1530
- G(this), Zt(t, this), this.finished = !0;
1531
- const { buffer: n, view: s, blockLen: o, isLE: r } = this;
1532
- let { pos: i } = this;
1533
- n[i++] = 128, S(this.buffer.subarray(i)), this.padOffset > o - i && (this.process(s, 0), i = 0);
1534
- for (let u = i; u < o; u++)
1535
- n[u] = 0;
1536
- s.setBigUint64(o - 8, BigInt(this.length * 8), r), this.process(s, 0);
1537
- const a = rt(t), c = this.outputLen;
1538
- if (c % 4)
1539
- throw new Error("_sha2: outputLen must be aligned to 32bit");
1540
- const l = c / 4, h = this.get();
1541
- if (l > h.length)
1542
- throw new Error("_sha2: outputLen bigger than state");
1543
- for (let u = 0; u < l; u++)
1544
- a.setUint32(4 * u, h[u], r);
1545
- }
1546
- digest() {
1547
- const { buffer: t, outputLen: n } = this;
1548
- this.digestInto(t);
1549
- const s = t.slice(0, n);
1550
- return this.destroy(), s;
1551
- }
1552
- _cloneInto(t) {
1553
- t || (t = new this.constructor()), t.set(...this.get());
1554
- const { blockLen: n, buffer: s, length: o, finished: r, destroyed: i, pos: a } = this;
1555
- return t.destroyed = i, t.finished = r, t.length = o, t.pos = a, o % n && t.buffer.set(s), t;
1556
- }
1557
- clone() {
1558
- return this._cloneInto();
1559
- }
1560
- }
1561
- const O = /* @__PURE__ */ Uint32Array.from([
1562
- 1779033703,
1563
- 3144134277,
1564
- 1013904242,
1565
- 2773480762,
1566
- 1359893119,
1567
- 2600822924,
1568
- 528734635,
1569
- 1541459225
1570
- ]), k = /* @__PURE__ */ Uint32Array.from([
1571
- 1779033703,
1572
- 4089235720,
1573
- 3144134277,
1574
- 2227873595,
1575
- 1013904242,
1576
- 4271175723,
1577
- 2773480762,
1578
- 1595750129,
1579
- 1359893119,
1580
- 2917565137,
1581
- 2600822924,
1582
- 725511199,
1583
- 528734635,
1584
- 4215389547,
1585
- 1541459225,
1586
- 327033209
1587
- ]), Je = /* @__PURE__ */ Uint8Array.from([
1588
- 7,
1589
- 4,
1590
- 13,
1591
- 1,
1592
- 10,
1593
- 6,
1594
- 15,
1595
- 3,
1596
- 12,
1597
- 0,
1598
- 9,
1599
- 5,
1600
- 2,
1601
- 14,
1602
- 11,
1603
- 8
1604
- ]), Yt = Uint8Array.from(new Array(16).fill(0).map((e, t) => t)), Qe = Yt.map((e) => (9 * e + 5) % 16), te = /* @__PURE__ */ (() => {
1605
- const n = [[Yt], [Qe]];
1606
- for (let s = 0; s < 4; s++)
1607
- for (let o of n)
1608
- o.push(o[s].map((r) => Je[r]));
1609
- return n;
1610
- })(), ee = te[0], ne = te[1], se = /* @__PURE__ */ [
1611
- [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
1612
- [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
1613
- [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
1614
- [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
1615
- [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
1616
- ].map((e) => Uint8Array.from(e)), Ye = /* @__PURE__ */ ee.map((e, t) => e.map((n) => se[t][n])), tn = /* @__PURE__ */ ne.map((e, t) => e.map((n) => se[t][n])), en = /* @__PURE__ */ Uint32Array.from([
1617
- 0,
1618
- 1518500249,
1619
- 1859775393,
1620
- 2400959708,
1621
- 2840853838
1622
- ]), nn = /* @__PURE__ */ Uint32Array.from([
1623
- 1352829926,
1624
- 1548603684,
1625
- 1836072691,
1626
- 2053994217,
1627
- 0
1628
- ]);
1629
- function Lt(e, t, n, s) {
1630
- 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);
1631
- }
1632
- const Q = /* @__PURE__ */ new Uint32Array(16);
1633
- class sn extends Pt {
1634
- constructor() {
1635
- super(64, 20, 8, !0);
1636
- p(this, "h0", 1732584193);
1637
- p(this, "h1", -271733879);
1638
- p(this, "h2", -1732584194);
1639
- p(this, "h3", 271733878);
1640
- p(this, "h4", -1009589776);
1641
- }
1642
- get() {
1643
- const { h0: n, h1: s, h2: o, h3: r, h4: i } = this;
1644
- return [n, s, o, r, i];
1645
- }
1646
- set(n, s, o, r, i) {
1647
- this.h0 = n | 0, this.h1 = s | 0, this.h2 = o | 0, this.h3 = r | 0, this.h4 = i | 0;
1648
- }
1649
- process(n, s) {
1650
- for (let b = 0; b < 16; b++, s += 4)
1651
- Q[b] = n.getUint32(s, !0);
1652
- let o = this.h0 | 0, r = o, i = this.h1 | 0, a = i, c = this.h2 | 0, l = c, h = this.h3 | 0, u = h, d = this.h4 | 0, y = d;
1653
- for (let b = 0; b < 5; b++) {
1654
- const x = 4 - b, P = en[b], m = nn[b], g = ee[b], f = ne[b], w = Ye[b], v = tn[b];
1655
- for (let T = 0; T < 16; T++) {
1656
- const H = J(o + Lt(b, i, c, h) + Q[g[T]] + P, w[T]) + d | 0;
1657
- o = d, d = h, h = J(c, 10) | 0, c = i, i = H;
1658
- }
1659
- for (let T = 0; T < 16; T++) {
1660
- const H = J(r + Lt(x, a, l, u) + Q[f[T]] + m, v[T]) + y | 0;
1661
- r = y, y = u, u = J(l, 10) | 0, l = a, a = H;
1662
- }
1663
- }
1664
- this.set(this.h1 + c + u | 0, this.h2 + h + y | 0, this.h3 + d + r | 0, this.h4 + o + a | 0, this.h0 + i + l | 0);
1665
- }
1666
- roundClean() {
1667
- S(Q);
1668
- }
1669
- destroy() {
1670
- this.destroyed = !0, S(this.buffer), this.set(0, 0, 0, 0, 0);
1671
- }
1672
- }
1673
- const on = /* @__PURE__ */ ct(() => new sn()), Y = /* @__PURE__ */ BigInt(2 ** 32 - 1), _t = /* @__PURE__ */ BigInt(32);
1674
- function rn(e, t = !1) {
1675
- return t ? { h: Number(e & Y), l: Number(e >> _t & Y) } : { h: Number(e >> _t & Y) | 0, l: Number(e & Y) | 0 };
1676
- }
1677
- function oe(e, t = !1) {
1678
- const n = e.length;
1679
- let s = new Uint32Array(n), o = new Uint32Array(n);
1680
- for (let r = 0; r < n; r++) {
1681
- const { h: i, l: a } = rn(e[r], t);
1682
- [s[r], o[r]] = [i, a];
1683
- }
1684
- return [s, o];
1685
- }
1686
- const Rt = (e, t, n) => e >>> n, Wt = (e, t, n) => e << 32 - n | t >>> n, N = (e, t, n) => e >>> n | t << 32 - n, X = (e, t, n) => e << 32 - n | t >>> n, tt = (e, t, n) => e << 64 - n | t >>> n - 32, et = (e, t, n) => e >>> n - 32 | t << 64 - n, an = (e, t, n) => e << n | t >>> 32 - n, cn = (e, t, n) => t << n | e >>> 32 - n, un = (e, t, n) => t << n - 32 | e >>> 64 - n, ln = (e, t, n) => e << n - 32 | t >>> 64 - n;
1687
- function F(e, t, n, s) {
1688
- const o = (t >>> 0) + (s >>> 0);
1689
- return { h: e + n + (o / 2 ** 32 | 0) | 0, l: o | 0 };
1690
- }
1691
- const hn = (e, t, n) => (e >>> 0) + (t >>> 0) + (n >>> 0), dn = (e, t, n, s) => t + n + s + (e / 2 ** 32 | 0) | 0, fn = (e, t, n, s) => (e >>> 0) + (t >>> 0) + (n >>> 0) + (s >>> 0), pn = (e, t, n, s, o) => t + n + s + o + (e / 2 ** 32 | 0) | 0, bn = (e, t, n, s, o) => (e >>> 0) + (t >>> 0) + (n >>> 0) + (s >>> 0) + (o >>> 0), gn = (e, t, n, s, o, r) => t + n + s + o + r + (e / 2 ** 32 | 0) | 0, yn = /* @__PURE__ */ Uint32Array.from([
1692
- 1116352408,
1693
- 1899447441,
1694
- 3049323471,
1695
- 3921009573,
1696
- 961987163,
1697
- 1508970993,
1698
- 2453635748,
1699
- 2870763221,
1700
- 3624381080,
1701
- 310598401,
1702
- 607225278,
1703
- 1426881987,
1704
- 1925078388,
1705
- 2162078206,
1706
- 2614888103,
1707
- 3248222580,
1708
- 3835390401,
1709
- 4022224774,
1710
- 264347078,
1711
- 604807628,
1712
- 770255983,
1713
- 1249150122,
1714
- 1555081692,
1715
- 1996064986,
1716
- 2554220882,
1717
- 2821834349,
1718
- 2952996808,
1719
- 3210313671,
1720
- 3336571891,
1721
- 3584528711,
1722
- 113926993,
1723
- 338241895,
1724
- 666307205,
1725
- 773529912,
1726
- 1294757372,
1727
- 1396182291,
1728
- 1695183700,
1729
- 1986661051,
1730
- 2177026350,
1731
- 2456956037,
1732
- 2730485921,
1733
- 2820302411,
1734
- 3259730800,
1735
- 3345764771,
1736
- 3516065817,
1737
- 3600352804,
1738
- 4094571909,
1739
- 275423344,
1740
- 430227734,
1741
- 506948616,
1742
- 659060556,
1743
- 883997877,
1744
- 958139571,
1745
- 1322822218,
1746
- 1537002063,
1747
- 1747873779,
1748
- 1955562222,
1749
- 2024104815,
1750
- 2227730452,
1751
- 2361852424,
1752
- 2428436474,
1753
- 2756734187,
1754
- 3204031479,
1755
- 3329325298
1756
- ]), L = /* @__PURE__ */ new Uint32Array(64);
1757
- class xn extends Pt {
1758
- constructor(t) {
1759
- super(64, t, 8, !1);
1760
- }
1761
- get() {
1762
- const { A: t, B: n, C: s, D: o, E: r, F: i, G: a, H: c } = this;
1763
- return [t, n, s, o, r, i, a, c];
1764
- }
1765
- // prettier-ignore
1766
- set(t, n, s, o, r, i, a, c) {
1767
- this.A = t | 0, this.B = n | 0, this.C = s | 0, this.D = o | 0, this.E = r | 0, this.F = i | 0, this.G = a | 0, this.H = c | 0;
1768
- }
1769
- process(t, n) {
1770
- for (let u = 0; u < 16; u++, n += 4)
1771
- L[u] = t.getUint32(n, !1);
1772
- for (let u = 16; u < 64; u++) {
1773
- const d = L[u - 15], y = L[u - 2], b = A(d, 7) ^ A(d, 18) ^ d >>> 3, x = A(y, 17) ^ A(y, 19) ^ y >>> 10;
1774
- L[u] = x + L[u - 7] + b + L[u - 16] | 0;
1775
- }
1776
- let { A: s, B: o, C: r, D: i, E: a, F: c, G: l, H: h } = this;
1777
- for (let u = 0; u < 64; u++) {
1778
- const d = A(a, 6) ^ A(a, 11) ^ A(a, 25), y = h + d + ze(a, c, l) + yn[u] + L[u] | 0, x = (A(s, 2) ^ A(s, 13) ^ A(s, 22)) + Ze(s, o, r) | 0;
1779
- h = l, l = c, c = a, a = i + y | 0, i = r, r = o, o = s, s = y + x | 0;
1780
- }
1781
- s = s + this.A | 0, o = o + this.B | 0, r = r + this.C | 0, i = i + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, l = l + this.G | 0, h = h + this.H | 0, this.set(s, o, r, i, a, c, l, h);
1782
- }
1783
- roundClean() {
1784
- S(L);
1785
- }
1786
- destroy() {
1787
- this.set(0, 0, 0, 0, 0, 0, 0, 0), S(this.buffer);
1788
- }
1789
- }
1790
- class wn extends xn {
1791
- constructor() {
1792
- super(32);
1793
- // We cannot use array here since array allows indexing by variable
1794
- // which means optimizer/compiler cannot use registers.
1795
- p(this, "A", O[0] | 0);
1796
- p(this, "B", O[1] | 0);
1797
- p(this, "C", O[2] | 0);
1798
- p(this, "D", O[3] | 0);
1799
- p(this, "E", O[4] | 0);
1800
- p(this, "F", O[5] | 0);
1801
- p(this, "G", O[6] | 0);
1802
- p(this, "H", O[7] | 0);
1803
- }
1804
- }
1805
- const re = oe([
1806
- "0x428a2f98d728ae22",
1807
- "0x7137449123ef65cd",
1808
- "0xb5c0fbcfec4d3b2f",
1809
- "0xe9b5dba58189dbbc",
1810
- "0x3956c25bf348b538",
1811
- "0x59f111f1b605d019",
1812
- "0x923f82a4af194f9b",
1813
- "0xab1c5ed5da6d8118",
1814
- "0xd807aa98a3030242",
1815
- "0x12835b0145706fbe",
1816
- "0x243185be4ee4b28c",
1817
- "0x550c7dc3d5ffb4e2",
1818
- "0x72be5d74f27b896f",
1819
- "0x80deb1fe3b1696b1",
1820
- "0x9bdc06a725c71235",
1821
- "0xc19bf174cf692694",
1822
- "0xe49b69c19ef14ad2",
1823
- "0xefbe4786384f25e3",
1824
- "0x0fc19dc68b8cd5b5",
1825
- "0x240ca1cc77ac9c65",
1826
- "0x2de92c6f592b0275",
1827
- "0x4a7484aa6ea6e483",
1828
- "0x5cb0a9dcbd41fbd4",
1829
- "0x76f988da831153b5",
1830
- "0x983e5152ee66dfab",
1831
- "0xa831c66d2db43210",
1832
- "0xb00327c898fb213f",
1833
- "0xbf597fc7beef0ee4",
1834
- "0xc6e00bf33da88fc2",
1835
- "0xd5a79147930aa725",
1836
- "0x06ca6351e003826f",
1837
- "0x142929670a0e6e70",
1838
- "0x27b70a8546d22ffc",
1839
- "0x2e1b21385c26c926",
1840
- "0x4d2c6dfc5ac42aed",
1841
- "0x53380d139d95b3df",
1842
- "0x650a73548baf63de",
1843
- "0x766a0abb3c77b2a8",
1844
- "0x81c2c92e47edaee6",
1845
- "0x92722c851482353b",
1846
- "0xa2bfe8a14cf10364",
1847
- "0xa81a664bbc423001",
1848
- "0xc24b8b70d0f89791",
1849
- "0xc76c51a30654be30",
1850
- "0xd192e819d6ef5218",
1851
- "0xd69906245565a910",
1852
- "0xf40e35855771202a",
1853
- "0x106aa07032bbd1b8",
1854
- "0x19a4c116b8d2d0c8",
1855
- "0x1e376c085141ab53",
1856
- "0x2748774cdf8eeb99",
1857
- "0x34b0bcb5e19b48a8",
1858
- "0x391c0cb3c5c95a63",
1859
- "0x4ed8aa4ae3418acb",
1860
- "0x5b9cca4f7763e373",
1861
- "0x682e6ff3d6b2b8a3",
1862
- "0x748f82ee5defb2fc",
1863
- "0x78a5636f43172f60",
1864
- "0x84c87814a1f0ab72",
1865
- "0x8cc702081a6439ec",
1866
- "0x90befffa23631e28",
1867
- "0xa4506cebde82bde9",
1868
- "0xbef9a3f7b2c67915",
1869
- "0xc67178f2e372532b",
1870
- "0xca273eceea26619c",
1871
- "0xd186b8c721c0c207",
1872
- "0xeada7dd6cde0eb1e",
1873
- "0xf57d4f7fee6ed178",
1874
- "0x06f067aa72176fba",
1875
- "0x0a637dc5a2c898a6",
1876
- "0x113f9804bef90dae",
1877
- "0x1b710b35131c471b",
1878
- "0x28db77f523047d84",
1879
- "0x32caab7b40c72493",
1880
- "0x3c9ebe0a15c9bebc",
1881
- "0x431d67c49c100d4c",
1882
- "0x4cc5d4becb3e42b6",
1883
- "0x597f299cfc657e2a",
1884
- "0x5fcb6fab3ad6faec",
1885
- "0x6c44198c4a475817"
1886
- ].map((e) => BigInt(e))), mn = re[0], Pn = re[1], _ = /* @__PURE__ */ new Uint32Array(80), R = /* @__PURE__ */ new Uint32Array(80);
1887
- class Tn extends Pt {
1888
- constructor(t) {
1889
- super(128, t, 16, !1);
1890
- }
1891
- // prettier-ignore
1892
- get() {
1893
- const { Ah: t, Al: n, Bh: s, Bl: o, Ch: r, Cl: i, Dh: a, Dl: c, Eh: l, El: h, Fh: u, Fl: d, Gh: y, Gl: b, Hh: x, Hl: P } = this;
1894
- return [t, n, s, o, r, i, a, c, l, h, u, d, y, b, x, P];
1895
- }
1896
- // prettier-ignore
1897
- set(t, n, s, o, r, i, a, c, l, h, u, d, y, b, x, P) {
1898
- this.Ah = t | 0, this.Al = n | 0, this.Bh = s | 0, this.Bl = o | 0, this.Ch = r | 0, this.Cl = i | 0, this.Dh = a | 0, this.Dl = c | 0, this.Eh = l | 0, this.El = h | 0, this.Fh = u | 0, this.Fl = d | 0, this.Gh = y | 0, this.Gl = b | 0, this.Hh = x | 0, this.Hl = P | 0;
1899
- }
1900
- process(t, n) {
1901
- for (let f = 0; f < 16; f++, n += 4)
1902
- _[f] = t.getUint32(n), R[f] = t.getUint32(n += 4);
1903
- for (let f = 16; f < 80; f++) {
1904
- const w = _[f - 15] | 0, v = R[f - 15] | 0, T = N(w, v, 1) ^ N(w, v, 8) ^ Rt(w, v, 7), H = X(w, v, 1) ^ X(w, v, 8) ^ Wt(w, v, 7), I = _[f - 2] | 0, E = R[f - 2] | 0, C = N(I, E, 19) ^ tt(I, E, 61) ^ Rt(I, E, 6), M = X(I, E, 19) ^ et(I, E, 61) ^ Wt(I, E, 6), $ = fn(H, M, R[f - 7], R[f - 16]), ut = pn($, T, C, _[f - 7], _[f - 16]);
1905
- _[f] = ut | 0, R[f] = $ | 0;
1906
- }
1907
- let { Ah: s, Al: o, Bh: r, Bl: i, Ch: a, Cl: c, Dh: l, Dl: h, Eh: u, El: d, Fh: y, Fl: b, Gh: x, Gl: P, Hh: m, Hl: g } = this;
1908
- for (let f = 0; f < 80; f++) {
1909
- const w = N(u, d, 14) ^ N(u, d, 18) ^ tt(u, d, 41), v = X(u, d, 14) ^ X(u, d, 18) ^ et(u, d, 41), T = u & y ^ ~u & x, H = d & b ^ ~d & P, I = bn(g, v, H, Pn[f], R[f]), E = gn(I, m, w, T, mn[f], _[f]), C = I | 0, M = N(s, o, 28) ^ tt(s, o, 34) ^ tt(s, o, 39), $ = X(s, o, 28) ^ et(s, o, 34) ^ et(s, o, 39), ut = s & r ^ s & a ^ r & a, de = o & i ^ o & c ^ i & c;
1910
- m = x | 0, g = P | 0, x = y | 0, P = b | 0, y = u | 0, b = d | 0, { h: u, l: d } = F(l | 0, h | 0, E | 0, C | 0), l = a | 0, h = c | 0, a = r | 0, c = i | 0, r = s | 0, i = o | 0;
1911
- const vt = hn(C, $, de);
1912
- s = dn(vt, E, M, ut), o = vt | 0;
1913
- }
1914
- ({ h: s, l: o } = F(this.Ah | 0, this.Al | 0, s | 0, o | 0)), { h: r, l: i } = F(this.Bh | 0, this.Bl | 0, r | 0, i | 0), { h: a, l: c } = F(this.Ch | 0, this.Cl | 0, a | 0, c | 0), { h: l, l: h } = F(this.Dh | 0, this.Dl | 0, l | 0, h | 0), { h: u, l: d } = F(this.Eh | 0, this.El | 0, u | 0, d | 0), { h: y, l: b } = F(this.Fh | 0, this.Fl | 0, y | 0, b | 0), { h: x, l: P } = F(this.Gh | 0, this.Gl | 0, x | 0, P | 0), { h: m, l: g } = F(this.Hh | 0, this.Hl | 0, m | 0, g | 0), this.set(s, o, r, i, a, c, l, h, u, d, y, b, x, P, m, g);
1915
- }
1916
- roundClean() {
1917
- S(_, R);
1918
- }
1919
- destroy() {
1920
- S(this.buffer), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1921
- }
1922
- }
1923
- class vn extends Tn {
1924
- constructor() {
1925
- super(64);
1926
- p(this, "Ah", k[0] | 0);
1927
- p(this, "Al", k[1] | 0);
1928
- p(this, "Bh", k[2] | 0);
1929
- p(this, "Bl", k[3] | 0);
1930
- p(this, "Ch", k[4] | 0);
1931
- p(this, "Cl", k[5] | 0);
1932
- p(this, "Dh", k[6] | 0);
1933
- p(this, "Dl", k[7] | 0);
1934
- p(this, "Eh", k[8] | 0);
1935
- p(this, "El", k[9] | 0);
1936
- p(this, "Fh", k[10] | 0);
1937
- p(this, "Fl", k[11] | 0);
1938
- p(this, "Gh", k[12] | 0);
1939
- p(this, "Gl", k[13] | 0);
1940
- p(this, "Hh", k[14] | 0);
1941
- p(this, "Hl", k[15] | 0);
1942
- }
1943
- }
1944
- const kn = /* @__PURE__ */ ct(
1945
- () => new wn(),
1946
- /* @__PURE__ */ Jt(1)
1947
- ), ie = /* @__PURE__ */ ct(
1948
- () => new vn(),
1949
- /* @__PURE__ */ Jt(3)
1950
- ), Hn = BigInt(0), z = BigInt(1), In = BigInt(2), En = BigInt(7), Bn = BigInt(256), Sn = BigInt(113), ae = [], ce = [], ue = [];
1951
- for (let e = 0, t = z, n = 1, s = 0; e < 24; e++) {
1952
- [n, s] = [s, (2 * n + 3 * s) % 5], ae.push(2 * (5 * s + n)), ce.push((e + 1) * (e + 2) / 2 % 64);
1953
- let o = Hn;
1954
- for (let r = 0; r < 7; r++)
1955
- t = (t << z ^ (t >> En) * Sn) % Bn, t & In && (o ^= z << (z << BigInt(r)) - z);
1956
- ue.push(o);
1957
- }
1958
- const le = oe(ue, !0), An = le[0], Un = le[1], Vt = (e, t, n) => n > 32 ? un(e, t, n) : an(e, t, n), Dt = (e, t, n) => n > 32 ? ln(e, t, n) : cn(e, t, n);
1959
- function Fn(e, t = 24) {
1960
- const n = new Uint32Array(10);
1961
- for (let s = 24 - t; s < 24; s++) {
1962
- for (let i = 0; i < 10; i++)
1963
- n[i] = e[i] ^ e[i + 10] ^ e[i + 20] ^ e[i + 30] ^ e[i + 40];
1964
- for (let i = 0; i < 10; i += 2) {
1965
- const a = (i + 8) % 10, c = (i + 2) % 10, l = n[c], h = n[c + 1], u = Vt(l, h, 1) ^ n[a], d = Dt(l, h, 1) ^ n[a + 1];
1966
- for (let y = 0; y < 50; y += 10)
1967
- e[i + y] ^= u, e[i + y + 1] ^= d;
1968
- }
1969
- let o = e[2], r = e[3];
1970
- for (let i = 0; i < 24; i++) {
1971
- const a = ce[i], c = Vt(o, r, a), l = Dt(o, r, a), h = ae[i];
1972
- o = e[h], r = e[h + 1], e[h] = c, e[h + 1] = l;
1973
- }
1974
- for (let i = 0; i < 50; i += 10) {
1975
- for (let a = 0; a < 10; a++)
1976
- n[a] = e[i + a];
1977
- for (let a = 0; a < 10; a++)
1978
- e[i + a] ^= ~n[(a + 2) % 10] & n[(a + 4) % 10];
1979
- }
1980
- e[0] ^= An[s], e[1] ^= Un[s];
1981
- }
1982
- S(n);
1983
- }
1984
- class Tt {
1985
- // NOTE: we accept arguments in bytes instead of bits here.
1986
- constructor(t, n, s, o = !1, r = 24) {
1987
- p(this, "state");
1988
- p(this, "pos", 0);
1989
- p(this, "posOut", 0);
1990
- p(this, "finished", !1);
1991
- p(this, "state32");
1992
- p(this, "destroyed", !1);
1993
- p(this, "blockLen");
1994
- p(this, "suffix");
1995
- p(this, "outputLen");
1996
- p(this, "enableXOF", !1);
1997
- p(this, "rounds");
1998
- if (this.blockLen = t, this.suffix = n, this.outputLen = s, this.enableXOF = o, this.rounds = r, V(s, "outputLen"), !(0 < t && t < 200))
1999
- throw new Error("only keccak-f1600 function is supported");
2000
- this.state = new Uint8Array(200), this.state32 = Ke(this.state);
2001
- }
2002
- clone() {
2003
- return this._cloneInto();
2004
- }
2005
- keccak() {
2006
- $t(this.state32), Fn(this.state32, this.rounds), $t(this.state32), this.posOut = 0, this.pos = 0;
2007
- }
2008
- update(t) {
2009
- G(this), D(t);
2010
- const { blockLen: n, state: s } = this, o = t.length;
2011
- for (let r = 0; r < o; ) {
2012
- const i = Math.min(n - this.pos, o - r);
2013
- for (let a = 0; a < i; a++)
2014
- s[this.pos++] ^= t[r++];
2015
- this.pos === n && this.keccak();
2016
- }
2017
- return this;
2018
- }
2019
- finish() {
2020
- if (this.finished)
2021
- return;
2022
- this.finished = !0;
2023
- const { state: t, suffix: n, pos: s, blockLen: o } = this;
2024
- t[s] ^= n, (n & 128) !== 0 && s === o - 1 && this.keccak(), t[o - 1] ^= 128, this.keccak();
2025
- }
2026
- writeInto(t) {
2027
- G(this, !1), D(t), this.finish();
2028
- const n = this.state, { blockLen: s } = this;
2029
- for (let o = 0, r = t.length; o < r; ) {
2030
- this.posOut >= s && this.keccak();
2031
- const i = Math.min(s - this.posOut, r - o);
2032
- t.set(n.subarray(this.posOut, this.posOut + i), o), this.posOut += i, o += i;
2033
- }
2034
- return t;
2035
- }
2036
- xofInto(t) {
2037
- if (!this.enableXOF)
2038
- throw new Error("XOF is not possible for this instance");
2039
- return this.writeInto(t);
2040
- }
2041
- xof(t) {
2042
- return V(t), this.xofInto(new Uint8Array(t));
2043
- }
2044
- digestInto(t) {
2045
- if (Zt(t, this), this.finished)
2046
- throw new Error("digest() was already called");
2047
- return this.writeInto(t), this.destroy(), t;
2048
- }
2049
- digest() {
2050
- return this.digestInto(new Uint8Array(this.outputLen));
2051
- }
2052
- destroy() {
2053
- this.destroyed = !0, S(this.state);
2054
- }
2055
- _cloneInto(t) {
2056
- const { blockLen: n, suffix: s, outputLen: o, rounds: r, enableXOF: i } = this;
2057
- return t || (t = new Tt(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;
2058
- }
2059
- }
2060
- const Cn = (e, t, n, s = {}) => ct(() => new Tt(t, e, n), s), $n = /* @__PURE__ */ Cn(1, 136, 32);
2061
- function On(e, t, n, s) {
2062
- zt(e);
2063
- const o = je({ dkLen: 32, asyncTick: 10 }, s), { c: r, dkLen: i, asyncTick: a } = o;
2064
- if (V(r, "c"), V(i, "dkLen"), V(a, "asyncTick"), r < 1)
2065
- throw new Error("iterations (c) must be >= 1");
2066
- const c = Ot(t, "password"), l = Ot(n, "salt"), h = new Uint8Array(i), u = mt.create(e, c), d = u._cloneInto().update(l);
2067
- return { c: r, dkLen: i, asyncTick: a, DK: h, PRF: u, PRFSalt: d };
2068
- }
2069
- function Ln(e, t, n, s, o) {
2070
- return e.destroy(), t.destroy(), s && s.destroy(), S(o), n;
2071
- }
2072
- function _n(e, t, n, s) {
2073
- const { c: o, dkLen: r, DK: i, PRF: a, PRFSalt: c } = On(e, t, n, s);
2074
- let l;
2075
- const h = new Uint8Array(4), u = rt(h), d = new Uint8Array(a.outputLen);
2076
- for (let y = 1, b = 0; b < r; y++, b += a.outputLen) {
2077
- const x = i.subarray(b, b + a.outputLen);
2078
- u.setInt32(0, y, !1), (l = c._cloneInto(l)).update(h).digestInto(d), x.set(d.subarray(0, x.length));
2079
- for (let P = 1; P < o; P++) {
2080
- a._cloneInto(l).update(d).digestInto(d);
2081
- for (let m = 0; m < x.length; m++)
2082
- x[m] ^= d[m];
2083
- }
2084
- }
2085
- return Ln(a, c, i, l, d);
2086
- }
2087
- function he(e) {
2088
- if (typeof e != "string")
2089
- throw new TypeError("invalid mnemonic type: " + typeof e);
2090
- return e.normalize("NFKD");
2091
- }
2092
- function Rn(e) {
2093
- const t = he(e), n = t.split(" ");
2094
- if (![12, 15, 18, 21, 24].includes(n.length))
2095
- throw new Error("Invalid mnemonic");
2096
- return { nfkd: t, words: n };
2097
- }
2098
- const Wn = (e) => he("mnemonic" + e);
2099
- function Vn(e, t = "") {
2100
- return _n(ie, Rn(e).nfkd, Wn(t), { c: 2048, dkLen: 64 });
2101
- }
2102
- const Dn = 508, Mt = 16, nt = 32, st = 64, Kt = 5, Mn = 4;
2103
- function Z(...e) {
2104
- const t = e.reduce((o, r) => o + r.length, 0), n = new Uint8Array(t);
2105
- let s = 0;
2106
- for (const o of e)
2107
- n.set(o, s), s += o.length;
2108
- return n;
2109
- }
2110
- function ft(e) {
2111
- return new TextEncoder().encode(e);
2112
- }
2113
- function pt(e) {
2114
- const t = new Uint8Array(Mn);
2115
- return new DataView(t.buffer).setUint32(0, e.length, !1), Z(t, e);
2116
- }
2117
- function bt(e, t) {
2118
- return mt(ie, e, t);
2119
- }
2120
- function Nt(e) {
2121
- return on(kn(e));
2122
- }
2123
- const yt = (e) => Array.from(e).map((t) => t.toString(16).padStart(2, "0")).join("");
2124
- function Kn(e) {
2125
- const t = Vn(e), n = new Uint8Array(t);
2126
- return t.fill(0), n;
2127
- }
2128
- async function Nn(e, t, n, s) {
2129
- if (e.length !== st)
2130
- throw new Error(
2131
- `WOTS seed must be ${st} bytes, got ${e.length}`
2132
- );
2133
- t = B(t), n = B(n);
2134
- const o = e.slice(nt, st), r = e.slice(0, nt), i = [o, r];
2135
- try {
2136
- const a = Z(
2137
- pt(ft(t)),
2138
- pt(ft(n)),
2139
- pt(ft(s))
2140
- ), c = Z(r, a);
2141
- i.push(c);
2142
- const l = bt(o, c);
2143
- i.push(l);
2144
- const h = l.slice(0, nt), u = l.slice(nt, st);
2145
- i.push(h, u);
2146
- const d = [], y = [], b = [], x = [];
2147
- let P = !1;
2148
- try {
2149
- for (let m = 0; m < Dn; m++) {
2150
- const g = new Uint8Array(Kt);
2151
- g[0] = 0, new DataView(g.buffer).setUint32(1, m, !1);
2152
- const f = new Uint8Array(Kt);
2153
- f[0] = 1, new DataView(f.buffer).setUint32(1, m, !1);
2154
- const w = Z(h, g), v = Z(h, f), T = bt(u, w), H = bt(u, v);
2155
- try {
2156
- const I = T.slice(0, Mt), E = H.slice(0, Mt);
2157
- d.push(I), y.push(E), b.push(Nt(I)), x.push(Nt(E));
2158
- } finally {
2159
- w.fill(0), v.fill(0), T.fill(0), H.fill(0);
2160
- }
2161
- }
2162
- return P = !0, { falsePreimages: d, truePreimages: y, falseHashes: b, trueHashes: x };
2163
- } finally {
2164
- if (!P) {
2165
- for (const m of d) m.fill(0);
2166
- for (const m of y) m.fill(0);
2167
- }
2168
- }
2169
- } finally {
2170
- for (const a of i)
2171
- a.fill(0);
2172
- }
2173
- }
2174
- function us(e) {
2175
- return {
2176
- false_list: e.falseHashes.map(yt),
2177
- true_list: e.trueHashes.map(yt)
2178
- };
2179
- }
2180
- function Xn(e) {
2181
- if (e.falseHashes.length === 0 || e.trueHashes.length === 0)
2182
- throw new Error(
2183
- "computeWotsPkHash: keypair hash arrays must not be empty"
2184
- );
2185
- const t = e.falseHashes[0].length, n = (e.falseHashes.length + e.trueHashes.length) * t, s = new Uint8Array(n);
2186
- let o = 0;
2187
- for (const i of e.falseHashes)
2188
- s.set(i, o), o += t;
2189
- for (const i of e.trueHashes)
2190
- s.set(i, o), o += t;
2191
- const r = $n(s);
2192
- return `0x${yt(r)}`;
2193
- }
2194
- async function ls(e, t, n, s) {
2195
- const o = Kn(e);
2196
- try {
2197
- const r = await Nn(
2198
- o,
2199
- t,
2200
- n,
2201
- s
2202
- );
2203
- try {
2204
- return Xn(r);
2205
- } finally {
2206
- for (const i of r.falsePreimages) i.fill(0);
2207
- for (const i of r.truePreimages) i.fill(0);
2208
- }
2209
- } finally {
2210
- o.fill(0);
2211
- }
2212
- }
2213
- function hs(e) {
2214
- const t = (e instanceof Error ? e.message : typeof e == "string" ? e : "").toLowerCase();
2215
- return t.includes("wots") && t.includes("hash") && t.includes("does not match");
2216
- }
2217
- export {
2218
- hs as A,
2219
- ot as B,
2220
- q as C,
2221
- Le as M,
2222
- as as P,
2223
- Qn as a,
2224
- Fe as b,
2225
- dt as c,
2226
- Ce as d,
2227
- gt as e,
2228
- cs as f,
2229
- Yn as g,
2230
- ss as h,
2231
- es as i,
2232
- ns as j,
2233
- os as k,
2234
- ts as l,
2235
- Re as m,
2236
- We as n,
2237
- j as o,
2238
- _e as p,
2239
- wt as q,
2240
- rs as r,
2241
- Ue as s,
2242
- is as t,
2243
- K as u,
2244
- Kn as v,
2245
- Nn as w,
2246
- us as x,
2247
- Xn as y,
2248
- ls as z
2249
- };
2250
- //# sourceMappingURL=errors-BeFfs5_J.js.map