@babylonlabs-io/ts-sdk 0.51.1 → 0.53.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 (131) hide show
  1. package/dist/ApplicationRegistry.abi-CLaa6E99.cjs +2 -0
  2. package/dist/ApplicationRegistry.abi-CLaa6E99.cjs.map +1 -0
  3. package/dist/{ApplicationRegistry.abi-Dn2qk6JG.js → ApplicationRegistry.abi-w5prf7Ig.js} +14 -1
  4. package/dist/ApplicationRegistry.abi-w5prf7Ig.js.map +1 -0
  5. package/dist/PayoutManager-1GWmbvI9.cjs +2 -0
  6. package/dist/PayoutManager-1GWmbvI9.cjs.map +1 -0
  7. package/dist/{PayoutManager-D26nGR-e.js → PayoutManager-Ddo9_Ozc.js} +34 -32
  8. package/dist/PayoutManager-Ddo9_Ozc.js.map +1 -0
  9. package/dist/{PeginManager-COxRVrxa.js → PeginManager-CTU0wgkJ.js} +37 -34
  10. package/dist/PeginManager-CTU0wgkJ.js.map +1 -0
  11. package/dist/PeginManager-De-eHl3v.cjs +2 -0
  12. package/dist/PeginManager-De-eHl3v.cjs.map +1 -0
  13. package/dist/buildAndBroadcastRefund-BnD2qUDW.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-BnD2qUDW.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastRefund-Bmz9WJuN.js → buildAndBroadcastRefund-DjS9nf87.js} +221 -209
  16. package/dist/buildAndBroadcastRefund-DjS9nf87.js.map +1 -0
  17. package/dist/{challengeAssert-HNbugpqL.cjs → challengeAssert-DLQfNcfU.cjs} +2 -2
  18. package/dist/{challengeAssert-HNbugpqL.cjs.map → challengeAssert-DLQfNcfU.cjs.map} +1 -1
  19. package/dist/{challengeAssert-csvYXBJB.js → challengeAssert-DvdbpEDY.js} +2 -2
  20. package/dist/{challengeAssert-csvYXBJB.js.map → challengeAssert-DvdbpEDY.js.map} +1 -1
  21. package/dist/constants-BhclpREj.js +19 -0
  22. package/dist/constants-BhclpREj.js.map +1 -0
  23. package/dist/constants-CvbARMl-.cjs +2 -0
  24. package/dist/constants-CvbARMl-.cjs.map +1 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +193 -190
  27. package/dist/index.js.map +1 -1
  28. package/dist/{mempoolApi-Dc1KSVNI.js → mempoolApi-CB7bHuwi.js} +106 -101
  29. package/dist/mempoolApi-CB7bHuwi.js.map +1 -0
  30. package/dist/mempoolApi-DqJByvqR.cjs +2 -0
  31. package/dist/mempoolApi-DqJByvqR.cjs.map +1 -0
  32. package/dist/noPayout-8dDKwi6n.cjs +2 -0
  33. package/dist/noPayout-8dDKwi6n.cjs.map +1 -0
  34. package/dist/{noPayout-C1WCsqfd.js → noPayout-tZFoNun3.js} +12 -10
  35. package/dist/noPayout-tZFoNun3.js.map +1 -0
  36. package/dist/{peginInput-BPRB9tUi.js → peginInput-BKD_b3gq.js} +8 -7
  37. package/dist/peginInput-BKD_b3gq.js.map +1 -0
  38. package/dist/peginInput-CAiiDZeO.cjs +2 -0
  39. package/dist/peginInput-CAiiDZeO.cjs.map +1 -0
  40. package/dist/primeVpAuth-CF4cH5_e.cjs +2 -0
  41. package/dist/primeVpAuth-CF4cH5_e.cjs.map +1 -0
  42. package/dist/{primeVpAuth-DxMuWQCi.js → primeVpAuth-l-5x_2UV.js} +91 -85
  43. package/dist/{primeVpAuth-yTddDmGy.cjs.map → primeVpAuth-l-5x_2UV.js.map} +1 -1
  44. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
  46. package/dist/tbv/core/clients/eth/types.d.ts +8 -0
  47. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  48. package/dist/tbv/core/clients/index.cjs +1 -1
  49. package/dist/tbv/core/clients/index.js +2 -2
  50. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +10 -0
  51. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
  52. package/dist/tbv/core/contracts/index.cjs +1 -1
  53. package/dist/tbv/core/contracts/index.js +1 -1
  54. package/dist/tbv/core/index.cjs +1 -1
  55. package/dist/tbv/core/index.js +191 -188
  56. package/dist/tbv/core/index.js.map +1 -1
  57. package/dist/tbv/core/managers/PayoutManager.d.ts +6 -0
  58. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  59. package/dist/tbv/core/managers/PeginManager.d.ts +7 -0
  60. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  61. package/dist/tbv/core/managers/index.cjs +1 -1
  62. package/dist/tbv/core/managers/index.js +2 -2
  63. package/dist/tbv/core/primitives/__tests__/vaultCoreVersion.test.d.ts +8 -0
  64. package/dist/tbv/core/primitives/__tests__/vaultCoreVersion.test.d.ts.map +1 -0
  65. package/dist/tbv/core/primitives/index.cjs +1 -1
  66. package/dist/tbv/core/primitives/index.d.ts +2 -1
  67. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  68. package/dist/tbv/core/primitives/index.js +39 -36
  69. package/dist/tbv/core/primitives/index.js.map +1 -1
  70. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  71. package/dist/tbv/core/primitives/psbt/payout.d.ts +6 -0
  72. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  73. package/dist/tbv/core/primitives/psbt/pegin.d.ts +7 -0
  74. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  75. package/dist/tbv/core/primitives/psbt/peginInput.d.ts +6 -0
  76. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  77. package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
  78. package/dist/tbv/core/primitives/scripts/payout.d.ts +6 -0
  79. package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/vaultCoreVersion.d.ts +26 -0
  81. package/dist/tbv/core/primitives/vaultCoreVersion.d.ts.map +1 -0
  82. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +7 -0
  83. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  84. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +6 -0
  85. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  86. package/dist/tbv/core/services/deposit/verifyRegisteredVaultVersions.d.ts +8 -0
  87. package/dist/tbv/core/services/deposit/verifyRegisteredVaultVersions.d.ts.map +1 -1
  88. package/dist/tbv/core/services/index.cjs +1 -1
  89. package/dist/tbv/core/services/index.js +2 -2
  90. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +6 -0
  91. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
  92. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +5 -2
  93. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -1
  94. package/dist/tbv/index.cjs +1 -1
  95. package/dist/tbv/index.js +191 -188
  96. package/dist/tbv/index.js.map +1 -1
  97. package/dist/{verifyScriptPathSchnorrSignature-CeZp6tMw.js → verifyScriptPathSchnorrSignature-DpWZx5J0.js} +67 -61
  98. package/dist/verifyScriptPathSchnorrSignature-DpWZx5J0.js.map +1 -0
  99. package/dist/verifyScriptPathSchnorrSignature-a4Us7D3e.cjs +2 -0
  100. package/dist/verifyScriptPathSchnorrSignature-a4Us7D3e.cjs.map +1 -0
  101. package/package.json +1 -1
  102. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs +0 -2
  103. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs.map +0 -1
  104. package/dist/ApplicationRegistry.abi-Dn2qk6JG.js.map +0 -1
  105. package/dist/PayoutManager-BZVEyi10.cjs +0 -2
  106. package/dist/PayoutManager-BZVEyi10.cjs.map +0 -1
  107. package/dist/PayoutManager-D26nGR-e.js.map +0 -1
  108. package/dist/PeginManager-BvxfSwsr.cjs +0 -2
  109. package/dist/PeginManager-BvxfSwsr.cjs.map +0 -1
  110. package/dist/PeginManager-COxRVrxa.js.map +0 -1
  111. package/dist/buildAndBroadcastRefund-Bmz9WJuN.js.map +0 -1
  112. package/dist/buildAndBroadcastRefund-ob1n2iB3.cjs +0 -2
  113. package/dist/buildAndBroadcastRefund-ob1n2iB3.cjs.map +0 -1
  114. package/dist/constants-CSG2XeD8.cjs +0 -2
  115. package/dist/constants-CSG2XeD8.cjs.map +0 -1
  116. package/dist/constants-Cd_fN8VT.js +0 -12
  117. package/dist/constants-Cd_fN8VT.js.map +0 -1
  118. package/dist/mempoolApi-Dc1KSVNI.js.map +0 -1
  119. package/dist/mempoolApi-NMiYQAXI.cjs +0 -2
  120. package/dist/mempoolApi-NMiYQAXI.cjs.map +0 -1
  121. package/dist/noPayout-C1WCsqfd.js.map +0 -1
  122. package/dist/noPayout-lyIRiUyG.cjs +0 -2
  123. package/dist/noPayout-lyIRiUyG.cjs.map +0 -1
  124. package/dist/peginInput-BPRB9tUi.js.map +0 -1
  125. package/dist/peginInput-DH6X4ITS.cjs +0 -2
  126. package/dist/peginInput-DH6X4ITS.cjs.map +0 -1
  127. package/dist/primeVpAuth-DxMuWQCi.js.map +0 -1
  128. package/dist/primeVpAuth-yTddDmGy.cjs +0 -2
  129. package/dist/verifyScriptPathSchnorrSignature-CeZp6tMw.js.map +0 -1
  130. package/dist/verifyScriptPathSchnorrSignature-Cl7tu77P.cjs +0 -2
  131. package/dist/verifyScriptPathSchnorrSignature-Cl7tu77P.cjs.map +0 -1
