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