@babylonlabs-io/ts-sdk 0.67.0 → 0.68.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/PeginManager-Bsv6caG3.js +1466 -0
  2. package/dist/PeginManager-Bsv6caG3.js.map +1 -0
  3. package/dist/PeginManager-C5NWzGT7.cjs +2 -0
  4. package/dist/PeginManager-C5NWzGT7.cjs.map +1 -0
  5. package/dist/{batchPoll-cIxrSLLJ.js → batchPoll-Bc_UKaTz.js} +372 -421
  6. package/dist/batchPoll-Bc_UKaTz.js.map +1 -0
  7. package/dist/batchPoll-C9cZ5usJ.cjs +2 -0
  8. package/dist/batchPoll-C9cZ5usJ.cjs.map +1 -0
  9. package/dist/{bitcoin-d9eaaZB_.js → bitcoin-Ch_jxnDa.js} +3 -3
  10. package/dist/{bitcoin-d9eaaZB_.js.map → bitcoin-Ch_jxnDa.js.map} +1 -1
  11. package/dist/{buildAndBroadcastRefund-C4LiPATK.js → buildAndBroadcastRefund-CpMDJ8up.js} +142 -150
  12. package/dist/buildAndBroadcastRefund-CpMDJ8up.js.map +1 -0
  13. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs.map +1 -0
  15. package/dist/challengeAssert-BNQ8sToz.js +64 -0
  16. package/dist/challengeAssert-BNQ8sToz.js.map +1 -0
  17. package/dist/challengeAssert-BrpC3-cQ.cjs +2 -0
  18. package/dist/challengeAssert-BrpC3-cQ.cjs.map +1 -0
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +246 -243
  21. package/dist/{mempoolApi-BxSINXIB.js → mempoolApi-71R_CNZa.js} +193 -117
  22. package/dist/mempoolApi-71R_CNZa.js.map +1 -0
  23. package/dist/mempoolApi-BJN9fGEd.cjs +2 -0
  24. package/dist/mempoolApi-BJN9fGEd.cjs.map +1 -0
  25. package/dist/{noPayout-BaZGRLD2.js → noPayout-CXn-geIS.js} +3 -3
  26. package/dist/{noPayout-BaZGRLD2.js.map → noPayout-CXn-geIS.js.map} +1 -1
  27. package/dist/{noPayout-CnQ1WLtr.cjs → noPayout-Ox27Td9x.cjs} +2 -2
  28. package/dist/{noPayout-CnQ1WLtr.cjs.map → noPayout-Ox27Td9x.cjs.map} +1 -1
  29. package/dist/{onChainBtcPubkey-DeF4cKoO.js → onChainBtcPubkey-BAHZyKQL.js} +2 -2
  30. package/dist/{onChainBtcPubkey-DeF4cKoO.js.map → onChainBtcPubkey-BAHZyKQL.js.map} +1 -1
  31. package/dist/{parseFundingOutpoints-pBRE11Hr.js → parseFundingOutpoints-CO-f6IHK.js} +2 -2
  32. package/dist/{parseFundingOutpoints-pBRE11Hr.js.map → parseFundingOutpoints-CO-f6IHK.js.map} +1 -1
  33. package/dist/{reservation-B4i_PQhY.js → reservation-CBAvoF3U.js} +2 -2
  34. package/dist/{reservation-B4i_PQhY.js.map → reservation-CBAvoF3U.js.map} +1 -1
  35. package/dist/{signPsbtsWithFallback-Bb66DfY5.js → signPsbtsWithFallback-Bv79gLFe.js} +122 -100
  36. package/dist/signPsbtsWithFallback-Bv79gLFe.js.map +1 -0
  37. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs +2 -0
  38. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs.map +1 -0
  39. package/dist/tbv/core/clients/index.cjs +1 -1
  40. package/dist/tbv/core/clients/index.js +3 -3
  41. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322P2wpkhVectors.d.ts +32 -0
  42. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322P2wpkhVectors.d.ts.map +1 -0
  43. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts +9 -6
  44. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +54 -20
  46. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -1
  47. package/dist/tbv/core/deposit-terms/__tests__/depositTerms.test.d.ts +2 -0
  48. package/dist/tbv/core/deposit-terms/__tests__/depositTerms.test.d.ts.map +1 -0
  49. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +41 -4
  50. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -1
  51. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts +10 -5
  52. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts.map +1 -1
  53. package/dist/tbv/core/index.cjs +1 -1
  54. package/dist/tbv/core/index.js +244 -241
  55. package/dist/tbv/core/managers/PayoutManager.d.ts +8 -2
  56. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  57. package/dist/tbv/core/managers/PeginManager.d.ts +7 -0
  58. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  59. package/dist/tbv/core/managers/index.cjs +1 -1
  60. package/dist/tbv/core/managers/index.js +2 -2
  61. package/dist/tbv/core/managers/pegin/__tests__/verifyPopWitness.test.d.ts +11 -0
  62. package/dist/tbv/core/managers/pegin/__tests__/verifyPopWitness.test.d.ts.map +1 -0
  63. package/dist/tbv/core/managers/pegin/expandPerVaultSecrets.d.ts.map +1 -1
  64. package/dist/tbv/core/managers/pegin/index.d.ts +1 -0
  65. package/dist/tbv/core/managers/pegin/index.d.ts.map +1 -1
  66. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts +21 -0
  67. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts.map +1 -0
  68. package/dist/tbv/core/primitives/challengers.d.ts +31 -5
  69. package/dist/tbv/core/primitives/challengers.d.ts.map +1 -1
  70. package/dist/tbv/core/primitives/index.cjs +1 -1
  71. package/dist/tbv/core/primitives/index.d.ts +2 -0
  72. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  73. package/dist/tbv/core/primitives/index.js +43 -41
  74. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +5 -0
  75. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts.map +1 -1
  76. package/dist/tbv/core/primitives/psbt/__tests__/verifyKeyPathSchnorrSignature.test.d.ts +12 -0
  77. package/dist/tbv/core/primitives/psbt/__tests__/verifyKeyPathSchnorrSignature.test.d.ts.map +1 -0
  78. package/dist/tbv/core/primitives/psbt/payout.d.ts +19 -7
  79. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts +65 -0
  81. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts.map +1 -0
  82. package/dist/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.d.ts +40 -0
  83. package/dist/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.d.ts.map +1 -0
  84. package/dist/tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature.d.ts +2 -1
  85. package/dist/tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature.d.ts.map +1 -1
  86. package/dist/tbv/core/primitives/utils/__tests__/taproot.test.d.ts +13 -0
  87. package/dist/tbv/core/primitives/utils/__tests__/taproot.test.d.ts.map +1 -0
  88. package/dist/tbv/core/primitives/utils/taproot.d.ts +29 -0
  89. package/dist/tbv/core/primitives/utils/taproot.d.ts.map +1 -0
  90. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +2 -2
  91. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  92. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  93. package/dist/tbv/core/services/index.cjs +1 -1
  94. package/dist/tbv/core/services/index.js +2 -2
  95. package/dist/tbv/core/utils/index.js +2 -2
  96. package/dist/tbv/core/utils/witness/witnessStack.d.ts +24 -0
  97. package/dist/tbv/core/utils/witness/witnessStack.d.ts.map +1 -0
  98. package/dist/tbv/core/vault-secrets/index.js +1 -1
  99. package/dist/tbv/index.cjs +1 -1
  100. package/dist/tbv/index.js +244 -241
  101. package/dist/testing/MockBitcoinWallet.d.ts +9 -0
  102. package/dist/testing/MockBitcoinWallet.d.ts.map +1 -1
  103. package/dist/testing/__tests__/MockBitcoinWallet.test.d.ts +2 -0
  104. package/dist/testing/__tests__/MockBitcoinWallet.test.d.ts.map +1 -0
  105. package/dist/testing/index.cjs +1 -1
  106. package/dist/testing/index.cjs.map +1 -1
  107. package/dist/testing/index.js +136 -45
  108. package/dist/testing/index.js.map +1 -1
  109. package/dist/testing/signBip322P2wpkhWitness.d.ts +25 -0
  110. package/dist/testing/signBip322P2wpkhWitness.d.ts.map +1 -0
  111. package/dist/{toRefundInputs-BY_fcvrv.js → toRefundInputs-4UJfSVEz.js} +6 -6
  112. package/dist/{toRefundInputs-BY_fcvrv.js.map → toRefundInputs-4UJfSVEz.js.map} +1 -1
  113. package/dist/{toRefundInputs-DYL9C-aG.cjs → toRefundInputs-DgDhx_Ut.cjs} +2 -2
  114. package/dist/{toRefundInputs-DYL9C-aG.cjs.map → toRefundInputs-DgDhx_Ut.cjs.map} +1 -1
  115. package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js +372 -0
  116. package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +1 -0
  117. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +2 -0
  118. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +1 -0
  119. package/dist/verifyScriptPathSchnorrSignature-Dy9gF5RF.js +931 -0
  120. package/dist/verifyScriptPathSchnorrSignature-Dy9gF5RF.js.map +1 -0
  121. package/dist/verifyScriptPathSchnorrSignature-la8XOAFm.cjs +2 -0
  122. package/dist/verifyScriptPathSchnorrSignature-la8XOAFm.cjs.map +1 -0
  123. package/package.json +1 -1
  124. package/dist/PeginManager-BBl4xkWz.js +0 -1359
  125. package/dist/PeginManager-BBl4xkWz.js.map +0 -1
  126. package/dist/PeginManager-p-ajwSxG.cjs +0 -2
  127. package/dist/PeginManager-p-ajwSxG.cjs.map +0 -1
  128. package/dist/batchPoll-6L5oToGr.cjs +0 -2
  129. package/dist/batchPoll-6L5oToGr.cjs.map +0 -1
  130. package/dist/batchPoll-cIxrSLLJ.js.map +0 -1
  131. package/dist/buildAndBroadcastRefund-C4LiPATK.js.map +0 -1
  132. package/dist/buildAndBroadcastRefund-Daw5ZUKR.cjs +0 -2
  133. package/dist/buildAndBroadcastRefund-Daw5ZUKR.cjs.map +0 -1
  134. package/dist/challengeAssert-BFRE2DM-.cjs +0 -2
  135. package/dist/challengeAssert-BFRE2DM-.cjs.map +0 -1
  136. package/dist/challengeAssert-C7PzyJ7g.js +0 -75
  137. package/dist/challengeAssert-C7PzyJ7g.js.map +0 -1
  138. package/dist/mempoolApi-BxSINXIB.js.map +0 -1
  139. package/dist/mempoolApi-CXfr-L6x.cjs +0 -2
  140. package/dist/mempoolApi-CXfr-L6x.cjs.map +0 -1
  141. package/dist/peginInput-Ci921gTl.cjs +0 -2
  142. package/dist/peginInput-Ci921gTl.cjs.map +0 -1
  143. package/dist/peginInput-HQPWZfly.js +0 -123
  144. package/dist/peginInput-HQPWZfly.js.map +0 -1
  145. package/dist/signPsbtsWithFallback-Bb66DfY5.js.map +0 -1
  146. package/dist/signPsbtsWithFallback-PTgWxsG3.cjs +0 -2
  147. package/dist/signPsbtsWithFallback-PTgWxsG3.cjs.map +0 -1
  148. package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs +0 -2
  149. package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs.map +0 -1
  150. package/dist/verifyScriptPathSchnorrSignature-i-koT139.js +0 -817
  151. package/dist/verifyScriptPathSchnorrSignature-i-koT139.js.map +0 -1