@@ -1,27 +1,28 @@
1
1
  import * as x from "@bitcoin-js/tiny-secp256k1-asmjs";
2
2
  import { h as y } from "./bitcoin-B5aNKtsk.js";
3
3
  import { B as s } from "./BTCVaultRegistry.abi-Chs4AFBj.js";
4
- import { B as A, H as C, K as E, T as F } from "./validation-CxqROCno.js";
5
- const h = 65535, g = 1e4, l = 4294967295, p = 255;
6
- function m(e) {
4
+ import { a as A } from "./constants-BhclpREj.js";
5
+ import { B as C, H as E, K as F, T as B } from "./validation-CxqROCno.js";
6
+ const m = 65535, g = 1e4, l = 4294967295, p = 255;
7
+ function h(e) {
7
8
  if (!Number.isInteger(e) || e < 0 || e > l)
8
9
  throw new Error(
9
10
  `Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`
10
11
  );
11
12
  }
12
- function B(e) {
13
+ function k(e) {
13
14
  const t = [];
14
15
  if (e.timelockAssert <= 0n && t.push(
15
16
  `timelockAssert must be positive, got ${e.timelockAssert}`
16
- ), e.timelockAssert > BigInt(h) && t.push(
17
- `timelockAssert ${e.timelockAssert} exceeds uint16 max (${h})`
17
+ ), e.timelockAssert > BigInt(m) && t.push(
18
+ `timelockAssert ${e.timelockAssert} exceeds uint16 max (${m})`
18
19
  ), e.timelockChallengeAssert <= 0n && t.push(
19
20
  `timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`
20
21
  ), e.tRefund <= 0 && t.push(`tRefund must be positive, got ${e.tRefund}`), e.tStale <= 0 && t.push(`tStale must be positive, got ${e.tStale}`), e.securityCouncilKeys.length === 0 && t.push("securityCouncilKeys must not be empty"), e.councilQuorum <= 0 && t.push(`councilQuorum must be positive, got ${e.councilQuorum}`), e.councilQuorum > e.securityCouncilKeys.length && t.push(
21
22
  `councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`
22
23
  ), e.feeRate <= 0n && t.push(`feeRate must be positive, got ${e.feeRate}`), e.minPeginFeeRate <= 0n && t.push(
23
24
  `minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`
24
- ), (!Number.isInteger(e.proverCircuitVersion) || e.proverCircuitVersion < 0 || e.proverCircuitVersion > h) && t.push(
25
+ ), (!Number.isInteger(e.proverCircuitVersion) || e.proverCircuitVersion < 0 || e.proverCircuitVersion > m) && t.push(
25
26
  `proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`
26
27
  ), (!Number.isInteger(e.minPrepeginDepth) || e.minPrepeginDepth <= 0 || e.minPrepeginDepth > l) && t.push(
27
28
  `minPrepeginDepth must be a uint32 in [1, ${l}], got ${e.minPrepeginDepth}`
@@ -38,7 +39,7 @@ function B(e) {
38
39
  `Invalid offchain protocol parameters: ${t.join("; ")}`
39
40
  );
40
41
  }
41
- function k(e) {
42
+ function S(e) {
42
43
  const t = [];
43
44
  if (e.minimumPegInAmount <= 0n && t.push(
44
45
  `minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`
@@ -55,11 +56,15 @@ function k(e) {
55
56
  ), t.length > 0)
56
57
  throw new Error(`Invalid TBV protocol parameters: ${t.join("; ")}`);
57
58
  }
58
- function M(e) {
59
- if (k(e), B(e.offchainParams), !Number.isInteger(e.offchainParamsVersion) || e.offchainParamsVersion < 0 || e.offchainParamsVersion > l)
59
+ function X(e) {
60
+ if (S(e), k(e.offchainParams), !Number.isInteger(e.offchainParamsVersion) || e.offchainParamsVersion < 0 || e.offchainParamsVersion > l)
60
61
  throw new Error(
61
62
  `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`
62
63
  );
64
+ A(
65
+ e.activeVaultCoreVersion,
66
+ "ProtocolParams.activeVaultCoreVersion()"
67
+ );
63
68
  }
64
69
  const w = 9999;
65
70
  function P(e) {
@@ -75,7 +80,7 @@ function P(e) {
75
80
  }
76
81
  function $(e) {
77
82
  const t = Number(e.offchainParamsVersion);
78
- return m(t), {
83
+ return h(t), {
79
84
  depositorSignedPeginTx: e.depositorSignedPeginTx,
80
85
  universalChallengersVersion: e.universalChallengersVersion,
81
86
  appVaultKeepersVersion: e.appVaultKeepersVersion,
@@ -91,7 +96,7 @@ function $(e) {
91
96
  vaultCoreVersion: e.vaultCoreVersion
92
97
  };
93
98
  }
94
- class _ {
99
+ class D {
95
100
  constructor(t, o) {
96
101
  this.publicClient = t, this.contractAddress = o;
97
102
  }
@@ -102,22 +107,22 @@ class _ {
102
107
  * hex without the `0x` prefix.
103
108
  */
104
109
  async getVaultProviderBtcPubKey(t) {
105
- const i = (await this.publicClient.readContract({
110
+ const r = (await this.publicClient.readContract({
106
111
  address: this.contractAddress,
107
112
  abi: s,
108
113
  functionName: "getVaultProviderBTCKey",
109
114
  args: [t]
110
115
  })).toLowerCase();
111
- if (!/^0x[0-9a-f]{64}$/.test(i))
116
+ if (!/^0x[0-9a-f]{64}$/.test(r))
112
117
  throw new Error(
113
- `getVaultProviderBTCKey returned an unexpected value (vp=${t}, length ${i.length}, prefix "${i.slice(0, 2)}")`
118
+ `getVaultProviderBTCKey returned an unexpected value (vp=${t}, length ${r.length}, prefix "${r.slice(0, 2)}")`
114
119
  );
115
- const r = i.slice(2);
116
- if (!x.isXOnlyPoint(y(r)))
120
+ const i = r.slice(2);
121
+ if (!x.isXOnlyPoint(y(i)))
117
122
  throw new Error(
118
123
  `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${t})`
119
124
  );
120
- return r;
125
+ return i;
121
126
  }
122
127
  async getVaultBasicInfo(t) {
123
128
  const o = await this.publicClient.readContract({
@@ -139,21 +144,21 @@ class _ {
139
144
  }
140
145
  async getProtocolInfoBatch(t) {
141
146
  return t.length === 0 ? [] : (await this.publicClient.multicall({
142
- contracts: t.map((i) => ({
147
+ contracts: t.map((r) => ({
143
148
  address: this.contractAddress,
144
149
  abi: s,
145
150
  functionName: "getBtcVaultProtocolInfo",
146
- args: [i]
151
+ args: [r]
147
152
  })),
148
153
  allowFailure: !1
149
- })).map((i, r) => {
150
- const n = i;
154
+ })).map((r, i) => {
155
+ const n = r;
151
156
  if (!n.depositorSignedPeginTx || n.depositorSignedPeginTx === "0x")
152
157
  throw new Error(
153
- `Vault ${t[r]} not found on-chain or has no pegin transaction`
158
+ `Vault ${t[i]} not found on-chain or has no pegin transaction`
154
159
  );
155
160
  const a = Number(n.offchainParamsVersion);
156
- return m(a), {
161
+ return h(a), {
157
162
  depositorSignedPeginTx: n.depositorSignedPeginTx,
158
163
  universalChallengersVersion: n.universalChallengersVersion,
159
164
  appVaultKeepersVersion: n.appVaultKeepersVersion,
@@ -203,7 +208,7 @@ class _ {
203
208
  return o;
204
209
  }
205
210
  async getVaultData(t) {
206
- const [o, i] = await this.publicClient.multicall({
211
+ const [o, r] = await this.publicClient.multicall({
207
212
  contracts: [
208
213
  {
209
214
  address: this.contractAddress,
@@ -219,12 +224,12 @@ class _ {
219
224
  }
220
225
  ],
221
226
  allowFailure: !1
222
- }), r = P(o), n = $(i);
227
+ }), i = P(o), n = $(r);
223
228
  if (!n.depositorSignedPeginTx || n.depositorSignedPeginTx === "0x")
224
229
  throw new Error(
225
230
  `Vault ${t} not found on-chain or has no pegin transaction`
226
231
  );
227
- return { basic: r, protocol: n };
232
+ return { basic: i, protocol: n };
228
233
  }
229
234
  /**
230
235
  * Read `offchainParamsVersion` for many vaults in a single multicall.
@@ -233,74 +238,74 @@ class _ {
233
238
  */
234
239
  async getOffchainParamsVersionsByVaultIds(t) {
235
240
  return t.length === 0 ? [] : (await this.publicClient.multicall({
236
- contracts: t.map((i) => ({
241
+ contracts: t.map((r) => ({
237
242
  address: this.contractAddress,
238
243
  abi: s,
239
244
  functionName: "getBtcVaultProtocolInfo",
240
- args: [i]
245
+ args: [r]
241
246
  })),
242
247
  allowFailure: !1
243
- })).map((i) => {
244
- const r = i;
245
- if (!r.depositorSignedPeginTx || r.depositorSignedPeginTx === "0x")
248
+ })).map((r) => {
249
+ const i = r;
250
+ if (!i.depositorSignedPeginTx || i.depositorSignedPeginTx === "0x")
246
251
  throw new Error(
247
252
  "Vault not found on-chain or has no pegin transaction while reading offchain params version"
248
253
  );
249
- const n = Number(r.offchainParamsVersion);
250
- return m(n), n;
254
+ const n = Number(i.offchainParamsVersion);
255
+ return h(n), n;
251
256
  });
252
257
  }
253
258
  }
254
- const S = 21e6 * 1e8, b = 3e4;
259
+ const N = 21e6 * 1e8, b = 3e4;
255
260
  async function f(e, t) {
256
- const o = new AbortController(), i = setTimeout(
261
+ const o = new AbortController(), r = setTimeout(
257
262
  () => o.abort(),
258
263
  b
259
- ), r = [o.signal, t == null ? void 0 : t.signal].filter(
264
+ ), i = [o.signal, t == null ? void 0 : t.signal].filter(
260
265
  Boolean
261
266
  );
262
267
  try {
263
268
  return await fetch(e, {
264
269
  ...t,
265
- signal: AbortSignal.any(r)
270
+ signal: AbortSignal.any(i)
266
271
  });
267
272
  } catch (n) {
268
- throw clearTimeout(i), n != null && typeof n == "object" && "name" in n && n.name === "AbortError" ? new Error(
273
+ throw clearTimeout(r), n != null && typeof n == "object" && "name" in n && n.name === "AbortError" ? new Error(
269
274
  `Mempool API request timed out after ${b}ms: ${e}`
270
275
  ) : n;
271
276
  }
272
277
  }
273
278
  const I = 1e4;
274
279
  function v(e) {
275
- return Number.isInteger(e) && e > 0 && e <= S;
280
+ return Number.isInteger(e) && e > 0 && e <= N;
276
281
  }
277
- function N(e) {
282
+ function O(e) {
278
283
  return Number.isInteger(e) && e > 0 && e <= I;
279
284
  }
280
285
  function d(e, t) {
281
286
  return !Number.isInteger(e) || e < 0 ? !1 : t === void 0 || e < t;
282
287
  }
283
288
  function u(e) {
284
- if (!F.test(e))
289
+ if (!B.test(e))
285
290
  throw new Error(`Invalid transaction ID format: ${e}`);
286
291
  }
287
292
  function V(e) {
288
- if (!A.test(e))
293
+ if (!C.test(e))
289
294
  throw new Error(`Invalid Bitcoin address format: ${e}`);
290
295
  }
291
296
  function T(e, t) {
292
- if (!C.test(e))
297
+ if (!E.test(e))
293
298
  throw new Error(
294
299
  `Invalid scriptPubKey: not valid hex for ${t}`
295
300
  );
296
- if (!E.some(
297
- (i) => e.toLowerCase().startsWith(i)
301
+ if (!F.some(
302
+ (r) => e.toLowerCase().startsWith(r)
298
303
  ))
299
304
  throw new Error(
300
305
  `Unrecognized scriptPubKey type for ${t}: prefix ${e.slice(0, 6)} does not match any known Bitcoin script type`
301
306
  );
302
307
  }
303
- const O = {
308
+ const K = {
304
309
  mainnet: "https://mempool.space/api",
305
310
  testnet: "https://mempool.space/testnet/api",
306
311
  signet: "https://mempool.space/signet/api"
@@ -309,18 +314,18 @@ async function c(e, t) {
309
314
  try {
310
315
  const o = await f(e, t);
311
316
  if (!o.ok) {
312
- const r = await o.text();
317
+ const i = await o.text();
313
318
  throw new Error(
314
- `Mempool API error (${o.status}): ${r || o.statusText}`
319
+ `Mempool API error (${o.status}): ${i || o.statusText}`
315
320
  );
316
321
  }
317
- const i = o.headers.get("content-type");
318
- return i != null && i.includes("application/json") ? await o.json() : await o.text();
322
+ const r = o.headers.get("content-type");
323
+ return r != null && r.includes("application/json") ? await o.json() : await o.text();
319
324
  } catch (o) {
320
325
  throw o instanceof Error ? new Error(`Failed to fetch from mempool API: ${o.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
321
326
  }
322
327
  }
323
- async function X(e, t) {
328
+ async function j(e, t) {
324
329
  try {
325
330
  const o = await f(`${t}/tx`, {
326
331
  method: "POST",
@@ -330,13 +335,13 @@ async function X(e, t) {
330
335
  }
331
336
  });
332
337
  if (!o.ok) {
333
- const r = await o.text();
338
+ const i = await o.text();
334
339
  let n;
335
340
  try {
336
- const a = JSON.parse(r);
341
+ const a = JSON.parse(i);
337
342
  n = a.message ?? a.error;
338
343
  } catch {
339
- n = r;
344
+ n = i;
340
345
  }
341
346
  throw new Error(
342
347
  n || `Failed to broadcast transaction: ${o.statusText}`
@@ -347,10 +352,10 @@ async function X(e, t) {
347
352
  throw o instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${o.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
348
353
  }
349
354
  }
350
- async function K(e, t) {
355
+ async function R(e, t) {
351
356
  return u(e), c(`${t}/tx/${e}`);
352
357
  }
353
- async function D(e) {
358
+ async function z(e) {
354
359
  const t = await c(`${e}/blocks/tip/height`), o = t.trim();
355
360
  if (!/^\d+$/.test(o))
356
361
  throw new Error(
@@ -358,19 +363,19 @@ async function D(e) {
358
363
  );
359
364
  return Number.parseInt(o, 10);
360
365
  }
361
- async function j(e, t, o) {
366
+ async function Q(e, t, o) {
362
367
  if (u(e), !d(t))
363
368
  throw new Error(`Invalid vout ${t} for transaction ${e}`);
364
369
  return c(`${o}/tx/${e}/outspend/${t}`);
365
370
  }
366
- async function z(e, t) {
371
+ async function W(e, t) {
367
372
  u(e);
368
373
  try {
369
374
  const o = await f(`${t}/tx/${e}/hex`);
370
375
  if (!o.ok) {
371
- const i = await o.text();
376
+ const r = await o.text();
372
377
  throw new Error(
373
- `Mempool API error (${o.status}): ${i || o.statusText}`
378
+ `Mempool API error (${o.status}): ${r || o.statusText}`
374
379
  );
375
380
  }
376
381
  return await o.text();
@@ -378,32 +383,32 @@ async function z(e, t) {
378
383
  throw o instanceof Error ? new Error(`Failed to get transaction hex for ${e}: ${o.message}`) : new Error(`Failed to get transaction hex for ${e}: Unknown error`);
379
384
  }
380
385
  }
381
- async function Q(e, t, o) {
386
+ async function L(e, t, o) {
382
387
  u(e);
383
- const i = await K(e, o);
384
- if (!d(t, i.vout.length))
388
+ const r = await R(e, o);
389
+ if (!d(t, r.vout.length))
385
390
  throw new Error(
386
- `Invalid vout ${t} for transaction ${e} (has ${i.vout.length} outputs)`
391
+ `Invalid vout ${t} for transaction ${e} (has ${r.vout.length} outputs)`
387
392
  );
388
- const r = i.vout[t];
389
- if (!v(r.value))
390
- throw new Error(`Invalid UTXO value ${r.value} for ${e}:${t}`);
391
- return T(r.scriptpubkey, `${e}:${t}`), {
393
+ const i = r.vout[t];
394
+ if (!v(i.value))
395
+ throw new Error(`Invalid UTXO value ${i.value} for ${e}:${t}`);
396
+ return T(i.scriptpubkey, `${e}:${t}`), {
392
397
  txid: e,
393
398
  vout: t,
394
- value: r.value,
395
- scriptPubKey: r.scriptpubkey
399
+ value: i.value,
400
+ scriptPubKey: i.scriptpubkey
396
401
  };
397
402
  }
398
- async function W(e, t) {
403
+ async function G(e, t) {
399
404
  V(e);
400
405
  try {
401
- const o = await c(`${t}/address/${e}/utxo`), i = await c(`${t}/v1/validate-address/${e}`);
402
- if (!i.isvalid)
406
+ const o = await c(`${t}/address/${e}/utxo`), r = await c(`${t}/v1/validate-address/${e}`);
407
+ if (!r.isvalid)
403
408
  throw new Error(
404
409
  `Invalid Bitcoin address: ${e}. Mempool API validation failed.`
405
410
  );
406
- T(i.scriptPubKey, e);
411
+ T(r.scriptPubKey, e);
407
412
  for (const n of o) {
408
413
  if (u(n.txid), !d(n.vout))
409
414
  throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);
@@ -416,7 +421,7 @@ async function W(e, t) {
416
421
  txid: n.txid,
417
422
  vout: n.vout,
418
423
  value: n.value,
419
- scriptPubKey: i.scriptPubKey,
424
+ scriptPubKey: r.scriptPubKey,
420
425
  confirmed: n.status.confirmed
421
426
  }));
422
427
  } catch (o) {
@@ -427,29 +432,29 @@ async function W(e, t) {
427
432
  );
428
433
  }
429
434
  }
430
- function L(e) {
431
- return O[e];
435
+ function J(e) {
436
+ return K[e];
432
437
  }
433
- async function G(e, t) {
438
+ async function q(e, t) {
434
439
  return V(e), c(`${t}/address/${e}/txs`);
435
440
  }
436
- async function J(e) {
441
+ async function Y(e) {
437
442
  const t = await f(`${e}/v1/fees/recommended`);
438
443
  if (!t.ok)
439
444
  throw new Error(
440
445
  `Failed to fetch network fees: ${t.status} ${t.statusText}`
441
446
  );
442
- const o = await t.json(), i = [
447
+ const o = await t.json(), r = [
443
448
  "fastestFee",
444
449
  "halfHourFee",
445
450
  "hourFee",
446
451
  "economyFee",
447
452
  "minimumFee"
448
453
  ];
449
- for (const r of i)
450
- if (!N(o[r]))
454
+ for (const i of r)
455
+ if (!O(o[i]))
451
456
  throw new Error(
452
- `Invalid fee rate ${r}=${o[r]} from mempool API: expected a positive number ≤ ${I}`
457
+ `Invalid fee rate ${i}=${o[i]} from mempool API: expected a positive number ≤ ${I}`
453
458
  );
454
459
  if (o.minimumFee > o.economyFee || o.economyFee > o.hourFee || o.hourFee > o.halfHourFee || o.halfHourFee > o.fastestFee)
455
460
  throw new Error(
@@ -458,21 +463,21 @@ async function J(e) {
458
463
  return o;
459
464
  }
460
465
  export {
461
- O as M,
462
- _ as V,
463
- W as a,
464
- L as b,
465
- J as c,
466
- j as d,
467
- D as e,
468
- z as f,
469
- G as g,
470
- K as h,
471
- Q as i,
472
- M as j,
473
- k,
474
- m as l,
475
- X as p,
476
- B as v
466
+ K as M,
467
+ D as V,
468
+ G as a,
469
+ J as b,
470
+ Y as c,
471
+ Q as d,
472
+ z as e,
473
+ W as f,
474
+ q as g,
475
+ R as h,
476
+ L as i,
477
+ X as j,
478
+ S as k,
479
+ h as l,
480
+ j as p,
481
+ k as v
477
482
  };
478
- //# sourceMappingURL=mempoolApi-Dc1KSVNI.js.map
483
+ //# sourceMappingURL=mempoolApi-CB7bHuwi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-CB7bHuwi.js","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":";;;;;AAwBA,MAAMA,IAAa,OAGbC,IAAmB,KAGnBC,IAAa,YAGbC,IAAY;AAQX,SAASC,EAAiCC,GAAuB;AACtE,MACE,CAAC,OAAO,UAAUA,CAAO,KACzBA,IAAU,KACVA,IAAUH;AAEV,UAAM,IAAI;AAAA,MACR,sEAAsEG,CAAO;AAAA,IAAA;AAGnF;AAMO,SAASC,EAAuBC,GAAuC;AAC5E,QAAMC,IAAmB,CAAA;AA+FzB,MA7FID,EAAO,kBAAkB,MAC3BC,EAAO;AAAA,IACL,wCAAwCD,EAAO,cAAc;AAAA,EAAA,GAG7DA,EAAO,iBAAiB,OAAOP,CAAU,KAC3CQ,EAAO;AAAA,IACL,kBAAkBD,EAAO,cAAc,wBAAwBP,CAAU;AAAA,EAAA,GAIzEO,EAAO,2BAA2B,MACpCC,EAAO;AAAA,IACL,iDAAiDD,EAAO,uBAAuB;AAAA,EAAA,GAI/EA,EAAO,WAAW,KACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,GAG3DA,EAAO,UAAU,KACnBC,EAAO,KAAK,gCAAgCD,EAAO,MAAM,EAAE,GAGzDA,EAAO,oBAAoB,WAAW,KACxCC,EAAO,KAAK,uCAAuC,GAGjDD,EAAO,iBAAiB,KAC1BC,EAAO,KAAK,uCAA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ACR,mCAAmCY,CAAO;AAAA,IAAA;AAAA,EAE9C;AACF;AAQO,SAASiC,EACdC,GACQ;AACR,SAAO1B,EAAiB0B,CAAO;AACjC;AAuBA,eAAsBC,EACpBnC,GACAe,GACsB;AACtB,SAAAhB,EAAmBC,CAAO,GACnBS,EAAsB,GAAGM,CAAM,YAAYf,CAAO,MAAM;AACjE;AAWA,eAAsBoC,EAAerB,GAAsC;AACzE,QAAML,IAAW,MAAM5B,EAAiB,GAAGiC,CAAM,sBAAsB;AAEvE,MAAI,CAACL,EAAS;AACZ,UAAM,IAAI;AAAA,MACR,iCAAiCA,EAAS,MAAM,IAAIA,EAAS,UAAU;AAAA,IAAA;AAI3E,QAAM2B,IAAO,MAAM3B,EAAS,KAAA,GAEtB4B,IAAY;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,aAAWC,KAASD;AAClB,QAAI,CAAC9C,EAAe6C,EAAKE,CAAK,CAAC;AAC7B,YAAM,IAAI;AAAA,QACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmDlD,CAAY;AAAA,MAAA;AAK7G,MACEgD,EAAK,aAAaA,EAAK,cACvBA,EAAK,aAAaA,EAAK,WACvBA,EAAK,UAAUA,EAAK,eACpBA,EAAK,cAAcA,EAAK;AAExB,UAAM,IAAI;AAAA,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const B=require("@bitcoin-js/tiny-secp256k1-asmjs"),F=require("./bitcoin-CHfKAhcI.cjs"),s=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),k=require("./constants-CvbARMl-.cjs"),l=require("./validation-u8W7Lp2x.cjs");function S(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const o in e)if(o!=="default"){const r=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,r.get?r:{enumerable:!0,get:()=>e[o]})}}return t.default=e,Object.freeze(t)}const O=S(B),h=65535,p=1e4,f=4294967295,P=255;function d(e){if(!Number.isInteger(e)||e<0||e>f)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`)}function V(e){const t=[];if(e.timelockAssert<=0n&&t.push(`timelockAssert must be positive, got ${e.timelockAssert}`),e.timelockAssert>BigInt(h)&&t.push(`timelockAssert ${e.timelockAssert} exceeds uint16 max (${h})`),e.timelockChallengeAssert<=0n&&t.push(`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`),e.tRefund<=0&&t.push(`tRefund must be positive, got ${e.tRefund}`),e.tStale<=0&&t.push(`tStale must be positive, got ${e.tStale}`),e.securityCouncilKeys.length===0&&t.push("securityCouncilKeys must not be empty"),e.councilQuorum<=0&&t.push(`councilQuorum must be positive, got ${e.councilQuorum}`),e.councilQuorum>e.securityCouncilKeys.length&&t.push(`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`),e.feeRate<=0n&&t.push(`feeRate must be positive, got ${e.feeRate}`),e.minPeginFeeRate<=0n&&t.push(`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`),(!Number.isInteger(e.proverCircuitVersion)||e.proverCircuitVersion<0||e.proverCircuitVersion>h)&&t.push(`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`),(!Number.isInteger(e.minPrepeginDepth)||e.minPrepeginDepth<=0||e.minPrepeginDepth>f)&&t.push(`minPrepeginDepth must be a uint32 in [1, ${f}], got ${e.minPrepeginDepth}`),e.babeTotalInstances<=0&&t.push(`babeTotalInstances must be positive, got ${e.babeTotalInstances}`),e.babeInstancesToFinalize<=0&&t.push(`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`),e.babeInstancesToFinalize>e.babeTotalInstances&&t.push(`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`),(e.minVpCommissionBps<0||e.minVpCommissionBps>p)&&t.push(`minVpCommissionBps must be in [0, ${p}], got ${e.minVpCommissionBps}`),t.length>0)throw new Error(`Invalid offchain protocol parameters: ${t.join("; ")}`)}function T(e){const t=[];if(e.minimumPegInAmount<=0n&&t.push(`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`),e.maxPegInAmount<e.minimumPegInAmount&&t.push(`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`),e.pegInAckTimeout<=0n&&t.push(`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`),e.pegInActivationTimeout<=0n&&t.push(`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`),(!Number.isInteger(e.maxHtlcOutputCount)||e.maxHtlcOutputCount<=0||e.maxHtlcOutputCount>P)&&t.push(`maxHtlcOutputCount must be an integer in [1, ${P}], got ${e.maxHtlcOutputCount}`),(typeof e.expiredPegInGraceBlocks!="bigint"||e.expiredPegInGraceBlocks<=0n)&&t.push(`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`),t.length>0)throw new Error(`Invalid TBV protocol parameters: ${t.join("; ")}`)}function R(e){if(T(e),V(e.offchainParams),!Number.isInteger(e.offchainParamsVersion)||e.offchainParamsVersion<0||e.offchainParamsVersion>f)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`);k.assertValidVaultCoreVersion(e.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const w=9999;function b(e){return{depositor:e.depositor,depositorBtcPubKey:e.depositorBtcPubKey,amount:e.amount,vaultProvider:e.vaultProvider,status:e.status,applicationEntryPoint:e.applicationEntryPoint,createdAt:e.createdAt}}function I(e){const t=Number(e.offchainParamsVersion);return d(t),{depositorSignedPeginTx:e.depositorSignedPeginTx,universalChallengersVersion:e.universalChallengersVersion,appVaultKeepersVersion:e.appVaultKeepersVersion,offchainParamsVersion:t,verifiedAt:e.verifiedAt,depositorWotsPkHash:e.depositorWotsPkHash,hashlock:e.hashlock,htlcVout:e.htlcVout,depositorPopSignature:e.depositorPopSignature,prePeginTxHash:e.prePeginTxHash,vaultProviderCommissionBps:e.vaultProviderCommissionBps,claimExpiredUntil:e.claimExpiredUntil,vaultCoreVersion:e.vaultCoreVersion}}class N{constructor(t,o){this.publicClient=t,this.contractAddress=o}async getVaultProviderBtcPubKey(t){const r=(await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderBTCKey",args:[t]})).toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`getVaultProviderBTCKey returned an unexpected value (vp=${t}, length ${r.length}, prefix "${r.slice(0,2)}")`);const i=r.slice(2);if(!O.isXOnlyPoint(F.hexToUint8Array(i)))throw new Error(`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${t})`);return i}async getVaultBasicInfo(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]});return b(o)}async getVaultProtocolInfo(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return I(o)}async getProtocolInfoBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map((r,i)=>{const n=r;if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t[i]} not found on-chain or has no pegin transaction`);const a=Number(n.offchainParamsVersion);return d(a),{depositorSignedPeginTx:n.depositorSignedPeginTx,universalChallengersVersion:n.universalChallengersVersion,appVaultKeepersVersion:n.appVaultKeepersVersion,offchainParamsVersion:a,verifiedAt:n.verifiedAt,depositorWotsPkHash:n.depositorWotsPkHash,hashlock:n.hashlock,htlcVout:n.htlcVout,depositorPopSignature:n.depositorPopSignature,prePeginTxHash:n.prePeginTxHash,vaultProviderCommissionBps:n.vaultProviderCommissionBps,claimExpiredUntil:n.claimExpiredUntil,vaultCoreVersion:n.vaultCoreVersion}})}async getPegInFee(t){return await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}async getVaultProviderCommission(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[t]});if(!Number.isInteger(o)||o<0||o>w)throw new Error(`getVaultProviderCommission returned ${o} bps for ${t}, outside the protocol range [0, ${w}]`);return o}async getVaultData(t){const[o,r]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]},{address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]}],allowFailure:!1}),i=b(o),n=I(r);if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:i,protocol:n}}async getOffchainParamsVersionsByVaultIds(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map(r=>{const i=r;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error("Vault not found on-chain or has no pegin transaction while reading offchain params version");const n=Number(i.offchainParamsVersion);return d(n),n})}}const U=21e6*1e8,$=3e4;async function g(e,t){const o=new AbortController,r=setTimeout(()=>o.abort(),$),i=[o.signal,t==null?void 0:t.signal].filter(Boolean);try{return await fetch(e,{...t,signal:AbortSignal.any(i)})}catch(n){throw clearTimeout(r),n!=null&&typeof n=="object"&&"name"in n&&n.name==="AbortError"?new Error(`Mempool API request timed out after ${$}ms: ${e}`):n}}const v=1e4;function y(e){return Number.isInteger(e)&&e>0&&e<=U}function _(e){return Number.isInteger(e)&&e>0&&e<=v}function m(e,t){return!Number.isInteger(e)||e<0?!1:t===void 0||e<t}function u(e){if(!l.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function A(e){if(!l.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function x(e,t){if(!l.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${t}`);if(!l.KNOWN_SCRIPT_PREFIXES.some(r=>e.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${t}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const C={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(e,t){try{const o=await g(e,t);if(!o.ok){const i=await o.text();throw new Error(`Mempool API error (${o.status}): ${i||o.statusText}`)}const r=o.headers.get("content-type");return r!=null&&r.includes("application/json")?await o.json():await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to fetch from mempool API: ${o.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function M(e,t){try{const o=await g(`${t}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!o.ok){const i=await o.text();let n;try{const a=JSON.parse(i);n=a.message??a.error}catch{n=i}throw new Error(n||`Failed to broadcast transaction: ${o.statusText}`)}return await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to broadcast BTC transaction: ${o.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function E(e,t){return u(e),c(`${t}/tx/${e}`)}async function H(e){const t=await c(`${e}/blocks/tip/height`),o=t.trim();if(!/^\d+$/.test(o))throw new Error(`Mempool API returned an invalid block tip height: "${t}"`);return Number.parseInt(o,10)}async function K(e,t,o){if(u(e),!m(t))throw new Error(`Invalid vout ${t} for transaction ${e}`);return c(`${o}/tx/${e}/outspend/${t}`)}async function X(e,t){u(e);try{const o=await g(`${t}/tx/${e}/hex`);if(!o.ok){const r=await o.text();throw new Error(`Mempool API error (${o.status}): ${r||o.statusText}`)}return await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${o.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function D(e,t,o){u(e);const r=await E(e,o);if(!m(t,r.vout.length))throw new Error(`Invalid vout ${t} for transaction ${e} (has ${r.vout.length} outputs)`);const i=r.vout[t];if(!y(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${e}:${t}`);return x(i.scriptpubkey,`${e}:${t}`),{txid:e,vout:t,value:i.value,scriptPubKey:i.scriptpubkey}}async function j(e,t){A(e);try{const o=await c(`${t}/address/${e}/utxo`),r=await c(`${t}/v1/validate-address/${e}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);x(r.scriptPubKey,e);for(const n of o){if(u(n.txid),!m(n.vout))throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);if(!y(n.value))throw new Error(`Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`)}return o.sort((n,a)=>a.value-n.value).map(n=>({txid:n.txid,vout:n.vout,value:n.value,scriptPubKey:r.scriptPubKey,confirmed:n.status.confirmed}))}catch(o){throw o instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${o.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function z(e){return C[e]}async function L(e,t){return A(e),c(`${t}/address/${e}/txs`)}async function Q(e){const t=await g(`${e}/v1/fees/recommended`);if(!t.ok)throw new Error(`Failed to fetch network fees: ${t.status} ${t.statusText}`);const o=await t.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of r)if(!_(o[i]))throw new Error(`Invalid fee rate ${i}=${o[i]} from mempool API: expected a positive number ≤ ${v}`);if(o.minimumFee>o.economyFee||o.economyFee>o.hourFee||o.hourFee>o.halfHourFee||o.halfHourFee>o.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${o.minimumFee}) <= economyFee (${o.economyFee}) <= hourFee (${o.hourFee}) <= halfHourFee (${o.halfHourFee}) <= fastestFee (${o.fastestFee}).`);return o}exports.MEMPOOL_API_URLS=C;exports.ViemVaultRegistryReader=N;exports.assertValidOffchainParamsVersion=d;exports.getAddressTxs=L;exports.getAddressUtxos=j;exports.getMempoolApiUrl=z;exports.getNetworkFees=Q;exports.getOutspend=K;exports.getTipHeight=H;exports.getTxHex=X;exports.getTxInfo=E;exports.getUtxoInfo=D;exports.pushTx=M;exports.validateOffchainParams=V;exports.validatePegInConfiguration=R;exports.validateTBVProtocolParams=T;
2
+ //# sourceMappingURL=mempoolApi-DqJByvqR.cjs.map