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