@babylonlabs-io/ts-sdk 0.33.3 → 0.33.5

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 (153) hide show
  1. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js +417 -0
  2. package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js.map +1 -0
  3. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs +2 -0
  4. package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs.map +1 -0
  5. package/dist/PayoutManager-C9XHKZ5j.js +200 -0
  6. package/dist/PayoutManager-C9XHKZ5j.js.map +1 -0
  7. package/dist/PayoutManager-DDnNB0mj.cjs +2 -0
  8. package/dist/PayoutManager-DDnNB0mj.cjs.map +1 -0
  9. package/dist/PeginManager-BXg2S1mH.cjs +2 -0
  10. package/dist/PeginManager-BXg2S1mH.cjs.map +1 -0
  11. package/dist/{PeginManager-C-L3huRO.js → PeginManager-C5HaMAcw.js} +328 -437
  12. package/dist/PeginManager-C5HaMAcw.js.map +1 -0
  13. package/dist/ProtocolParams.abi-BmvHwQJV.cjs +2 -0
  14. package/dist/ProtocolParams.abi-BmvHwQJV.cjs.map +1 -0
  15. package/dist/ProtocolParams.abi-DXu8L0Fn.js +382 -0
  16. package/dist/ProtocolParams.abi-DXu8L0Fn.js.map +1 -0
  17. package/dist/buildAndBroadcastRefund-B332dykQ.cjs +2 -0
  18. package/dist/buildAndBroadcastRefund-B332dykQ.cjs.map +1 -0
  19. package/dist/buildAndBroadcastRefund-CPjXNaMi.js +782 -0
  20. package/dist/buildAndBroadcastRefund-CPjXNaMi.js.map +1 -0
  21. package/dist/challengeAssert-BzxQmdZy.js +128 -0
  22. package/dist/challengeAssert-BzxQmdZy.js.map +1 -0
  23. package/dist/challengeAssert-Yyyj-EdR.cjs +2 -0
  24. package/dist/challengeAssert-Yyyj-EdR.cjs.map +1 -0
  25. package/dist/errors-9AkghWyk.js +22 -0
  26. package/dist/errors-9AkghWyk.js.map +1 -0
  27. package/dist/errors-BP73_stm.cjs +2 -0
  28. package/dist/errors-BP73_stm.cjs.map +1 -0
  29. package/dist/errors-Bu0H-dZD.cjs +2 -0
  30. package/dist/errors-Bu0H-dZD.cjs.map +1 -0
  31. package/dist/errors-CznAK5NB.js +96 -0
  32. package/dist/errors-CznAK5NB.js.map +1 -0
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +159 -147
  35. package/dist/index.js.map +1 -1
  36. package/dist/mempoolApi-CAIge7Nj.js +205 -0
  37. package/dist/mempoolApi-CAIge7Nj.js.map +1 -0
  38. package/dist/mempoolApi-YNkKjQCU.cjs +2 -0
  39. package/dist/mempoolApi-YNkKjQCU.cjs.map +1 -0
  40. package/dist/noPayout-BXeUw0Qq.cjs +2 -0
  41. package/dist/noPayout-BXeUw0Qq.cjs.map +1 -0
  42. package/dist/noPayout-DBX6G96_.js +141 -0
  43. package/dist/noPayout-DBX6G96_.js.map +1 -0
  44. package/dist/payout-BNFMBXS6.js +193 -0
  45. package/dist/payout-BNFMBXS6.js.map +1 -0
  46. package/dist/payout-DQ_fmJUA.cjs +2 -0
  47. package/dist/payout-DQ_fmJUA.cjs.map +1 -0
  48. package/dist/peginInput-C2QPvuhR.js +177 -0
  49. package/dist/peginInput-C2QPvuhR.js.map +1 -0
  50. package/dist/peginInput-tbw9BpZy.cjs +2 -0
  51. package/dist/peginInput-tbw9BpZy.cjs.map +1 -0
  52. package/dist/peginState-BijNNT15.cjs +2 -0
  53. package/dist/peginState-BijNNT15.cjs.map +1 -0
  54. package/dist/peginState-CBAlxgXk.js +51 -0
  55. package/dist/peginState-CBAlxgXk.js.map +1 -0
  56. package/dist/psbtInputFields-2224j2ZY.js +128 -0
  57. package/dist/psbtInputFields-2224j2ZY.js.map +1 -0
  58. package/dist/psbtInputFields-B1lrwYzH.cjs +2 -0
  59. package/dist/psbtInputFields-B1lrwYzH.cjs.map +1 -0
  60. package/dist/reservation-CHUGW0F_.js +142 -0
  61. package/dist/reservation-CHUGW0F_.js.map +1 -0
  62. package/dist/reservation-ho7mjW3X.cjs +2 -0
  63. package/dist/reservation-ho7mjW3X.cjs.map +1 -0
  64. package/dist/signing-Bnsro0hE.cjs +2 -0
  65. package/dist/signing-Bnsro0hE.cjs.map +1 -0
  66. package/dist/signing-DaLvGwQe.js +16 -0
  67. package/dist/signing-DaLvGwQe.js.map +1 -0
  68. package/dist/tbv/core/clients/index.cjs +1 -1
  69. package/dist/tbv/core/clients/index.js +35 -32
  70. package/dist/tbv/core/clients/index.js.map +1 -1
  71. package/dist/tbv/core/clients/vault-provider/__tests__/batchAttribution.test.d.ts +2 -0
  72. package/dist/tbv/core/clients/vault-provider/__tests__/batchAttribution.test.d.ts.map +1 -0
  73. package/dist/tbv/core/clients/vault-provider/__tests__/batchPoll.test.d.ts +2 -0
  74. package/dist/tbv/core/clients/vault-provider/__tests__/batchPoll.test.d.ts.map +1 -0
  75. package/dist/tbv/core/clients/vault-provider/api.d.ts +13 -4
  76. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
  77. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts +45 -0
  78. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts.map +1 -0
  79. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts +55 -0
  80. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts.map +1 -0
  81. package/dist/tbv/core/clients/vault-provider/index.d.ts +2 -0
  82. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
  83. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +3 -3
  84. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  85. package/dist/tbv/core/clients/vault-provider/types.d.ts +68 -24
  86. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
  87. package/dist/tbv/core/clients/vault-provider/validators.d.ts +12 -2
  88. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
  89. package/dist/tbv/core/contracts/index.cjs +2 -0
  90. package/dist/tbv/core/contracts/index.cjs.map +1 -0
  91. package/dist/tbv/core/contracts/index.js +14 -0
  92. package/dist/tbv/core/contracts/index.js.map +1 -0
  93. package/dist/tbv/core/index.cjs +1 -1
  94. package/dist/tbv/core/index.js +157 -145
  95. package/dist/tbv/core/index.js.map +1 -1
  96. package/dist/tbv/core/managers/index.cjs +2 -0
  97. package/dist/tbv/core/managers/index.cjs.map +1 -0
  98. package/dist/tbv/core/managers/index.js +7 -0
  99. package/dist/tbv/core/managers/index.js.map +1 -0
  100. package/dist/tbv/core/primitives/index.cjs +1 -1
  101. package/dist/tbv/core/primitives/index.js +31 -29
  102. package/dist/tbv/core/primitives/index.js.map +1 -1
  103. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -1
  104. package/dist/tbv/core/services/index.cjs +1 -1
  105. package/dist/tbv/core/services/index.js +28 -27
  106. package/dist/tbv/core/services/index.js.map +1 -1
  107. package/dist/tbv/core/services/pegout/state.d.ts +1 -1
  108. package/dist/tbv/core/utils/index.cjs +1 -1
  109. package/dist/tbv/core/utils/index.js +21 -20
  110. package/dist/tbv/core/utils/index.js.map +1 -1
  111. package/dist/tbv/index.cjs +1 -1
  112. package/dist/tbv/index.js +157 -145
  113. package/dist/tbv/index.js.map +1 -1
  114. package/dist/types-DnyyBNcC.cjs +2 -0
  115. package/dist/types-DnyyBNcC.cjs.map +1 -0
  116. package/dist/types-TiIjyo2b.js +320 -0
  117. package/dist/types-TiIjyo2b.js.map +1 -0
  118. package/dist/vault-registry-reader-BDFpXeH7.js +1152 -0
  119. package/dist/vault-registry-reader-BDFpXeH7.js.map +1 -0
  120. package/dist/vault-registry-reader-ejm2UYzk.cjs +2 -0
  121. package/dist/vault-registry-reader-ejm2UYzk.cjs.map +1 -0
  122. package/package.json +11 -1
  123. package/dist/PeginManager-C-L3huRO.js.map +0 -1
  124. package/dist/PeginManager-DmPmzPHz.cjs +0 -2
  125. package/dist/PeginManager-DmPmzPHz.cjs.map +0 -1
  126. package/dist/buildAndBroadcastRefund-Dx09Zbla.js +0 -965
  127. package/dist/buildAndBroadcastRefund-Dx09Zbla.js.map +0 -1
  128. package/dist/buildAndBroadcastRefund-PmJMNrhO.cjs +0 -2
  129. package/dist/buildAndBroadcastRefund-PmJMNrhO.cjs.map +0 -1
  130. package/dist/challengeAssert-D3tHnLWb.js +0 -298
  131. package/dist/challengeAssert-D3tHnLWb.js.map +0 -1
  132. package/dist/challengeAssert-Dp9d1bg1.cjs +0 -2
  133. package/dist/challengeAssert-Dp9d1bg1.cjs.map +0 -1
  134. package/dist/noPayout-BnsetBKW.js +0 -327
  135. package/dist/noPayout-BnsetBKW.js.map +0 -1
  136. package/dist/noPayout-DWaCtpMU.cjs +0 -2
  137. package/dist/noPayout-DWaCtpMU.cjs.map +0 -1
  138. package/dist/psbtInputFields-6sRcZqdb.cjs +0 -2
  139. package/dist/psbtInputFields-6sRcZqdb.cjs.map +0 -1
  140. package/dist/psbtInputFields-C5QPn1YK.js +0 -264
  141. package/dist/psbtInputFields-C5QPn1YK.js.map +0 -1
  142. package/dist/signing-BZigafm0.js +0 -64
  143. package/dist/signing-BZigafm0.js.map +0 -1
  144. package/dist/signing-DHSXjhLM.cjs +0 -2
  145. package/dist/signing-DHSXjhLM.cjs.map +0 -1
  146. package/dist/types-PthVHz5q.cjs +0 -2
  147. package/dist/types-PthVHz5q.cjs.map +0 -1
  148. package/dist/types-SYvSQWnc.js +0 -732
  149. package/dist/types-SYvSQWnc.js.map +0 -1
  150. package/dist/vault-registry-reader-CKe9TbX6.cjs +0 -2
  151. package/dist/vault-registry-reader-CKe9TbX6.cjs.map +0 -1
  152. package/dist/vault-registry-reader-CWGbw_wZ.js +0 -1567
  153. package/dist/vault-registry-reader-CWGbw_wZ.js.map +0 -1
