@babylonlabs-io/ts-sdk 0.0.0-semantic-release.2 → 0.1.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 (203) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +124 -6
  3. package/dist/MockEthereumWallet-CKQlH2AM.cjs +2 -0
  4. package/dist/MockEthereumWallet-CKQlH2AM.cjs.map +1 -0
  5. package/dist/MockEthereumWallet-ibdry7pZ.js +127 -0
  6. package/dist/MockEthereumWallet-ibdry7pZ.js.map +1 -0
  7. package/dist/PayoutManager-Dg_i_S7w.cjs +2 -0
  8. package/dist/PayoutManager-Dg_i_S7w.cjs.map +1 -0
  9. package/dist/PayoutManager-rMj54HDh.js +1112 -0
  10. package/dist/PayoutManager-rMj54HDh.js.map +1 -0
  11. package/dist/challengeAssert-34HqeVFH.cjs +2 -0
  12. package/dist/challengeAssert-34HqeVFH.cjs.map +1 -0
  13. package/dist/challengeAssert-DVErOd8l.js +423 -0
  14. package/dist/challengeAssert-DVErOd8l.js.map +1 -0
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.js +62 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/shared/index.cjs +1 -1
  19. package/dist/shared/index.d.ts +3 -1
  20. package/dist/shared/index.d.ts.map +1 -1
  21. package/dist/shared/index.js +5 -1
  22. package/dist/shared/index.js.map +1 -1
  23. package/dist/shared/wallets/__tests__/BitcoinWallet.test.d.ts +2 -0
  24. package/dist/shared/wallets/__tests__/BitcoinWallet.test.d.ts.map +1 -0
  25. package/dist/shared/wallets/__tests__/EthereumWallet.test.d.ts +2 -0
  26. package/dist/shared/wallets/__tests__/EthereumWallet.test.d.ts.map +1 -0
  27. package/dist/shared/wallets/index.d.ts +4 -0
  28. package/dist/shared/wallets/index.d.ts.map +1 -0
  29. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts +106 -0
  30. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -0
  31. package/dist/shared/wallets/interfaces/EthereumWallet.d.ts +6 -0
  32. package/dist/shared/wallets/interfaces/EthereumWallet.d.ts.map +1 -0
  33. package/dist/shared/wallets/interfaces/index.d.ts +4 -0
  34. package/dist/shared/wallets/interfaces/index.d.ts.map +1 -0
  35. package/dist/shared/wallets/mocks/MockBitcoinWallet.d.ts +29 -0
  36. package/dist/shared/wallets/mocks/MockBitcoinWallet.d.ts.map +1 -0
  37. package/dist/shared/wallets/mocks/MockEthereumWallet.d.ts +51 -0
  38. package/dist/shared/wallets/mocks/MockEthereumWallet.d.ts.map +1 -0
  39. package/dist/shared/wallets/mocks/index.d.ts +5 -0
  40. package/dist/shared/wallets/mocks/index.d.ts.map +1 -0
  41. package/dist/tbv/core/clients/index.d.ts +9 -0
  42. package/dist/tbv/core/clients/index.d.ts.map +1 -0
  43. package/dist/tbv/core/clients/mempool/index.d.ts +11 -0
  44. package/dist/tbv/core/clients/mempool/index.d.ts.map +1 -0
  45. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +94 -0
  46. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -0
  47. package/dist/tbv/core/clients/mempool/types.d.ts +98 -0
  48. package/dist/tbv/core/clients/mempool/types.d.ts.map +1 -0
  49. package/dist/tbv/core/contracts/abis/BTCVaultsManager.abi.d.ts +187 -0
  50. package/dist/tbv/core/contracts/abis/BTCVaultsManager.abi.d.ts.map +1 -0
  51. package/dist/tbv/core/contracts/errors.d.ts +50 -0
  52. package/dist/tbv/core/contracts/errors.d.ts.map +1 -0
  53. package/dist/tbv/core/contracts/index.d.ts +11 -0
  54. package/dist/tbv/core/contracts/index.d.ts.map +1 -0
  55. package/dist/tbv/core/index.cjs +1 -1
  56. package/dist/tbv/core/index.d.ts +17 -1
  57. package/dist/tbv/core/index.d.ts.map +1 -1
  58. package/dist/tbv/core/index.js +59 -1
  59. package/dist/tbv/core/index.js.map +1 -1
  60. package/dist/tbv/core/managers/PayoutManager.d.ts +158 -0
  61. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -0
  62. package/dist/tbv/core/managers/PeginManager.d.ts +327 -0
  63. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -0
  64. package/dist/tbv/core/managers/__tests__/PayoutManager.test.d.ts +8 -0
  65. package/dist/tbv/core/managers/__tests__/PayoutManager.test.d.ts.map +1 -0
  66. package/dist/tbv/core/managers/__tests__/PeginManager.test.d.ts +8 -0
  67. package/dist/tbv/core/managers/__tests__/PeginManager.test.d.ts.map +1 -0
  68. package/dist/tbv/core/managers/index.d.ts +75 -0
  69. package/dist/tbv/core/managers/index.d.ts.map +1 -0
  70. package/dist/tbv/core/primitives/index.cjs +2 -0
  71. package/dist/tbv/core/primitives/index.d.ts +77 -0
  72. package/dist/tbv/core/primitives/index.d.ts.map +1 -0
  73. package/dist/tbv/core/primitives/index.js +21 -0
  74. package/dist/tbv/{integrations/morpho → core/primitives}/index.js.map +1 -1
  75. package/dist/tbv/core/primitives/psbt/__tests__/constants.d.ts +137 -0
  76. package/dist/tbv/core/primitives/psbt/__tests__/constants.d.ts.map +1 -0
  77. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +71 -0
  78. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts.map +1 -0
  79. package/dist/tbv/core/primitives/psbt/__tests__/payout.test.d.ts +8 -0
  80. package/dist/tbv/core/primitives/psbt/__tests__/payout.test.d.ts.map +1 -0
  81. package/dist/tbv/core/primitives/psbt/__tests__/pegin.test.d.ts +5 -0
  82. package/dist/tbv/core/primitives/psbt/__tests__/pegin.test.d.ts.map +1 -0
  83. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +27 -0
  84. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -0
  85. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts +27 -0
  86. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts.map +1 -0
  87. package/dist/tbv/core/primitives/psbt/index.d.ts +27 -0
  88. package/dist/tbv/core/primitives/psbt/index.d.ts.map +1 -0
  89. package/dist/tbv/core/primitives/psbt/noPayout.d.ts +28 -0
  90. package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -0
  91. package/dist/tbv/core/primitives/psbt/payout.d.ts +99 -0
  92. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -0
  93. package/dist/tbv/core/primitives/psbt/pegin.d.ts +88 -0
  94. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -0
  95. package/dist/tbv/core/primitives/scripts/__tests__/payout.test.d.ts +5 -0
  96. package/dist/tbv/core/primitives/scripts/__tests__/payout.test.d.ts.map +1 -0
  97. package/dist/tbv/core/primitives/scripts/index.d.ts +10 -0
  98. package/dist/tbv/core/primitives/scripts/index.d.ts.map +1 -0
  99. package/dist/tbv/core/primitives/scripts/payout.d.ts +102 -0
  100. package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -0
  101. package/dist/tbv/core/primitives/utils/__tests__/bitcoin.test.d.ts +5 -0
  102. package/dist/tbv/core/primitives/utils/__tests__/bitcoin.test.d.ts.map +1 -0
  103. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +132 -0
  104. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -0
  105. package/dist/tbv/core/primitives/utils/index.d.ts +9 -0
  106. package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -0
  107. package/dist/tbv/core/utils/btc/index.d.ts +10 -0
  108. package/dist/tbv/core/utils/btc/index.d.ts.map +1 -0
  109. package/dist/tbv/core/utils/btc/psbtInputFields.d.ts +41 -0
  110. package/dist/tbv/core/utils/btc/psbtInputFields.d.ts.map +1 -0
  111. package/dist/tbv/core/utils/btc/scriptType.d.ts +34 -0
  112. package/dist/tbv/core/utils/btc/scriptType.d.ts.map +1 -0
  113. package/dist/tbv/core/utils/fee/constants.d.ts +25 -0
  114. package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -0
  115. package/dist/tbv/core/utils/fee/index.d.ts +7 -0
  116. package/dist/tbv/core/utils/fee/index.d.ts.map +1 -0
  117. package/dist/tbv/core/utils/index.d.ts +16 -0
  118. package/dist/tbv/core/utils/index.d.ts.map +1 -0
  119. package/dist/tbv/core/utils/transaction/__tests__/btcTxHash.test.d.ts +5 -0
  120. package/dist/tbv/core/utils/transaction/__tests__/btcTxHash.test.d.ts.map +1 -0
  121. package/dist/tbv/core/utils/transaction/__tests__/createSplitTransaction.test.d.ts +5 -0
  122. package/dist/tbv/core/utils/transaction/__tests__/createSplitTransaction.test.d.ts.map +1 -0
  123. package/dist/tbv/core/utils/transaction/__tests__/fundPeginTransaction.test.d.ts +5 -0
  124. package/dist/tbv/core/utils/transaction/__tests__/fundPeginTransaction.test.d.ts.map +1 -0
  125. package/dist/tbv/core/utils/transaction/btcTxHash.d.ts +15 -0
  126. package/dist/tbv/core/utils/transaction/btcTxHash.d.ts.map +1 -0
  127. package/dist/tbv/core/utils/transaction/createSplitTransaction.d.ts +106 -0
  128. package/dist/tbv/core/utils/transaction/createSplitTransaction.d.ts.map +1 -0
  129. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +70 -0
  130. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -0
  131. package/dist/tbv/core/utils/transaction/index.d.ts +9 -0
  132. package/dist/tbv/core/utils/transaction/index.d.ts.map +1 -0
  133. package/dist/tbv/core/utils/utxo/__tests__/selectUtxos.test.d.ts +5 -0
  134. package/dist/tbv/core/utils/utxo/__tests__/selectUtxos.test.d.ts.map +1 -0
  135. package/dist/tbv/core/utils/utxo/index.d.ts +7 -0
  136. package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -0
  137. package/dist/tbv/core/utils/utxo/selectUtxos.d.ts +65 -0
  138. package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -0
  139. package/dist/tbv/index.cjs +1 -1
  140. package/dist/tbv/index.js +59 -1
  141. package/dist/tbv/index.js.map +1 -1
  142. package/dist/tbv/integrations/aave/clients/__tests__/spoke.test.d.ts +2 -0
  143. package/dist/tbv/integrations/aave/clients/__tests__/spoke.test.d.ts.map +1 -0
  144. package/dist/tbv/integrations/aave/clients/__tests__/transaction.test.d.ts +2 -0
  145. package/dist/tbv/integrations/aave/clients/__tests__/transaction.test.d.ts.map +1 -0
  146. package/dist/tbv/integrations/aave/clients/abis/AaveIntegrationController.abi.json.d.ts +1879 -0
  147. package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +1262 -0
  148. package/dist/tbv/integrations/aave/clients/index.d.ts +4 -0
  149. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -0
  150. package/dist/tbv/integrations/aave/clients/query.d.ts +27 -0
  151. package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -0
  152. package/dist/tbv/integrations/aave/clients/spoke.d.ts +161 -0
  153. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -0
  154. package/dist/tbv/integrations/aave/clients/transaction.d.ts +110 -0
  155. package/dist/tbv/integrations/aave/clients/transaction.d.ts.map +1 -0
  156. package/dist/tbv/integrations/aave/config.d.ts +7 -0
  157. package/dist/tbv/integrations/aave/config.d.ts.map +1 -0
  158. package/dist/tbv/integrations/aave/constants.d.ts +113 -0
  159. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -0
  160. package/dist/tbv/integrations/aave/index.cjs +2 -0
  161. package/dist/tbv/integrations/aave/index.cjs.map +1 -0
  162. package/dist/tbv/integrations/aave/index.d.ts +53 -0
  163. package/dist/tbv/integrations/aave/index.d.ts.map +1 -0
  164. package/dist/tbv/integrations/aave/index.js +307 -0
  165. package/dist/tbv/integrations/aave/index.js.map +1 -0
  166. package/dist/tbv/integrations/aave/types.d.ts +66 -0
  167. package/dist/tbv/integrations/aave/types.d.ts.map +1 -0
  168. package/dist/tbv/integrations/aave/utils/__tests__/aaveConversions.test.d.ts +5 -0
  169. package/dist/tbv/integrations/aave/utils/__tests__/aaveConversions.test.d.ts.map +1 -0
  170. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts +5 -0
  171. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts.map +1 -0
  172. package/dist/tbv/integrations/aave/utils/__tests__/debtUtils.test.d.ts +5 -0
  173. package/dist/tbv/integrations/aave/utils/__tests__/debtUtils.test.d.ts.map +1 -0
  174. package/dist/tbv/integrations/aave/utils/__tests__/healthFactor.test.d.ts +5 -0
  175. package/dist/tbv/integrations/aave/utils/__tests__/healthFactor.test.d.ts.map +1 -0
  176. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts +2 -0
  177. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts.map +1 -0
  178. package/dist/tbv/integrations/aave/utils/__tests__/vaultSplit.test.d.ts +5 -0
  179. package/dist/tbv/integrations/aave/utils/__tests__/vaultSplit.test.d.ts.map +1 -0
  180. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts +24 -0
  181. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts.map +1 -0
  182. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts +15 -0
  183. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts.map +1 -0
  184. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts +14 -0
  185. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts.map +1 -0
  186. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +108 -0
  187. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -0
  188. package/dist/tbv/integrations/aave/utils/index.d.ts +10 -0
  189. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -0
  190. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts +33 -0
  191. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts.map +1 -0
  192. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts +191 -0
  193. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -0
  194. package/package.json +37 -7
  195. package/dist/shared/__tests__/example.test.d.ts +0 -6
  196. package/dist/shared/__tests__/example.test.d.ts.map +0 -1
  197. package/dist/tbv/core/__tests__/example.test.d.ts +0 -6
  198. package/dist/tbv/core/__tests__/example.test.d.ts.map +0 -1
  199. package/dist/tbv/integrations/morpho/index.cjs +0 -2
  200. package/dist/tbv/integrations/morpho/index.d.ts +0 -2
  201. package/dist/tbv/integrations/morpho/index.d.ts.map +0 -1
  202. package/dist/tbv/integrations/morpho/index.js +0 -2
  203. /package/dist/tbv/{integrations/morpho → core/primitives}/index.cjs.map +0 -0
