@babylonlabs-io/ts-sdk 0.72.1 → 0.74.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 (165) hide show
  1. package/README.md +56 -13
  2. package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs +2 -0
  3. package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs.map +1 -0
  4. package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js +229 -0
  5. package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js.map +1 -0
  6. package/dist/PeginManager-C9RPOd0L.js +1216 -0
  7. package/dist/PeginManager-C9RPOd0L.js.map +1 -0
  8. package/dist/PeginManager-E-UHA1un.cjs +2 -0
  9. package/dist/PeginManager-E-UHA1un.cjs.map +1 -0
  10. package/dist/bip322Verify-B7_gIhRk.cjs +2 -0
  11. package/dist/bip322Verify-B7_gIhRk.cjs.map +1 -0
  12. package/dist/bip322Verify-D6sBBUHE.js +79 -0
  13. package/dist/bip322Verify-D6sBBUHE.js.map +1 -0
  14. package/dist/{buildAndBroadcastReclaim-QIN8Mcwq.js → buildAndBroadcastReclaim-BXclIcu_.js} +3 -3
  15. package/dist/{buildAndBroadcastReclaim-QIN8Mcwq.js.map → buildAndBroadcastReclaim-BXclIcu_.js.map} +1 -1
  16. package/dist/{buildAndBroadcastReclaim-HX2xQlbM.cjs → buildAndBroadcastReclaim-U-PyFfDg.cjs} +2 -2
  17. package/dist/{buildAndBroadcastReclaim-HX2xQlbM.cjs.map → buildAndBroadcastReclaim-U-PyFfDg.cjs.map} +1 -1
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.js +237 -228
  20. package/dist/index.js.map +1 -1
  21. package/dist/onChainBtcPubkey-BbxRrbvg.cjs +2 -0
  22. package/dist/onChainBtcPubkey-BbxRrbvg.cjs.map +1 -0
  23. package/dist/onChainBtcPubkey-C-6UWpD8.js +34 -0
  24. package/dist/onChainBtcPubkey-C-6UWpD8.js.map +1 -0
  25. package/dist/{parseFundingOutpoints-BkgGihaY.cjs → parseFundingOutpoints-B4iQeX6q.cjs} +2 -2
  26. package/dist/{parseFundingOutpoints-BkgGihaY.cjs.map → parseFundingOutpoints-B4iQeX6q.cjs.map} +1 -1
  27. package/dist/{parseFundingOutpoints-DlINgQ3X.js → parseFundingOutpoints-B67CoXpF.js} +2 -2
  28. package/dist/{parseFundingOutpoints-DlINgQ3X.js.map → parseFundingOutpoints-B67CoXpF.js.map} +1 -1
  29. package/dist/pegin-registration-client-6vLk2itL.cjs +2 -0
  30. package/dist/pegin-registration-client-6vLk2itL.cjs.map +1 -0
  31. package/dist/pegin-registration-client-BdRiR8br.js +2635 -0
  32. package/dist/pegin-registration-client-BdRiR8br.js.map +1 -0
  33. package/dist/primeVpAuth-DBHohVKM.cjs +2 -0
  34. package/dist/primeVpAuth-DBHohVKM.cjs.map +1 -0
  35. package/dist/primeVpAuth-DvaD45q_.js +745 -0
  36. package/dist/primeVpAuth-DvaD45q_.js.map +1 -0
  37. package/dist/psbtInputFields-B3e05Xe6.js +171 -0
  38. package/dist/psbtInputFields-B3e05Xe6.js.map +1 -0
  39. package/dist/psbtInputFields-BIxBpPj2.cjs +2 -0
  40. package/dist/psbtInputFields-BIxBpPj2.cjs.map +1 -0
  41. package/dist/sha2-CrlWM5S8.js +312 -0
  42. package/dist/{sha2-BYVxyZzX.js.map → sha2-CrlWM5S8.js.map} +1 -1
  43. package/dist/sha2-DI0-0SHr.cjs +2 -0
  44. package/dist/{sha2-DsrLC4NM.cjs.map → sha2-DI0-0SHr.cjs.map} +1 -1
  45. package/dist/{signPsbtsWithFallback-CCFTzE0o.js → signPsbtsWithFallback-0VBALhjS.js} +2 -2
  46. package/dist/{signPsbtsWithFallback-CCFTzE0o.js.map → signPsbtsWithFallback-0VBALhjS.js.map} +1 -1
  47. package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs → signPsbtsWithFallback-DMSpIQWH.cjs} +2 -2
  48. package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs.map → signPsbtsWithFallback-DMSpIQWH.cjs.map} +1 -1
  49. package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts +2 -0
  50. package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts.map +1 -0
  51. package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts +2 -0
  52. package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts.map +1 -0
  53. package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts +2 -0
  54. package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts.map +1 -0
  55. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts +2 -0
  56. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts.map +1 -0
  57. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts +2 -0
  58. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts.map +1 -0
  59. package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts +2 -0
  60. package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts.map +1 -0
  61. package/dist/tbv/core/clients/eth/index.cjs +2 -0
  62. package/dist/tbv/core/clients/eth/index.cjs.map +1 -0
  63. package/dist/tbv/core/clients/eth/index.d.ts +4 -0
  64. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  65. package/dist/tbv/core/clients/eth/index.js +22 -0
  66. package/dist/tbv/core/clients/eth/index.js.map +1 -0
  67. package/dist/tbv/core/clients/eth/onChainBtcPubkey.d.ts.map +1 -1
  68. package/dist/tbv/core/clients/eth/payout-script.d.ts +4 -0
  69. package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -0
  70. package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts +99 -0
  71. package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts.map +1 -0
  72. package/dist/tbv/core/clients/eth/pegin-transaction.d.ts +14 -0
  73. package/dist/tbv/core/clients/eth/pegin-transaction.d.ts.map +1 -0
  74. package/dist/tbv/core/clients/index.cjs +1 -1
  75. package/dist/tbv/core/clients/index.js +55 -48
  76. package/dist/tbv/core/clients/index.js.map +1 -1
  77. package/dist/tbv/core/clients/mempool/index.cjs +2 -0
  78. package/dist/tbv/core/clients/mempool/index.cjs.map +1 -0
  79. package/dist/tbv/core/clients/mempool/index.js +222 -0
  80. package/dist/tbv/core/clients/mempool/index.js.map +1 -0
  81. package/dist/tbv/core/contracts/index.cjs +1 -1
  82. package/dist/tbv/core/contracts/index.cjs.map +1 -1
  83. package/dist/tbv/core/contracts/index.js +491 -12
  84. package/dist/tbv/core/contracts/index.js.map +1 -1
  85. package/dist/tbv/core/index.cjs +1 -1
  86. package/dist/tbv/core/index.d.ts +4 -0
  87. package/dist/tbv/core/index.d.ts.map +1 -1
  88. package/dist/tbv/core/index.js +235 -226
  89. package/dist/tbv/core/index.js.map +1 -1
  90. package/dist/tbv/core/managers/PeginManager.d.ts +38 -30
  91. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  92. package/dist/tbv/core/managers/index.cjs +1 -1
  93. package/dist/tbv/core/managers/index.d.ts +2 -1
  94. package/dist/tbv/core/managers/index.d.ts.map +1 -1
  95. package/dist/tbv/core/managers/index.js +2 -2
  96. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.golden.test.d.ts +62 -0
  97. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.golden.test.d.ts.map +1 -0
  98. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.test.d.ts +15 -0
  99. package/dist/tbv/core/pegin-fingerprint/__tests__/peginFingerprint.test.d.ts.map +1 -0
  100. package/dist/tbv/core/pegin-fingerprint/index.d.ts +14 -0
  101. package/dist/tbv/core/pegin-fingerprint/index.d.ts.map +1 -0
  102. package/dist/tbv/core/pegin-fingerprint/peginFingerprint.d.ts +141 -0
  103. package/dist/tbv/core/pegin-fingerprint/peginFingerprint.d.ts.map +1 -0
  104. package/dist/tbv/core/services/index.cjs +1 -1
  105. package/dist/tbv/core/services/index.js +2 -2
  106. package/dist/tbv/core/utils/eth/index.cjs +2 -0
  107. package/dist/tbv/core/utils/eth/index.cjs.map +1 -0
  108. package/dist/tbv/core/utils/eth/index.js +109 -0
  109. package/dist/tbv/core/utils/eth/index.js.map +1 -0
  110. package/dist/tbv/core/utils/index.cjs +1 -1
  111. package/dist/tbv/core/utils/index.js +41 -40
  112. package/dist/tbv/core/utils/index.js.map +1 -1
  113. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  114. package/dist/tbv/core/vault-secrets/index.js +1 -1
  115. package/dist/tbv/index.cjs +1 -1
  116. package/dist/tbv/index.js +235 -226
  117. package/dist/tbv/index.js.map +1 -1
  118. package/dist/testing/index.cjs +1 -1
  119. package/dist/testing/index.js +1 -1
  120. package/dist/toRefundInputs-BwG6T0PP.cjs +2 -0
  121. package/dist/toRefundInputs-BwG6T0PP.cjs.map +1 -0
  122. package/dist/{toRefundInputs-BG-qHCEu.js → toRefundInputs-C3oIN0aW.js} +237 -139
  123. package/dist/toRefundInputs-C3oIN0aW.js.map +1 -0
  124. package/dist/types-CPDLZm3l.js +430 -0
  125. package/dist/types-CPDLZm3l.js.map +1 -0
  126. package/dist/types-DSlcXtog.cjs +2 -0
  127. package/dist/types-DSlcXtog.cjs.map +1 -0
  128. package/package.json +32 -3
  129. package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js +0 -111
  130. package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js.map +0 -1
  131. package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs +0 -2
  132. package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs.map +0 -1
  133. package/dist/PeginManager-Bwjqb0_6.cjs +0 -2
  134. package/dist/PeginManager-Bwjqb0_6.cjs.map +0 -1
  135. package/dist/PeginManager-DjatPUPS.js +0 -1503
  136. package/dist/PeginManager-DjatPUPS.js.map +0 -1
  137. package/dist/ProtocolParams.abi-C0TSRaHV.js +0 -486
  138. package/dist/ProtocolParams.abi-C0TSRaHV.js.map +0 -1
  139. package/dist/ProtocolParams.abi-CYZoV2EI.cjs +0 -2
  140. package/dist/ProtocolParams.abi-CYZoV2EI.cjs.map +0 -1
  141. package/dist/errors-Blc-JWnI.js +0 -121
  142. package/dist/errors-Blc-JWnI.js.map +0 -1
  143. package/dist/errors-CGcNP0rV.cjs +0 -2
  144. package/dist/errors-CGcNP0rV.cjs.map +0 -1
  145. package/dist/mempoolApi-BJvC9nPF.cjs +0 -2
  146. package/dist/mempoolApi-BJvC9nPF.cjs.map +0 -1
  147. package/dist/mempoolApi-_CoQH5vH.js +0 -612
  148. package/dist/mempoolApi-_CoQH5vH.js.map +0 -1
  149. package/dist/onChainBtcPubkey-B5ZvWCCF.cjs +0 -2
  150. package/dist/onChainBtcPubkey-B5ZvWCCF.cjs.map +0 -1
  151. package/dist/onChainBtcPubkey-DATNfAAl.js +0 -19
  152. package/dist/onChainBtcPubkey-DATNfAAl.js.map +0 -1
  153. package/dist/primeVpAuth-BI63kgdd.js +0 -1171
  154. package/dist/primeVpAuth-BI63kgdd.js.map +0 -1
  155. package/dist/primeVpAuth-D3xbar3j.cjs +0 -2
  156. package/dist/primeVpAuth-D3xbar3j.cjs.map +0 -1
  157. package/dist/sha2-BYVxyZzX.js +0 -274
  158. package/dist/sha2-DsrLC4NM.cjs +0 -2
  159. package/dist/toRefundInputs-BG-qHCEu.js.map +0 -1
  160. package/dist/toRefundInputs-kVR-3EdD.cjs +0 -2
  161. package/dist/toRefundInputs-kVR-3EdD.cjs.map +0 -1
  162. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs +0 -2
  163. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs.map +0 -1
  164. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js +0 -277
  165. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js.map +0 -1