@@ -0,0 +1,205 @@
1
+ import { B as $, H as p, K as E, T as F } from "./validation-CxqROCno.js";
2
+ const y = 21e6 * 1e8, u = 3e4;
3
+ async function i(e, r) {
4
+ const t = new AbortController(), n = setTimeout(
5
+ () => t.abort(),
6
+ u
7
+ ), a = [t.signal, r == null ? void 0 : r.signal].filter(
8
+ Boolean
9
+ );
10
+ try {
11
+ return await fetch(e, {
12
+ ...r,
13
+ signal: AbortSignal.any(a)
14
+ });
15
+ } catch (o) {
16
+ throw clearTimeout(n), o != null && typeof o == "object" && "name" in o && o.name === "AbortError" ? new Error(
17
+ `Mempool API request timed out after ${u}ms: ${e}`
18
+ ) : o;
19
+ }
20
+ }
21
+ const l = 1e4;
22
+ function w(e) {
23
+ return Number.isInteger(e) && e > 0 && e <= y;
24
+ }
25
+ function I(e) {
26
+ return Number.isInteger(e) && e > 0 && e <= l;
27
+ }
28
+ function m(e, r) {
29
+ return !Number.isInteger(e) || e < 0 ? !1 : r === void 0 || e < r;
30
+ }
31
+ function c(e) {
32
+ if (!F.test(e))
33
+ throw new Error(`Invalid transaction ID format: ${e}`);
34
+ }
35
+ function h(e) {
36
+ if (!$.test(e))
37
+ throw new Error(`Invalid Bitcoin address format: ${e}`);
38
+ }
39
+ function d(e, r) {
40
+ if (!p.test(e))
41
+ throw new Error(
42
+ `Invalid scriptPubKey: not valid hex for ${r}`
43
+ );
44
+ if (!E.some(
45
+ (n) => e.toLowerCase().startsWith(n)
46
+ ))
47
+ throw new Error(
48
+ `Unrecognized scriptPubKey type for ${r}: prefix ${e.slice(0, 6)} does not match any known Bitcoin script type`
49
+ );
50
+ }
51
+ const T = {
52
+ mainnet: "https://mempool.space/api",
53
+ testnet: "https://mempool.space/testnet/api",
54
+ signet: "https://mempool.space/signet/api"
55
+ };
56
+ async function s(e, r) {
57
+ try {
58
+ const t = await i(e, r);
59
+ if (!t.ok) {
60
+ const a = await t.text();
61
+ throw new Error(
62
+ `Mempool API error (${t.status}): ${a || t.statusText}`
63
+ );
64
+ }
65
+ const n = t.headers.get("content-type");
66
+ return n != null && n.includes("application/json") ? await t.json() : await t.text();
67
+ } catch (t) {
68
+ throw t instanceof Error ? new Error(`Failed to fetch from mempool API: ${t.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
69
+ }
70
+ }
71
+ async function v(e, r) {
72
+ try {
73
+ const t = await i(`${r}/tx`, {
74
+ method: "POST",
75
+ body: e,
76
+ headers: {
77
+ "Content-Type": "text/plain"
78
+ }
79
+ });
80
+ if (!t.ok) {
81
+ const a = await t.text();
82
+ let o;
83
+ try {
84
+ o = JSON.parse(a).message;
85
+ } catch {
86
+ o = a;
87
+ }
88
+ throw new Error(
89
+ o || `Failed to broadcast transaction: ${t.statusText}`
90
+ );
91
+ }
92
+ return await t.text();
93
+ } catch (t) {
94
+ throw t instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${t.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
95
+ }
96
+ }
97
+ async function g(e, r) {
98
+ return c(e), s(`${r}/tx/${e}`);
99
+ }
100
+ async function A(e, r) {
101
+ c(e);
102
+ try {
103
+ const t = await i(`${r}/tx/${e}/hex`);
104
+ if (!t.ok) {
105
+ const n = await t.text();
106
+ throw new Error(
107
+ `Mempool API error (${t.status}): ${n || t.statusText}`
108
+ );
109
+ }
110
+ return await t.text();
111
+ } catch (t) {
112
+ throw t instanceof Error ? new Error(`Failed to get transaction hex for ${e}: ${t.message}`) : new Error(`Failed to get transaction hex for ${e}: Unknown error`);
113
+ }
114
+ }
115
+ async function b(e, r, t) {
116
+ c(e);
117
+ const n = await g(e, t);
118
+ if (!m(r, n.vout.length))
119
+ throw new Error(
120
+ `Invalid vout ${r} for transaction ${e} (has ${n.vout.length} outputs)`
121
+ );
122
+ const a = n.vout[r];
123
+ if (!w(a.value))
124
+ throw new Error(`Invalid UTXO value ${a.value} for ${e}:${r}`);
125
+ return d(a.scriptpubkey, `${e}:${r}`), {
126
+ txid: e,
127
+ vout: r,
128
+ value: a.value,
129
+ scriptPubKey: a.scriptpubkey
130
+ };
131
+ }
132
+ async function P(e, r) {
133
+ h(e);
134
+ try {
135
+ const t = await s(`${r}/address/${e}/utxo`), n = await s(`${r}/v1/validate-address/${e}`);
136
+ if (!n.isvalid)
137
+ throw new Error(
138
+ `Invalid Bitcoin address: ${e}. Mempool API validation failed.`
139
+ );
140
+ d(n.scriptPubKey, e);
141
+ for (const o of t) {
142
+ if (c(o.txid), !m(o.vout))
143
+ throw new Error(`Invalid vout ${o.vout} for ${o.txid}`);
144
+ if (!w(o.value))
145
+ throw new Error(
146
+ `Invalid UTXO value ${o.value} for ${o.txid}:${o.vout}`
147
+ );
148
+ }
149
+ return t.sort((o, f) => f.value - o.value).map((o) => ({
150
+ txid: o.txid,
151
+ vout: o.vout,
152
+ value: o.value,
153
+ scriptPubKey: n.scriptPubKey,
154
+ confirmed: o.status.confirmed
155
+ }));
156
+ } catch (t) {
157
+ throw t instanceof Error ? new Error(
158
+ `Failed to get UTXOs for address ${e}: ${t.message}`
159
+ ) : new Error(
160
+ `Failed to get UTXOs for address ${e}: Unknown error`
161
+ );
162
+ }
163
+ }
164
+ function O(e) {
165
+ return T[e];
166
+ }
167
+ async function U(e, r) {
168
+ return h(e), s(`${r}/address/${e}/txs`);
169
+ }
170
+ async function S(e) {
171
+ const r = await i(`${e}/v1/fees/recommended`);
172
+ if (!r.ok)
173
+ throw new Error(
174
+ `Failed to fetch network fees: ${r.status} ${r.statusText}`
175
+ );
176
+ const t = await r.json(), n = [
177
+ "fastestFee",
178
+ "halfHourFee",
179
+ "hourFee",
180
+ "economyFee",
181
+ "minimumFee"
182
+ ];
183
+ for (const a of n)
184
+ if (!I(t[a]))
185
+ throw new Error(
186
+ `Invalid fee rate ${a}=${t[a]} from mempool API: expected a positive number ≤ ${l}`
187
+ );
188
+ if (t.minimumFee > t.economyFee || t.economyFee > t.hourFee || t.hourFee > t.halfHourFee || t.halfHourFee > t.fastestFee)
189
+ throw new Error(
190
+ `Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`
191
+ );
192
+ return t;
193
+ }
194
+ export {
195
+ T as M,
196
+ P as a,
197
+ O as b,
198
+ S as c,
199
+ A as d,
200
+ g as e,
201
+ b as f,
202
+ U as g,
203
+ v as p
204
+ };
205
+ //# sourceMappingURL=mempoolApi-CAIge7Nj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-CAIge7Nj.js","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\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 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":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":";AAmBA,MAAMA,IAAe,OAAa,KAG5BC,IAA6B;AAMnC,eAAeC,EACbC,GACAC,GACmB;AACnB,QAAMC,IAAa,IAAI,gBAAA,GACjBC,IAAY;AAAA,IAChB,MAAMD,EAAW,MAAA;AAAA,IACjBJ;AAAA,EAAA,GAIIM,IAAU,CAACF,EAAW,QAAQD,KAAA,gBAAAA,EAAS,MAAM,EAAE;AAAA,IACnD;AAAA,EAAA;AAGF,MAAI;AAEF,WAAO,MAAM,MAAMD,GAAK;AAAA,MACtB,GAAGC;AAAA,MACH,QAAQ,YAAY,IAAIG,CAAO;AAAA,IAAA,CAChC;AAAA,EACH,SAASC,GAAO;AAEd,UADA,aAAaF,CAAS,GAEpBE,KAAS,QACT,OAAOA,KAAU,YACjB,UAAUA,KACVA,EAAM,SAAS,eAET,IAAI;AAAA,MACR,uCAAuCP,CAA0B,OAAOE,CAAG;AAAA,IAAA,IAGzEK;AAAA,EACR;AACF;AAMA,MAAMC,IAAe;AAErB,SAASC,EAAoBC,GAAwB;AACnD,SAAO,OAAO,UAAUA,CAAK,KAAKA,IAAQ,KAAKA,KAASX;AAC1D;AAEA,SAASY,EAAeD,GAAwB;AAC9C,SAAO,OAAO,UAAUA,CAAK,KAAKA,IAAQ,KAAKA,KAASF;AAC1D;AAEA,SAASI,EAAYC,GAAcC,GAA+B;AAChE,SAAI,CAAC,OAAO,UAAUD,CAAI,KAAKA,IAAO,IAAU,KACzCC,MAAgB,UAAaD,IAAOC;AAC7C;AAGA,SAASC,EAAgBC,GAAoB;AAC3C,MAAI,CAACC,EAAQ,KAAKD,CAAI;AACpB,UAAM,IAAI,MAAM,kCAAkCA,CAAI,EAAE;AAE5D;AAE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A,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const a=require("./validation-u8W7Lp2x.cjs"),F=21e6*1e8,l=3e4;async function c(e,r){const t=new AbortController,n=setTimeout(()=>t.abort(),l),s=[t.signal,r==null?void 0:r.signal].filter(Boolean);try{return await fetch(e,{...r,signal:AbortSignal.any(s)})}catch(o){throw clearTimeout(n),o!=null&&typeof o=="object"&&"name"in o&&o.name==="AbortError"?new Error(`Mempool API request timed out after ${l}ms: ${e}`):o}}const w=1e4;function m(e){return Number.isInteger(e)&&e>0&&e<=F}function g(e){return Number.isInteger(e)&&e>0&&e<=w}function h(e,r){return!Number.isInteger(e)||e<0?!1:r===void 0||e<r}function f(e){if(!a.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function d(e){if(!a.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function $(e,r){if(!a.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${r}`);if(!a.KNOWN_SCRIPT_PREFIXES.some(n=>e.toLowerCase().startsWith(n)))throw new Error(`Unrecognized scriptPubKey type for ${r}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const p={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function i(e,r){try{const t=await c(e,r);if(!t.ok){const s=await t.text();throw new Error(`Mempool API error (${t.status}): ${s||t.statusText}`)}const n=t.headers.get("content-type");return n!=null&&n.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function I(e,r){try{const t=await c(`${r}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!t.ok){const s=await t.text();let o;try{o=JSON.parse(s).message}catch{o=s}throw new Error(o||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function E(e,r){return f(e),i(`${r}/tx/${e}`)}async function T(e,r){f(e);try{const t=await c(`${r}/tx/${e}/hex`);if(!t.ok){const n=await t.text();throw new Error(`Mempool API error (${t.status}): ${n||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${t.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function x(e,r,t){f(e);const n=await E(e,t);if(!h(r,n.vout.length))throw new Error(`Invalid vout ${r} for transaction ${e} (has ${n.vout.length} outputs)`);const s=n.vout[r];if(!m(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${e}:${r}`);return $(s.scriptpubkey,`${e}:${r}`),{txid:e,vout:r,value:s.value,scriptPubKey:s.scriptpubkey}}async function y(e,r){d(e);try{const t=await i(`${r}/address/${e}/utxo`),n=await i(`${r}/v1/validate-address/${e}`);if(!n.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);$(n.scriptPubKey,e);for(const o of t){if(f(o.txid),!h(o.vout))throw new Error(`Invalid vout ${o.vout} for ${o.txid}`);if(!m(o.value))throw new Error(`Invalid UTXO value ${o.value} for ${o.txid}:${o.vout}`)}return t.sort((o,u)=>u.value-o.value).map(o=>({txid:o.txid,vout:o.vout,value:o.value,scriptPubKey:n.scriptPubKey,confirmed:o.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${t.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function v(e){return p[e]}async function A(e,r){return d(e),i(`${r}/address/${e}/txs`)}async function P(e){const r=await c(`${e}/v1/fees/recommended`);if(!r.ok)throw new Error(`Failed to fetch network fees: ${r.status} ${r.statusText}`);const t=await r.json(),n=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const s of n)if(!g(t[s]))throw new Error(`Invalid fee rate ${s}=${t[s]} from mempool API: expected a positive number ≤ ${w}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}exports.MEMPOOL_API_URLS=p;exports.getAddressTxs=A;exports.getAddressUtxos=y;exports.getMempoolApiUrl=v;exports.getNetworkFees=P;exports.getTxHex=T;exports.getTxInfo=E;exports.getUtxoInfo=x;exports.pushTx=I;
2
+ //# sourceMappingURL=mempoolApi-YNkKjQCU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-YNkKjQCU.cjs","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\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 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":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"0DAmBMA,EAAe,KAAa,IAG5BC,EAA6B,IAMnC,eAAeC,EACbC,EACAC,EACmB,CACnB,MAAMC,EAAa,IAAI,gBACjBC,EAAY,WAChB,IAAMD,EAAW,MAAA,EACjBJ,CAAA,EAIIM,EAAU,CAACF,EAAW,OAAQD,GAAA,YAAAA,EAAS,MAAM,EAAE,OACnD,OAAA,EAGF,GAAI,CAEF,OAAO,MAAM,MAAMD,EAAK,CACtB,GAAGC,EACH,OAAQ,YAAY,IAAIG,CAAO,CAAA,CAChC,CACH,OAASC,EAAO,CAEd,MADA,aAAaF,CAAS,EAEpBE,GAAS,MACT,OAAOA,GAAU,UACjB,SAAUA,GACVA,EAAM,OAAS,aAET,IAAI,MACR,uCAAuCP,CAA0B,OAAOE,CAAG,EAAA,EAGzEK,CACR,CACF,CAMA,MAAMC,EAAe,IAErB,SAASC,EAAoBC,EAAwB,CACnD,OAAO,OAAO,UAAUA,CAAK,GAAKA,EAAQ,GAAKA,GAASX,CAC1D,CAEA,SAASY,EAAeD,EAAwB,CAC9C,OAAO,OAAO,UAAUA,CAAK,GAAKA,EAAQ,GAAKA,GAASF,CAC1D,CAEA,SAASI,EAAYC,EAAcC,EAA+B,CAChE,MAAI,CAAC,OAAO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,aAAcD,EAAY,aAC1B,UAAWC,EAAK,OAAO,SAAA,EACvB,CACJ,OAASrC,EAAO,CACd,MAAIA,aAAiB,MACb,IAAI,MACR,mCAAmCY,CAAO,KAAKZ,EAAM,OAAO,EAAA,EAG1D,IAAI,MACR,mCAAmCY,CAAO,iBAAA,CAE9C,CACF,CAQO,SAAS4B,EACdC,EACQ,CACR,OAAOrB,EAAiBqB,CAAO,CACjC,CAuBA,eAAsBC,EACpB9B,EACAe,EACsB,CACtB,OAAAhB,EAAmBC,CAAO,EACnBS,EAAsB,GAAGM,CAAM,YAAYf,CAAO,MAAM,CACjE,CAWA,eAAsB+B,EAAehB,EAAsC,CACzE,MAAML,EAAW,MAAM5B,EAAiB,GAAGiC,CAAM,sBAAsB,EAEvE,GAAI,CAACL,EAAS,GACZ,MAAM,IAAI,MACR,iCAAiCA,EAAS,MAAM,IAAIA,EAAS,UAAU,EAAA,EAI3E,MAAMsB,EAAO,MAAMtB,EAAS,KAAA,EAEtBuB,EAAY,CAChB,aACA,cACA,UACA,aACA,YAAA,EAGF,UAAWC,KAASD,EAClB,GAAI,CAACzC,EAAewC,EAAKE,CAAK,CAAC,EAC7B,MAAM,IAAI,MACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmD7C,CAAY,EAAA,EAK7G,GACE2C,EAAK,WAAaA,EAAK,YACvBA,EAAK,WAAaA,EAAK,SACvBA,EAAK,QAAUA,EAAK,aACpBA,EAAK,YAAcA,EAAK,WAExB,MAAM,IAAI,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU,IAAA,EAIpC,OAAOA,CACT"}
@@ -0,0 +1,2 @@
1
+ "use strict";const d=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("buffer"),c=require("bitcoinjs-lib"),t=require("./bitcoin-B3aqjuMP.cjs");async function w(s){await d.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:n,htlcVout:o,refundFee:h,hashlock:l}=s,b=new d.WasmPrePeginTx(e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(e.pegInAmounts),e.timelockRefund,e.feeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network);let r=null;try{r=b.fromFundedTransaction(n);const u=r.buildRefundTx(h,o),f=await d.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:l,timelockRefund:e.timelockRefund,network:e.network}),x=n.startsWith("0x")?n.slice(2):n,a=c.Transaction.fromHex(x),k=a.outs[o];if(!k)throw new Error(`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${a.outs.length} outputs)`);const p=c.Transaction.fromHex(u);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const P=p.ins[0],g=a.getId(),v=t.uint8ArrayToHex(new Uint8Array(P.hash).slice().reverse());if(v!==g)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${g}, got ${v}`);if(P.index!==o)throw new Error(`Refund input index ${P.index} does not match expected htlcVout ${o}`);const y=new c.Psbt;y.setVersion(p.version),y.setLocktime(p.locktime),y.addInput({hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:k.script,value:k.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(t.hexToUint8Array(f.refundScript)),controlBlock:i.Buffer.from(t.hexToUint8Array(f.refundControlBlock))}],tapInternalKey:i.Buffer.from(d.tapInternalPubkey)});for(const T of p.outs)y.addOutput({script:T.script,value:T.value});return{psbtHex:y.toHex()}}finally{r==null||r.free(),b.free()}}async function m(s){const e=t.stripHexPrefix(s.noPayoutTxHex),n=c.Transaction.fromHex(e),{noPayoutScript:o,noPayoutControlBlock:h}=await d.getAssertNoPayoutScriptInfo(s.connectorParams,s.challengerPubkey),l=t.hexToUint8Array(o),b=t.hexToUint8Array(h),r=new c.Psbt;r.setVersion(n.version),r.setLocktime(n.locktime);for(let u=0;u<n.ins.length;u++){const f=n.ins[u],x=s.prevouts[u];if(!x)throw new Error(`Missing prevout data for input ${u}`);const a={hash:f.hash,index:f.index,sequence:f.sequence,witnessUtxo:{script:i.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(x.script_pubkey))),value:x.value}};u===0&&(a.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(l),controlBlock:i.Buffer.from(b)}],a.tapInternalKey=i.Buffer.from(d.tapInternalPubkey)),r.addInput(a)}for(const u of n.outs)r.addOutput({script:u.script,value:u.value});return r.toHex()}function I(s,e,n){const o=c.Transaction.fromHex(t.stripHexPrefix(s));if(o.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${o.outs.length}`);const h=t.hexToUint8Array(t.processPublicKeyToXOnly(e)),{output:l}=c.payments.p2tr({internalPubkey:i.Buffer.from(h),network:t.getNetwork(n)});if(!l)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!o.outs[0].script.equals(l))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=I;exports.buildNoPayoutPsbt=m;exports.buildRefundPsbt=w;
2
+ //# sourceMappingURL=noPayout-BXeUw0Qq.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"noPayout-BXeUw0Qq.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 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 { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport 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 const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\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 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 for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\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 `assertPayoutOutputMatchesRegistered` for the NoPayout path, where\n * the sink is fixed by the 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","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"yJAkEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAEIO,EAAa,IAAIC,EAAAA,eACrBN,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eAAeA,EAAe,YAAY,EAC9CA,EAAe,eACfA,EAAe,QACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,OAAA,EAGjB,IAAIO,EAAkC,KACtC,GAAI,CACFA,EAAWF,EAAW,sBAAsBJ,CAAmB,EAE/D,MAAMO,EAAcD,EAAS,cAAcJ,EAAWD,CAAQ,EAExDO,EAAgB,MAAMC,+BAA6B,CACvD,gBAAiBV,EAAe,gBAChC,oBAAqBA,EAAe,oBACpC,mBAAoBA,EAAe,mBACnC,2BAA4BA,EAAe,2BAC3C,SAAAI,EACA,eAAgBJ,EAAe,eAC/B,QAASA,EAAe,OAAA,CACzB,EAEKW,EAAmBV,EAAoB,WAAW,IAAI,EACxDA,EAAoB,MAAM,CAAC,EAC3BA,EACEW,EAAaC,EAAAA,YAAY,QAAQF,CAAgB,EAEjDG,EAAaF,EAAW,KAAKV,CAAQ,EAC3C,GAAI,CAACY,EACH,MAAM,IAAI,MACR,uBAAuBZ,CAAQ,6CAClBU,EAAW,KAAK,MAAM,WAAA,EAIvC,MAAMG,EAA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,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQpB,EAAAA,gBAAgBqB,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgBxB,EAAAA,OAAO,KAAKqB,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"}
@@ -0,0 +1,141 @@
1
+ import { initWasm as H, WasmPrePeginTx as R, getPrePeginHtlcConnectorInfo as B, tapInternalPubkey as b, getAssertNoPayoutScriptInfo as C } from "@babylonlabs-io/babylon-tbv-rust-wasm";
2
+ import { Buffer as u } from "buffer";
3
+ import { Transaction as y, Psbt as T, payments as E } from "bitcoinjs-lib";
4
+ import { u as S, T as I, h as f, s as k, p as $, g as A } from "./bitcoin-B0S8SHCX.js";
5
+ async function V(s) {
6
+ await H();
7
+ const { prePeginParams: e, fundedPrePeginTxHex: t, htlcVout: o, refundFee: d, hashlock: a } = s, x = new R(
8
+ e.depositorPubkey,
9
+ e.vaultProviderPubkey,
10
+ e.vaultKeeperPubkeys,
11
+ e.universalChallengerPubkeys,
12
+ [...e.hashlocks],
13
+ new BigUint64Array(e.pegInAmounts),
14
+ e.timelockRefund,
15
+ e.feeRate,
16
+ e.numLocalChallengers,
17
+ e.councilQuorum,
18
+ e.councilSize,
19
+ e.network
20
+ );
21
+ let n = null;
22
+ try {
23
+ n = x.fromFundedTransaction(t);
24
+ const r = n.buildRefundTx(d, o), c = await B({
25
+ depositorPubkey: e.depositorPubkey,
26
+ vaultProviderPubkey: e.vaultProviderPubkey,
27
+ vaultKeeperPubkeys: e.vaultKeeperPubkeys,
28
+ universalChallengerPubkeys: e.universalChallengerPubkeys,
29
+ hashlock: a,
30
+ timelockRefund: e.timelockRefund,
31
+ network: e.network
32
+ }), P = t.startsWith("0x") ? t.slice(2) : t, i = y.fromHex(P), m = i.outs[o];
33
+ if (!m)
34
+ throw new Error(
35
+ `HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${i.outs.length} outputs)`
36
+ );
37
+ const l = y.fromHex(r);
38
+ if (l.ins.length !== 1)
39
+ throw new Error(
40
+ `Refund transaction must have exactly 1 input, got ${l.ins.length}`
41
+ );
42
+ const p = l.ins[0], g = i.getId(), v = S(
43
+ new Uint8Array(p.hash).slice().reverse()
44
+ );
45
+ if (v !== g)
46
+ throw new Error(
47
+ `Refund input does not reference the Pre-PegIn transaction. Expected ${g}, got ${v}`
48
+ );
49
+ if (p.index !== o)
50
+ throw new Error(
51
+ `Refund input index ${p.index} does not match expected htlcVout ${o}`
52
+ );
53
+ const h = new T();
54
+ h.setVersion(l.version), h.setLocktime(l.locktime), h.addInput({
55
+ hash: p.hash,
56
+ index: p.index,
57
+ sequence: p.sequence,
58
+ witnessUtxo: {
59
+ script: m.script,
60
+ value: m.value
61
+ },
62
+ tapLeafScript: [
63
+ {
64
+ leafVersion: I,
65
+ script: u.from(f(c.refundScript)),
66
+ controlBlock: u.from(
67
+ f(c.refundControlBlock)
68
+ )
69
+ }
70
+ ],
71
+ tapInternalKey: u.from(b)
72
+ });
73
+ for (const w of l.outs)
74
+ h.addOutput({
75
+ script: w.script,
76
+ value: w.value
77
+ });
78
+ return { psbtHex: h.toHex() };
79
+ } finally {
80
+ n == null || n.free(), x.free();
81
+ }
82
+ }
83
+ async function q(s) {
84
+ const e = k(s.noPayoutTxHex), t = y.fromHex(e), { noPayoutScript: o, noPayoutControlBlock: d } = await C(
85
+ s.connectorParams,
86
+ s.challengerPubkey
87
+ ), a = f(o), x = f(d), n = new T();
88
+ n.setVersion(t.version), n.setLocktime(t.locktime);
89
+ for (let r = 0; r < t.ins.length; r++) {
90
+ const c = t.ins[r], P = s.prevouts[r];
91
+ if (!P)
92
+ throw new Error(`Missing prevout data for input ${r}`);
93
+ const i = {
94
+ hash: c.hash,
95
+ index: c.index,
96
+ sequence: c.sequence,
97
+ witnessUtxo: {
98
+ script: u.from(f(k(P.script_pubkey))),
99
+ value: P.value
100
+ }
101
+ };
102
+ r === 0 && (i.tapLeafScript = [
103
+ {
104
+ leafVersion: I,
105
+ script: u.from(a),
106
+ controlBlock: u.from(x)
107
+ }
108
+ ], i.tapInternalKey = u.from(b)), n.addInput(i);
109
+ }
110
+ for (const r of t.outs)
111
+ n.addOutput({
112
+ script: r.script,
113
+ value: r.value
114
+ });
115
+ return n.toHex();
116
+ }
117
+ function U(s, e, t) {
118
+ const o = y.fromHex(k(s));
119
+ if (o.outs.length !== 1)
120
+ throw new Error(
121
+ `NoPayout transaction must have exactly 1 output, got ${o.outs.length}`
122
+ );
123
+ const d = f($(e)), { output: a } = E.p2tr({
124
+ internalPubkey: u.from(d),
125
+ network: A(t)
126
+ });
127
+ if (!a)
128
+ throw new Error(
129
+ "Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation"
130
+ );
131
+ if (!o.outs[0].script.equals(a))
132
+ throw new Error(
133
+ "NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address"
134
+ );
135
+ }
136
+ export {
137
+ q as a,
138
+ V as b,
139
+ U as c
140
+ };
141
+ //# sourceMappingURL=noPayout-DBX6G96_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"noPayout-DBX6G96_.js","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 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 { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport 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 const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\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 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 for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\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 `assertPayoutOutputMatchesRegistered` for the NoPayout path, where\n * the sink is fixed by the 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","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;AAkEA,eAAsBA,EACpBC,GACgC;AAChC,QAAMC,EAAA;AAEN,QAAM,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEN,GAEIO,IAAa,IAAIC;AAAA,IACrBN,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACf,CAAC,GAAGA,EAAe,SAAS;AAAA,IAC5B,IAAI,eAAeA,EAAe,YAAY;AAAA,IAC9CA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,EAAA;AAGjB,MAAIO,IAAkC;AACtC,MAAI;AACF,IAAAA,IAAWF,EAAW,sBAAsBJ,CAAmB;AAE/D,UAAMO,IAAcD,EAAS,cAAcJ,GAAWD,CAAQ,GAExDO,IAAgB,MAAMC,EAA6B;AAAA,MACvD,iBAAiBV,EAAe;AAAA,MAChC,qBAAqBA,EAAe;AAAA,MACpC,oBAAoBA,EAAe;AAAA,MACnC,4BAA4BA,EAAe;AAAA,MAC3C,UAAAI;AAAA,MACA,gBAAgBJ,EAAe;AAAA,MAC/B,SAASA,EAAe;AAAA,IAAA,CACzB,GAEKW,IAAmBV,EAAoB,WAAW,IAAI,IACxDA,EAAoB,MAAM,CAAC,IAC3BA,GACEW,IAAaC,EAAY,QAAQF,CAAgB,GAEjDG,IAAaF,EAAW,KAAKV,CAAQ;AAC3C,QAAI,CAACY;AACH,YAAM,IAAI;AAAA,QACR,uBAAuBZ,CAAQ,6CAClBU,EAAW,KAAK,MAAM;AAAA,MAAA;AAIvC,UAAMG,IAAWF,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