@babylonlabs-io/ts-sdk 0.55.2 → 0.56.1

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 (155) hide show
  1. package/README.md +1 -2
  2. package/dist/{PayoutManager-BJmPnyRP.js → PayoutManager-BVgmuKuK.js} +117 -105
  3. package/dist/PayoutManager-BVgmuKuK.js.map +1 -0
  4. package/dist/PayoutManager-Cu4_l-_Y.cjs +2 -0
  5. package/dist/PayoutManager-Cu4_l-_Y.cjs.map +1 -0
  6. package/dist/{PeginManager-CW03-M3T.js → PeginManager-Ba7Cr51Z.js} +520 -460
  7. package/dist/PeginManager-Ba7Cr51Z.js.map +1 -0
  8. package/dist/PeginManager-CcjGRo4O.cjs +2 -0
  9. package/dist/PeginManager-CcjGRo4O.cjs.map +1 -0
  10. package/dist/{buildAndBroadcastRefund-BiSO4zg2.js → buildAndBroadcastRefund-BtXUqBkb.js} +444 -430
  11. package/dist/buildAndBroadcastRefund-BtXUqBkb.js.map +1 -0
  12. package/dist/buildAndBroadcastRefund-Cq01wyZX.cjs +2 -0
  13. package/dist/buildAndBroadcastRefund-Cq01wyZX.cjs.map +1 -0
  14. package/dist/challengeAssert-BVQq50su.js +75 -0
  15. package/dist/challengeAssert-BVQq50su.js.map +1 -0
  16. package/dist/challengeAssert-Cu-PtJ1g.cjs +2 -0
  17. package/dist/challengeAssert-Cu-PtJ1g.cjs.map +1 -0
  18. package/dist/constants-BqU1Uz15.cjs +2 -0
  19. package/dist/{constants-CvbARMl-.cjs.map → constants-BqU1Uz15.cjs.map} +1 -1
  20. package/dist/{constants-BhclpREj.js → constants-CDQE812z.js} +8 -6
  21. package/dist/{constants-BhclpREj.js.map → constants-CDQE812z.js.map} +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.js +195 -192
  24. package/dist/{mempoolApi-DqJByvqR.cjs → mempoolApi-DkyKmmgI.cjs} +2 -2
  25. package/dist/mempoolApi-DkyKmmgI.cjs.map +1 -0
  26. package/dist/{mempoolApi-CB7bHuwi.js → mempoolApi-lpJdvPkK.js} +66 -66
  27. package/dist/mempoolApi-lpJdvPkK.js.map +1 -0
  28. package/dist/{noPayout-CNMqNNpc.cjs → noPayout-Cb8vFrkY.cjs} +2 -2
  29. package/dist/{noPayout-CNMqNNpc.cjs.map → noPayout-Cb8vFrkY.cjs.map} +1 -1
  30. package/dist/{noPayout-CfBg3HzC.js → noPayout-CihCk1HE.js} +2 -2
  31. package/dist/{noPayout-CfBg3HzC.js.map → noPayout-CihCk1HE.js.map} +1 -1
  32. package/dist/{primeVpAuth-l-5x_2UV.js → primeVpAuth-Caa5J_uv.js} +4 -4
  33. package/dist/{primeVpAuth-l-5x_2UV.js.map → primeVpAuth-Caa5J_uv.js.map} +1 -1
  34. package/dist/{primeVpAuth-CF4cH5_e.cjs → primeVpAuth-y-4A88ah.cjs} +2 -2
  35. package/dist/{primeVpAuth-CF4cH5_e.cjs.map → primeVpAuth-y-4A88ah.cjs.map} +1 -1
  36. package/dist/tbv/core/clients/index.cjs +1 -1
  37. package/dist/tbv/core/clients/index.js +2 -2
  38. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  39. package/dist/tbv/core/deposit-terms/__tests__/buildDepositTerms.test.d.ts +2 -0
  40. package/dist/tbv/core/deposit-terms/__tests__/buildDepositTerms.test.d.ts.map +1 -0
  41. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts +8 -0
  42. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts.map +1 -0
  43. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +92 -0
  44. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -0
  45. package/dist/tbv/core/deposit-terms/index.d.ts +12 -0
  46. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -0
  47. package/dist/tbv/core/index.cjs +1 -1
  48. package/dist/tbv/core/index.d.ts +1 -0
  49. package/dist/tbv/core/index.d.ts.map +1 -1
  50. package/dist/tbv/core/index.js +194 -191
  51. package/dist/tbv/core/managers/PayoutManager.d.ts +7 -0
  52. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  53. package/dist/tbv/core/managers/PeginManager.d.ts +13 -0
  54. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  55. package/dist/tbv/core/managers/index.cjs +1 -1
  56. package/dist/tbv/core/managers/index.js +2 -2
  57. package/dist/tbv/core/primitives/index.cjs +1 -1
  58. package/dist/tbv/core/primitives/index.d.ts +0 -3
  59. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  60. package/dist/tbv/core/primitives/index.js +37 -38
  61. package/dist/tbv/core/primitives/psbt/__tests__/assertPayoutFeeBand.test.d.ts +7 -0
  62. package/dist/tbv/core/primitives/psbt/__tests__/assertPayoutFeeBand.test.d.ts.map +1 -0
  63. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts +63 -0
  64. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts.map +1 -0
  65. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +4 -1
  66. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  67. package/dist/tbv/core/primitives/psbt/constants.d.ts +18 -4
  68. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  69. package/dist/tbv/core/primitives/psbt/payout.d.ts +21 -2
  70. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  71. package/dist/tbv/core/primitives/psbt/pegin.d.ts +6 -0
  72. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  73. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +12 -0
  74. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  75. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +5 -0
  76. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  77. package/dist/tbv/core/services/index.cjs +1 -1
  78. package/dist/tbv/core/services/index.js +2 -2
  79. package/dist/tbv/core/utils/__tests__/abortSignals.test.d.ts +11 -0
  80. package/dist/tbv/core/utils/__tests__/abortSignals.test.d.ts.map +1 -0
  81. package/dist/tbv/core/utils/abortSignals.d.ts +23 -0
  82. package/dist/tbv/core/utils/abortSignals.d.ts.map +1 -0
  83. package/dist/tbv/core/utils/index.cjs +1 -1
  84. package/dist/tbv/core/utils/index.d.ts +1 -0
  85. package/dist/tbv/core/utils/index.d.ts.map +1 -1
  86. package/dist/tbv/core/utils/index.js +44 -43
  87. package/dist/tbv/index.cjs +1 -1
  88. package/dist/tbv/index.js +194 -191
  89. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  90. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  91. package/dist/tbv/integrations/aave/clients/spoke.d.ts +0 -20
  92. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
  93. package/dist/tbv/integrations/aave/constants.d.ts +0 -22
  94. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  95. package/dist/tbv/integrations/aave/index.cjs +1 -1
  96. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  97. package/dist/tbv/integrations/aave/index.d.ts +5 -6
  98. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  99. package/dist/tbv/integrations/aave/index.js +236 -339
  100. package/dist/tbv/integrations/aave/index.js.map +1 -1
  101. package/dist/tbv/integrations/aave/types.d.ts +0 -7
  102. package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
  103. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -7
  104. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
  105. package/dist/tbv/integrations/aave/utils/index.d.ts +3 -8
  106. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  107. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts +0 -65
  108. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
  109. package/dist/validation-CDbOaDj7.cjs +2 -0
  110. package/dist/validation-CDbOaDj7.cjs.map +1 -0
  111. package/dist/validation-Dj3dqYtl.js +30 -0
  112. package/dist/validation-Dj3dqYtl.js.map +1 -0
  113. package/dist/verifyScriptPathSchnorrSignature-BZhX-SOd.cjs +2 -0
  114. package/dist/verifyScriptPathSchnorrSignature-BZhX-SOd.cjs.map +1 -0
  115. package/dist/verifyScriptPathSchnorrSignature-CgrnAjMW.js +724 -0
  116. package/dist/verifyScriptPathSchnorrSignature-CgrnAjMW.js.map +1 -0
  117. package/package.json +2 -2
  118. package/dist/PayoutManager-BJmPnyRP.js.map +0 -1
  119. package/dist/PayoutManager-aqtsj60t.cjs +0 -2
  120. package/dist/PayoutManager-aqtsj60t.cjs.map +0 -1
  121. package/dist/PeginManager-CW03-M3T.js.map +0 -1
  122. package/dist/PeginManager-C_akOB1E.cjs +0 -2
  123. package/dist/PeginManager-C_akOB1E.cjs.map +0 -1
  124. package/dist/buildAndBroadcastRefund-BiSO4zg2.js.map +0 -1
  125. package/dist/buildAndBroadcastRefund-Bwi1I5we.cjs +0 -2
  126. package/dist/buildAndBroadcastRefund-Bwi1I5we.cjs.map +0 -1
  127. package/dist/challengeAssert-DLQfNcfU.cjs +0 -2
  128. package/dist/challengeAssert-DLQfNcfU.cjs.map +0 -1
  129. package/dist/challengeAssert-DvdbpEDY.js +0 -128
  130. package/dist/challengeAssert-DvdbpEDY.js.map +0 -1
  131. package/dist/constants-CvbARMl-.cjs +0 -2
  132. package/dist/mempoolApi-CB7bHuwi.js.map +0 -1
  133. package/dist/mempoolApi-DqJByvqR.cjs.map +0 -1
  134. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts +0 -34
  135. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts.map +0 -1
  136. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts +0 -5
  137. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts.map +0 -1
  138. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts +0 -5
  139. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts.map +0 -1
  140. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts +0 -2
  141. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts.map +0 -1
  142. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts +0 -15
  143. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts.map +0 -1
  144. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts +0 -109
  145. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts.map +0 -1
  146. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts +0 -33
  147. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts.map +0 -1
  148. package/dist/validation-CxqROCno.js +0 -15
  149. package/dist/validation-CxqROCno.js.map +0 -1
  150. package/dist/validation-u8W7Lp2x.cjs +0 -2
  151. package/dist/validation-u8W7Lp2x.cjs.map +0 -1
  152. package/dist/verifyScriptPathSchnorrSignature-BDznSCOR.cjs +0 -2
  153. package/dist/verifyScriptPathSchnorrSignature-BDznSCOR.cjs.map +0 -1
  154. package/dist/verifyScriptPathSchnorrSignature-DA4Z4yZ3.js +0 -658
  155. package/dist/verifyScriptPathSchnorrSignature-DA4Z4yZ3.js.map +0 -1
