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