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