@@ -0,0 +1,1112 @@
1
+ var X = Object.defineProperty;
2
+ var L = (n, t, e) => t in n ? X(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var I = (n, t, e) => L(n, typeof t != "symbol" ? t + "" : t, e);
4
+ import * as $ from "bitcoinjs-lib";
5
+ import { script as D, Transaction as E, address as q, Psbt as S } from "bitcoinjs-lib";
6
+ import { Buffer as p } from "buffer";
7
+ import { m as C, s as T, b as z, k as j, v as A, a as O, e as W } from "./challengeAssert-DVErOd8l.js";
8
+ import { createPublicClient as F, http as M, encodeFunctionData as Y, zeroAddress as J } from "viem";
9
+ import "@babylonlabs-io/babylon-tbv-rust-wasm";
10
+ import "@bitcoin-js/tiny-secp256k1-asmjs";
11
+ const Z = 58, V = 43, G = 11, N = 546, H = BigInt(N), Q = 30, tt = 2, mt = 1.1;
12
+ function et(n) {
13
+ return n <= tt ? Q : 0;
14
+ }
15
+ function nt(n, t, e) {
16
+ if (n.length === 0)
17
+ throw new Error("Insufficient funds: no UTXOs available");
18
+ const s = n.filter((r) => {
19
+ const c = p.from(r.scriptPubKey, "hex");
20
+ return !!D.decompile(c);
21
+ });
22
+ if (s.length === 0)
23
+ throw new Error(
24
+ "Insufficient funds: no valid UTXOs available (all have invalid scripts)"
25
+ );
26
+ const a = [...s].sort((r, c) => c.value - r.value), o = [];
27
+ let u = 0n, i = 0n;
28
+ for (const r of a) {
29
+ o.push(r), u += BigInt(r.value);
30
+ const c = o.length * Z, l = 2 * V, d = c + l + G;
31
+ if (i = BigInt(Math.ceil(d * e)) + BigInt(et(e)), u - t - i > H) {
32
+ const g = BigInt(
33
+ Math.ceil(V * e)
34
+ );
35
+ i += g;
36
+ }
37
+ if (u >= t + i) {
38
+ const g = u - t - i;
39
+ return {
40
+ selectedUTXOs: o,
41
+ totalValue: u,
42
+ fee: i,
43
+ changeAmount: g
44
+ };
45
+ }
46
+ }
47
+ throw new Error(
48
+ `Insufficient funds: need ${t + i} sats (${t} pegin + ${i} fee), have ${u} sats`
49
+ );
50
+ }
51
+ function wt(n) {
52
+ return n > H;
53
+ }
54
+ function xt() {
55
+ return N;
56
+ }
57
+ function st(n) {
58
+ const e = n.substring(8, 12) === "0001" ? 12 : 8, s = parseInt(
59
+ n.substring(e, e + 2),
60
+ 16
61
+ ), a = parseInt(
62
+ n.substring(e + 2, e + 4),
63
+ 16
64
+ );
65
+ if (s !== 0)
66
+ throw new Error(`Expected 0 inputs from WASM, got ${s}`);
67
+ if (a === 0)
68
+ throw new Error("Expected at least 1 output from WASM, got 0");
69
+ const o = p.from(n.substring(0, 8), "hex").readUInt32LE(0), u = p.from(
70
+ n.substring(n.length - 8),
71
+ "hex"
72
+ ).readUInt32LE(0), i = [];
73
+ let r = e + 4;
74
+ for (let c = 0; c < a; c++) {
75
+ const l = n.substring(r, r + 16), d = Number(p.from(l, "hex").readBigUInt64LE(0));
76
+ r += 16;
77
+ const f = parseInt(n.substring(r, r + 2), 16);
78
+ r += 2;
79
+ const g = n.substring(r, r + f * 2), b = p.from(g, "hex");
80
+ r += f * 2, i.push({ value: d, script: b });
81
+ }
82
+ return { version: o, locktime: u, outputs: i };
83
+ }
84
+ function rt(n) {
85
+ const { unfundedTxHex: t, selectedUTXOs: e, changeAddress: s, changeAmount: a, network: o } = n, { version: u, locktime: i, outputs: r } = st(t), c = new $.Transaction();
86
+ c.version = u, c.locktime = i;
87
+ for (const l of e) {
88
+ const d = p.from(l.txid, "hex").reverse();
89
+ c.addInput(d, l.vout);
90
+ }
91
+ for (const l of r)
92
+ c.addOutput(l.script, l.value);
93
+ if (a > H) {
94
+ const l = $.address.toOutputScript(s, o);
95
+ c.addOutput(l, Number(a));
96
+ }
97
+ return c.toHex();
98
+ }
99
+ function R(n) {
100
+ const t = n.startsWith("0x") ? n.slice(2) : n;
101
+ return `0x${E.fromHex(t).getId()}`;
102
+ }
103
+ function Pt(n, t, e) {
104
+ if (n.length === 0)
105
+ throw new Error("No input UTXOs provided for split transaction");
106
+ if (t.length === 0)
107
+ throw new Error("No outputs specified for split transaction");
108
+ for (const r of t)
109
+ if (r.amount <= 0n)
110
+ throw new Error(
111
+ `Invalid output amount for ${r.address}: ${r.amount} satoshis. Amount must be greater than zero.`
112
+ );
113
+ const s = C(e), a = new E();
114
+ a.version = 2;
115
+ for (const r of n) {
116
+ const c = p.from(r.txid, "hex").reverse();
117
+ a.addInput(c, r.vout);
118
+ }
119
+ const o = [];
120
+ for (let r = 0; r < t.length; r++) {
121
+ const c = t[r];
122
+ let l;
123
+ try {
124
+ l = q.toOutputScript(c.address, s);
125
+ } catch (d) {
126
+ throw new Error(
127
+ `Failed to decode address "${c.address}": ${d instanceof Error ? d.message : String(d)}`
128
+ );
129
+ }
130
+ a.addOutput(l, Number(c.amount)), o.push({
131
+ txid: "",
132
+ // Will be set after txid calculation
133
+ vout: r,
134
+ value: Number(c.amount),
135
+ scriptPubKey: l.toString("hex")
136
+ });
137
+ }
138
+ const u = a.toHex(), i = a.getId();
139
+ for (const r of o)
140
+ r.txid = i;
141
+ return {
142
+ txHex: u,
143
+ txid: i,
144
+ outputs: o
145
+ };
146
+ }
147
+ function Tt(n, t, e) {
148
+ const s = E.fromHex(n), a = new S();
149
+ if (a.setVersion(s.version), a.setLocktime(s.locktime), !p.isBuffer(e) || e.length !== 32)
150
+ throw new Error(
151
+ `Invalid publicKeyNoCoord: expected 32-byte Buffer (x-only pubkey), got ${p.isBuffer(e) ? `${e.length}-byte Buffer` : typeof e}`
152
+ );
153
+ if (t.length !== s.ins.length)
154
+ throw new Error(
155
+ `UTXO count mismatch: transaction has ${s.ins.length} input${s.ins.length !== 1 ? "s" : ""}, but ${t.length} UTXO${t.length !== 1 ? "s were" : " was"} provided`
156
+ );
157
+ for (let o = 0; o < s.ins.length; o++) {
158
+ const u = s.ins[o], i = t[o];
159
+ if (!i)
160
+ throw new Error(`Missing UTXO data for input ${o}`);
161
+ const r = p.from(u.hash).reverse().toString("hex"), c = u.index;
162
+ if (i.txid !== r || i.vout !== c)
163
+ throw new Error(
164
+ `Input ${o} outpoint mismatch: transaction expects ${r}:${c}, but UTXO ${i.txid}:${i.vout} was provided. Ensure inputs array matches the order used in createSplitTransaction().`
165
+ );
166
+ const l = p.from(i.scriptPubKey, "hex");
167
+ if (!(l.length === 34 && l[0] === 81 && // OP_1 (witness version 1)
168
+ l[1] === 32))
169
+ throw new Error(
170
+ `Input ${o} must be P2TR (Taproot). createSplitTransactionPsbt() requires P2TR inputs because it uses tapInternalKey for Taproot signing. ScriptPubKey: ${i.scriptPubKey.substring(0, 20)}...`
171
+ );
172
+ const f = {
173
+ script: p.from(i.scriptPubKey, "hex"),
174
+ value: i.value
175
+ };
176
+ a.addInput({
177
+ hash: u.hash,
178
+ index: u.index,
179
+ sequence: u.sequence,
180
+ witnessUtxo: f,
181
+ tapInternalKey: e
182
+ });
183
+ }
184
+ for (const o of s.outs)
185
+ a.addOutput({
186
+ script: o.script,
187
+ value: o.value
188
+ });
189
+ return a.toHex();
190
+ }
191
+ var v = /* @__PURE__ */ ((n) => (n.P2PKH = "P2PKH", n.P2SH = "P2SH", n.P2WPKH = "P2WPKH", n.P2WSH = "P2WSH", n.P2TR = "P2TR", n.UNKNOWN = "UNKNOWN", n))(v || {});
192
+ function ot(n) {
193
+ const t = n.length;
194
+ return t === 25 && n[0] === 118 && // OP_DUP
195
+ n[1] === 169 && // OP_HASH160
196
+ n[2] === 20 && // Push 20 bytes
197
+ n[23] === 136 && // OP_EQUALVERIFY
198
+ n[24] === 172 ? "P2PKH" : t === 23 && n[0] === 169 && // OP_HASH160
199
+ n[1] === 20 && // Push 20 bytes
200
+ n[22] === 135 ? "P2SH" : t === 22 && n[0] === 0 && // OP_0
201
+ n[1] === 20 ? "P2WPKH" : t === 34 && n[0] === 0 && // OP_0
202
+ n[1] === 32 ? "P2WSH" : t === 34 && n[0] === 81 && // OP_1
203
+ n[1] === 32 ? "P2TR" : "UNKNOWN";
204
+ }
205
+ function at(n, t) {
206
+ const e = p.from(n.scriptPubKey, "hex"), s = ot(e);
207
+ switch (s) {
208
+ case v.P2WPKH:
209
+ return {
210
+ witnessUtxo: {
211
+ script: e,
212
+ value: n.value
213
+ }
214
+ };
215
+ case v.P2WSH: {
216
+ if (!n.witnessScript)
217
+ throw new Error("Missing witnessScript for P2WSH input");
218
+ return {
219
+ witnessUtxo: {
220
+ script: e,
221
+ value: n.value
222
+ },
223
+ witnessScript: p.from(n.witnessScript, "hex")
224
+ };
225
+ }
226
+ case v.P2TR: {
227
+ if (t && t.length !== 32)
228
+ throw new Error(
229
+ `Invalid tapInternalKey length: expected 32 bytes, got ${t.length}`
230
+ );
231
+ return {
232
+ witnessUtxo: {
233
+ script: e,
234
+ value: n.value
235
+ },
236
+ // tapInternalKey is needed for Taproot signing
237
+ ...t && { tapInternalKey: t }
238
+ };
239
+ }
240
+ default:
241
+ throw new Error(`Unsupported script type: ${s}`);
242
+ }
243
+ }
244
+ const it = {
245
+ mainnet: "https://mempool.space/api",
246
+ testnet: "https://mempool.space/testnet/api",
247
+ signet: "https://mempool.space/signet/api"
248
+ };
249
+ async function k(n, t) {
250
+ try {
251
+ const e = await fetch(n, t);
252
+ if (!e.ok) {
253
+ const a = await e.text();
254
+ throw new Error(
255
+ `Mempool API error (${e.status}): ${a || e.statusText}`
256
+ );
257
+ }
258
+ const s = e.headers.get("content-type");
259
+ return s != null && s.includes("application/json") ? await e.json() : await e.text();
260
+ } catch (e) {
261
+ throw e instanceof Error ? new Error(`Failed to fetch from mempool API: ${e.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
262
+ }
263
+ }
264
+ async function ct(n, t) {
265
+ try {
266
+ const e = await fetch(`${t}/tx`, {
267
+ method: "POST",
268
+ body: n,
269
+ headers: {
270
+ "Content-Type": "text/plain"
271
+ }
272
+ });
273
+ if (!e.ok) {
274
+ const a = await e.text();
275
+ let o;
276
+ try {
277
+ o = JSON.parse(a).message;
278
+ } catch {
279
+ o = a;
280
+ }
281
+ throw new Error(
282
+ o || `Failed to broadcast transaction: ${e.statusText}`
283
+ );
284
+ }
285
+ return await e.text();
286
+ } catch (e) {
287
+ throw e instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${e.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
288
+ }
289
+ }
290
+ async function ut(n, t) {
291
+ return k(`${t}/tx/${n}`);
292
+ }
293
+ async function vt(n, t) {
294
+ try {
295
+ const e = await fetch(`${t}/tx/${n}/hex`);
296
+ if (!e.ok) {
297
+ const s = await e.text();
298
+ throw new Error(
299
+ `Mempool API error (${e.status}): ${s || e.statusText}`
300
+ );
301
+ }
302
+ return await e.text();
303
+ } catch (e) {
304
+ throw e instanceof Error ? new Error(`Failed to get transaction hex for ${n}: ${e.message}`) : new Error(`Failed to get transaction hex for ${n}: Unknown error`);
305
+ }
306
+ }
307
+ async function lt(n, t, e) {
308
+ const s = await ut(n, e);
309
+ if (t >= s.vout.length)
310
+ throw new Error(
311
+ `Invalid vout ${t} for transaction ${n} (has ${s.vout.length} outputs)`
312
+ );
313
+ const a = s.vout[t];
314
+ return {
315
+ txid: n,
316
+ vout: t,
317
+ value: a.value,
318
+ scriptPubKey: a.scriptpubkey
319
+ };
320
+ }
321
+ async function kt(n, t) {
322
+ try {
323
+ const e = await k(`${t}/address/${n}/utxo`), s = await k(`${t}/v1/validate-address/${n}`);
324
+ if (!s.isvalid)
325
+ throw new Error(
326
+ `Invalid Bitcoin address: ${n}. Mempool API validation failed.`
327
+ );
328
+ return e.sort((o, u) => u.value - o.value).map((o) => ({
329
+ txid: o.txid,
330
+ vout: o.vout,
331
+ value: o.value,
332
+ scriptPubKey: s.scriptPubKey,
333
+ confirmed: o.status.confirmed
334
+ }));
335
+ } catch (e) {
336
+ throw e instanceof Error ? new Error(
337
+ `Failed to get UTXOs for address ${n}: ${e.message}`
338
+ ) : new Error(
339
+ `Failed to get UTXOs for address ${n}: Unknown error`
340
+ );
341
+ }
342
+ }
343
+ function Et(n) {
344
+ return it[n];
345
+ }
346
+ async function It(n, t) {
347
+ return k(`${t}/address/${n}/txs`);
348
+ }
349
+ async function Bt(n) {
350
+ const t = await fetch(`${n}/v1/fees/recommended`);
351
+ if (!t.ok)
352
+ throw new Error(
353
+ `Failed to fetch network fees: ${t.status} ${t.statusText}`
354
+ );
355
+ const e = await t.json();
356
+ if (typeof e.fastestFee != "number" || typeof e.halfHourFee != "number" || typeof e.hourFee != "number" || typeof e.economyFee != "number" || typeof e.minimumFee != "number")
357
+ throw new Error(
358
+ "Invalid fee data structure from mempool API. Expected all fee fields to be numbers."
359
+ );
360
+ return e;
361
+ }
362
+ const B = [
363
+ {
364
+ type: "function",
365
+ name: "submitPeginRequest",
366
+ inputs: [
367
+ {
368
+ name: "depositor",
369
+ type: "address",
370
+ internalType: "address"
371
+ },
372
+ {
373
+ name: "depositorBtcPubKey",
374
+ type: "bytes32",
375
+ internalType: "bytes32"
376
+ },
377
+ {
378
+ name: "btcPopSignature",
379
+ type: "bytes",
380
+ internalType: "bytes"
381
+ },
382
+ {
383
+ name: "unsignedPegInTx",
384
+ type: "bytes",
385
+ internalType: "bytes"
386
+ },
387
+ {
388
+ name: "vaultProvider",
389
+ type: "address",
390
+ internalType: "address"
391
+ },
392
+ {
393
+ name: "depositorPayoutBtcAddress",
394
+ type: "bytes",
395
+ internalType: "bytes"
396
+ },
397
+ {
398
+ name: "depositorLamportPkHash",
399
+ type: "bytes32",
400
+ internalType: "bytes32"
401
+ }
402
+ ],
403
+ outputs: [
404
+ {
405
+ name: "",
406
+ type: "bytes32",
407
+ internalType: "bytes32"
408
+ }
409
+ ],
410
+ stateMutability: "payable"
411
+ },
412
+ {
413
+ type: "function",
414
+ name: "submitPeginRequest",
415
+ inputs: [
416
+ {
417
+ name: "depositor",
418
+ type: "address",
419
+ internalType: "address"
420
+ },
421
+ {
422
+ name: "depositorBtcPubKey",
423
+ type: "bytes32",
424
+ internalType: "bytes32"
425
+ },
426
+ {
427
+ name: "btcPopSignature",
428
+ type: "bytes",
429
+ internalType: "bytes"
430
+ },
431
+ {
432
+ name: "unsignedPegInTx",
433
+ type: "bytes",
434
+ internalType: "bytes"
435
+ },
436
+ {
437
+ name: "vaultProvider",
438
+ type: "address",
439
+ internalType: "address"
440
+ },
441
+ {
442
+ name: "referralCode",
443
+ type: "uint32",
444
+ internalType: "uint32"
445
+ },
446
+ {
447
+ name: "depositorPayoutBtcAddress",
448
+ type: "bytes",
449
+ internalType: "bytes"
450
+ },
451
+ {
452
+ name: "depositorLamportPkHash",
453
+ type: "bytes32",
454
+ internalType: "bytes32"
455
+ }
456
+ ],
457
+ outputs: [
458
+ {
459
+ name: "",
460
+ type: "bytes32",
461
+ internalType: "bytes32"
462
+ }
463
+ ],
464
+ stateMutability: "payable"
465
+ },
466
+ {
467
+ type: "function",
468
+ name: "getPegInFee",
469
+ inputs: [
470
+ {
471
+ name: "vaultProvider",
472
+ type: "address",
473
+ internalType: "address"
474
+ }
475
+ ],
476
+ outputs: [
477
+ {
478
+ name: "totalFee",
479
+ type: "uint256",
480
+ internalType: "uint256"
481
+ }
482
+ ],
483
+ stateMutability: "view"
484
+ },
485
+ {
486
+ type: "function",
487
+ name: "getBTCVault",
488
+ inputs: [
489
+ {
490
+ name: "vaultId",
491
+ type: "bytes32",
492
+ internalType: "bytes32"
493
+ }
494
+ ],
495
+ outputs: [
496
+ {
497
+ name: "vault",
498
+ type: "tuple",
499
+ internalType: "struct IBTCVaultsManager.BTCVault",
500
+ components: [
501
+ { name: "depositor", type: "address", internalType: "address" },
502
+ { name: "depositorBtcPubKey", type: "bytes32", internalType: "bytes32" },
503
+ { name: "unsignedPegInTx", type: "bytes", internalType: "bytes" },
504
+ { name: "amount", type: "uint256", internalType: "uint256" },
505
+ { name: "vaultProvider", type: "address", internalType: "address" },
506
+ { name: "status", type: "uint8", internalType: "enum IBTCVaultsManager.BTCVaultStatus" },
507
+ { name: "applicationController", type: "address", internalType: "address" },
508
+ { name: "universalChallengersVersion", type: "uint16", internalType: "uint16" },
509
+ { name: "appVaultKeepersVersion", type: "uint16", internalType: "uint16" },
510
+ { name: "offchainParamsVersion", type: "uint16", internalType: "uint16" },
511
+ { name: "createdAt", type: "uint256", internalType: "uint256" },
512
+ { name: "verifiedAt", type: "uint256", internalType: "uint256" },
513
+ { name: "depositorLamportPkHash", type: "bytes32", internalType: "bytes32" }
514
+ ]
515
+ }
516
+ ],
517
+ stateMutability: "view"
518
+ },
519
+ {
520
+ type: "error",
521
+ name: "InvalidPeginFee",
522
+ inputs: [
523
+ {
524
+ name: "provided",
525
+ type: "uint256",
526
+ internalType: "uint256"
527
+ },
528
+ {
529
+ name: "required",
530
+ type: "uint256",
531
+ internalType: "uint256"
532
+ }
533
+ ]
534
+ }
535
+ ], x = {
536
+ // VaultAlreadyExists()
537
+ "0x04aabf33": "Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.",
538
+ // ScriptPubKeyMismatch() - taproot output doesn't match expected script
539
+ "0x4fec082d": "Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.",
540
+ // InvalidBTCProofOfPossession()
541
+ "0x6cc363a5": "Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.",
542
+ // InvalidBTCPublicKey()
543
+ "0x6c3f2bf6": "Invalid BTC public key: The Bitcoin public key format is invalid.",
544
+ // InvalidAmount()
545
+ "0x2c5211c6": "Invalid amount: The deposit amount is invalid or below the minimum required.",
546
+ // ApplicationNotRegistered()
547
+ "0x0405f772": "Application not registered: The application controller is not registered in the system.",
548
+ // InvalidProviderStatus()
549
+ "0x24e165cc": "Invalid provider status: The vault provider is not in a valid state to accept deposits.",
550
+ // ZeroAddress()
551
+ "0xd92e233d": "Zero address: One of the required addresses is the zero address.",
552
+ // BtcKeyMismatch()
553
+ "0x65aa7007": "BTC key mismatch: The Bitcoin public key does not match the expected key.",
554
+ // Unauthorized()
555
+ "0x82b42900": "Unauthorized: You must be the depositor or vault provider to submit this transaction.",
556
+ // InvalidSignature() - common signature verification error
557
+ "0x8baa579f": "Invalid signature: The BTC proof of possession signature could not be verified.",
558
+ // InvalidBtcTransaction()
559
+ "0x2f9d01e9": "Invalid BTC transaction: The Bitcoin transaction format is invalid.",
560
+ // VaultProviderNotRegistered()
561
+ "0x5a3c6b3e": "Vault provider not registered: The selected vault provider is not registered.",
562
+ // InvalidPeginFee(uint256,uint256)
563
+ "0x979f4518": "Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction."
564
+ };
565
+ function U(n) {
566
+ if (!n || typeof n != "object") return;
567
+ const t = n;
568
+ if (typeof t.data == "string" && t.data.startsWith("0x"))
569
+ return t.data;
570
+ if (typeof t.details == "string" && t.details.startsWith("0x"))
571
+ return t.details;
572
+ let e = t.cause, s = 0;
573
+ const a = 5;
574
+ for (; e && typeof e == "object" && s < a; ) {
575
+ const i = e;
576
+ if (typeof i.data == "string" && i.data.startsWith("0x"))
577
+ return i.data;
578
+ e = i.cause, s++;
579
+ }
580
+ const u = (typeof t.message == "string" ? t.message : "").match(/\b(0x[a-fA-F0-9]{8})\b/);
581
+ if (u)
582
+ return u[1];
583
+ }
584
+ function $t(n) {
585
+ const t = U(n);
586
+ if (t) {
587
+ const e = t.substring(0, 10);
588
+ return x[t] ?? x[e];
589
+ }
590
+ }
591
+ function St(n) {
592
+ const t = U(n);
593
+ if (t === void 0) return !1;
594
+ const e = t.substring(0, 10);
595
+ return t in x || e in x;
596
+ }
597
+ function K(n) {
598
+ console.error("[Contract Error] Raw error:", n);
599
+ const t = U(n);
600
+ if (console.error("[Contract Error] Extracted error data:", t), t) {
601
+ const s = t.substring(0, 10), a = x[t] ?? x[s];
602
+ if (a)
603
+ throw console.error("[Contract Error] Known error:", a), new Error(a);
604
+ }
605
+ const e = (n == null ? void 0 : n.message) || "";
606
+ if (e.includes("gas limit too high") || e.includes("21000000") || e.includes("Internal JSON-RPC error")) {
607
+ const s = t ? ` (error code: ${t})` : "";
608
+ throw console.error(
609
+ "[Contract Error] Transaction rejected. Error code:",
610
+ t,
611
+ "Message:",
612
+ e
613
+ ), new Error(
614
+ `Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`
615
+ );
616
+ }
617
+ throw n instanceof Error ? (console.error("[Contract Error] Unhandled error:", n.message), n) : new Error(`Contract call failed: ${String(n)}`);
618
+ }
619
+ class Ct {
620
+ /**
621
+ * Creates a new PeginManager instance.
622
+ *
623
+ * @param config - Manager configuration including wallets and contract addresses
624
+ */
625
+ constructor(t) {
626
+ I(this, "config");
627
+ this.config = t;
628
+ }
629
+ /**
630
+ * Prepares a peg-in transaction by building and funding it.
631
+ *
632
+ * This method orchestrates the following steps:
633
+ * 1. Get depositor BTC public key from wallet
634
+ * 2. Build unfunded PSBT using primitives
635
+ * 3. Select UTXOs using iterative fee calculation
636
+ * 4. Fund transaction by adding inputs and change output
637
+ *
638
+ * The returned transaction is funded but unsigned. Use `signAndBroadcast()`
639
+ * to complete the Bitcoin side, and `registerPeginOnChain()` for Ethereum.
640
+ *
641
+ * @param params - Peg-in parameters including amount, provider, UTXOs, and fee rate
642
+ * @returns Peg-in result with funded transaction and selection details
643
+ * @throws Error if wallet operations fail or insufficient funds
644
+ */
645
+ async preparePegin(t) {
646
+ const e = await this.config.btcWallet.getPublicKeyHex(), s = e.length === 66 ? e.slice(2) : e, a = T(t.vaultProviderBtcPubkey), o = t.vaultKeeperBtcPubkeys.map(T), u = t.universalChallengerBtcPubkeys.map(T), i = await z({
647
+ depositorPubkey: s,
648
+ vaultProviderPubkey: a,
649
+ vaultKeeperPubkeys: o,
650
+ universalChallengerPubkeys: u,
651
+ timelockPegin: t.timelockPegin,
652
+ pegInAmount: t.amount,
653
+ depositorClaimValue: t.depositorClaimValue,
654
+ network: this.config.btcNetwork
655
+ }), r = t.amount + t.depositorClaimValue, c = nt(
656
+ t.availableUTXOs,
657
+ r,
658
+ t.feeRate
659
+ ), l = C(this.config.btcNetwork), d = rt({
660
+ unfundedTxHex: i.psbtHex,
661
+ selectedUTXOs: c.selectedUTXOs,
662
+ changeAddress: t.changeAddress,
663
+ changeAmount: c.changeAmount,
664
+ network: l
665
+ }), f = R(d);
666
+ return {
667
+ btcTxHash: T(f),
668
+ fundedTxHex: d,
669
+ vaultScriptPubKey: i.vaultScriptPubKey,
670
+ selectedUTXOs: c.selectedUTXOs,
671
+ fee: c.fee,
672
+ changeAmount: c.changeAmount,
673
+ ethTxHash: null
674
+ };
675
+ }
676
+ /**
677
+ * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.
678
+ *
679
+ * This method:
680
+ * 1. Parses the funded transaction hex
681
+ * 2. Fetches UTXO data from mempool for each input
682
+ * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey
683
+ * 4. Signs via btcWallet.signPsbt()
684
+ * 5. Finalizes and extracts the transaction
685
+ * 6. Broadcasts via mempool API
686
+ *
687
+ * @param params - Transaction hex and depositor public key
688
+ * @returns The broadcasted Bitcoin transaction ID
689
+ * @throws Error if signing or broadcasting fails
690
+ */
691
+ async signAndBroadcast(t) {
692
+ const { fundedTxHex: e, depositorBtcPubkey: s } = t, a = e.startsWith("0x") ? e.slice(2) : e, o = E.fromHex(a);
693
+ if (o.ins.length === 0)
694
+ throw new Error("Transaction has no inputs");
695
+ const u = new S();
696
+ u.setVersion(o.version), u.setLocktime(o.locktime);
697
+ const i = s.startsWith("0x") ? s.slice(2) : s;
698
+ if (i.length !== 64 || !/^[0-9a-fA-F]+$/.test(i))
699
+ throw new Error(
700
+ "Invalid depositorBtcPubkey: expected 64 hex characters (x-only pubkey)"
701
+ );
702
+ const r = p.from(i, "hex");
703
+ if (r.length !== 32)
704
+ throw new Error(
705
+ `Invalid depositorBtcPubkey length: expected 32 bytes, got ${r.length}`
706
+ );
707
+ const c = this.config.mempoolApiUrl, l = o.ins.map((h) => {
708
+ const y = p.from(h.hash).reverse().toString("hex"), m = h.index;
709
+ return lt(y, m, c).then((P) => ({
710
+ input: h,
711
+ utxoData: P,
712
+ txid: y,
713
+ vout: m
714
+ }));
715
+ }), d = await Promise.all(l);
716
+ for (const { input: h, utxoData: y, txid: m, vout: P } of d) {
717
+ const w = at(
718
+ {
719
+ value: y.value,
720
+ scriptPubKey: y.scriptPubKey
721
+ },
722
+ r
723
+ );
724
+ u.addInput({
725
+ hash: h.hash,
726
+ index: h.index,
727
+ sequence: h.sequence,
728
+ ...w
729
+ });
730
+ }
731
+ for (const h of o.outs)
732
+ u.addOutput({
733
+ script: h.script,
734
+ value: h.value
735
+ });
736
+ const f = await this.config.btcWallet.signPsbt(u.toHex()), g = S.fromHex(f);
737
+ try {
738
+ g.finalizeAllInputs();
739
+ } catch {
740
+ }
741
+ const b = g.extractTransaction().toHex();
742
+ return await ct(b, c);
743
+ }
744
+ /**
745
+ * Registers a peg-in on Ethereum by calling the BTCVaultsManager contract.
746
+ *
747
+ * This method:
748
+ * 1. Gets depositor ETH address from wallet
749
+ * 2. Creates proof of possession (BTC signature of ETH address)
750
+ * 3. Checks if vault already exists (pre-flight check)
751
+ * 4. Encodes the contract call using viem
752
+ * 5. Estimates gas (catches contract errors early with proper revert reasons)
753
+ * 6. Sends transaction with pre-estimated gas via ethWallet.sendTransaction()
754
+ *
755
+ * @param params - Registration parameters including BTC pubkey and unsigned tx
756
+ * @returns Result containing Ethereum transaction hash and vault ID
757
+ * @throws Error if signing or transaction fails
758
+ * @throws Error if vault already exists
759
+ * @throws Error if contract simulation fails (e.g., invalid signature, unauthorized)
760
+ */
761
+ async registerPeginOnChain(t) {
762
+ const {
763
+ depositorBtcPubkey: e,
764
+ unsignedBtcTx: s,
765
+ vaultProvider: a,
766
+ onPopSigned: o,
767
+ depositorPayoutBtcAddress: u,
768
+ depositorLamportPkHash: i,
769
+ preSignedBtcPopSignature: r
770
+ } = t;
771
+ if (!this.config.ethWallet.account)
772
+ throw new Error("Ethereum wallet account not found");
773
+ const c = this.config.ethWallet.account.address, l = await this.resolvePopSignature(
774
+ c,
775
+ r
776
+ );
777
+ o && await o();
778
+ const d = e.startsWith("0x") ? e : `0x${e}`, f = s.startsWith("0x") ? s : `0x${s}`, g = await this.resolvePayoutScriptPubKey(
779
+ u
780
+ ), b = R(f);
781
+ if (await this.checkVaultExists(b))
782
+ throw new Error(
783
+ `Vault already exists for this transaction (ID: ${b}). Vault IDs are deterministically derived from the unsigned Bitcoin transaction, so using the same UTXOs and amount will always produce the same vault. To create a new vault, please use different UTXOs or a different amount to generate a unique transaction.`
784
+ );
785
+ const h = F({
786
+ chain: this.config.ethChain,
787
+ transport: M()
788
+ });
789
+ let y;
790
+ try {
791
+ y = await h.readContract({
792
+ address: this.config.vaultContracts.btcVaultsManager,
793
+ abi: B,
794
+ functionName: "getPegInFee",
795
+ args: [a]
796
+ });
797
+ } catch {
798
+ throw new Error(
799
+ "Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct."
800
+ );
801
+ }
802
+ const m = Y({
803
+ abi: B,
804
+ functionName: "submitPeginRequest",
805
+ args: [
806
+ c,
807
+ d,
808
+ l,
809
+ f,
810
+ a,
811
+ g,
812
+ i
813
+ ]
814
+ });
815
+ let P;
816
+ try {
817
+ P = await h.estimateGas({
818
+ to: this.config.vaultContracts.btcVaultsManager,
819
+ data: m,
820
+ value: y,
821
+ account: this.config.ethWallet.account.address
822
+ });
823
+ } catch (w) {
824
+ K(w);
825
+ }
826
+ try {
827
+ return {
828
+ ethTxHash: await this.config.ethWallet.sendTransaction({
829
+ to: this.config.vaultContracts.btcVaultsManager,
830
+ data: m,
831
+ value: y,
832
+ account: this.config.ethWallet.account,
833
+ chain: this.config.ethChain,
834
+ gas: P
835
+ }),
836
+ vaultId: b,
837
+ btcPopSignature: l
838
+ };
839
+ } catch (w) {
840
+ K(w);
841
+ }
842
+ }
843
+ /**
844
+ * Check if a vault already exists for a given vault ID.
845
+ *
846
+ * @param vaultId - The Bitcoin transaction hash (vault ID)
847
+ * @returns True if vault exists, false otherwise
848
+ */
849
+ async checkVaultExists(t) {
850
+ try {
851
+ return (await F({
852
+ chain: this.config.ethChain,
853
+ transport: M()
854
+ }).readContract({
855
+ address: this.config.vaultContracts.btcVaultsManager,
856
+ abi: B,
857
+ functionName: "getBTCVault",
858
+ args: [t]
859
+ })).depositor !== J;
860
+ } catch {
861
+ return !1;
862
+ }
863
+ }
864
+ /**
865
+ * Resolve the BTC payout address to a scriptPubKey hex for the contract.
866
+ *
867
+ * If a payout address is provided, converts it directly.
868
+ * If omitted, uses the wallet's address and validates it against the
869
+ * wallet's public key to guard against a compromised wallet provider.
870
+ */
871
+ async resolvePayoutScriptPubKey(t) {
872
+ let e;
873
+ if (t)
874
+ e = t;
875
+ else {
876
+ e = await this.config.btcWallet.getAddress();
877
+ const a = await this.config.btcWallet.getPublicKeyHex();
878
+ if (!j(
879
+ e,
880
+ a,
881
+ this.config.btcNetwork
882
+ ))
883
+ throw new Error(
884
+ "The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit)."
885
+ );
886
+ }
887
+ const s = C(this.config.btcNetwork);
888
+ try {
889
+ return `0x${$.address.toOutputScript(e, s).toString("hex")}`;
890
+ } catch {
891
+ throw new Error(
892
+ `Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`
893
+ );
894
+ }
895
+ }
896
+ /**
897
+ * Resolve or create a BTC Proof-of-Possession signature.
898
+ *
899
+ * Reuses a pre-signed signature when provided (e.g. multi-vault deposits),
900
+ * otherwise signs a BIP-322 message with the BTC wallet.
901
+ */
902
+ async resolvePopSignature(t, e) {
903
+ if (e)
904
+ return e;
905
+ const s = this.config.vaultContracts.btcVaultsManager, a = `${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`, o = await this.config.btcWallet.signMessage(
906
+ a,
907
+ "bip322-simple"
908
+ );
909
+ return o.startsWith("0x") ? o : `0x${p.from(o, "base64").toString("hex")}`;
910
+ }
911
+ /**
912
+ * Gets the configured Bitcoin network.
913
+ *
914
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
915
+ */
916
+ getNetwork() {
917
+ return this.config.btcNetwork;
918
+ }
919
+ /**
920
+ * Gets the configured BTCVaultsManager contract address.
921
+ *
922
+ * @returns The Ethereum address of the BTCVaultsManager contract
923
+ */
924
+ getVaultContractAddress() {
925
+ return this.config.vaultContracts.btcVaultsManager;
926
+ }
927
+ }
928
+ class Ht {
929
+ /**
930
+ * Creates a new PayoutManager instance.
931
+ *
932
+ * @param config - Manager configuration including wallet
933
+ */
934
+ constructor(t) {
935
+ I(this, "config");
936
+ this.config = t;
937
+ }
938
+ /**
939
+ * Signs a Payout transaction and extracts the Schnorr signature.
940
+ *
941
+ * Flow:
942
+ * 1. Vault provider submits Claim transaction
943
+ * 2. Claimer submits Assert transaction to prove validity
944
+ * 3. Payout can be executed (references Assert tx)
945
+ *
946
+ * This method orchestrates the following steps:
947
+ * 1. Get wallet's public key and convert to x-only format
948
+ * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)
949
+ * 3. Build unsigned PSBT using primitives
950
+ * 4. Sign PSBT via btcWallet.signPsbt()
951
+ * 5. Extract 64-byte Schnorr signature using primitives
952
+ *
953
+ * The returned signature can be submitted to the vault provider API.
954
+ *
955
+ * @param params - Payout signing parameters
956
+ * @returns Signature result with 64-byte Schnorr signature and depositor pubkey
957
+ * @throws Error if wallet pubkey doesn't match depositor pubkey
958
+ * @throws Error if wallet operations fail or signature extraction fails
959
+ */
960
+ async signPayoutTransaction(t) {
961
+ const e = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: s } = A(
962
+ e,
963
+ t.depositorBtcPubkey
964
+ ), a = await O({
965
+ payoutTxHex: t.payoutTxHex,
966
+ peginTxHex: t.peginTxHex,
967
+ assertTxHex: t.assertTxHex,
968
+ depositorBtcPubkey: s,
969
+ vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
970
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
971
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
972
+ timelockPegin: t.timelockPegin,
973
+ network: this.config.network
974
+ }), o = await this.config.btcWallet.signPsbt(
975
+ a.psbtHex,
976
+ {
977
+ autoFinalized: !1,
978
+ signInputs: [
979
+ {
980
+ index: 0,
981
+ publicKey: e,
982
+ disableTweakSigner: !0
983
+ }
984
+ ]
985
+ }
986
+ );
987
+ return {
988
+ signature: W(o, s),
989
+ depositorBtcPubkey: s
990
+ };
991
+ }
992
+ /**
993
+ * Gets the configured Bitcoin network.
994
+ *
995
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
996
+ */
997
+ getNetwork() {
998
+ return this.config.network;
999
+ }
1000
+ /**
1001
+ * Checks if the wallet supports batch signing (signPsbts).
1002
+ *
1003
+ * @returns true if batch signing is supported
1004
+ */
1005
+ supportsBatchSigning() {
1006
+ return typeof this.config.btcWallet.signPsbts == "function";
1007
+ }
1008
+ /**
1009
+ * Batch signs multiple payout transactions (1 per claimer).
1010
+ * This allows signing all transactions with a single wallet interaction.
1011
+ *
1012
+ * @param transactions - Array of payout params to sign
1013
+ * @returns Array of signature results matching input order
1014
+ * @throws Error if wallet doesn't support batch signing
1015
+ * @throws Error if any signing operation fails
1016
+ */
1017
+ async signPayoutTransactionsBatch(t) {
1018
+ if (!this.supportsBatchSigning())
1019
+ throw new Error(
1020
+ "Wallet does not support batch signing (signPsbts method not available)"
1021
+ );
1022
+ const e = await this.config.btcWallet.getPublicKeyHex(), s = [], a = [], o = [];
1023
+ for (const r of t) {
1024
+ const { depositorPubkey: c } = A(
1025
+ e,
1026
+ r.depositorBtcPubkey
1027
+ );
1028
+ o.push(c);
1029
+ const l = await O({
1030
+ payoutTxHex: r.payoutTxHex,
1031
+ peginTxHex: r.peginTxHex,
1032
+ assertTxHex: r.assertTxHex,
1033
+ depositorBtcPubkey: c,
1034
+ vaultProviderBtcPubkey: r.vaultProviderBtcPubkey,
1035
+ vaultKeeperBtcPubkeys: r.vaultKeeperBtcPubkeys,
1036
+ universalChallengerBtcPubkeys: r.universalChallengerBtcPubkeys,
1037
+ timelockPegin: r.timelockPegin,
1038
+ network: this.config.network
1039
+ });
1040
+ s.push(l.psbtHex), a.push({
1041
+ autoFinalized: !1,
1042
+ signInputs: [
1043
+ {
1044
+ index: 0,
1045
+ publicKey: e,
1046
+ disableTweakSigner: !0
1047
+ }
1048
+ ]
1049
+ });
1050
+ }
1051
+ const u = await this.config.btcWallet.signPsbts(
1052
+ s,
1053
+ a
1054
+ );
1055
+ if (u.length !== t.length)
1056
+ throw new Error(
1057
+ `Expected ${t.length} signed PSBTs but received ${u.length}`
1058
+ );
1059
+ const i = [];
1060
+ for (let r = 0; r < t.length; r++) {
1061
+ const c = o[r], l = W(
1062
+ u[r],
1063
+ c
1064
+ );
1065
+ i.push({
1066
+ payoutSignature: l,
1067
+ depositorBtcPubkey: c
1068
+ });
1069
+ }
1070
+ return i;
1071
+ }
1072
+ }
1073
+ export {
1074
+ St as A,
1075
+ N as B,
1076
+ x as C,
1077
+ H as D,
1078
+ K as E,
1079
+ mt as F,
1080
+ Q as L,
1081
+ V as M,
1082
+ Z as P,
1083
+ G as T,
1084
+ tt as W,
1085
+ wt as a,
1086
+ Pt as b,
1087
+ R as c,
1088
+ Tt as d,
1089
+ v as e,
1090
+ rt as f,
1091
+ xt as g,
1092
+ ot as h,
1093
+ at as i,
1094
+ Ct as j,
1095
+ Ht as k,
1096
+ It as l,
1097
+ kt as m,
1098
+ Et as n,
1099
+ Bt as o,
1100
+ st as p,
1101
+ vt as q,
1102
+ et as r,
1103
+ nt as s,
1104
+ ut as t,
1105
+ lt as u,
1106
+ it as v,
1107
+ ct as w,
1108
+ B as x,
1109
+ U as y,
1110
+ $t as z
1111
+ };
1112
+ //# sourceMappingURL=PayoutManager-rMj54HDh.js.map