@@ -0,0 +1,1216 @@
1
+ var Te = Object.defineProperty;
2
+ var Se = (o, e, t) => e in o ? Te(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var P = (o, e, t) => Se(o, typeof e != "symbol" ? e + "" : e, t);
4
+ import { c as ve, a as Y, u as _e, b as z, d as j, e as Q, f as Be, g as de, s as pe } from "./sha2-CrlWM5S8.js";
5
+ import * as ge from "bitcoinjs-lib";
6
+ import { Transaction as fe, Psbt as Z } from "bitcoinjs-lib";
7
+ import { Buffer as B } from "buffer";
8
+ import { isAddressEqual as J, encodeFunctionData as Ce } from "viem";
9
+ import { r as Ae, e as Ie, V as He, M as $e, N as Re } from "./pegin-registration-client-BdRiR8br.js";
10
+ import { pushTx as Oe, getUtxoInfo as Fe } from "./tbv/core/clients/mempool/index.js";
11
+ import { B as ee } from "./BTCVaultRegistry.abi-CJwWI2EO.js";
12
+ import { expandWotsSeed as We, expandHashlockSecret as Me, expandAuthAnchor as Ve } from "./tbv/core/wasm/index.js";
13
+ import { a as te, b as De, i as oe, j as Ne } from "./verifyScriptPathSchnorrSignature-Ciq_xZhw.js";
14
+ import { d as Ue, b as Ke, e as Le, f as Xe, c as Ge } from "./verifyKeyPathSchnorrSignature-BrgUJmV0.js";
15
+ import { p as qe, h as K, u as L, e as Ye, i as se, s as w, k as ne } from "./bitcoin-C-TuHb-v.js";
16
+ import { c as ze, a as je } from "./signing-Cm-McVR2.js";
17
+ import { M as ie, X as Qe } from "./validation-OSC0xTHB.js";
18
+ import { p as Ze, d as me } from "./parseFundingOutpoints-B67CoXpF.js";
19
+ import { c as Je, s as C, r as et, b as tt, d as ot } from "./signPsbtsWithFallback-0VBALhjS.js";
20
+ import { s as st, h as nt } from "./psbtInputFields-B3e05Xe6.js";
21
+ import { p as it, f as rt } from "./fundPeginTransaction-B2wyjqp0.js";
22
+ import { M as re, B as at } from "./constants-CPzppOdq.js";
23
+ import * as ct from "@bitcoin-js/tiny-secp256k1-asmjs";
24
+ import { v as lt, P as ut, a as ht, b as dt } from "./bip322Verify-D6sBBUHE.js";
25
+ const R = /* @__PURE__ */ BigInt(2 ** 32 - 1), ae = /* @__PURE__ */ BigInt(32);
26
+ function pt(o, e = !1) {
27
+ return e ? { h: Number(o & R), l: Number(o >> ae & R) } : { h: Number(o >> ae & R) | 0, l: Number(o & R) | 0 };
28
+ }
29
+ function gt(o, e = !1) {
30
+ const t = o.length;
31
+ let s = new Uint32Array(t), r = new Uint32Array(t);
32
+ for (let n = 0; n < t; n++) {
33
+ const { h: i, l: a } = pt(o[n], e);
34
+ [s[n], r[n]] = [i, a];
35
+ }
36
+ return [s, r];
37
+ }
38
+ const ft = (o, e, t) => o << t | e >>> 32 - t, mt = (o, e, t) => e << t | o >>> 32 - t, Pt = (o, e, t) => e << t - 32 | o >>> 64 - t, bt = (o, e, t) => o << t - 32 | e >>> 64 - t, wt = 64;
39
+ function yt(o) {
40
+ const e = o.prepeginTxid.toLowerCase();
41
+ if (!/^[0-9a-f]+$/.test(e) || e.length !== wt)
42
+ throw new Error(
43
+ `buildDepositTerms: prepeginTxid must be 64 hex chars, got "${o.prepeginTxid}"`
44
+ );
45
+ if (o.peginAmounts.length === 0)
46
+ throw new Error("buildDepositTerms: at least one pegin amount is required");
47
+ if (o.timelockPegin <= 0 || o.timelockAssert <= 0 || o.timelockRefund <= 0)
48
+ throw new Error("buildDepositTerms: timelocks must be positive");
49
+ if (!Number.isInteger(o.maxAcceptableCommissionBps) || o.maxAcceptableCommissionBps < 0 || o.maxAcceptableCommissionBps >= re)
50
+ throw new Error(
51
+ `buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${re}), got ${o.maxAcceptableCommissionBps}`
52
+ );
53
+ const t = BigInt(at), s = o.peginAmounts.map(
54
+ (r, n) => ({
55
+ htlcVout: n,
56
+ vaultProviderBtcPubkey: o.vaultProviderBtcPubkey,
57
+ peginAmount: r,
58
+ // Ceiling, not quote: floor(peginAmount * maxAcceptableBps / 10_000) —
59
+ // the same bound the registration calldata enforces on-chain, so any
60
+ // stamped commission the contract admits stays under it (firmware
61
+ // >= c8db53e checks the payout commission output <= this value).
62
+ commissionFee: r * BigInt(o.maxAcceptableCommissionBps) / t,
63
+ depositorClaimValue: o.depositorClaimValue,
64
+ peginMaxFee: o.peginMaxFee
65
+ })
66
+ );
67
+ return {
68
+ vaultCoreVersion: o.vaultCoreVersion,
69
+ protocolFeeRate: o.protocolFeeRate,
70
+ timelockPegin: o.timelockPegin,
71
+ timelockAssert: o.timelockAssert,
72
+ timelockRefund: o.timelockRefund,
73
+ prepeginTxid: e,
74
+ prepeginMaxFee: o.prepeginMaxFee,
75
+ vaultKeeperBtcPubkeys: [...o.vaultKeeperBtcPubkeys],
76
+ universalChallengerBtcPubkeys: [...o.universalChallengerBtcPubkeys],
77
+ vaults: s
78
+ };
79
+ }
80
+ const xt = /^0x[0-9a-f]+$/i, kt = /^[0-9a-f]+$/i, Et = /^[A-Za-z0-9+/]+={0,2}$/;
81
+ function _(o) {
82
+ if (typeof o != "string" || o.length === 0)
83
+ throw new Error("BTC wallet returned empty public key");
84
+ return qe(o).toLowerCase();
85
+ }
86
+ function Tt(o) {
87
+ if (typeof o != "string" || o.length === 0)
88
+ throw new Error("BTC wallet returned empty BIP-322 signature");
89
+ if (o.startsWith("0x") || o.startsWith("0X")) {
90
+ if (!xt.test(o) || o.length < 4 || o.length % 2 !== 0)
91
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
92
+ return o.toLowerCase();
93
+ }
94
+ if (kt.test(o)) {
95
+ if (o.length % 2 !== 0)
96
+ throw new Error("BTC wallet returned malformed hex BIP-322 signature");
97
+ return `0x${o.toLowerCase()}`;
98
+ }
99
+ if (!Et.test(o) || o.length % 4 !== 0)
100
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
101
+ const e = B.from(o, "base64");
102
+ if (e.length === 0 || e.toString("base64") !== o)
103
+ throw new Error("BTC wallet returned malformed base64 BIP-322 signature");
104
+ return `0x${e.toString("hex")}`;
105
+ }
106
+ async function St(o) {
107
+ const { wallet: e, depositTerms: t, fundedPrePeginTxHex: s, depositorBtcPubkey: r } = o, n = typeof e.approveDepositTerms == "function" ? e.approveDepositTerms : void 0;
108
+ if (!n && !t)
109
+ return;
110
+ const i = s.startsWith("0x") ? s.slice(2) : s, c = fe.fromHex(i).getId();
111
+ if (t && t.prepeginTxid.replace(/^0x/, "").toLowerCase() !== c)
112
+ throw new Error(
113
+ `Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${t.prepeginTxid}, but this transaction is ${c}.`
114
+ );
115
+ if (!n)
116
+ return;
117
+ if (!t)
118
+ throw new Error(
119
+ "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."
120
+ );
121
+ if (typeof e.deriveContextHash != "function")
122
+ throw new Error(
123
+ "A deposit-approval wallet must also implement deriveContextHash, but this one does not."
124
+ );
125
+ if (typeof e.holdsApprovedDepositTerms == "function") {
126
+ let f = !1;
127
+ try {
128
+ f = await e.holdsApprovedDepositTerms(t);
129
+ } catch {
130
+ }
131
+ if (f)
132
+ return;
133
+ }
134
+ typeof e.validateDepositTerms == "function" && await e.validateDepositTerms(t);
135
+ const u = Ze(s);
136
+ (await me(
137
+ { deriveContextHash: e.deriveContextHash.bind(e) },
138
+ {
139
+ depositorBtcPubkey: K(
140
+ _(r)
141
+ ),
142
+ fundingOutpoints: u
143
+ }
144
+ )).fill(0), await n.call(e, t);
145
+ }
146
+ const vt = BigInt(0), A = BigInt(1), _t = BigInt(2), Bt = BigInt(7), Ct = BigInt(256), At = BigInt(113), Pe = [], be = [], we = [];
147
+ for (let o = 0, e = A, t = 1, s = 0; o < 24; o++) {
148
+ [t, s] = [s, (2 * t + 3 * s) % 5], Pe.push(2 * (5 * s + t)), be.push((o + 1) * (o + 2) / 2 % 64);
149
+ let r = vt;
150
+ for (let n = 0; n < 7; n++)
151
+ e = (e << A ^ (e >> Bt) * At) % Ct, e & _t && (r ^= A << (A << BigInt(n)) - A);
152
+ we.push(r);
153
+ }
154
+ const ye = gt(we, !0), It = ye[0], Ht = ye[1], ce = (o, e, t) => t > 32 ? Pt(o, e, t) : ft(o, e, t), le = (o, e, t) => t > 32 ? bt(o, e, t) : mt(o, e, t);
155
+ function $t(o, e = 24) {
156
+ const t = new Uint32Array(10);
157
+ for (let s = 24 - e; s < 24; s++) {
158
+ for (let i = 0; i < 10; i++)
159
+ t[i] = o[i] ^ o[i + 10] ^ o[i + 20] ^ o[i + 30] ^ o[i + 40];
160
+ for (let i = 0; i < 10; i += 2) {
161
+ const a = (i + 8) % 10, c = (i + 2) % 10, u = t[c], d = t[c + 1], f = ce(u, d, 1) ^ t[a], x = le(u, d, 1) ^ t[a + 1];
162
+ for (let b = 0; b < 50; b += 10)
163
+ o[i + b] ^= f, o[i + b + 1] ^= x;
164
+ }
165
+ let r = o[2], n = o[3];
166
+ for (let i = 0; i < 24; i++) {
167
+ const a = be[i], c = ce(r, n, a), u = le(r, n, a), d = Pe[i];
168
+ r = o[d], n = o[d + 1], o[d] = c, o[d + 1] = u;
169
+ }
170
+ for (let i = 0; i < 50; i += 10) {
171
+ for (let a = 0; a < 10; a++)
172
+ t[a] = o[i + a];
173
+ for (let a = 0; a < 10; a++)
174
+ o[i + a] ^= ~t[(a + 2) % 10] & t[(a + 4) % 10];
175
+ }
176
+ o[0] ^= It[s], o[1] ^= Ht[s];
177
+ }
178
+ de(t);
179
+ }
180
+ class G {
181
+ // NOTE: we accept arguments in bytes instead of bits here.
182
+ constructor(e, t, s, r = !1, n = 24) {
183
+ P(this, "state");
184
+ P(this, "pos", 0);
185
+ P(this, "posOut", 0);
186
+ P(this, "finished", !1);
187
+ P(this, "state32");
188
+ P(this, "destroyed", !1);
189
+ P(this, "blockLen");
190
+ P(this, "suffix");
191
+ P(this, "outputLen");
192
+ P(this, "enableXOF", !1);
193
+ P(this, "rounds");
194
+ if (this.blockLen = e, this.suffix = t, this.outputLen = s, this.enableXOF = r, this.rounds = n, Y(s, "outputLen"), !(0 < e && e < 200))
195
+ throw new Error("only keccak-f1600 function is supported");
196
+ this.state = new Uint8Array(200), this.state32 = _e(this.state);
197
+ }
198
+ clone() {
199
+ return this._cloneInto();
200
+ }
201
+ keccak() {
202
+ z(this.state32), $t(this.state32, this.rounds), z(this.state32), this.posOut = 0, this.pos = 0;
203
+ }
204
+ update(e) {
205
+ j(this), Q(e);
206
+ const { blockLen: t, state: s } = this, r = e.length;
207
+ for (let n = 0; n < r; ) {
208
+ const i = Math.min(t - this.pos, r - n);
209
+ for (let a = 0; a < i; a++)
210
+ s[this.pos++] ^= e[n++];
211
+ this.pos === t && this.keccak();
212
+ }
213
+ return this;
214
+ }
215
+ finish() {
216
+ if (this.finished)
217
+ return;
218
+ this.finished = !0;
219
+ const { state: e, suffix: t, pos: s, blockLen: r } = this;
220
+ e[s] ^= t, (t & 128) !== 0 && s === r - 1 && this.keccak(), e[r - 1] ^= 128, this.keccak();
221
+ }
222
+ writeInto(e) {
223
+ j(this, !1), Q(e), this.finish();
224
+ const t = this.state, { blockLen: s } = this;
225
+ for (let r = 0, n = e.length; r < n; ) {
226
+ this.posOut >= s && this.keccak();
227
+ const i = Math.min(s - this.posOut, n - r);
228
+ e.set(t.subarray(this.posOut, this.posOut + i), r), this.posOut += i, r += i;
229
+ }
230
+ return e;
231
+ }
232
+ xofInto(e) {
233
+ if (!this.enableXOF)
234
+ throw new Error("XOF is not possible for this instance");
235
+ return this.writeInto(e);
236
+ }
237
+ xof(e) {
238
+ return Y(e), this.xofInto(new Uint8Array(e));
239
+ }
240
+ digestInto(e) {
241
+ if (Be(e, this), this.finished)
242
+ throw new Error("digest() was already called");
243
+ return this.writeInto(e), this.destroy(), e;
244
+ }
245
+ digest() {
246
+ return this.digestInto(new Uint8Array(this.outputLen));
247
+ }
248
+ destroy() {
249
+ this.destroyed = !0, de(this.state);
250
+ }
251
+ _cloneInto(e) {
252
+ const { blockLen: t, suffix: s, outputLen: r, rounds: n, enableXOF: i } = this;
253
+ return e || (e = new G(t, s, r, i, n)), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = n, e.suffix = s, e.outputLen = r, e.enableXOF = i, e.destroyed = this.destroyed, e;
254
+ }
255
+ }
256
+ const Rt = (o, e, t, s = {}) => ve(() => new G(e, o, t), s), Ot = /* @__PURE__ */ Rt(1, 136, 32), ue = 64, y = 20, X = 4, xe = 2, Ft = 0, Wt = 1, O = [64, 64], Mt = (o) => Array.from(o).map((e) => e.toString(16).padStart(2, "0")).join("");
257
+ function q(o) {
258
+ return Ae(pe(o));
259
+ }
260
+ function ke(o) {
261
+ return (1 << o) - 1;
262
+ }
263
+ function Vt(o) {
264
+ let e = 1;
265
+ for (; e * e < o + 1; ) e++;
266
+ return Math.max(e, 2);
267
+ }
268
+ function Dt(o) {
269
+ const e = X, t = o * ke(e);
270
+ return { d: e, n: o, checksum_radix: Vt(t) };
271
+ }
272
+ function M(o, e) {
273
+ const t = [];
274
+ let s = e;
275
+ for (; s > 0; )
276
+ t.push(s & 255), s >>>= 8;
277
+ const r = new Uint8Array(o.length + t.length);
278
+ r.set(o);
279
+ for (let n = 0; n < t.length; n++)
280
+ r[o.length + n] = t[n];
281
+ return q(r);
282
+ }
283
+ function V(o, e) {
284
+ let t = o;
285
+ for (let s = 0; s < e; s++)
286
+ t = q(t);
287
+ return t;
288
+ }
289
+ function Nt(o, e) {
290
+ const t = ke(e.d), s = e.checksum_radix - 1, r = Math.floor(e.n * t / e.checksum_radix), n = [];
291
+ for (let d = 0; d < e.n; d++) {
292
+ const f = M(o, d + xe), x = V(f, t);
293
+ n.push(Array.from(x));
294
+ }
295
+ const i = M(
296
+ o,
297
+ Ft
298
+ ), a = V(
299
+ i,
300
+ s
301
+ ), c = M(
302
+ o,
303
+ Wt
304
+ ), u = V(
305
+ c,
306
+ r
307
+ );
308
+ return {
309
+ config: e,
310
+ message_terminals: n,
311
+ checksum_major_terminal: Array.from(u),
312
+ checksum_minor_terminal: Array.from(a)
313
+ };
314
+ }
315
+ async function Ut(o) {
316
+ try {
317
+ if (o.length !== ue)
318
+ throw new Error(
319
+ `WOTS seed must be exactly ${ue} bytes, got ${o.length}`
320
+ );
321
+ const e = [];
322
+ for (let t = 0; t < O.length; t++) {
323
+ const s = O[t], r = Dt(s), n = new Uint8Array(o.length + 1);
324
+ n.set(o), n[o.length] = t;
325
+ const i = q(n);
326
+ try {
327
+ const a = Nt(i, r);
328
+ if (a.config.d !== X)
329
+ throw new Error(
330
+ `Block ${t}: expected d=${X}, got d=${a.config.d}`
331
+ );
332
+ if (a.config.n !== s)
333
+ throw new Error(
334
+ `Block ${t}: expected n=${s}, got n=${a.config.n}`
335
+ );
336
+ if (a.message_terminals.length !== s)
337
+ throw new Error(
338
+ `Block ${t}: expected ${s} message terminals, got ${a.message_terminals.length}`
339
+ );
340
+ for (let c = 0; c < a.message_terminals.length; c++)
341
+ if (a.message_terminals[c].length !== y)
342
+ throw new Error(
343
+ `Block ${t} terminal ${c}: expected ${y} bytes, got ${a.message_terminals[c].length}`
344
+ );
345
+ if (a.checksum_minor_terminal.length !== y)
346
+ throw new Error(
347
+ `Block ${t} checksum_minor: expected ${y} bytes`
348
+ );
349
+ if (a.checksum_major_terminal.length !== y)
350
+ throw new Error(
351
+ `Block ${t} checksum_major: expected ${y} bytes`
352
+ );
353
+ e.push(a);
354
+ } finally {
355
+ n.fill(0), i.fill(0);
356
+ }
357
+ }
358
+ if (e.length !== O.length)
359
+ throw new Error(
360
+ `Expected ${O.length} blocks, got ${e.length}`
361
+ );
362
+ return e;
363
+ } finally {
364
+ o.fill(0);
365
+ }
366
+ }
367
+ function D(o, e, t) {
368
+ if (o.length !== y)
369
+ throw new Error(
370
+ `Block ${e} ${t}: expected ${y} bytes, got ${o.length}`
371
+ );
372
+ for (let s = 0; s < o.length; s++) {
373
+ const r = o[s];
374
+ if (!Number.isInteger(r) || r < 0 || r > 255)
375
+ throw new Error(
376
+ `Block ${e} ${t}[${s}]: invalid byte value ${r}`
377
+ );
378
+ }
379
+ }
380
+ function Kt(o) {
381
+ if (o.length === 0)
382
+ throw new Error("Public keys array must not be empty");
383
+ for (let n = 0; n < o.length; n++) {
384
+ const i = o[n];
385
+ D(i.checksum_minor_terminal, n, "checksum_minor_terminal"), D(i.checksum_major_terminal, n, "checksum_major_terminal");
386
+ for (let a = 0; a < i.message_terminals.length; a++)
387
+ D(i.message_terminals[a], n, `message_terminal[${a}]`);
388
+ }
389
+ let e = 0;
390
+ for (const n of o)
391
+ e += xe + n.message_terminals.length;
392
+ const t = new Uint8Array(e * y);
393
+ let s = 0;
394
+ for (const n of o) {
395
+ t.set(n.checksum_minor_terminal, s), s += y, t.set(n.checksum_major_terminal, s), s += y;
396
+ for (const i of n.message_terminals)
397
+ t.set(i, s), s += y;
398
+ }
399
+ const r = Ot(t);
400
+ return `0x${Mt(r)}`;
401
+ }
402
+ async function Lt(o, e) {
403
+ const t = [], s = [], r = [], n = [];
404
+ try {
405
+ for (let i = 0; i < e; i++) {
406
+ const a = await We(o, i);
407
+ try {
408
+ const u = await Ut(a);
409
+ t.push(u), s.push(Kt(u));
410
+ } finally {
411
+ a.fill(0);
412
+ }
413
+ const c = await Me(o, i);
414
+ try {
415
+ const u = L(c);
416
+ r.push(u), n.push(Je(Ye(u)).slice(2));
417
+ } finally {
418
+ c.fill(0);
419
+ }
420
+ }
421
+ } finally {
422
+ o.fill(0);
423
+ }
424
+ return { perVaultWotsKeys: t, wotsPkHashes: s, htlcSecretHexes: r, hashlocks: n };
425
+ }
426
+ const Xt = 1, Gt = 2, qt = 33, Yt = 2, zt = 3, jt = 1, F = 64, Qt = 0, N = 1, he = /^[0-9a-f]{64}$/i, Zt = /^(?:[0-9a-f]{2})+$/;
427
+ function Jt(o) {
428
+ const e = o.slice(2);
429
+ if (!Zt.test(e))
430
+ throw new Error(
431
+ "proof of possession witness is not even-length lowercase hex"
432
+ );
433
+ return Ue(
434
+ Uint8Array.from(B.from(e, "hex")),
435
+ "proof of possession witness"
436
+ );
437
+ }
438
+ function eo(o, e, t) {
439
+ var r;
440
+ const s = Jt(t);
441
+ if (s.length === Xt) {
442
+ const [n] = s;
443
+ let i, a;
444
+ if (n.length === F)
445
+ i = n, a = Qt;
446
+ else if (n.length === F + 1 && n[F] === N)
447
+ i = n.subarray(0, F), a = N;
448
+ else
449
+ throw new Error(
450
+ "proof of possession witness item must be a 64-byte Schnorr signature (or 65 bytes ending in 0x01)"
451
+ );
452
+ if (!he.test(e))
453
+ throw new Error(
454
+ `depositor public key must be bare 64-char x-only hex, got "${e}"`
455
+ );
456
+ const c = Uint8Array.from(B.from(e, "hex"));
457
+ if (!lt(o, c, i, a))
458
+ throw new Error(
459
+ "proof of possession signature does not verify against the depositor key"
460
+ );
461
+ return { kind: "p2tr-verified" };
462
+ }
463
+ if (s.length === Gt) {
464
+ if (!he.test(e))
465
+ throw new Error(
466
+ `depositor public key must be bare 64-char x-only hex, got "${e}"`
467
+ );
468
+ const [n, i] = s;
469
+ if (i.length !== qt || i[0] !== Yt && i[0] !== zt)
470
+ throw new Error(
471
+ `proof of possession P2WPKH witness item 1 is not a compressed public key (${i.length} bytes, prefix 0x${((r = i[0]) == null ? void 0 : r.toString(16)) ?? "none"})`
472
+ );
473
+ if (!ct.isPointCompressed(i))
474
+ throw new Error(
475
+ "proof of possession P2WPKH witness pubkey is not a valid secp256k1 point"
476
+ );
477
+ const a = B.from(
478
+ i.subarray(jt)
479
+ ).toString("hex");
480
+ if (a !== e.toLowerCase())
481
+ throw new Error(
482
+ `proof of possession witness pubkey does not match the depositor key: witness carries ${a}, expected ${e}`
483
+ );
484
+ if (n.length < ut || n.length > ht)
485
+ throw new Error(
486
+ `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`
487
+ );
488
+ if (n[n.length - 1] !== N)
489
+ throw new Error(
490
+ `proof of possession P2WPKH signature must end in a SIGHASH_ALL (0x01) byte, got 0x${n[n.length - 1].toString(16)}`
491
+ );
492
+ if (!dt(o, i, n))
493
+ throw new Error(
494
+ "proof of possession signature does not verify against the depositor key"
495
+ );
496
+ return { kind: "p2wpkh-verified" };
497
+ }
498
+ throw new Error(
499
+ `proof of possession witness has ${s.length} items; expected 1 (P2TR) or 2 (P2WPKH)`
500
+ );
501
+ }
502
+ const U = "00".repeat(32), to = "00".repeat(32);
503
+ function oo(o, e) {
504
+ const t = {
505
+ bitcoin: "bc",
506
+ testnet: "tb",
507
+ signet: "tb",
508
+ regtest: "bcrt"
509
+ };
510
+ try {
511
+ const s = ge.address.fromBech32(o);
512
+ return s.prefix === t[e] && s.version === 0 && s.data.length === 20;
513
+ } catch {
514
+ return !1;
515
+ }
516
+ }
517
+ function so(o, e, t, s) {
518
+ const r = t == null ? void 0 : t[`${o}:${e}`];
519
+ return r ? Promise.resolve({
520
+ txid: o,
521
+ vout: e,
522
+ value: r.value,
523
+ scriptPubKey: r.scriptPubKey
524
+ }) : Fe(o, e, s);
525
+ }
526
+ class Io {
527
+ /**
528
+ * Creates a new PeginManager instance.
529
+ *
530
+ * @param config - Manager configuration including wallets and contract addresses
531
+ */
532
+ constructor(e) {
533
+ P(this, "config");
534
+ this.config = e;
535
+ }
536
+ /**
537
+ * Prepare a peg-in: sizing pass → vault-root derivation (one wallet
538
+ * popup) → per-vault WOTS / hashlock derivation → commit pass with
539
+ * PSBT signing (signPsbt for a single vault, one batch popup for a
540
+ * split). Returns broadcast-ready txs, the pubkey snapshot, and the
541
+ * sensitive derived material.
542
+ *
543
+ * @throws If the wallet rejects, insufficient funds, or an internal
544
+ * invariant violation.
545
+ */
546
+ async preparePegin(e) {
547
+ if (e.amounts.length === 0)
548
+ throw new Error("amounts must contain at least one entry");
549
+ const t = await this.config.btcWallet.getPublicKeyHex(), s = _(t);
550
+ if (C(this.config.btcWallet)) {
551
+ const l = (await et(this.config.btcWallet)).trim();
552
+ if (e.changeAddress.trim() !== l)
553
+ throw new Error(
554
+ `Pre-PegIn changeAddress "${e.changeAddress}" is not the approval wallet's change address ("${l}"). Refusing to build a tx the signing device would reject.`
555
+ );
556
+ } else if (!se(
557
+ e.changeAddress,
558
+ t,
559
+ this.config.btcNetwork
560
+ ))
561
+ throw new Error(
562
+ `Pre-PegIn changeAddress "${e.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.`
563
+ );
564
+ const r = await this.prepareSizing(s, e);
565
+ if (C(this.config.btcWallet)) {
566
+ const { validateDepositTerms: l } = this.config.btcWallet;
567
+ typeof l == "function" && await l.call(
568
+ this.config.btcWallet,
569
+ this.buildPeginDepositTerms({
570
+ params: e,
571
+ prepeginTxid: to,
572
+ prepeginMaxFee: r.fee,
573
+ depositorClaimValue: r.depositorClaimValue,
574
+ peginMaxFee: r.minPeginFee
575
+ })
576
+ );
577
+ }
578
+ const n = r.selectedUTXOs.map(
579
+ (l) => ({
580
+ txid: K(l.txid),
581
+ vout: l.vout
582
+ })
583
+ ), i = await me(this.config.btcWallet, {
584
+ depositorBtcPubkey: K(s),
585
+ fundingOutpoints: n
586
+ });
587
+ let a, c;
588
+ try {
589
+ const l = await Ve(i);
590
+ try {
591
+ a = L(l), c = L(pe(l));
592
+ } finally {
593
+ l.fill(0);
594
+ }
595
+ } catch (l) {
596
+ throw i.fill(0), l;
597
+ }
598
+ const u = await Lt(i, e.amounts.length), { perVaultWotsKeys: d, wotsPkHashes: f, htlcSecretHexes: x, hashlocks: b } = u, g = await this.preparePeginCommit({
599
+ depositorBtcPubkeyRaw: t,
600
+ depositorBtcPubkey: s,
601
+ hashlocks: b,
602
+ authAnchorHash: c,
603
+ sizing: r,
604
+ params: e
605
+ });
606
+ for (let l = 0; l < g.perVault.length; l++)
607
+ if (g.perVault[l].htlcVout !== l)
608
+ throw new Error(
609
+ `Internal invariant violation: htlcVout/index mismatch at vault ${l} (expected ${l}, got ${g.perVault[l].htlcVout})`
610
+ );
611
+ tt(
612
+ g.fundedPrePeginTxHex,
613
+ e.amounts.length,
614
+ c
615
+ );
616
+ const { depositTerms: T, ...k } = g;
617
+ return {
618
+ transaction: {
619
+ ...k,
620
+ selectedUTXOs: r.selectedUTXOs,
621
+ fee: r.fee,
622
+ changeAmount: r.changeAmount
623
+ },
624
+ depositorBtcPubkey: s,
625
+ derivedSecrets: {
626
+ perVaultWotsKeys: d,
627
+ wotsPkHashes: f,
628
+ htlcSecretHexes: x,
629
+ authAnchorHex: a
630
+ },
631
+ depositTerms: T
632
+ };
633
+ }
634
+ /**
635
+ * Build unfunded Pre-PegIn + select UTXOs. No PSBT signing.
636
+ *
637
+ * Returns the full selection result (UTXOs, fee, changeAmount) so the
638
+ * commit pass funds the broadcast tx with the exact same set used to
639
+ * build the vault-context funding-outpoints commitment. Re-running
640
+ * `selectUtxosForPegin` in the commit pass would be deterministic given
641
+ * the same inputs, but threading the result through guarantees the
642
+ * domain separator structurally matches the funded tx inputs.
643
+ *
644
+ * Sizing runs before the wallet popup, so neither the real per-vault
645
+ * hashlocks nor the real `authAnchorHash` are known yet. Both slots
646
+ * are filled with a 32-byte placeholder; the commit pass swaps in the
647
+ * real values. Output budget is identical (32-byte push regardless of
648
+ * content), so UTXO selection is invariant under substitution.
649
+ */
650
+ async prepareSizing(e, t) {
651
+ const s = t.amounts.map(
652
+ () => U
653
+ ), r = t.vaultKeeperBtcPubkeys.length, n = await te({
654
+ vaultCoreVersion: t.vaultCoreVersion,
655
+ depositorPubkey: e,
656
+ vaultProviderPubkey: w(t.vaultProviderBtcPubkey),
657
+ vaultKeeperPubkeys: t.vaultKeeperBtcPubkeys.map(w),
658
+ universalChallengerPubkeys: t.universalChallengerBtcPubkeys.map(w),
659
+ hashlocks: s,
660
+ timelockRefund: t.timelockRefund,
661
+ pegInAmounts: t.amounts,
662
+ feeRate: t.protocolFeeRate,
663
+ minPeginFeeRate: t.minPeginFeeRate,
664
+ numLocalChallengers: r,
665
+ councilQuorum: t.councilQuorum,
666
+ councilSize: t.councilSize,
667
+ network: this.config.btcNetwork,
668
+ authAnchorHash: U
669
+ }), i = st(
670
+ [...t.availableUTXOs],
671
+ n.totalOutputValue,
672
+ t.mempoolFeeRate,
673
+ it(n.htlcValues.length, !0)
674
+ );
675
+ return {
676
+ selectedUTXOs: i.selectedUTXOs,
677
+ fee: i.fee,
678
+ changeAmount: i.changeAmount,
679
+ depositorClaimValue: n.depositorClaimValue,
680
+ minPeginFee: n.minPeginFee
681
+ };
682
+ }
683
+ /**
684
+ * One projection for both the provisional (pre-derive, placeholder-txid)
685
+ * terms and the final approved terms, so the fields the pre-check validated
686
+ * cannot drift from the fields the device later displays (#2110 T4).
687
+ */
688
+ buildPeginDepositTerms(e) {
689
+ const { params: t } = e;
690
+ return yt({
691
+ vaultCoreVersion: t.vaultCoreVersion,
692
+ protocolFeeRate: t.protocolFeeRate,
693
+ timelockPegin: t.timelockPegin,
694
+ timelockAssert: t.timelockAssert,
695
+ timelockRefund: t.timelockRefund,
696
+ prepeginTxid: e.prepeginTxid,
697
+ prepeginMaxFee: e.prepeginMaxFee,
698
+ vaultProviderBtcPubkey: w(t.vaultProviderBtcPubkey),
699
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys.map(w),
700
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys.map(w),
701
+ maxAcceptableCommissionBps: Ie(
702
+ t.commissionBps
703
+ ),
704
+ peginAmounts: t.amounts,
705
+ depositorClaimValue: e.depositorClaimValue,
706
+ peginMaxFee: e.peginMaxFee
707
+ });
708
+ }
709
+ /** Build PegIn txs and batch-sign their inputs with real hashlocks. */
710
+ async preparePeginCommit(e) {
711
+ const {
712
+ depositorBtcPubkeyRaw: t,
713
+ depositorBtcPubkey: s,
714
+ hashlocks: r,
715
+ authAnchorHash: n,
716
+ sizing: i,
717
+ params: a
718
+ } = e, c = U.toLowerCase();
719
+ for (let h = 0; h < r.length; h++)
720
+ if (r[h].toLowerCase() === c)
721
+ throw new Error(
722
+ `preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${h} — internal substitution bug`
723
+ );
724
+ if (n.toLowerCase() === c)
725
+ throw new Error(
726
+ "preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug"
727
+ );
728
+ const u = w(
729
+ a.vaultProviderBtcPubkey
730
+ ), d = a.vaultKeeperBtcPubkeys.map(w), f = a.universalChallengerBtcPubkeys.map(w), x = d.length, b = {
731
+ vaultCoreVersion: a.vaultCoreVersion,
732
+ depositorPubkey: s,
733
+ vaultProviderPubkey: u,
734
+ vaultKeeperPubkeys: d,
735
+ universalChallengerPubkeys: f,
736
+ hashlocks: r,
737
+ timelockRefund: a.timelockRefund,
738
+ pegInAmounts: a.amounts,
739
+ feeRate: a.protocolFeeRate,
740
+ minPeginFeeRate: a.minPeginFeeRate,
741
+ numLocalChallengers: x,
742
+ councilQuorum: a.councilQuorum,
743
+ councilSize: a.councilSize,
744
+ network: this.config.btcNetwork,
745
+ authAnchorHash: n
746
+ }, g = await te(b);
747
+ if (g.depositorClaimValue !== i.depositorClaimValue || g.minPeginFee !== i.minPeginFee)
748
+ throw new Error(
749
+ `Pre-PegIn sizing/commit divergence: depositorClaimValue ${i.depositorClaimValue} -> ${g.depositorClaimValue}, minPeginFee ${i.minPeginFee} -> ${g.minPeginFee}. The provisional deposit terms validated before derivation would not match the terms sent for approval; refusing to continue.`
750
+ );
751
+ const T = ne(this.config.btcNetwork), k = rt({
752
+ unfundedTxHex: g.psbtHex,
753
+ selectedUTXOs: i.selectedUTXOs,
754
+ changeAddress: a.changeAddress,
755
+ changeAmount: i.changeAmount,
756
+ network: T
757
+ }), l = i.selectedUTXOs.reduce((h, v) => h + BigInt(v.value), 0n) - g.totalOutputValue - i.changeAmount;
758
+ if (l !== i.fee)
759
+ throw new Error(
760
+ `Pre-PegIn funded fee ${l} does not match the sizing-pass fee ${i.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`
761
+ );
762
+ const I = w(
763
+ ze(k)
764
+ ), H = [], p = [], m = [];
765
+ for (let h = 0; h < r.length; h++) {
766
+ const v = await De({
767
+ prePeginParams: b,
768
+ timelockPegin: a.timelockPegin,
769
+ fundedPrePeginTxHex: k,
770
+ htlcVout: h
771
+ }), W = await Ke({
772
+ vaultCoreVersion: a.vaultCoreVersion,
773
+ peginTxHex: v.txHex,
774
+ fundedPrePeginTxHex: k,
775
+ depositorPubkey: s,
776
+ vaultProviderPubkey: u,
777
+ vaultKeeperPubkeys: d,
778
+ universalChallengerPubkeys: f,
779
+ hashlock: r[h],
780
+ timelockRefund: a.timelockRefund,
781
+ network: this.config.btcNetwork
782
+ });
783
+ H.push(v), p.push(W.psbtHex), m.push(
784
+ je(t, 1)
785
+ );
786
+ }
787
+ const E = this.buildPeginDepositTerms({
788
+ params: a,
789
+ prepeginTxid: I,
790
+ prepeginMaxFee: i.fee,
791
+ depositorClaimValue: g.depositorClaimValue,
792
+ peginMaxFee: g.minPeginFee
793
+ });
794
+ C(this.config.btcWallet) && await this.config.btcWallet.approveDepositTerms(E);
795
+ const S = await ot(
796
+ this.config.btcWallet,
797
+ p,
798
+ m
799
+ ), $ = [];
800
+ for (let h = 0; h < S.length; h++) {
801
+ oe({
802
+ requestedPsbtHex: p[h],
803
+ returnedPsbtHex: S[h]
804
+ });
805
+ const v = Le(
806
+ S[h],
807
+ s
808
+ );
809
+ Ne({
810
+ requestedPsbtHex: p[h],
811
+ signatureHex: v,
812
+ signerXOnlyPubkeyHex: s,
813
+ inputIndex: 0
814
+ });
815
+ const W = Xe(S[h]);
816
+ $.push({
817
+ htlcVout: h,
818
+ htlcValue: g.htlcValues[h],
819
+ peginTxHex: W,
820
+ peginTxid: H[h].txid,
821
+ peginInputSignature: v,
822
+ vaultScriptPubKey: H[h].vaultScriptPubKey
823
+ });
824
+ }
825
+ return {
826
+ fundedPrePeginTxHex: k,
827
+ prePeginTxid: I,
828
+ perVault: $,
829
+ depositTerms: E
830
+ };
831
+ }
832
+ /**
833
+ * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
834
+ *
835
+ * This method:
836
+ * 1. Parses the funded transaction hex
837
+ * 2. Fetches UTXO data from mempool for each input
838
+ * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
839
+ * 4. Signs via btcWallet.signPsbt()
840
+ * 5. Finalizes and extracts the transaction
841
+ * 6. Broadcasts via mempool API
842
+ *
843
+ * IMPORTANT — this method does NOT gate on Ethereum finality. Committing
844
+ * BTC to the HTLC while the peg-in registration is still reorg-exposed can
845
+ * strand the deposit: the vault record disappears from the chain while the
846
+ * BTC stays locked until the HTLC refund timelock. Callers must await
847
+ * `waitForPeginRegistrationDepth` for the registered vault(s) before calling
848
+ * this. The gate is not applied here because the params carry no vault ID —
849
+ * adding one would be a breaking signature change.
850
+ *
851
+ * @param params - Transaction hex and depositor public key
852
+ * @returns The broadcasted Bitcoin transaction ID
853
+ * @throws Error if signing or broadcasting fails
854
+ */
855
+ async signAndBroadcast(e) {
856
+ const { fundedPrePeginTxHex: t, depositorBtcPubkey: s } = e, r = t.startsWith("0x") ? t.slice(2) : t, n = fe.fromHex(r);
857
+ if (n.ins.length === 0)
858
+ throw new Error("Transaction has no inputs");
859
+ const i = new Z();
860
+ i.setVersion(n.version), i.setLocktime(n.locktime);
861
+ const a = B.from(
862
+ _(s),
863
+ "hex"
864
+ ), c = this.config.mempoolApiUrl, u = n.ins.map((p) => {
865
+ const m = B.from(p.hash).reverse().toString("hex"), E = p.index;
866
+ return so(m, E, e.localPrevouts, c).then(
867
+ (S) => ({ input: p, utxoData: S, txid: m, vout: E })
868
+ );
869
+ }), d = await Promise.all(u), f = d.reduce(
870
+ (p, m) => p + BigInt(m.utxoData.value),
871
+ 0n
872
+ ), x = n.outs.reduce(
873
+ (p, m) => p + BigInt(m.value),
874
+ 0n
875
+ );
876
+ if (f < x)
877
+ throw new Error(
878
+ `UTXO value mismatch: total input value (${f} sat) is less than total output value (${x} sat). This may indicate the mempool API returned manipulated UTXO data.`
879
+ );
880
+ const b = f - x;
881
+ if (b > ie)
882
+ throw new Error(
883
+ `Implied transaction fee (${b} sat) exceeds maximum reasonable fee (${ie} sat). This may indicate manipulated UTXO data.`
884
+ );
885
+ for (const { input: p, utxoData: m, txid: E, vout: S } of d) {
886
+ const $ = nt(
887
+ {
888
+ value: m.value,
889
+ scriptPubKey: m.scriptPubKey
890
+ },
891
+ a
892
+ );
893
+ i.addInput({
894
+ hash: p.hash,
895
+ index: p.index,
896
+ sequence: p.sequence,
897
+ ...$
898
+ });
899
+ }
900
+ for (const p of n.outs)
901
+ i.addOutput({
902
+ script: p.script,
903
+ value: p.value
904
+ });
905
+ await St({
906
+ wallet: this.config.btcWallet,
907
+ depositTerms: e.depositTerms,
908
+ fundedPrePeginTxHex: t,
909
+ depositorBtcPubkey: s
910
+ });
911
+ const g = i.toHex(), T = await this.config.btcWallet.signPsbt(g);
912
+ oe({
913
+ requestedPsbtHex: g,
914
+ returnedPsbtHex: T
915
+ });
916
+ const k = Ge({
917
+ requestedPsbtHex: g,
918
+ returnedPsbtHex: T
919
+ });
920
+ if (C(this.config.btcWallet) && k !== i.data.inputs.length)
921
+ throw new Error(
922
+ `Key-path verification covered ${k} of ${i.data.inputs.length} Pre-PegIn inputs; an approval wallet signs every input key-path, so the unverified ones must not be broadcast.`
923
+ );
924
+ const l = Z.fromHex(T);
925
+ try {
926
+ l.finalizeAllInputs();
927
+ } catch (p) {
928
+ if (!l.data.inputs.every(
929
+ (E) => E.finalScriptWitness || E.finalScriptSig
930
+ ))
931
+ throw new Error(
932
+ `PSBT finalization failed and wallet did not auto-finalize: ${p}`
933
+ );
934
+ }
935
+ const I = l.extractTransaction().toHex();
936
+ return await Oe(I, c);
937
+ }
938
+ /**
939
+ * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.
940
+ *
941
+ * This method:
942
+ * 1. Re-verifies the PopSignature against the currently connected ETH
943
+ * and BTC wallets — refuses to proceed if either has changed
944
+ * 2. Derives vault ID and checks if it already exists (pre-flight)
945
+ * 3. Encodes the contract call using viem
946
+ * 4. Estimates gas (catches contract errors early with proper revert
947
+ * reasons)
948
+ * 5. Sends transaction with pre-estimated gas via
949
+ * ethWallet.sendTransaction()
950
+ *
951
+ * The PopSignature must be obtained via
952
+ * {@link signProofOfPossession} before this call.
953
+ *
954
+ * @param params - Registration parameters including the PopSignature
955
+ * and the prepared Pre-PegIn / PegIn transactions
956
+ * @returns Result containing Ethereum transaction hash and vault ID
957
+ * @throws Error if the PopSignature does not match the connected wallets
958
+ * @throws Error if the vault already exists
959
+ * @throws Error if contract simulation fails (e.g., invalid signature,
960
+ * unauthorized)
961
+ */
962
+ async registerPeginOnChain(e) {
963
+ if (!this.config.ethWallet.account)
964
+ throw new Error("Ethereum wallet account not found");
965
+ const t = this.config.ethWallet.account.address;
966
+ if (!J(
967
+ e.popSignature.depositorEthAddress,
968
+ t
969
+ ))
970
+ throw new Error(
971
+ `Proof of possession was signed for ${e.popSignature.depositorEthAddress} but the Ethereum wallet is currently connected to ${t}. Reconnect the original account or call signProofOfPossession() again.`
972
+ );
973
+ const s = await this.assertPopMatchesBtcWallet(
974
+ e.popSignature
975
+ ), r = e.depositorPayoutBtcAddress ?? await this.config.btcWallet.getAddress(), n = this.resolvePayoutScriptPubKey(
976
+ s,
977
+ r
978
+ );
979
+ return this.createRegistrationClient().registerPeginOnChain({
980
+ unsignedPrePeginTx: e.unsignedPrePeginTx,
981
+ depositorSignedPeginTx: e.depositorSignedPeginTx,
982
+ vaultProvider: e.vaultProvider,
983
+ hashlock: e.hashlock,
984
+ htlcVout: e.htlcVout,
985
+ depositorPayoutScriptPubKey: n,
986
+ depositorBtcPubkeyRaw: s,
987
+ depositorWotsPkHash: e.depositorWotsPkHash,
988
+ popSignature: e.popSignature,
989
+ quotedCommissionBps: e.quotedCommissionBps
990
+ });
991
+ }
992
+ /**
993
+ * Register multiple pegins on Ethereum in a single transaction.
994
+ *
995
+ * Uses the contract's submitPeginRequestBatch() to submit all vault
996
+ * registrations atomically. All vaults must share the same vault provider.
997
+ * The PoP signature is signed once and included in each request.
998
+ *
999
+ * @param params - Batch registration parameters
1000
+ * @returns Batch result with per-vault IDs and single ETH tx hash
1001
+ */
1002
+ async registerPeginBatchOnChain(e) {
1003
+ if (e.requests.length === 0)
1004
+ throw new Error("Batch pegin requires at least one request");
1005
+ if (!this.config.ethWallet.account)
1006
+ throw new Error("Ethereum wallet account not found");
1007
+ const t = this.config.ethWallet.account.address;
1008
+ if (!J(
1009
+ e.popSignature.depositorEthAddress,
1010
+ t
1011
+ ))
1012
+ throw new Error(
1013
+ `Proof of possession was signed for ${e.popSignature.depositorEthAddress} but the Ethereum wallet is currently connected to ${t}. Reconnect the original account or call signProofOfPossession() again.`
1014
+ );
1015
+ const s = await this.assertPopMatchesBtcWallet(
1016
+ e.popSignature
1017
+ ), r = e.requests.map(
1018
+ (n) => this.resolvePayoutScriptPubKey(
1019
+ s,
1020
+ n.depositorPayoutBtcAddress
1021
+ )
1022
+ );
1023
+ return this.createRegistrationClient().registerPeginBatchOnChain({
1024
+ vaultProvider: e.vaultProvider,
1025
+ unsignedPrePeginTx: e.unsignedPrePeginTx,
1026
+ popSignature: e.popSignature,
1027
+ depositorBtcPubkeyRaw: s,
1028
+ quotedCommissionBps: e.quotedCommissionBps,
1029
+ requests: e.requests.map((n, i) => ({
1030
+ depositorSignedPeginTx: n.depositorSignedPeginTx,
1031
+ hashlock: n.hashlock,
1032
+ htlcVout: n.htlcVout,
1033
+ depositorPayoutScriptPubKey: r[i],
1034
+ depositorWotsPkHash: n.depositorWotsPkHash
1035
+ }))
1036
+ });
1037
+ }
1038
+ createRegistrationClient() {
1039
+ return new He({
1040
+ ethWallet: this.config.ethWallet,
1041
+ ethChain: this.config.ethChain,
1042
+ publicClient: this.config.publicClient,
1043
+ btcVaultRegistry: this.config.vaultContracts.btcVaultRegistry,
1044
+ requireQuotedCommissionBps: C(
1045
+ this.config.btcWallet
1046
+ )
1047
+ });
1048
+ }
1049
+ /**
1050
+ * Resolve the BTC scriptPubKey to register as the depositor's payout sink.
1051
+ *
1052
+ * `address` is validated against the verified depositor pubkey, sourced
1053
+ * from `assertPopMatchesBtcWallet`'s return value rather than
1054
+ * `popSignature.depositorBtcPubkey` (which is x-only, parity stripped).
1055
+ * For wallets that expose a compressed key this preserves y-parity end to
1056
+ * end. For Taproot wallets that only expose an x-only key, the helper
1057
+ * itself fails closed for P2WPKH — the parity is unknowable, so the
1058
+ * payout sink must be a P2TR address derived from that same x.
1059
+ *
1060
+ * The helper does not call into the wallet so the batch path can resolve
1061
+ * many requests without any extra adapter reads. Threat closed: a
1062
+ * state-race or stale FE state that lets a non-wallet address reach the
1063
+ * on-chain payout-script registration.
1064
+ */
1065
+ resolvePayoutScriptPubKey(e, t) {
1066
+ if (!se(
1067
+ t,
1068
+ e,
1069
+ this.config.btcNetwork
1070
+ ))
1071
+ throw w(e).length === Qe && oo(t, this.config.btcNetwork) ? new Error(
1072
+ `BTC payout address "${t}" 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.`
1073
+ ) : new Error(
1074
+ `BTC payout address "${t}" 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.`
1075
+ );
1076
+ const s = ne(this.config.btcNetwork);
1077
+ let r;
1078
+ try {
1079
+ r = ge.address.toOutputScript(t, s).toString("hex");
1080
+ } catch {
1081
+ throw new Error(
1082
+ `Invalid BTC payout address: "${t}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
1083
+ );
1084
+ }
1085
+ return r;
1086
+ }
1087
+ /**
1088
+ * Sign a BIP-322 BTC Proof-of-Possession binding the connected BTC
1089
+ * wallet to the connected ETH account for this chain and vault
1090
+ * registry. The returned {@link PopSignature} can be reused across
1091
+ * every register call in the same session.
1092
+ *
1093
+ * The witness is verified against the depositor key before it is
1094
+ * returned — Schnorr for one-item (P2TR), ECDSA over the BIP-322
1095
+ * P2WPKH virtual transaction for two-item — see {@link verifyPopWitness}.
1096
+ *
1097
+ * @throws If the wallet returns a malformed witness or a signature that
1098
+ * does not verify.
1099
+ */
1100
+ async signProofOfPossession() {
1101
+ if (!this.config.ethWallet.account)
1102
+ throw new Error("Ethereum wallet account not found");
1103
+ const e = this.config.ethWallet.account.address, t = _(
1104
+ await this.config.btcWallet.getPublicKeyHex()
1105
+ ), s = this.config.vaultContracts.btcVaultRegistry, r = `${e.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`, n = await this.config.btcWallet.signMessage(
1106
+ r,
1107
+ "bip322-simple"
1108
+ ), i = Tt(n);
1109
+ return eo(
1110
+ new TextEncoder().encode(r),
1111
+ t,
1112
+ i
1113
+ ), { btcPopSignature: i, depositorEthAddress: e, depositorBtcPubkey: t };
1114
+ }
1115
+ /**
1116
+ * Confirm the connected BTC wallet still matches the PoP it produced, and
1117
+ * return the wallet's *raw* pubkey hex (parity-preserving form, as the
1118
+ * wallet adapter returns it). The raw form is required by callers that
1119
+ * validate Native SegWit / P2WPKH addresses, since P2WPKH is derived from
1120
+ * a parity-bearing compressed key — an x-only form would let an attacker
1121
+ * substitute the opposite-parity P2WPKH address.
1122
+ */
1123
+ async assertPopMatchesBtcWallet(e) {
1124
+ const t = await this.config.btcWallet.getPublicKeyHex(), s = _(t), r = _(e.depositorBtcPubkey);
1125
+ if (s !== r)
1126
+ throw new Error(
1127
+ `Proof of possession was signed with BTC pubkey ${r} but the BTC wallet is currently connected to ${s}. Reconnect the original wallet or call signProofOfPossession() again.`
1128
+ );
1129
+ return t;
1130
+ }
1131
+ /**
1132
+ * Gets the configured Bitcoin network.
1133
+ *
1134
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
1135
+ */
1136
+ getNetwork() {
1137
+ return this.config.btcNetwork;
1138
+ }
1139
+ /**
1140
+ * Gets the configured BTCVaultRegistry contract address.
1141
+ *
1142
+ * @returns The Ethereum address of the BTCVaultRegistry contract
1143
+ */
1144
+ getVaultContractAddress() {
1145
+ return this.config.vaultContracts.btcVaultRegistry;
1146
+ }
1147
+ }
1148
+ const no = 80, io = 250, ro = 300, ao = 22, Ee = "ab";
1149
+ function co(o, e) {
1150
+ const t = Ee.repeat(ro), s = w(o).toLowerCase(), r = e.toString(16).padStart(8, "0"), n = `${s}${r}`, i = t.slice(n.length);
1151
+ return `0x${n}${i}`;
1152
+ }
1153
+ function lo(o, e) {
1154
+ const t = (s) => `0x${Ee.repeat(s)}`;
1155
+ return {
1156
+ depositorBtcPubKey: t(32),
1157
+ btcPopSignature: t(no),
1158
+ unsignedPrePeginTx: t(io),
1159
+ depositorSignedPeginTx: co(
1160
+ o,
1161
+ e
1162
+ ),
1163
+ hashlock: t(32),
1164
+ htlcVout: e,
1165
+ referralCode: Re,
1166
+ depositorPayoutBtcAddress: t(ao),
1167
+ depositorWotsPkHash: t(32)
1168
+ };
1169
+ }
1170
+ async function Ho(o) {
1171
+ const {
1172
+ publicClient: e,
1173
+ btcVaultRegistry: t,
1174
+ depositorEthAddress: s,
1175
+ vaultProvider: r,
1176
+ batchSize: n
1177
+ } = o;
1178
+ if (n <= 0)
1179
+ throw new Error(
1180
+ `estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${n})`
1181
+ );
1182
+ const a = await e.readContract({
1183
+ address: t,
1184
+ abi: ee,
1185
+ functionName: "getPegInFee",
1186
+ args: [r]
1187
+ }) * BigInt(n), c = Array.from(
1188
+ { length: n },
1189
+ (d, f) => lo(s, f)
1190
+ ), u = Ce({
1191
+ abi: ee,
1192
+ functionName: "submitPeginRequestBatch",
1193
+ args: [
1194
+ s,
1195
+ r,
1196
+ $e,
1197
+ c
1198
+ ]
1199
+ });
1200
+ return e.estimateGas({
1201
+ to: t,
1202
+ data: u,
1203
+ value: a,
1204
+ account: s
1205
+ });
1206
+ }
1207
+ export {
1208
+ Io as P,
1209
+ St as a,
1210
+ yt as b,
1211
+ Kt as c,
1212
+ Ut as d,
1213
+ Ho as e,
1214
+ Lt as f
1215
+ };
1216
+ //# sourceMappingURL=PeginManager-C9RPOd0L.js.map