@@ -1,8 +1,8 @@
1
1
  import * as x from "@bitcoin-js/tiny-secp256k1-asmjs";
2
2
  import { h as y } from "./bitcoin-B5aNKtsk.js";
3
- import { B as s } from "./BTCVaultRegistry.abi-Chs4AFBj.js";
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";
3
+ import { B as a } from "./BTCVaultRegistry.abi-Chs4AFBj.js";
4
+ import { a as A } from "./constants-CDQE812z.js";
5
+ import { B as C, H as E, K as F, T as B, c as k } from "./validation-Dj3dqYtl.js";
6
6
  const m = 65535, g = 1e4, l = 4294967295, p = 255;
7
7
  function h(e) {
8
8
  if (!Number.isInteger(e) || e < 0 || e > l)
@@ -10,7 +10,7 @@ function h(e) {
10
10
  `Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`
11
11
  );
12
12
  }
13
- function k(e) {
13
+ function S(e) {
14
14
  const t = [];
15
15
  if (e.timelockAssert <= 0n && t.push(
16
16
  `timelockAssert must be positive, got ${e.timelockAssert}`
@@ -39,7 +39,7 @@ function k(e) {
39
39
  `Invalid offchain protocol parameters: ${t.join("; ")}`
40
40
  );
41
41
  }
42
- function S(e) {
42
+ function N(e) {
43
43
  const t = [];
44
44
  if (e.minimumPegInAmount <= 0n && t.push(
45
45
  `minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`
@@ -56,8 +56,8 @@ function S(e) {
56
56
  ), t.length > 0)
57
57
  throw new Error(`Invalid TBV protocol parameters: ${t.join("; ")}`);
58
58
  }
59
- function X(e) {
60
- if (S(e), k(e.offchainParams), !Number.isInteger(e.offchainParamsVersion) || e.offchainParamsVersion < 0 || e.offchainParamsVersion > l)
59
+ function D(e) {
60
+ if (N(e), S(e.offchainParams), !Number.isInteger(e.offchainParamsVersion) || e.offchainParamsVersion < 0 || e.offchainParamsVersion > l)
61
61
  throw new Error(
62
62
  `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`
63
63
  );
@@ -78,7 +78,7 @@ function P(e) {
78
78
  createdAt: e.createdAt
79
79
  };
80
80
  }
81
- function $(e) {
81
+ function b(e) {
82
82
  const t = Number(e.offchainParamsVersion);
83
83
  return h(t), {
84
84
  depositorSignedPeginTx: e.depositorSignedPeginTx,
@@ -96,7 +96,7 @@ function $(e) {
96
96
  vaultCoreVersion: e.vaultCoreVersion
97
97
  };
98
98
  }
99
- class D {
99
+ class j {
100
100
  constructor(t, o) {
101
101
  this.publicClient = t, this.contractAddress = o;
102
102
  }
@@ -109,7 +109,7 @@ class D {
109
109
  async getVaultProviderBtcPubKey(t) {
110
110
  const r = (await this.publicClient.readContract({
111
111
  address: this.contractAddress,
112
- abi: s,
112
+ abi: a,
113
113
  functionName: "getVaultProviderBTCKey",
114
114
  args: [t]
115
115
  })).toLowerCase();
@@ -127,7 +127,7 @@ class D {
127
127
  async getVaultBasicInfo(t) {
128
128
  const o = await this.publicClient.readContract({
129
129
  address: this.contractAddress,
130
- abi: s,
130
+ abi: a,
131
131
  functionName: "getBtcVaultBasicInfo",
132
132
  args: [t]
133
133
  });
@@ -136,17 +136,17 @@ class D {
136
136
  async getVaultProtocolInfo(t) {
137
137
  const o = await this.publicClient.readContract({
138
138
  address: this.contractAddress,
139
- abi: s,
139
+ abi: a,
140
140
  functionName: "getBtcVaultProtocolInfo",
141
141
  args: [t]
142
142
  });
143
- return $(o);
143
+ return b(o);
144
144
  }
145
145
  async getProtocolInfoBatch(t) {
146
146
  return t.length === 0 ? [] : (await this.publicClient.multicall({
147
147
  contracts: t.map((r) => ({
148
148
  address: this.contractAddress,
149
- abi: s,
149
+ abi: a,
150
150
  functionName: "getBtcVaultProtocolInfo",
151
151
  args: [r]
152
152
  })),
@@ -157,12 +157,12 @@ class D {
157
157
  throw new Error(
158
158
  `Vault ${t[i]} not found on-chain or has no pegin transaction`
159
159
  );
160
- const a = Number(n.offchainParamsVersion);
161
- return h(a), {
160
+ const s = Number(n.offchainParamsVersion);
161
+ return h(s), {
162
162
  depositorSignedPeginTx: n.depositorSignedPeginTx,
163
163
  universalChallengersVersion: n.universalChallengersVersion,
164
164
  appVaultKeepersVersion: n.appVaultKeepersVersion,
165
- offchainParamsVersion: a,
165
+ offchainParamsVersion: s,
166
166
  verifiedAt: n.verifiedAt,
167
167
  depositorWotsPkHash: n.depositorWotsPkHash,
168
168
  hashlock: n.hashlock,
@@ -182,7 +182,7 @@ class D {
182
182
  async getPegInFee(t) {
183
183
  return await this.publicClient.readContract({
184
184
  address: this.contractAddress,
185
- abi: s,
185
+ abi: a,
186
186
  functionName: "getPegInFee",
187
187
  args: [t]
188
188
  });
@@ -197,7 +197,7 @@ class D {
197
197
  async getVaultProviderCommission(t) {
198
198
  const o = await this.publicClient.readContract({
199
199
  address: this.contractAddress,
200
- abi: s,
200
+ abi: a,
201
201
  functionName: "getVaultProviderCommission",
202
202
  args: [t]
203
203
  });
@@ -212,19 +212,19 @@ class D {
212
212
  contracts: [
213
213
  {
214
214
  address: this.contractAddress,
215
- abi: s,
215
+ abi: a,
216
216
  functionName: "getBtcVaultBasicInfo",
217
217
  args: [t]
218
218
  },
219
219
  {
220
220
  address: this.contractAddress,
221
- abi: s,
221
+ abi: a,
222
222
  functionName: "getBtcVaultProtocolInfo",
223
223
  args: [t]
224
224
  }
225
225
  ],
226
226
  allowFailure: !1
227
- }), i = P(o), n = $(r);
227
+ }), i = P(o), n = b(r);
228
228
  if (!n.depositorSignedPeginTx || n.depositorSignedPeginTx === "0x")
229
229
  throw new Error(
230
230
  `Vault ${t} not found on-chain or has no pegin transaction`
@@ -240,7 +240,7 @@ class D {
240
240
  return t.length === 0 ? [] : (await this.publicClient.multicall({
241
241
  contracts: t.map((r) => ({
242
242
  address: this.contractAddress,
243
- abi: s,
243
+ abi: a,
244
244
  functionName: "getBtcVaultProtocolInfo",
245
245
  args: [r]
246
246
  })),
@@ -256,30 +256,30 @@ class D {
256
256
  });
257
257
  }
258
258
  }
259
- const N = 21e6 * 1e8, b = 3e4;
259
+ const O = 21e6 * 1e8, $ = 3e4;
260
260
  async function f(e, t) {
261
261
  const o = new AbortController(), r = setTimeout(
262
262
  () => o.abort(),
263
- b
263
+ $
264
264
  ), i = [o.signal, t == null ? void 0 : t.signal].filter(
265
265
  Boolean
266
- );
266
+ ), n = k(i);
267
267
  try {
268
268
  return await fetch(e, {
269
269
  ...t,
270
- signal: AbortSignal.any(i)
270
+ signal: n.signal
271
271
  });
272
- } catch (n) {
273
- throw clearTimeout(r), n != null && typeof n == "object" && "name" in n && n.name === "AbortError" ? new Error(
274
- `Mempool API request timed out after ${b}ms: ${e}`
275
- ) : n;
272
+ } catch (s) {
273
+ throw clearTimeout(r), n.cleanup(), s != null && typeof s == "object" && "name" in s && s.name === "AbortError" ? new Error(
274
+ `Mempool API request timed out after ${$}ms: ${e}`
275
+ ) : s;
276
276
  }
277
277
  }
278
278
  const I = 1e4;
279
279
  function v(e) {
280
- return Number.isInteger(e) && e > 0 && e <= N;
280
+ return Number.isInteger(e) && e > 0 && e <= O;
281
281
  }
282
- function O(e) {
282
+ function K(e) {
283
283
  return Number.isInteger(e) && e > 0 && e <= I;
284
284
  }
285
285
  function d(e, t) {
@@ -305,7 +305,7 @@ function T(e, t) {
305
305
  `Unrecognized scriptPubKey type for ${t}: prefix ${e.slice(0, 6)} does not match any known Bitcoin script type`
306
306
  );
307
307
  }
308
- const K = {
308
+ const R = {
309
309
  mainnet: "https://mempool.space/api",
310
310
  testnet: "https://mempool.space/testnet/api",
311
311
  signet: "https://mempool.space/signet/api"
@@ -325,7 +325,7 @@ async function c(e, t) {
325
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");
326
326
  }
327
327
  }
328
- async function j(e, t) {
328
+ async function z(e, t) {
329
329
  try {
330
330
  const o = await f(`${t}/tx`, {
331
331
  method: "POST",
@@ -338,8 +338,8 @@ async function j(e, t) {
338
338
  const i = await o.text();
339
339
  let n;
340
340
  try {
341
- const a = JSON.parse(i);
342
- n = a.message ?? a.error;
341
+ const s = JSON.parse(i);
342
+ n = s.message ?? s.error;
343
343
  } catch {
344
344
  n = i;
345
345
  }
@@ -352,10 +352,10 @@ async function j(e, t) {
352
352
  throw o instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${o.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
353
353
  }
354
354
  }
355
- async function R(e, t) {
355
+ async function U(e, t) {
356
356
  return u(e), c(`${t}/tx/${e}`);
357
357
  }
358
- async function z(e) {
358
+ async function Q(e) {
359
359
  const t = await c(`${e}/blocks/tip/height`), o = t.trim();
360
360
  if (!/^\d+$/.test(o))
361
361
  throw new Error(
@@ -363,12 +363,12 @@ async function z(e) {
363
363
  );
364
364
  return Number.parseInt(o, 10);
365
365
  }
366
- async function Q(e, t, o) {
366
+ async function W(e, t, o) {
367
367
  if (u(e), !d(t))
368
368
  throw new Error(`Invalid vout ${t} for transaction ${e}`);
369
369
  return c(`${o}/tx/${e}/outspend/${t}`);
370
370
  }
371
- async function W(e, t) {
371
+ async function L(e, t) {
372
372
  u(e);
373
373
  try {
374
374
  const o = await f(`${t}/tx/${e}/hex`);
@@ -383,9 +383,9 @@ async function W(e, t) {
383
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`);
384
384
  }
385
385
  }
386
- async function L(e, t, o) {
386
+ async function G(e, t, o) {
387
387
  u(e);
388
- const r = await R(e, o);
388
+ const r = await U(e, o);
389
389
  if (!d(t, r.vout.length))
390
390
  throw new Error(
391
391
  `Invalid vout ${t} for transaction ${e} (has ${r.vout.length} outputs)`
@@ -400,7 +400,7 @@ async function L(e, t, o) {
400
400
  scriptPubKey: i.scriptpubkey
401
401
  };
402
402
  }
403
- async function G(e, t) {
403
+ async function J(e, t) {
404
404
  V(e);
405
405
  try {
406
406
  const o = await c(`${t}/address/${e}/utxo`), r = await c(`${t}/v1/validate-address/${e}`);
@@ -417,7 +417,7 @@ async function G(e, t) {
417
417
  `Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`
418
418
  );
419
419
  }
420
- return o.sort((n, a) => a.value - n.value).map((n) => ({
420
+ return o.sort((n, s) => s.value - n.value).map((n) => ({
421
421
  txid: n.txid,
422
422
  vout: n.vout,
423
423
  value: n.value,
@@ -432,13 +432,13 @@ async function G(e, t) {
432
432
  );
433
433
  }
434
434
  }
435
- function J(e) {
436
- return K[e];
435
+ function q(e) {
436
+ return R[e];
437
437
  }
438
- async function q(e, t) {
438
+ async function Y(e, t) {
439
439
  return V(e), c(`${t}/address/${e}/txs`);
440
440
  }
441
- async function Y(e) {
441
+ async function Z(e) {
442
442
  const t = await f(`${e}/v1/fees/recommended`);
443
443
  if (!t.ok)
444
444
  throw new Error(
@@ -452,7 +452,7 @@ async function Y(e) {
452
452
  "minimumFee"
453
453
  ];
454
454
  for (const i of r)
455
- if (!O(o[i]))
455
+ if (!K(o[i]))
456
456
  throw new Error(
457
457
  `Invalid fee rate ${i}=${o[i]} from mempool API: expected a positive number ≤ ${I}`
458
458
  );
@@ -463,21 +463,21 @@ async function Y(e) {
463
463
  return o;
464
464
  }
465
465
  export {
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,
466
+ R as M,
467
+ j as V,
468
+ J as a,
469
+ q as b,
470
+ Z as c,
471
+ W as d,
472
+ Q as e,
473
+ L as f,
474
+ Y as g,
475
+ U as h,
476
+ G as i,
477
+ D as j,
478
+ N as k,
479
479
  h as l,
480
- j as p,
481
- k as v
480
+ z as p,
481
+ S as v
482
482
  };
483
- //# sourceMappingURL=mempoolApi-CB7bHuwi.js.map
483
+ //# sourceMappingURL=mempoolApi-lpJdvPkK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-lpJdvPkK.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 { combineAbortSignals } from \"../../utils/abortSignals\";\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 const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\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","combined","combineAbortSignals","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,EAA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;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;"}
@@ -1,2 +1,2 @@
1
- "use strict";const l=require("@babylonlabs-io/babylon-tbv-rust-wasm"),a=require("buffer"),d=require("bitcoinjs-lib"),t=require("./bitcoin-CHfKAhcI.cjs"),C=require("./verifyScriptPathSchnorrSignature-BDznSCOR.cjs");async function S(s){await l.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:o,htlcVout:r,refundFee:c,hashlock:f}=s,g=C.normalizeAuthAnchorHash(e.authAnchorHash),u=new l.WasmPrePeginTx(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(l.assertPositiveBigintArray(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,g);let n=null;try{const p=u.getHtlcScriptPubKey(r).toLowerCase(),h=u.getHtlcValue(r);n=u.fromFundedTransaction(o);const x=n.buildRefundTx(c,r),k=await l.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:f,timelockRefund:e.timelockRefund,network:e.network}),$=o.startsWith("0x")?o.slice(2):o,v=d.Transaction.fromHex($),y=v.outs[r];if(!y)throw new Error(`HTLC output at vout ${r} not found in funded Pre-PegIn tx (tx has ${v.outs.length} outputs)`);const T=t.uint8ArrayToHex(new Uint8Array(y.script)).toLowerCase();if(T!==p)throw new Error(`HTLC scriptPubKey mismatch at vout ${r}: reconstructed template expects ${p}, funded tx carries ${T}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const w=BigInt(y.value);if(w!==h)throw new Error(`HTLC value mismatch at vout ${r}: reconstructed template expects ${h} sat, funded tx carries ${w} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const i=d.Transaction.fromHex(x);if(i.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${i.ins.length}`);const P=i.ins[0],H=v.getId(),A=t.uint8ArrayToHex(new Uint8Array(P.hash).slice().reverse());if(A!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${A}`);if(P.index!==r)throw new Error(`Refund input index ${P.index} does not match expected htlcVout ${r}`);const m=new d.Psbt;if(m.setVersion(i.version),m.setLocktime(i.locktime),m.addInput({hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:y.script,value:y.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(t.hexToUint8Array(k.refundScript)),controlBlock:a.Buffer.from(t.hexToUint8Array(k.refundControlBlock))}],tapInternalKey:a.Buffer.from(l.tapInternalPubkey)}),i.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${i.outs.length}`);const b=i.outs[0],I=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),R=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(R!==I)throw new Error(`Refund output scriptPubKey ${R} does not match the depositor's BIP-86 address ${I}. Refund refused — the reclaimed funds would not return to the depositor.`);const B=w-c;if(BigInt(b.value)!==B)throw new Error(`Refund output value ${BigInt(b.value)} sat does not equal the HTLC value ${w} sat minus the requested fee ${c} sat (expected ${B} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return m.addOutput({script:b.script,value:b.value}),{psbtHex:m.toHex()}}finally{n==null||n.free(),u.free()}}async function E(s){const e=t.stripHexPrefix(s.noPayoutTxHex),o=d.Transaction.fromHex(e),{noPayoutScript:r,noPayoutControlBlock:c}=await l.getAssertNoPayoutScriptInfo(s.connectorParams,s.challengerPubkey),f=t.hexToUint8Array(r),g=t.hexToUint8Array(c),u=new d.Psbt;u.setVersion(o.version),u.setLocktime(o.locktime);for(let n=0;n<o.ins.length;n++){const p=o.ins[n],h=s.prevouts[n];if(!h)throw new Error(`Missing prevout data for input ${n}`);const x={hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:a.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(h.script_pubkey))),value:h.value}};n===0&&(x.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(f),controlBlock:a.Buffer.from(g)}],x.tapInternalKey=a.Buffer.from(l.tapInternalPubkey)),u.addInput(x)}for(const n of o.outs)u.addOutput({script:n.script,value:n.value});return u.toHex()}function K(s,e,o){const r=d.Transaction.fromHex(t.stripHexPrefix(s));if(r.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${r.outs.length}`);const c=t.hexToUint8Array(t.processPublicKeyToXOnly(e)),{output:f}=d.payments.p2tr({internalPubkey:a.Buffer.from(c),network:t.getNetwork(o)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!r.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=K;exports.buildNoPayoutPsbt=E;exports.buildRefundPsbt=S;
2
- //# sourceMappingURL=noPayout-CNMqNNpc.cjs.map
1
+ "use strict";const l=require("@babylonlabs-io/babylon-tbv-rust-wasm"),a=require("buffer"),d=require("bitcoinjs-lib"),t=require("./bitcoin-CHfKAhcI.cjs"),C=require("./verifyScriptPathSchnorrSignature-BZhX-SOd.cjs");async function S(s){await l.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:o,htlcVout:r,refundFee:c,hashlock:f}=s,g=C.normalizeAuthAnchorHash(e.authAnchorHash),u=new l.WasmPrePeginTx(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(l.assertPositiveBigintArray(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,g);let n=null;try{const p=u.getHtlcScriptPubKey(r).toLowerCase(),h=u.getHtlcValue(r);n=u.fromFundedTransaction(o);const x=n.buildRefundTx(c,r),k=await l.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:f,timelockRefund:e.timelockRefund,network:e.network}),$=o.startsWith("0x")?o.slice(2):o,v=d.Transaction.fromHex($),y=v.outs[r];if(!y)throw new Error(`HTLC output at vout ${r} not found in funded Pre-PegIn tx (tx has ${v.outs.length} outputs)`);const T=t.uint8ArrayToHex(new Uint8Array(y.script)).toLowerCase();if(T!==p)throw new Error(`HTLC scriptPubKey mismatch at vout ${r}: reconstructed template expects ${p}, funded tx carries ${T}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const w=BigInt(y.value);if(w!==h)throw new Error(`HTLC value mismatch at vout ${r}: reconstructed template expects ${h} sat, funded tx carries ${w} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const i=d.Transaction.fromHex(x);if(i.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${i.ins.length}`);const P=i.ins[0],H=v.getId(),A=t.uint8ArrayToHex(new Uint8Array(P.hash).slice().reverse());if(A!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${A}`);if(P.index!==r)throw new Error(`Refund input index ${P.index} does not match expected htlcVout ${r}`);const m=new d.Psbt;if(m.setVersion(i.version),m.setLocktime(i.locktime),m.addInput({hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:y.script,value:y.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(t.hexToUint8Array(k.refundScript)),controlBlock:a.Buffer.from(t.hexToUint8Array(k.refundControlBlock))}],tapInternalKey:a.Buffer.from(l.tapInternalPubkey)}),i.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${i.outs.length}`);const b=i.outs[0],I=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),R=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(R!==I)throw new Error(`Refund output scriptPubKey ${R} does not match the depositor's BIP-86 address ${I}. Refund refused — the reclaimed funds would not return to the depositor.`);const B=w-c;if(BigInt(b.value)!==B)throw new Error(`Refund output value ${BigInt(b.value)} sat does not equal the HTLC value ${w} sat minus the requested fee ${c} sat (expected ${B} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return m.addOutput({script:b.script,value:b.value}),{psbtHex:m.toHex()}}finally{n==null||n.free(),u.free()}}async function E(s){const e=t.stripHexPrefix(s.noPayoutTxHex),o=d.Transaction.fromHex(e),{noPayoutScript:r,noPayoutControlBlock:c}=await l.getAssertNoPayoutScriptInfo(s.connectorParams,s.challengerPubkey),f=t.hexToUint8Array(r),g=t.hexToUint8Array(c),u=new d.Psbt;u.setVersion(o.version),u.setLocktime(o.locktime);for(let n=0;n<o.ins.length;n++){const p=o.ins[n],h=s.prevouts[n];if(!h)throw new Error(`Missing prevout data for input ${n}`);const x={hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:a.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(h.script_pubkey))),value:h.value}};n===0&&(x.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(f),controlBlock:a.Buffer.from(g)}],x.tapInternalKey=a.Buffer.from(l.tapInternalPubkey)),u.addInput(x)}for(const n of o.outs)u.addOutput({script:n.script,value:n.value});return u.toHex()}function K(s,e,o){const r=d.Transaction.fromHex(t.stripHexPrefix(s));if(r.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${r.outs.length}`);const c=t.hexToUint8Array(t.processPublicKeyToXOnly(e)),{output:f}=d.payments.p2tr({internalPubkey:a.Buffer.from(c),network:t.getNetwork(o)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!r.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=K;exports.buildNoPayoutPsbt=E;exports.buildRefundPsbt=S;
2
+ //# sourceMappingURL=noPayout-Cb8vFrkY.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"noPayout-CNMqNNpc.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"sNAyEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAYIO,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAIXO,EAAa,IAAIC,EAAAA,eACrBR,EAAe,iBACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eACFS,4BAA0BT,EAAe,aAAc,cAAc,CAAA,EAEvEA,EAAe,eACfA,EAAe,QACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,QACfK,CAAA,EAGF,IAAIK,EAAkC,KACtC,GAAI,CASF,MAAMC,EAA2BJ,EAC9B,oBAAoBL,CAAQ,EAC5B,YAAA,EAMGU,EAAoBL,EAAW,aAAaL,CAAQ,EAE1DQ,EAAWH,EAAW,sBAAsBN,CAAmB,EAE/D,MAAMY,EAAcH,EAAS,cAA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EAAKrC,EAAAA,YAAY,QAAQiB,EAAAA,eAAeK,CAAa,CAAC,EAE5D,GAAIe,EAAG,KAAK,SAAW,EACrB,MAAM,IAAI,MACR,wDAAwDA,EAAG,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQzB,EAAAA,gBAAgB0B,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgB7B,EAAAA,OAAO,KAAK0B,CAAK,EACjC,QAASI,EAAAA,WAAWN,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
1
+ {"version":3,"file":"noPayout-Cb8vFrkY.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"sNAyEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAYIO,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAIXO,EAAa,IAAIC,EAAAA,eACrBR,EAAe,iBACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eACFS,4BAA0BT,EAAe,aAAc,cAAc,CAAA,EAEvEA,EAAe,eACfA,EAAe,QACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,QACfK,CAAA,EAGF,IAAIK,EAAkC,KACtC,GAAI,CASF,MAAMC,EAA2BJ,EAC9B,oBAAoBL,CAAQ,EAC5B,YAAA,EAMGU,EAAoBL,EAAW,aAAaL,CAAQ,EAE1DQ,EAAWH,EAAW,sBAAsBN,CAAmB,EAE/D,MAAMY,EAAcH,EAAS,cAAcP,EAAWD,CAAQ,EAExDY,EAAgB,MAAMC,+BAA6B,CACvD,eAAgBf,EAAe,i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,EAAG,KAAK,SAAW,EACrB,MAAM,IAAI,MACR,wDAAwDA,EAAG,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQzB,EAAAA,gBAAgB0B,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgB7B,EAAAA,OAAO,KAAK0B,CAAK,EACjC,QAASI,EAAAA,WAAWN,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
@@ -2,7 +2,7 @@ import { initWasm as L, WasmPrePeginTx as V, assertPositiveBigintArray as O, get
2
2
  import { Buffer as a } from "buffer";
3
3
  import { Transaction as w, Psbt as E, payments as U } from "bitcoinjs-lib";
4
4
  import { u as k, T as K, h as f, s as g, d as F, p as z, j as W } from "./bitcoin-B5aNKtsk.js";
5
- import { n as _ } from "./verifyScriptPathSchnorrSignature-DA4Z4yZ3.js";
5
+ import { n as _ } from "./verifyScriptPathSchnorrSignature-CgrnAjMW.js";
6
6
  async function X(s) {
7
7
  await L();
8
8
  const { prePeginParams: e, fundedPrePeginTxHex: n, htlcVout: t, refundFee: i, hashlock: c } = s, v = _(
@@ -175,4 +175,4 @@ export {
175
175
  X as b,
176
176
  Y as c
177
177
  };
178
- //# sourceMappingURL=noPayout-CfBg3HzC.js.map
178
+ //# sourceMappingURL=noPayout-CihCk1HE.js.map