@@ -0,0 +1,1466 @@
1
+ var Gt = Object.defineProperty;
2
+ var qt = (s, t, e) => t in s ? Gt(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var x = (s, t, e) => qt(s, typeof t != "symbol" ? t + "" : t, e);
4
+ import { c as _t, H as Yt, r as W, a as K, b as at, u as zt, d as ct, e as lt, f as ut, g as jt, s as Bt } from "./sha2-BYVxyZzX.js";
5
+ import * as At from "bitcoinjs-lib";
6
+ import { Transaction as Ct, Psbt as ht } from "bitcoinjs-lib";
7
+ import { Buffer as O } from "buffer";
8
+ import { isAddressEqual as dt, encodeFunctionData as tt, zeroAddress as Qt } from "viem";
9
+ import { B as H } from "./BTCVaultRegistry.abi-CJwWI2EO.js";
10
+ import { h as R } from "./errors-Blc-JWnI.js";
11
+ import { expandWotsSeed as Zt, expandHashlockSecret as Jt, expandAuthAnchor as te, deriveVaultId as ft } from "@babylonlabs-io/babylon-tbv-rust-wasm";
12
+ import { a as pt, b as ee, f as gt, g as se } from "./verifyScriptPathSchnorrSignature-Dy9gF5RF.js";
13
+ import { d as oe, b as ne, e as re, f as ie, c as ae } from "./verifyKeyPathSchnorrSignature-C6Cmk0R1.js";
14
+ import { p as ce, h as et, u as st, e as C, i as mt, s as S, k as wt, X as le } from "./bitcoin-Ch_jxnDa.js";
15
+ import { c as ue } from "./signing-DaLvGwQe.js";
16
+ import { M as bt } from "./validation-Dj3dqYtl.js";
17
+ import { p as he, d as It } from "./parseFundingOutpoints-CO-f6IHK.js";
18
+ import { c as de, s as U, r as fe, b as pe, d as ge } from "./signPsbtsWithFallback-Bv79gLFe.js";
19
+ import { s as me, f as q, i as we, w as Pt } from "./waitForTransactionReceiptSmartAware-lobLm0q0.js";
20
+ import { p as be, f as Pe } from "./fundPeginTransaction-B2wyjqp0.js";
21
+ import { M as X, B as ye } from "./constants-GjWXdaqV.js";
22
+ import { l as xe, P as ke, m as Ee, n as Te, p as ve, V as Se, i as _e } from "./mempoolApi-71R_CNZa.js";
23
+ import * as Be from "@bitcoin-js/tiny-secp256k1-asmjs";
24
+ const N = /* @__PURE__ */ BigInt(2 ** 32 - 1), yt = /* @__PURE__ */ BigInt(32);
25
+ function Ae(s, t = !1) {
26
+ return t ? { h: Number(s & N), l: Number(s >> yt & N) } : { h: Number(s >> yt & N) | 0, l: Number(s & N) | 0 };
27
+ }
28
+ function Ce(s, t = !1) {
29
+ const e = s.length;
30
+ let o = new Uint32Array(e), i = new Uint32Array(e);
31
+ for (let n = 0; n < e; n++) {
32
+ const { h: r, l: a } = Ae(s[n], t);
33
+ [o[n], i[n]] = [r, a];
34
+ }
35
+ return [o, i];
36
+ }
37
+ const Ie = (s, t, e) => s << e | t >>> 32 - e, He = (s, t, e) => t << e | s >>> 32 - e, Re = (s, t, e) => t << e - 32 | s >>> 64 - e, $e = (s, t, e) => s << e - 32 | t >>> 64 - e, Oe = 64;
38
+ function Ve(s) {
39
+ const t = s.prepeginTxid.toLowerCase();
40
+ if (!/^[0-9a-f]+$/.test(t) || t.length !== Oe)
41
+ throw new Error(
42
+ `buildDepositTerms: prepeginTxid must be 64 hex chars, got "${s.prepeginTxid}"`
43
+ );
44
+ if (s.peginAmounts.length === 0)
45
+ throw new Error("buildDepositTerms: at least one pegin amount is required");
46
+ if (s.timelockPegin <= 0 || s.timelockAssert <= 0 || s.timelockRefund <= 0)
47
+ throw new Error("buildDepositTerms: timelocks must be positive");
48
+ if (!Number.isInteger(s.maxAcceptableCommissionBps) || s.maxAcceptableCommissionBps < 0 || s.maxAcceptableCommissionBps >= X)
49
+ throw new Error(
50
+ `buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${X}), got ${s.maxAcceptableCommissionBps}`
51
+ );
52
+ const e = BigInt(ye), o = s.peginAmounts.map(
53
+ (i, n) => ({
54
+ htlcVout: n,
55
+ vaultProviderBtcPubkey: s.vaultProviderBtcPubkey,
56
+ peginAmount: i,
57
+ // Ceiling, not quote: floor(peginAmount * maxAcceptableBps / 10_000) —
58
+ // the same bound the registration calldata enforces on-chain, so any
59
+ // stamped commission the contract admits stays under it (firmware
60
+ // >= c8db53e checks the payout commission output <= this value).
61
+ commissionFee: i * BigInt(s.maxAcceptableCommissionBps) / e,
62
+ depositorClaimValue: s.depositorClaimValue,
63
+ peginMaxFee: s.peginMaxFee
64
+ })
65
+ );
66
+ return {
67
+ vaultCoreVersion: s.vaultCoreVersion,
68
+ protocolFeeRate: s.protocolFeeRate,
69
+ timelockPegin: s.timelockPegin,
70
+ timelockAssert: s.timelockAssert,
71
+ timelockRefund: s.timelockRefund,
72
+ prepeginTxid: t,
73
+ prepeginMaxFee: s.prepeginMaxFee,
74
+ vaultKeeperBtcPubkeys: [...s.vaultKeeperBtcPubkeys],
75
+ universalChallengerBtcPubkeys: [...s.universalChallengerBtcPubkeys],
76
+ vaults: o
77
+ };
78
+ }
79
+ const ot = 25, Ht = 9999;
80
+ function Y(s) {
81
+ if (!Number.isInteger(s) || s < 0 || s >= X)
82
+ throw new Error(
83
+ `Quoted commissionBps must be an integer in [0, ${X}), got ${s}`
84
+ );
85
+ return Math.min(
86
+ s + ot,
87
+ Ht
88
+ );
89
+ }
90
+ const Me = /^0x[0-9a-f]+$/i, We = /^[0-9a-f]+$/i, Ue = /^[A-Za-z0-9+/]+={0,2}$/;
91
+ function $(s) {
92
+ if (typeof s != "string" || s.length === 0)
93
+ throw new Error("BTC wallet returned empty public key");
94
+ return ce(s).toLowerCase();
95
+ }
96
+ function Ne(s) {
97
+ if (typeof s != "string" || s.length === 0)
98
+ throw new Error("BTC wallet returned empty BIP-322 signature");
99
+ if (s.startsWith("0x") || s.startsWith("0X")) {
100
+ if (!Me.test(s) || s.length < 4 || s.length % 2 !== 0)
101
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
102
+ return s.toLowerCase();
103
+ }
104
+ if (We.test(s)) {
105
+ if (s.length % 2 !== 0)
106
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
107
+ return `0x${s.toLowerCase()}`;
108
+ }
109
+ if (!Ue.test(s) || s.length % 4 !== 0)
110
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
111
+ const t = O.from(s, "base64");
112
+ if (t.length === 0 || t.toString("base64") !== s)
113
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
114
+ return `0x${t.toString("hex")}`;
115
+ }
116
+ async function Fe(s) {
117
+ const { wallet: t, depositTerms: e, fundedPrePeginTxHex: o, depositorBtcPubkey: i } = s, n = typeof t.approveDepositTerms == "function" ? t.approveDepositTerms : void 0;
118
+ if (!n && !e)
119
+ return;
120
+ const r = o.startsWith("0x") ? o.slice(2) : o, c = Ct.fromHex(r).getId();
121
+ if (e && e.prepeginTxid.replace(/^0x/, "").toLowerCase() !== c)
122
+ throw new Error(
123
+ `Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${e.prepeginTxid}, but this transaction is ${c}.`
124
+ );
125
+ if (!n)
126
+ return;
127
+ if (!e)
128
+ throw new Error(
129
+ "This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild."
130
+ );
131
+ if (typeof t.deriveContextHash != "function")
132
+ throw new Error(
133
+ "A deposit-approval wallet must also implement deriveContextHash, but this one does not."
134
+ );
135
+ if (typeof t.holdsApprovedDepositTerms == "function") {
136
+ let g = !1;
137
+ try {
138
+ g = await t.holdsApprovedDepositTerms(e);
139
+ } catch {
140
+ }
141
+ if (g)
142
+ return;
143
+ }
144
+ const u = he(o);
145
+ (await It(
146
+ { deriveContextHash: t.deriveContextHash.bind(t) },
147
+ {
148
+ depositorBtcPubkey: et(
149
+ $(i)
150
+ ),
151
+ fundingOutpoints: u
152
+ }
153
+ )).fill(0), await n.call(t, e);
154
+ }
155
+ const De = /* @__PURE__ */ Uint8Array.from([
156
+ 7,
157
+ 4,
158
+ 13,
159
+ 1,
160
+ 10,
161
+ 6,
162
+ 15,
163
+ 3,
164
+ 12,
165
+ 0,
166
+ 9,
167
+ 5,
168
+ 2,
169
+ 14,
170
+ 11,
171
+ 8
172
+ ]), Rt = Uint8Array.from(new Array(16).fill(0).map((s, t) => t)), Le = Rt.map((s) => (9 * s + 5) % 16), $t = /* @__PURE__ */ (() => {
173
+ const e = [[Rt], [Le]];
174
+ for (let o = 0; o < 4; o++)
175
+ for (let i of e)
176
+ i.push(i[o].map((n) => De[n]));
177
+ return e;
178
+ })(), Ot = $t[0], Vt = $t[1], Mt = /* @__PURE__ */ [
179
+ [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
180
+ [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
181
+ [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
182
+ [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
183
+ [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
184
+ ].map((s) => Uint8Array.from(s)), Ke = /* @__PURE__ */ Ot.map((s, t) => s.map((e) => Mt[t][e])), Xe = /* @__PURE__ */ Vt.map((s, t) => s.map((e) => Mt[t][e])), Ge = /* @__PURE__ */ Uint32Array.from([
185
+ 0,
186
+ 1518500249,
187
+ 1859775393,
188
+ 2400959708,
189
+ 2840853838
190
+ ]), qe = /* @__PURE__ */ Uint32Array.from([
191
+ 1352829926,
192
+ 1548603684,
193
+ 1836072691,
194
+ 2053994217,
195
+ 0
196
+ ]);
197
+ function xt(s, t, e, o) {
198
+ return s === 0 ? t ^ e ^ o : s === 1 ? t & e | ~t & o : s === 2 ? (t | ~e) ^ o : s === 3 ? t & o | e & ~o : t ^ (e | ~o);
199
+ }
200
+ const F = /* @__PURE__ */ new Uint32Array(16);
201
+ class Ye extends Yt {
202
+ constructor() {
203
+ super(64, 20, 8, !0);
204
+ x(this, "h0", 1732584193);
205
+ x(this, "h1", -271733879);
206
+ x(this, "h2", -1732584194);
207
+ x(this, "h3", 271733878);
208
+ x(this, "h4", -1009589776);
209
+ }
210
+ get() {
211
+ const { h0: e, h1: o, h2: i, h3: n, h4: r } = this;
212
+ return [e, o, i, n, r];
213
+ }
214
+ set(e, o, i, n, r) {
215
+ this.h0 = e | 0, this.h1 = o | 0, this.h2 = i | 0, this.h3 = n | 0, this.h4 = r | 0;
216
+ }
217
+ process(e, o) {
218
+ for (let d = 0; d < 16; d++, o += 4)
219
+ F[d] = e.getUint32(o, !0);
220
+ let i = this.h0 | 0, n = i, r = this.h1 | 0, a = r, c = this.h2 | 0, u = c, h = this.h3 | 0, g = h, w = this.h4 | 0, b = w;
221
+ for (let d = 0; d < 5; d++) {
222
+ const E = 4 - d, k = Ge[d], f = qe[d], v = Ot[d], B = Vt[d], p = Ke[d], P = Xe[d];
223
+ for (let l = 0; l < 16; l++) {
224
+ const y = W(i + xt(d, r, c, h) + F[v[l]] + k, p[l]) + w | 0;
225
+ i = w, w = h, h = W(c, 10) | 0, c = r, r = y;
226
+ }
227
+ for (let l = 0; l < 16; l++) {
228
+ const y = W(n + xt(E, a, u, g) + F[B[l]] + f, P[l]) + b | 0;
229
+ n = b, b = g, g = W(u, 10) | 0, u = a, a = y;
230
+ }
231
+ }
232
+ this.set(this.h1 + c + g | 0, this.h2 + h + b | 0, this.h3 + w + n | 0, this.h4 + i + a | 0, this.h0 + r + u | 0);
233
+ }
234
+ roundClean() {
235
+ K(F);
236
+ }
237
+ destroy() {
238
+ this.destroyed = !0, K(this.buffer), this.set(0, 0, 0, 0, 0);
239
+ }
240
+ }
241
+ const ze = /* @__PURE__ */ _t(() => new Ye()), je = BigInt(0), M = BigInt(1), Qe = BigInt(2), Ze = BigInt(7), Je = BigInt(256), ts = BigInt(113), Wt = [], Ut = [], Nt = [];
242
+ for (let s = 0, t = M, e = 1, o = 0; s < 24; s++) {
243
+ [e, o] = [o, (2 * e + 3 * o) % 5], Wt.push(2 * (5 * o + e)), Ut.push((s + 1) * (s + 2) / 2 % 64);
244
+ let i = je;
245
+ for (let n = 0; n < 7; n++)
246
+ t = (t << M ^ (t >> Ze) * ts) % Je, t & Qe && (i ^= M << (M << BigInt(n)) - M);
247
+ Nt.push(i);
248
+ }
249
+ const Ft = Ce(Nt, !0), es = Ft[0], ss = Ft[1], kt = (s, t, e) => e > 32 ? Re(s, t, e) : Ie(s, t, e), Et = (s, t, e) => e > 32 ? $e(s, t, e) : He(s, t, e);
250
+ function os(s, t = 24) {
251
+ const e = new Uint32Array(10);
252
+ for (let o = 24 - t; o < 24; o++) {
253
+ for (let r = 0; r < 10; r++)
254
+ e[r] = s[r] ^ s[r + 10] ^ s[r + 20] ^ s[r + 30] ^ s[r + 40];
255
+ for (let r = 0; r < 10; r += 2) {
256
+ const a = (r + 8) % 10, c = (r + 2) % 10, u = e[c], h = e[c + 1], g = kt(u, h, 1) ^ e[a], w = Et(u, h, 1) ^ e[a + 1];
257
+ for (let b = 0; b < 50; b += 10)
258
+ s[r + b] ^= g, s[r + b + 1] ^= w;
259
+ }
260
+ let i = s[2], n = s[3];
261
+ for (let r = 0; r < 24; r++) {
262
+ const a = Ut[r], c = kt(i, n, a), u = Et(i, n, a), h = Wt[r];
263
+ i = s[h], n = s[h + 1], s[h] = c, s[h + 1] = u;
264
+ }
265
+ for (let r = 0; r < 50; r += 10) {
266
+ for (let a = 0; a < 10; a++)
267
+ e[a] = s[r + a];
268
+ for (let a = 0; a < 10; a++)
269
+ s[r + a] ^= ~e[(a + 2) % 10] & e[(a + 4) % 10];
270
+ }
271
+ s[0] ^= es[o], s[1] ^= ss[o];
272
+ }
273
+ K(e);
274
+ }
275
+ class rt {
276
+ // NOTE: we accept arguments in bytes instead of bits here.
277
+ constructor(t, e, o, i = !1, n = 24) {
278
+ x(this, "state");
279
+ x(this, "pos", 0);
280
+ x(this, "posOut", 0);
281
+ x(this, "finished", !1);
282
+ x(this, "state32");
283
+ x(this, "destroyed", !1);
284
+ x(this, "blockLen");
285
+ x(this, "suffix");
286
+ x(this, "outputLen");
287
+ x(this, "enableXOF", !1);
288
+ x(this, "rounds");
289
+ if (this.blockLen = t, this.suffix = e, this.outputLen = o, this.enableXOF = i, this.rounds = n, at(o, "outputLen"), !(0 < t && t < 200))
290
+ throw new Error("only keccak-f1600 function is supported");
291
+ this.state = new Uint8Array(200), this.state32 = zt(this.state);
292
+ }
293
+ clone() {
294
+ return this._cloneInto();
295
+ }
296
+ keccak() {
297
+ ct(this.state32), os(this.state32, this.rounds), ct(this.state32), this.posOut = 0, this.pos = 0;
298
+ }
299
+ update(t) {
300
+ lt(this), ut(t);
301
+ const { blockLen: e, state: o } = this, i = t.length;
302
+ for (let n = 0; n < i; ) {
303
+ const r = Math.min(e - this.pos, i - n);
304
+ for (let a = 0; a < r; a++)
305
+ o[this.pos++] ^= t[n++];
306
+ this.pos === e && this.keccak();
307
+ }
308
+ return this;
309
+ }
310
+ finish() {
311
+ if (this.finished)
312
+ return;
313
+ this.finished = !0;
314
+ const { state: t, suffix: e, pos: o, blockLen: i } = this;
315
+ t[o] ^= e, (e & 128) !== 0 && o === i - 1 && this.keccak(), t[i - 1] ^= 128, this.keccak();
316
+ }
317
+ writeInto(t) {
318
+ lt(this, !1), ut(t), this.finish();
319
+ const e = this.state, { blockLen: o } = this;
320
+ for (let i = 0, n = t.length; i < n; ) {
321
+ this.posOut >= o && this.keccak();
322
+ const r = Math.min(o - this.posOut, n - i);
323
+ t.set(e.subarray(this.posOut, this.posOut + r), i), this.posOut += r, i += r;
324
+ }
325
+ return t;
326
+ }
327
+ xofInto(t) {
328
+ if (!this.enableXOF)
329
+ throw new Error("XOF is not possible for this instance");
330
+ return this.writeInto(t);
331
+ }
332
+ xof(t) {
333
+ return at(t), this.xofInto(new Uint8Array(t));
334
+ }
335
+ digestInto(t) {
336
+ if (jt(t, this), this.finished)
337
+ throw new Error("digest() was already called");
338
+ return this.writeInto(t), this.destroy(), t;
339
+ }
340
+ digest() {
341
+ return this.digestInto(new Uint8Array(this.outputLen));
342
+ }
343
+ destroy() {
344
+ this.destroyed = !0, K(this.state);
345
+ }
346
+ _cloneInto(t) {
347
+ const { blockLen: e, suffix: o, outputLen: i, rounds: n, enableXOF: r } = this;
348
+ return t || (t = new rt(e, o, i, r, n)), t.state32.set(this.state32), t.pos = this.pos, t.posOut = this.posOut, t.finished = this.finished, t.rounds = n, t.suffix = o, t.outputLen = i, t.enableXOF = r, t.destroyed = this.destroyed, t;
349
+ }
350
+ }
351
+ const ns = (s, t, e, o = {}) => _t(() => new rt(t, s, e), o), rs = /* @__PURE__ */ ns(1, 136, 32), Tt = 64, _ = 20, nt = 4, Dt = 2, is = 0, as = 1, D = [64, 64], cs = (s) => Array.from(s).map((t) => t.toString(16).padStart(2, "0")).join("");
352
+ function it(s) {
353
+ return ze(Bt(s));
354
+ }
355
+ function Lt(s) {
356
+ return (1 << s) - 1;
357
+ }
358
+ function ls(s) {
359
+ let t = 1;
360
+ for (; t * t < s + 1; ) t++;
361
+ return Math.max(t, 2);
362
+ }
363
+ function us(s) {
364
+ const t = nt, e = s * Lt(t);
365
+ return { d: t, n: s, checksum_radix: ls(e) };
366
+ }
367
+ function z(s, t) {
368
+ const e = [];
369
+ let o = t;
370
+ for (; o > 0; )
371
+ e.push(o & 255), o >>>= 8;
372
+ const i = new Uint8Array(s.length + e.length);
373
+ i.set(s);
374
+ for (let n = 0; n < e.length; n++)
375
+ i[s.length + n] = e[n];
376
+ return it(i);
377
+ }
378
+ function j(s, t) {
379
+ let e = s;
380
+ for (let o = 0; o < t; o++)
381
+ e = it(e);
382
+ return e;
383
+ }
384
+ function hs(s, t) {
385
+ const e = Lt(t.d), o = t.checksum_radix - 1, i = Math.floor(t.n * e / t.checksum_radix), n = [];
386
+ for (let h = 0; h < t.n; h++) {
387
+ const g = z(s, h + Dt), w = j(g, e);
388
+ n.push(Array.from(w));
389
+ }
390
+ const r = z(
391
+ s,
392
+ is
393
+ ), a = j(
394
+ r,
395
+ o
396
+ ), c = z(
397
+ s,
398
+ as
399
+ ), u = j(
400
+ c,
401
+ i
402
+ );
403
+ return {
404
+ config: t,
405
+ message_terminals: n,
406
+ checksum_major_terminal: Array.from(u),
407
+ checksum_minor_terminal: Array.from(a)
408
+ };
409
+ }
410
+ async function ds(s) {
411
+ try {
412
+ if (s.length !== Tt)
413
+ throw new Error(
414
+ `WOTS seed must be exactly ${Tt} bytes, got ${s.length}`
415
+ );
416
+ const t = [];
417
+ for (let e = 0; e < D.length; e++) {
418
+ const o = D[e], i = us(o), n = new Uint8Array(s.length + 1);
419
+ n.set(s), n[s.length] = e;
420
+ const r = it(n);
421
+ try {
422
+ const a = hs(r, i);
423
+ if (a.config.d !== nt)
424
+ throw new Error(
425
+ `Block ${e}: expected d=${nt}, got d=${a.config.d}`
426
+ );
427
+ if (a.config.n !== o)
428
+ throw new Error(
429
+ `Block ${e}: expected n=${o}, got n=${a.config.n}`
430
+ );
431
+ if (a.message_terminals.length !== o)
432
+ throw new Error(
433
+ `Block ${e}: expected ${o} message terminals, got ${a.message_terminals.length}`
434
+ );
435
+ for (let c = 0; c < a.message_terminals.length; c++)
436
+ if (a.message_terminals[c].length !== _)
437
+ throw new Error(
438
+ `Block ${e} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`
439
+ );
440
+ if (a.checksum_minor_terminal.length !== _)
441
+ throw new Error(
442
+ `Block ${e} checksum_minor: expected ${_} bytes`
443
+ );
444
+ if (a.checksum_major_terminal.length !== _)
445
+ throw new Error(
446
+ `Block ${e} checksum_major: expected ${_} bytes`
447
+ );
448
+ t.push(a);
449
+ } finally {
450
+ n.fill(0), r.fill(0);
451
+ }
452
+ }
453
+ if (t.length !== D.length)
454
+ throw new Error(
455
+ `Expected ${D.length} blocks, got ${t.length}`
456
+ );
457
+ return t;
458
+ } finally {
459
+ s.fill(0);
460
+ }
461
+ }
462
+ function Q(s, t, e) {
463
+ if (s.length !== _)
464
+ throw new Error(
465
+ `Block ${t} ${e}: expected ${_} bytes, got ${s.length}`
466
+ );
467
+ for (let o = 0; o < s.length; o++) {
468
+ const i = s[o];
469
+ if (!Number.isInteger(i) || i < 0 || i > 255)
470
+ throw new Error(
471
+ `Block ${t} ${e}[${o}]: invalid byte value ${i}`
472
+ );
473
+ }
474
+ }
475
+ function fs(s) {
476
+ if (s.length === 0)
477
+ throw new Error("Public keys array must not be empty");
478
+ for (let n = 0; n < s.length; n++) {
479
+ const r = s[n];
480
+ Q(r.checksum_minor_terminal, n, "checksum_minor_terminal"), Q(r.checksum_major_terminal, n, "checksum_major_terminal");
481
+ for (let a = 0; a < r.message_terminals.length; a++)
482
+ Q(r.message_terminals[a], n, `message_terminal[${a}]`);
483
+ }
484
+ let t = 0;
485
+ for (const n of s)
486
+ t += Dt + n.message_terminals.length;
487
+ const e = new Uint8Array(t * _);
488
+ let o = 0;
489
+ for (const n of s) {
490
+ e.set(n.checksum_minor_terminal, o), o += _, e.set(n.checksum_major_terminal, o), o += _;
491
+ for (const r of n.message_terminals)
492
+ e.set(r, o), o += _;
493
+ }
494
+ const i = rs(e);
495
+ return `0x${cs(i)}`;
496
+ }
497
+ async function ps(s, t) {
498
+ const e = [], o = [], i = [], n = [];
499
+ try {
500
+ for (let r = 0; r < t; r++) {
501
+ const a = await Zt(s, r);
502
+ try {
503
+ const u = await ds(a);
504
+ e.push(u), o.push(fs(u));
505
+ } finally {
506
+ a.fill(0);
507
+ }
508
+ const c = await Jt(s, r);
509
+ try {
510
+ const u = st(c);
511
+ i.push(u), n.push(de(C(u)).slice(2));
512
+ } finally {
513
+ c.fill(0);
514
+ }
515
+ }
516
+ } finally {
517
+ s.fill(0);
518
+ }
519
+ return { perVaultWotsKeys: e, wotsPkHashes: o, htlcSecretHexes: i, hashlocks: n };
520
+ }
521
+ const gs = 1, ms = 2, ws = 33, bs = 2, Ps = 3, ys = 1, L = 64, xs = 0, Z = 1, vt = /^[0-9a-f]{64}$/i, ks = /^(?:[0-9a-f]{2})+$/;
522
+ function Es(s) {
523
+ const t = s.slice(2);
524
+ if (!ks.test(t))
525
+ throw new Error(
526
+ "proof of possession witness is not even-length lowercase hex"
527
+ );
528
+ return oe(
529
+ Uint8Array.from(O.from(t, "hex")),
530
+ "proof of possession witness"
531
+ );
532
+ }
533
+ function Ts(s, t, e) {
534
+ var i;
535
+ const o = Es(e);
536
+ if (o.length === gs) {
537
+ const [n] = o;
538
+ let r, a;
539
+ if (n.length === L)
540
+ r = n, a = xs;
541
+ else if (n.length === L + 1 && n[L] === Z)
542
+ r = n.subarray(0, L), a = Z;
543
+ else
544
+ throw new Error(
545
+ "proof of possession witness item must be a 64-byte Schnorr signature (or 65 bytes ending in 0x01)"
546
+ );
547
+ if (!vt.test(t))
548
+ throw new Error(
549
+ `depositor public key must be bare 64-char x-only hex, got "${t}"`
550
+ );
551
+ const c = Uint8Array.from(O.from(t, "hex"));
552
+ if (!xe(s, c, r, a))
553
+ throw new Error(
554
+ "proof of possession signature does not verify against the depositor key"
555
+ );
556
+ return { kind: "p2tr-verified" };
557
+ }
558
+ if (o.length === ms) {
559
+ if (!vt.test(t))
560
+ throw new Error(
561
+ `depositor public key must be bare 64-char x-only hex, got "${t}"`
562
+ );
563
+ const [n, r] = o;
564
+ if (r.length !== ws || r[0] !== bs && r[0] !== Ps)
565
+ throw new Error(
566
+ `proof of possession P2WPKH witness item 1 is not a compressed public key (${r.length} bytes, prefix 0x${((i = r[0]) == null ? void 0 : i.toString(16)) ?? "none"})`
567
+ );
568
+ if (!Be.isPointCompressed(r))
569
+ throw new Error(
570
+ "proof of possession P2WPKH witness pubkey is not a valid secp256k1 point"
571
+ );
572
+ const a = O.from(
573
+ r.subarray(ys)
574
+ ).toString("hex");
575
+ if (a !== t.toLowerCase())
576
+ throw new Error(
577
+ `proof of possession witness pubkey does not match the depositor key: witness carries ${a}, expected ${t}`
578
+ );
579
+ if (n.length < ke || n.length > Ee)
580
+ throw new Error(
581
+ `proof of possession signature is ${n.length} bytes; vault ingestion accepts only 71/72-byte DER signatures with a sighash byte — try a different account or a Taproot address`
582
+ );
583
+ if (n[n.length - 1] !== Z)
584
+ throw new Error(
585
+ `proof of possession P2WPKH signature must end in a SIGHASH_ALL (0x01) byte, got 0x${n[n.length - 1].toString(16)}`
586
+ );
587
+ if (!Te(s, r, n))
588
+ throw new Error(
589
+ "proof of possession signature does not verify against the depositor key"
590
+ );
591
+ return { kind: "p2wpkh-verified" };
592
+ }
593
+ throw new Error(
594
+ `proof of possession witness has ${o.length} items; expected 1 (P2TR) or 2 (P2WPKH)`
595
+ );
596
+ }
597
+ const Kt = 0, J = "00".repeat(32);
598
+ function vs(s, t) {
599
+ const e = {
600
+ bitcoin: "bc",
601
+ testnet: "tb",
602
+ signet: "tb",
603
+ regtest: "bcrt"
604
+ };
605
+ try {
606
+ const o = At.address.fromBech32(s);
607
+ return o.prefix === e[t] && o.version === 0 && o.data.length === 20;
608
+ } catch {
609
+ return !1;
610
+ }
611
+ }
612
+ function Ss(s, t, e, o) {
613
+ const i = e == null ? void 0 : e[`${s}:${t}`];
614
+ return i ? Promise.resolve({
615
+ txid: s,
616
+ vout: t,
617
+ value: i.value,
618
+ scriptPubKey: i.scriptPubKey
619
+ }) : _e(s, t, o);
620
+ }
621
+ const St = 12e4;
622
+ class Zs {
623
+ /**
624
+ * Creates a new PeginManager instance.
625
+ *
626
+ * @param config - Manager configuration including wallets and contract addresses
627
+ */
628
+ constructor(t) {
629
+ x(this, "config");
630
+ this.config = t;
631
+ }
632
+ /**
633
+ * Prepare a peg-in: sizing pass → vault-root derivation (one wallet
634
+ * popup) → per-vault WOTS / hashlock derivation → commit pass with
635
+ * PSBT signing (signPsbt for a single vault, one batch popup for a
636
+ * split). Returns broadcast-ready txs, the pubkey snapshot, and the
637
+ * sensitive derived material.
638
+ *
639
+ * @throws If the wallet rejects, insufficient funds, or an internal
640
+ * invariant violation.
641
+ */
642
+ async preparePegin(t) {
643
+ if (t.amounts.length === 0)
644
+ throw new Error("amounts must contain at least one entry");
645
+ const e = await this.config.btcWallet.getPublicKeyHex(), o = $(e);
646
+ if (U(this.config.btcWallet)) {
647
+ const f = (await fe(this.config.btcWallet)).trim();
648
+ if (t.changeAddress.trim() !== f)
649
+ throw new Error(
650
+ `Pre-PegIn changeAddress "${t.changeAddress}" is not the approval wallet's change address ("${f}"). Refusing to build a tx the signing device would reject.`
651
+ );
652
+ } else if (!mt(
653
+ t.changeAddress,
654
+ e,
655
+ this.config.btcNetwork
656
+ ))
657
+ throw new Error(
658
+ `Pre-PegIn changeAddress "${t.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`
659
+ );
660
+ const i = await this.prepareSizing(o, t), n = i.selectedUTXOs.map(
661
+ (f) => ({
662
+ txid: et(f.txid),
663
+ vout: f.vout
664
+ })
665
+ ), r = await It(this.config.btcWallet, {
666
+ depositorBtcPubkey: et(o),
667
+ fundingOutpoints: n
668
+ });
669
+ let a, c;
670
+ try {
671
+ const f = await te(r);
672
+ try {
673
+ a = st(f), c = st(Bt(f));
674
+ } finally {
675
+ f.fill(0);
676
+ }
677
+ } catch (f) {
678
+ throw r.fill(0), f;
679
+ }
680
+ const u = await ps(r, t.amounts.length), { perVaultWotsKeys: h, wotsPkHashes: g, htlcSecretHexes: w, hashlocks: b } = u, d = await this.preparePeginCommit({
681
+ depositorBtcPubkeyRaw: e,
682
+ depositorBtcPubkey: o,
683
+ hashlocks: b,
684
+ authAnchorHash: c,
685
+ sizing: i,
686
+ params: t
687
+ });
688
+ for (let f = 0; f < d.perVault.length; f++)
689
+ if (d.perVault[f].htlcVout !== f)
690
+ throw new Error(
691
+ `Internal invariant violation: htlcVout/index mismatch at vault ${f} (expected ${f}, got ${d.perVault[f].htlcVout})`
692
+ );
693
+ pe(
694
+ d.fundedPrePeginTxHex,
695
+ t.amounts.length,
696
+ c
697
+ );
698
+ const { depositTerms: E, ...k } = d;
699
+ return {
700
+ transaction: {
701
+ ...k,
702
+ selectedUTXOs: i.selectedUTXOs,
703
+ fee: i.fee,
704
+ changeAmount: i.changeAmount
705
+ },
706
+ depositorBtcPubkey: o,
707
+ derivedSecrets: {
708
+ perVaultWotsKeys: h,
709
+ wotsPkHashes: g,
710
+ htlcSecretHexes: w,
711
+ authAnchorHex: a
712
+ },
713
+ depositTerms: E
714
+ };
715
+ }
716
+ /**
717
+ * Build unfunded Pre-PegIn + select UTXOs. No PSBT signing.
718
+ *
719
+ * Returns the full selection result (UTXOs, fee, changeAmount) so the
720
+ * commit pass funds the broadcast tx with the exact same set used to
721
+ * build the vault-context funding-outpoints commitment. Re-running
722
+ * `selectUtxosForPegin` in the commit pass would be deterministic given
723
+ * the same inputs, but threading the result through guarantees the
724
+ * domain separator structurally matches the funded tx inputs.
725
+ *
726
+ * Sizing runs before the wallet popup, so neither the real per-vault
727
+ * hashlocks nor the real `authAnchorHash` are known yet. Both slots
728
+ * are filled with a 32-byte placeholder; the commit pass swaps in the
729
+ * real values. Output budget is identical (32-byte push regardless of
730
+ * content), so UTXO selection is invariant under substitution.
731
+ */
732
+ async prepareSizing(t, e) {
733
+ const o = e.amounts.map(
734
+ () => J
735
+ ), i = e.vaultKeeperBtcPubkeys.length, n = await pt({
736
+ vaultCoreVersion: e.vaultCoreVersion,
737
+ depositorPubkey: t,
738
+ vaultProviderPubkey: S(e.vaultProviderBtcPubkey),
739
+ vaultKeeperPubkeys: e.vaultKeeperBtcPubkeys.map(S),
740
+ universalChallengerPubkeys: e.universalChallengerBtcPubkeys.map(S),
741
+ hashlocks: o,
742
+ timelockRefund: e.timelockRefund,
743
+ pegInAmounts: e.amounts,
744
+ feeRate: e.protocolFeeRate,
745
+ minPeginFeeRate: e.minPeginFeeRate,
746
+ numLocalChallengers: i,
747
+ councilQuorum: e.councilQuorum,
748
+ councilSize: e.councilSize,
749
+ network: this.config.btcNetwork,
750
+ authAnchorHash: J
751
+ }), r = me(
752
+ [...e.availableUTXOs],
753
+ n.totalOutputValue,
754
+ e.mempoolFeeRate,
755
+ be(n.htlcValues.length, !0)
756
+ );
757
+ return {
758
+ selectedUTXOs: r.selectedUTXOs,
759
+ fee: r.fee,
760
+ changeAmount: r.changeAmount
761
+ };
762
+ }
763
+ /** Build PegIn txs and batch-sign their inputs with real hashlocks. */
764
+ async preparePeginCommit(t) {
765
+ const {
766
+ depositorBtcPubkeyRaw: e,
767
+ depositorBtcPubkey: o,
768
+ hashlocks: i,
769
+ authAnchorHash: n,
770
+ sizing: r,
771
+ params: a
772
+ } = t, c = J.toLowerCase();
773
+ for (let m = 0; m < i.length; m++)
774
+ if (i[m].toLowerCase() === c)
775
+ throw new Error(
776
+ `preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${m} — internal substitution bug`
777
+ );
778
+ if (n.toLowerCase() === c)
779
+ throw new Error(
780
+ "preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug"
781
+ );
782
+ const u = S(
783
+ a.vaultProviderBtcPubkey
784
+ ), h = a.vaultKeeperBtcPubkeys.map(S), g = a.universalChallengerBtcPubkeys.map(S), w = h.length, b = {
785
+ vaultCoreVersion: a.vaultCoreVersion,
786
+ depositorPubkey: o,
787
+ vaultProviderPubkey: u,
788
+ vaultKeeperPubkeys: h,
789
+ universalChallengerPubkeys: g,
790
+ hashlocks: i,
791
+ timelockRefund: a.timelockRefund,
792
+ pegInAmounts: a.amounts,
793
+ feeRate: a.protocolFeeRate,
794
+ minPeginFeeRate: a.minPeginFeeRate,
795
+ numLocalChallengers: w,
796
+ councilQuorum: a.councilQuorum,
797
+ councilSize: a.councilSize,
798
+ network: this.config.btcNetwork,
799
+ authAnchorHash: n
800
+ }, d = await pt(b), E = wt(this.config.btcNetwork), k = Pe({
801
+ unfundedTxHex: d.psbtHex,
802
+ selectedUTXOs: r.selectedUTXOs,
803
+ changeAddress: a.changeAddress,
804
+ changeAmount: r.changeAmount,
805
+ network: E
806
+ }), f = r.selectedUTXOs.reduce((m, T) => m + BigInt(T.value), 0n) - d.totalOutputValue - r.changeAmount;
807
+ if (f !== r.fee)
808
+ throw new Error(
809
+ `Pre-PegIn funded fee ${f} does not match the sizing-pass fee ${r.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`
810
+ );
811
+ const v = S(
812
+ q(k)
813
+ ), B = [], p = [], P = [];
814
+ for (let m = 0; m < i.length; m++) {
815
+ const T = await ee({
816
+ prePeginParams: b,
817
+ timelockPegin: a.timelockPegin,
818
+ fundedPrePeginTxHex: k,
819
+ htlcVout: m
820
+ }), I = await ne({
821
+ vaultCoreVersion: a.vaultCoreVersion,
822
+ peginTxHex: T.txHex,
823
+ fundedPrePeginTxHex: k,
824
+ depositorPubkey: o,
825
+ vaultProviderPubkey: u,
826
+ vaultKeeperPubkeys: h,
827
+ universalChallengerPubkeys: g,
828
+ hashlock: i[m],
829
+ timelockRefund: a.timelockRefund,
830
+ network: this.config.btcNetwork
831
+ });
832
+ B.push(T), p.push(I.psbtHex), P.push(
833
+ ue(e, 1)
834
+ );
835
+ }
836
+ const l = Ve({
837
+ vaultCoreVersion: a.vaultCoreVersion,
838
+ protocolFeeRate: a.protocolFeeRate,
839
+ timelockPegin: a.timelockPegin,
840
+ timelockAssert: a.timelockAssert,
841
+ timelockRefund: a.timelockRefund,
842
+ prepeginTxid: v,
843
+ prepeginMaxFee: r.fee,
844
+ vaultProviderBtcPubkey: u,
845
+ vaultKeeperBtcPubkeys: h,
846
+ universalChallengerBtcPubkeys: g,
847
+ maxAcceptableCommissionBps: Y(
848
+ a.commissionBps
849
+ ),
850
+ peginAmounts: a.amounts,
851
+ depositorClaimValue: d.depositorClaimValue,
852
+ peginMaxFee: d.minPeginFee
853
+ });
854
+ U(this.config.btcWallet) && await this.config.btcWallet.approveDepositTerms(l);
855
+ const y = await ge(
856
+ this.config.btcWallet,
857
+ p,
858
+ P
859
+ ), A = [];
860
+ for (let m = 0; m < y.length; m++) {
861
+ gt({
862
+ requestedPsbtHex: p[m],
863
+ returnedPsbtHex: y[m]
864
+ });
865
+ const T = re(
866
+ y[m],
867
+ o
868
+ );
869
+ se({
870
+ requestedPsbtHex: p[m],
871
+ signatureHex: T,
872
+ signerXOnlyPubkeyHex: o,
873
+ inputIndex: 0
874
+ });
875
+ const I = ie(y[m]);
876
+ A.push({
877
+ htlcVout: m,
878
+ htlcValue: d.htlcValues[m],
879
+ peginTxHex: I,
880
+ peginTxid: B[m].txid,
881
+ peginInputSignature: T,
882
+ vaultScriptPubKey: B[m].vaultScriptPubKey
883
+ });
884
+ }
885
+ return {
886
+ fundedPrePeginTxHex: k,
887
+ prePeginTxid: v,
888
+ perVault: A,
889
+ depositTerms: l
890
+ };
891
+ }
892
+ /**
893
+ * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
894
+ *
895
+ * This method:
896
+ * 1. Parses the funded transaction hex
897
+ * 2. Fetches UTXO data from mempool for each input
898
+ * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
899
+ * 4. Signs via btcWallet.signPsbt()
900
+ * 5. Finalizes and extracts the transaction
901
+ * 6. Broadcasts via mempool API
902
+ *
903
+ * IMPORTANT — this method does NOT gate on Ethereum finality. Committing
904
+ * BTC to the HTLC while the peg-in registration is still reorg-exposed can
905
+ * strand the deposit: the vault record disappears from the chain while the
906
+ * BTC stays locked until the HTLC refund timelock. Callers must await
907
+ * `waitForPeginRegistrationDepth` for the registered vault(s) before calling
908
+ * this. The gate is not applied here because the params carry no vault ID —
909
+ * adding one would be a breaking signature change.
910
+ *
911
+ * @param params - Transaction hex and depositor public key
912
+ * @returns The broadcasted Bitcoin transaction ID
913
+ * @throws Error if signing or broadcasting fails
914
+ */
915
+ async signAndBroadcast(t) {
916
+ const { fundedPrePeginTxHex: e, depositorBtcPubkey: o } = t, i = e.startsWith("0x") ? e.slice(2) : e, n = Ct.fromHex(i);
917
+ if (n.ins.length === 0)
918
+ throw new Error("Transaction has no inputs");
919
+ const r = new ht();
920
+ r.setVersion(n.version), r.setLocktime(n.locktime);
921
+ const a = O.from(
922
+ $(o),
923
+ "hex"
924
+ ), c = this.config.mempoolApiUrl, u = n.ins.map((p) => {
925
+ const P = O.from(p.hash).reverse().toString("hex"), l = p.index;
926
+ return Ss(P, l, t.localPrevouts, c).then(
927
+ (y) => ({ input: p, utxoData: y, txid: P, vout: l })
928
+ );
929
+ }), h = await Promise.all(u), g = h.reduce(
930
+ (p, P) => p + BigInt(P.utxoData.value),
931
+ 0n
932
+ ), w = n.outs.reduce(
933
+ (p, P) => p + BigInt(P.value),
934
+ 0n
935
+ );
936
+ if (g < w)
937
+ throw new Error(
938
+ `UTXO value mismatch: total input value (${g} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`
939
+ );
940
+ const b = g - w;
941
+ if (b > bt)
942
+ throw new Error(
943
+ `Implied transaction fee (${b} sat) exceeds maximum reasonable fee (${bt} sat). This may indicate manipulated UTXO data.`
944
+ );
945
+ for (const { input: p, utxoData: P, txid: l, vout: y } of h) {
946
+ const A = we(
947
+ {
948
+ value: P.value,
949
+ scriptPubKey: P.scriptPubKey
950
+ },
951
+ a
952
+ );
953
+ r.addInput({
954
+ hash: p.hash,
955
+ index: p.index,
956
+ sequence: p.sequence,
957
+ ...A
958
+ });
959
+ }
960
+ for (const p of n.outs)
961
+ r.addOutput({
962
+ script: p.script,
963
+ value: p.value
964
+ });
965
+ await Fe({
966
+ wallet: this.config.btcWallet,
967
+ depositTerms: t.depositTerms,
968
+ fundedPrePeginTxHex: e,
969
+ depositorBtcPubkey: o
970
+ });
971
+ const d = r.toHex(), E = await this.config.btcWallet.signPsbt(d);
972
+ gt({
973
+ requestedPsbtHex: d,
974
+ returnedPsbtHex: E
975
+ });
976
+ const k = ae({
977
+ requestedPsbtHex: d,
978
+ returnedPsbtHex: E
979
+ });
980
+ if (U(this.config.btcWallet) && k !== r.data.inputs.length)
981
+ throw new Error(
982
+ `Key-path verification covered ${k} of ${r.data.inputs.length} Pre-PegIn inputs; an approval wallet signs every input key-path, so the unverified ones must not be broadcast.`
983
+ );
984
+ const f = ht.fromHex(E);
985
+ try {
986
+ f.finalizeAllInputs();
987
+ } catch (p) {
988
+ if (!f.data.inputs.every(
989
+ (l) => l.finalScriptWitness || l.finalScriptSig
990
+ ))
991
+ throw new Error(
992
+ `PSBT finalization failed and wallet did not auto-finalize: ${p}`
993
+ );
994
+ }
995
+ const v = f.extractTransaction().toHex();
996
+ return await ve(v, c);
997
+ }
998
+ /**
999
+ * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.
1000
+ *
1001
+ * This method:
1002
+ * 1. Re-verifies the PopSignature against the currently connected ETH
1003
+ * and BTC wallets — refuses to proceed if either has changed
1004
+ * 2. Derives vault ID and checks if it already exists (pre-flight)
1005
+ * 3. Encodes the contract call using viem
1006
+ * 4. Estimates gas (catches contract errors early with proper revert
1007
+ * reasons)
1008
+ * 5. Sends transaction with pre-estimated gas via
1009
+ * ethWallet.sendTransaction()
1010
+ *
1011
+ * The PopSignature must be obtained via
1012
+ * {@link signProofOfPossession} before this call.
1013
+ *
1014
+ * @param params - Registration parameters including the PopSignature
1015
+ * and the prepared Pre-PegIn / PegIn transactions
1016
+ * @returns Result containing Ethereum transaction hash and vault ID
1017
+ * @throws Error if the PopSignature does not match the connected wallets
1018
+ * @throws Error if the vault already exists
1019
+ * @throws Error if contract simulation fails (e.g., invalid signature,
1020
+ * unauthorized)
1021
+ */
1022
+ async registerPeginOnChain(t) {
1023
+ const {
1024
+ unsignedPrePeginTx: e,
1025
+ depositorSignedPeginTx: o,
1026
+ vaultProvider: i,
1027
+ hashlock: n,
1028
+ htlcVout: r,
1029
+ depositorPayoutBtcAddress: a,
1030
+ depositorWotsPkHash: c,
1031
+ popSignature: u
1032
+ } = t;
1033
+ if (!this.config.ethWallet.account)
1034
+ throw new Error("Ethereum wallet account not found");
1035
+ const h = this.config.ethWallet.account.address;
1036
+ if (!dt(u.depositorEthAddress, h))
1037
+ throw new Error(
1038
+ `Proof of possession was signed for ${u.depositorEthAddress} but the Ethereum wallet is currently connected to ${h}. Reconnect the original account or call signProofOfPossession() again.`
1039
+ );
1040
+ const g = await this.assertPopMatchesBtcWallet(u), w = u.btcPopSignature, b = C(
1041
+ u.depositorBtcPubkey
1042
+ ), d = C(e), E = C(o), k = a ?? await this.config.btcWallet.getAddress(), f = this.resolvePayoutScriptPubKey(
1043
+ g,
1044
+ k
1045
+ ), v = q(E), B = await ft(
1046
+ S(v),
1047
+ S(h)
1048
+ ), p = C(B);
1049
+ if (await this.checkVaultExists(p))
1050
+ throw new Error(
1051
+ `Vault already exists (ID: ${p}, peginTxHash: ${v}). 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.`
1052
+ );
1053
+ const l = this.config.publicClient;
1054
+ let y;
1055
+ try {
1056
+ y = await l.readContract({
1057
+ address: this.config.vaultContracts.btcVaultRegistry,
1058
+ abi: H,
1059
+ functionName: "getPegInFee",
1060
+ args: [i]
1061
+ });
1062
+ } catch (V) {
1063
+ throw new Error(
1064
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
1065
+ { cause: V }
1066
+ );
1067
+ }
1068
+ const A = await this.resolveMaxAcceptableCommissionBps(
1069
+ i,
1070
+ t.quotedCommissionBps
1071
+ ), m = tt({
1072
+ abi: H,
1073
+ functionName: "submitPeginRequest",
1074
+ args: [
1075
+ h,
1076
+ b,
1077
+ w,
1078
+ d,
1079
+ E,
1080
+ i,
1081
+ A,
1082
+ n,
1083
+ r,
1084
+ f,
1085
+ c
1086
+ ]
1087
+ });
1088
+ let T;
1089
+ try {
1090
+ T = await l.estimateGas({
1091
+ to: this.config.vaultContracts.btcVaultRegistry,
1092
+ data: m,
1093
+ value: y,
1094
+ account: this.config.ethWallet.account.address
1095
+ });
1096
+ } catch (V) {
1097
+ R(V);
1098
+ }
1099
+ let I;
1100
+ try {
1101
+ I = await this.config.ethWallet.sendTransaction({
1102
+ to: this.config.vaultContracts.btcVaultRegistry,
1103
+ data: m,
1104
+ value: y,
1105
+ account: this.config.ethWallet.account,
1106
+ chain: this.config.ethChain,
1107
+ gas: T
1108
+ });
1109
+ } catch (V) {
1110
+ R(V);
1111
+ }
1112
+ const G = await Pt({
1113
+ publicClient: l,
1114
+ walletAddress: this.config.ethWallet.account.address,
1115
+ hash: I,
1116
+ timeout: St
1117
+ });
1118
+ return G.status === "reverted" && R(
1119
+ new Error(
1120
+ `Transaction reverted. Hash: ${G.transactionHash}. Check the transaction on block explorer for details.`
1121
+ )
1122
+ ), {
1123
+ ethTxHash: G.transactionHash,
1124
+ vaultId: p,
1125
+ peginTxHash: v
1126
+ };
1127
+ }
1128
+ /**
1129
+ * Register multiple pegins on Ethereum in a single transaction.
1130
+ *
1131
+ * Uses the contract's submitPeginRequestBatch() to submit all vault
1132
+ * registrations atomically. All vaults must share the same vault provider.
1133
+ * The PoP signature is signed once and included in each request.
1134
+ *
1135
+ * @param params - Batch registration parameters
1136
+ * @returns Batch result with per-vault IDs and single ETH tx hash
1137
+ */
1138
+ async registerPeginBatchOnChain(t) {
1139
+ const { vaultProvider: e, unsignedPrePeginTx: o, requests: i, popSignature: n } = t;
1140
+ if (i.length === 0)
1141
+ throw new Error("Batch pegin requires at least one request");
1142
+ if (!this.config.ethWallet.account)
1143
+ throw new Error("Ethereum wallet account not found");
1144
+ const r = this.config.ethWallet.account.address;
1145
+ if (!dt(n.depositorEthAddress, r))
1146
+ throw new Error(
1147
+ `Proof of possession was signed for ${n.depositorEthAddress} but the Ethereum wallet is currently connected to ${r}. Reconnect the original account or call signProofOfPossession() again.`
1148
+ );
1149
+ const a = await this.assertPopMatchesBtcWallet(n), c = n.btcPopSignature, u = i.map(
1150
+ (l) => this.resolvePayoutScriptPubKey(
1151
+ a,
1152
+ l.depositorPayoutBtcAddress
1153
+ )
1154
+ ), h = [];
1155
+ for (const l of i) {
1156
+ const y = C(
1157
+ l.depositorSignedPeginTx
1158
+ ), A = q(y), m = await ft(
1159
+ S(A),
1160
+ S(r)
1161
+ ), T = C(m);
1162
+ if (await this.checkVaultExists(T))
1163
+ throw new Error(
1164
+ `Vault already exists (ID: ${T}, peginTxHash: ${A}). To create a new vault, use different UTXOs or a different amount.`
1165
+ );
1166
+ h.push({ vaultId: T, peginTxHash: A });
1167
+ }
1168
+ const g = this.config.publicClient;
1169
+ let w;
1170
+ try {
1171
+ w = await g.readContract({
1172
+ address: this.config.vaultContracts.btcVaultRegistry,
1173
+ abi: H,
1174
+ functionName: "getPegInFee",
1175
+ args: [e]
1176
+ });
1177
+ } catch (l) {
1178
+ throw new Error(
1179
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",
1180
+ { cause: l }
1181
+ );
1182
+ }
1183
+ const b = w * BigInt(i.length), d = await this.resolveMaxAcceptableCommissionBps(
1184
+ e,
1185
+ t.quotedCommissionBps
1186
+ ), E = C(
1187
+ n.depositorBtcPubkey
1188
+ ), k = C(o), f = i.map((l, y) => ({
1189
+ depositorBtcPubKey: E,
1190
+ btcPopSignature: c,
1191
+ unsignedPrePeginTx: k,
1192
+ depositorSignedPeginTx: C(
1193
+ l.depositorSignedPeginTx
1194
+ ),
1195
+ hashlock: l.hashlock,
1196
+ htlcVout: l.htlcVout,
1197
+ referralCode: Kt,
1198
+ depositorPayoutBtcAddress: u[y],
1199
+ depositorWotsPkHash: l.depositorWotsPkHash
1200
+ })), v = tt({
1201
+ abi: H,
1202
+ functionName: "submitPeginRequestBatch",
1203
+ args: [
1204
+ r,
1205
+ e,
1206
+ d,
1207
+ f
1208
+ ]
1209
+ });
1210
+ let B;
1211
+ try {
1212
+ B = await g.estimateGas({
1213
+ to: this.config.vaultContracts.btcVaultRegistry,
1214
+ data: v,
1215
+ value: b,
1216
+ account: this.config.ethWallet.account.address
1217
+ });
1218
+ } catch (l) {
1219
+ R(l);
1220
+ }
1221
+ let p;
1222
+ try {
1223
+ p = await this.config.ethWallet.sendTransaction({
1224
+ to: this.config.vaultContracts.btcVaultRegistry,
1225
+ data: v,
1226
+ value: b,
1227
+ account: this.config.ethWallet.account,
1228
+ chain: this.config.ethChain,
1229
+ gas: B
1230
+ });
1231
+ } catch (l) {
1232
+ R(l);
1233
+ }
1234
+ const P = await Pt({
1235
+ publicClient: g,
1236
+ walletAddress: this.config.ethWallet.account.address,
1237
+ hash: p,
1238
+ timeout: St
1239
+ });
1240
+ return P.status === "reverted" && R(
1241
+ new Error(
1242
+ `Batch transaction reverted. Hash: ${P.transactionHash}. Check the transaction on block explorer for details.`
1243
+ )
1244
+ ), {
1245
+ ethTxHash: P.transactionHash,
1246
+ vaults: h
1247
+ };
1248
+ }
1249
+ // Anchor to quoted+headroom when supplied (refuse if chain drifted past it);
1250
+ // otherwise fall back to chain-current+headroom — see #1691.
1251
+ async resolveMaxAcceptableCommissionBps(t, e) {
1252
+ if (e === void 0 && U(this.config.btcWallet))
1253
+ throw new Error(
1254
+ "quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote."
1255
+ );
1256
+ let o;
1257
+ try {
1258
+ o = await new Se(
1259
+ this.config.publicClient,
1260
+ this.config.vaultContracts.btcVaultRegistry
1261
+ ).getVaultProviderCommission(t);
1262
+ } catch (i) {
1263
+ throw new Error(
1264
+ "Failed to query vault provider commission from the contract. Please check your network connection and that the contract address is correct.",
1265
+ { cause: i }
1266
+ );
1267
+ }
1268
+ if (e !== void 0) {
1269
+ if (o > e + ot)
1270
+ throw new Error(
1271
+ `Vault provider commission changed since quote: quoted ${e} bps, chain currently reports ${o} bps (allowed drift ${ot} bps). Please refresh to see the new commission and try again.`
1272
+ );
1273
+ return Y(e);
1274
+ }
1275
+ return Y(o);
1276
+ }
1277
+ /**
1278
+ * Check if a vault already exists for a given vault ID.
1279
+ *
1280
+ * The contract returns a default struct (with `depositor === zeroAddress`)
1281
+ * when no vault is registered, so existence is signalled in the response,
1282
+ * not via a thrown error. RPC/network failures are propagated rather than
1283
+ * silently treated as "vault doesn't exist", which would otherwise let
1284
+ * downstream calls run with stale assumptions.
1285
+ *
1286
+ * @param vaultId - The Bitcoin transaction hash (vault ID)
1287
+ * @returns True if vault exists, false otherwise
1288
+ * @throws If the underlying RPC read fails
1289
+ */
1290
+ async checkVaultExists(t) {
1291
+ return (await this.config.publicClient.readContract({
1292
+ address: this.config.vaultContracts.btcVaultRegistry,
1293
+ abi: H,
1294
+ functionName: "getBtcVaultBasicInfo",
1295
+ args: [t]
1296
+ })).depositor !== Qt;
1297
+ }
1298
+ /**
1299
+ * Resolve the BTC scriptPubKey to register as the depositor's payout sink.
1300
+ *
1301
+ * `address` is validated against the verified depositor pubkey, sourced
1302
+ * from `assertPopMatchesBtcWallet`'s return value rather than
1303
+ * `popSignature.depositorBtcPubkey` (which is x-only, parity stripped).
1304
+ * For wallets that expose a compressed key this preserves y-parity end to
1305
+ * end. For Taproot wallets that only expose an x-only key, the helper
1306
+ * itself fails closed for P2WPKH — the parity is unknowable, so the
1307
+ * payout sink must be a P2TR address derived from that same x.
1308
+ *
1309
+ * The helper does not call into the wallet so the batch path can resolve
1310
+ * many requests without any extra adapter reads. Threat closed: a
1311
+ * state-race or stale FE state that lets a non-wallet address reach the
1312
+ * on-chain payout-script registration.
1313
+ */
1314
+ resolvePayoutScriptPubKey(t, e) {
1315
+ if (!mt(
1316
+ e,
1317
+ t,
1318
+ this.config.btcNetwork
1319
+ ))
1320
+ throw S(t).length === le && vs(e, this.config.btcNetwork) ? new Error(
1321
+ `BTC payout address "${e}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`
1322
+ ) : new Error(
1323
+ `BTC payout address "${e}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`
1324
+ );
1325
+ const o = wt(this.config.btcNetwork);
1326
+ try {
1327
+ return `0x${At.address.toOutputScript(e, o).toString("hex")}`;
1328
+ } catch {
1329
+ throw new Error(
1330
+ `Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
1331
+ );
1332
+ }
1333
+ }
1334
+ /**
1335
+ * Sign a BIP-322 BTC Proof-of-Possession binding the connected BTC
1336
+ * wallet to the connected ETH account for this chain and vault
1337
+ * registry. The returned {@link PopSignature} can be reused across
1338
+ * every register call in the same session.
1339
+ *
1340
+ * The witness is verified against the depositor key before it is
1341
+ * returned — Schnorr for one-item (P2TR), ECDSA over the BIP-322
1342
+ * P2WPKH virtual transaction for two-item — see {@link verifyPopWitness}.
1343
+ *
1344
+ * @throws If the wallet returns a malformed witness or a signature that
1345
+ * does not verify.
1346
+ */
1347
+ async signProofOfPossession() {
1348
+ if (!this.config.ethWallet.account)
1349
+ throw new Error("Ethereum wallet account not found");
1350
+ const t = this.config.ethWallet.account.address, e = $(
1351
+ await this.config.btcWallet.getPublicKeyHex()
1352
+ ), o = this.config.vaultContracts.btcVaultRegistry, i = `${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${o.toLowerCase()}`, n = await this.config.btcWallet.signMessage(
1353
+ i,
1354
+ "bip322-simple"
1355
+ ), r = Ne(n);
1356
+ return Ts(
1357
+ new TextEncoder().encode(i),
1358
+ e,
1359
+ r
1360
+ ), { btcPopSignature: r, depositorEthAddress: t, depositorBtcPubkey: e };
1361
+ }
1362
+ /**
1363
+ * Confirm the connected BTC wallet still matches the PoP it produced, and
1364
+ * return the wallet's *raw* pubkey hex (parity-preserving form, as the
1365
+ * wallet adapter returns it). The raw form is required by callers that
1366
+ * validate Native SegWit / P2WPKH addresses, since P2WPKH is derived from
1367
+ * a parity-bearing compressed key — an x-only form would let an attacker
1368
+ * substitute the opposite-parity P2WPKH address.
1369
+ */
1370
+ async assertPopMatchesBtcWallet(t) {
1371
+ const e = await this.config.btcWallet.getPublicKeyHex(), o = $(e), i = $(t.depositorBtcPubkey);
1372
+ if (o !== i)
1373
+ throw new Error(
1374
+ `Proof of possession was signed with BTC pubkey ${i} but the BTC wallet is currently connected to ${o}. Reconnect the original wallet or call signProofOfPossession() again.`
1375
+ );
1376
+ return e;
1377
+ }
1378
+ /**
1379
+ * Gets the configured Bitcoin network.
1380
+ *
1381
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1382
+ */
1383
+ getNetwork() {
1384
+ return this.config.btcNetwork;
1385
+ }
1386
+ /**
1387
+ * Gets the configured BTCVaultRegistry contract address.
1388
+ *
1389
+ * @returns The Ethereum address of the BTCVaultRegistry contract
1390
+ */
1391
+ getVaultContractAddress() {
1392
+ return this.config.vaultContracts.btcVaultRegistry;
1393
+ }
1394
+ }
1395
+ const _s = 80, Bs = 250, As = 300, Cs = 22, Xt = "ab";
1396
+ function Is(s, t) {
1397
+ const e = Xt.repeat(As), o = S(s).toLowerCase(), i = t.toString(16).padStart(8, "0"), n = `${o}${i}`, r = e.slice(n.length);
1398
+ return `0x${n}${r}`;
1399
+ }
1400
+ function Hs(s, t) {
1401
+ const e = (o) => `0x${Xt.repeat(o)}`;
1402
+ return {
1403
+ depositorBtcPubKey: e(32),
1404
+ btcPopSignature: e(_s),
1405
+ unsignedPrePeginTx: e(Bs),
1406
+ depositorSignedPeginTx: Is(
1407
+ s,
1408
+ t
1409
+ ),
1410
+ hashlock: e(32),
1411
+ htlcVout: t,
1412
+ referralCode: Kt,
1413
+ depositorPayoutBtcAddress: e(Cs),
1414
+ depositorWotsPkHash: e(32)
1415
+ };
1416
+ }
1417
+ async function Js(s) {
1418
+ const {
1419
+ publicClient: t,
1420
+ btcVaultRegistry: e,
1421
+ depositorEthAddress: o,
1422
+ vaultProvider: i,
1423
+ batchSize: n
1424
+ } = s;
1425
+ if (n <= 0)
1426
+ throw new Error(
1427
+ `estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${n})`
1428
+ );
1429
+ const a = await t.readContract({
1430
+ address: e,
1431
+ abi: H,
1432
+ functionName: "getPegInFee",
1433
+ args: [i]
1434
+ }) * BigInt(n), c = Array.from(
1435
+ { length: n },
1436
+ (h, g) => Hs(o, g)
1437
+ ), u = tt({
1438
+ abi: H,
1439
+ functionName: "submitPeginRequestBatch",
1440
+ args: [
1441
+ o,
1442
+ i,
1443
+ Ht,
1444
+ c
1445
+ ]
1446
+ });
1447
+ return t.estimateGas({
1448
+ to: e,
1449
+ data: u,
1450
+ value: a,
1451
+ account: o
1452
+ });
1453
+ }
1454
+ export {
1455
+ ot as C,
1456
+ Ht as M,
1457
+ Zs as P,
1458
+ Y as a,
1459
+ Ve as b,
1460
+ fs as c,
1461
+ ds as d,
1462
+ Js as e,
1463
+ Fe as f,
1464
+ ps as g
1465
+ };
1466
+ //# sourceMappingURL=PeginManager-Bsv6caG3.js.map