@babylonlabs-io/ts-sdk 0.26.2 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/{bitcoin-nOOgeRyl.js → bitcoin-B-Y0DlqR.js} +63 -60
  2. package/dist/bitcoin-B-Y0DlqR.js.map +1 -0
  3. package/dist/bitcoin-DIN0OupO.cjs +2 -0
  4. package/dist/bitcoin-DIN0OupO.cjs.map +1 -0
  5. package/dist/buildAndBroadcastRefund-BEASMFsz.cjs +2 -0
  6. package/dist/buildAndBroadcastRefund-BEASMFsz.cjs.map +1 -0
  7. package/dist/buildAndBroadcastRefund-BzYJv-Fv.js +862 -0
  8. package/dist/buildAndBroadcastRefund-BzYJv-Fv.js.map +1 -0
  9. package/dist/challengeAssert-BM8m9gPM.cjs +2 -0
  10. package/dist/challengeAssert-BM8m9gPM.cjs.map +1 -0
  11. package/dist/{challengeAssert-CH32j5cZ.js → challengeAssert-j2Vwqo0-.js} +135 -120
  12. package/dist/challengeAssert-j2Vwqo0-.js.map +1 -0
  13. package/dist/context-BSdcD4J_.cjs +2 -0
  14. package/dist/context-BSdcD4J_.cjs.map +1 -0
  15. package/dist/{errors-CQjAF9QE.js → context-CClNOyD3.js} +442 -324
  16. package/dist/context-CClNOyD3.js.map +1 -0
  17. package/dist/fundPeginTransaction-DaWoYCgO.cjs +2 -0
  18. package/dist/fundPeginTransaction-DaWoYCgO.cjs.map +1 -0
  19. package/dist/fundPeginTransaction-oV-dNJOU.js +76 -0
  20. package/dist/fundPeginTransaction-oV-dNJOU.js.map +1 -0
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +100 -91
  23. package/dist/{payout-DzGsAnhf.js → payout-B_fvQU3q.js} +2 -2
  24. package/dist/{payout-DzGsAnhf.js.map → payout-B_fvQU3q.js.map} +1 -1
  25. package/dist/{payout-RFIh7GLN.cjs → payout-DP6KMFP1.cjs} +2 -2
  26. package/dist/{payout-RFIh7GLN.cjs.map → payout-DP6KMFP1.cjs.map} +1 -1
  27. package/dist/psbtInputFields-C3dqKWjQ.js +258 -0
  28. package/dist/psbtInputFields-C3dqKWjQ.js.map +1 -0
  29. package/dist/psbtInputFields-DhGm77bP.cjs +2 -0
  30. package/dist/psbtInputFields-DhGm77bP.cjs.map +1 -0
  31. package/dist/sha2-1XZuToHP.cjs +2 -0
  32. package/dist/sha2-1XZuToHP.cjs.map +1 -0
  33. package/dist/sha2-ZzfZqQSw.js +1123 -0
  34. package/dist/sha2-ZzfZqQSw.js.map +1 -0
  35. package/dist/tbv/core/clients/index.cjs +1 -1
  36. package/dist/tbv/core/clients/index.js +27 -24
  37. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts +17 -0
  38. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts.map +1 -0
  39. package/dist/tbv/core/clients/vault-provider/auth/__tests__/cbor.test.d.ts +15 -0
  40. package/dist/tbv/core/clients/vault-provider/auth/__tests__/cbor.test.d.ts.map +1 -0
  41. package/dist/tbv/core/clients/vault-provider/auth/__tests__/goldenVectors.d.ts +44 -0
  42. package/dist/tbv/core/clients/vault-provider/auth/__tests__/goldenVectors.d.ts.map +1 -0
  43. package/dist/tbv/core/clients/vault-provider/auth/__tests__/serverIdentity.test.d.ts +2 -0
  44. package/dist/tbv/core/clients/vault-provider/auth/__tests__/serverIdentity.test.d.ts.map +1 -0
  45. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenProvider.test.d.ts +2 -0
  46. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenProvider.test.d.ts.map +1 -0
  47. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +56 -0
  48. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -0
  49. package/dist/tbv/core/clients/vault-provider/auth/cbor.d.ts +44 -0
  50. package/dist/tbv/core/clients/vault-provider/auth/cbor.d.ts.map +1 -0
  51. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +10 -0
  52. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -0
  53. package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts +68 -0
  54. package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts.map +1 -0
  55. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +81 -0
  56. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -0
  57. package/dist/tbv/core/clients/vault-provider/index.d.ts +2 -1
  58. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
  59. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +66 -1
  60. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  61. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
  62. package/dist/tbv/core/index.cjs +1 -1
  63. package/dist/tbv/core/index.d.ts +3 -0
  64. package/dist/tbv/core/index.d.ts.map +1 -1
  65. package/dist/tbv/core/index.js +96 -87
  66. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  67. package/dist/tbv/core/primitives/index.cjs +1 -1
  68. package/dist/tbv/core/primitives/index.js +3 -3
  69. package/dist/tbv/core/primitives/psbt/pegin.d.ts +17 -2
  70. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  71. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +19 -0
  72. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  73. package/dist/tbv/core/services/index.cjs +1 -1
  74. package/dist/tbv/core/services/index.js +1 -1
  75. package/dist/tbv/core/utils/fee/__tests__/constants.test.d.ts +2 -0
  76. package/dist/tbv/core/utils/fee/__tests__/constants.test.d.ts.map +1 -0
  77. package/dist/tbv/core/utils/fee/constants.d.ts +30 -9
  78. package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -1
  79. package/dist/tbv/core/utils/index.cjs +1 -1
  80. package/dist/tbv/core/utils/index.js +28 -27
  81. package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -1
  82. package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -1
  83. package/dist/tbv/core/vault-secrets/__tests__/context.golden.test.d.ts +34 -0
  84. package/dist/tbv/core/vault-secrets/__tests__/context.golden.test.d.ts.map +1 -0
  85. package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts +6 -0
  86. package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts.map +1 -0
  87. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +10 -0
  88. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -0
  89. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts +8 -0
  90. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts.map +1 -0
  91. package/dist/tbv/core/vault-secrets/context.d.ts +52 -0
  92. package/dist/tbv/core/vault-secrets/context.d.ts.map +1 -0
  93. package/dist/tbv/core/vault-secrets/expand.d.ts +43 -0
  94. package/dist/tbv/core/vault-secrets/expand.d.ts.map +1 -0
  95. package/dist/tbv/core/vault-secrets/index.d.ts +16 -0
  96. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -0
  97. package/dist/tbv/core/vault-secrets/info.d.ts +55 -0
  98. package/dist/tbv/core/vault-secrets/info.d.ts.map +1 -0
  99. package/dist/tbv/index.cjs +1 -1
  100. package/dist/tbv/index.js +96 -87
  101. package/dist/tbv/integrations/aave/index.cjs +1 -1
  102. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  103. package/dist/tbv/integrations/aave/index.js +164 -159
  104. package/dist/tbv/integrations/aave/index.js.map +1 -1
  105. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
  106. package/dist/vault-registry-reader-BizmBSBV.cjs +2 -0
  107. package/dist/vault-registry-reader-BizmBSBV.cjs.map +1 -0
  108. package/dist/{index-D7s2ilf8.js → vault-registry-reader-CpCOte7w.js} +522 -268
  109. package/dist/vault-registry-reader-CpCOte7w.js.map +1 -0
  110. package/package.json +8 -3
  111. package/dist/bitcoin-CNnPFU6Y.cjs +0 -2
  112. package/dist/bitcoin-CNnPFU6Y.cjs.map +0 -1
  113. package/dist/bitcoin-nOOgeRyl.js.map +0 -1
  114. package/dist/buildAndBroadcastRefund-Ccp-2GWW.js +0 -1334
  115. package/dist/buildAndBroadcastRefund-Ccp-2GWW.js.map +0 -1
  116. package/dist/buildAndBroadcastRefund-Mr3ck5ek.cjs +0 -2
  117. package/dist/buildAndBroadcastRefund-Mr3ck5ek.cjs.map +0 -1
  118. package/dist/challengeAssert-CH32j5cZ.js.map +0 -1
  119. package/dist/challengeAssert-X7V3Ik_Q.cjs +0 -2
  120. package/dist/challengeAssert-X7V3Ik_Q.cjs.map +0 -1
  121. package/dist/errors-BBrP8sLT.cjs +0 -2
  122. package/dist/errors-BBrP8sLT.cjs.map +0 -1
  123. package/dist/errors-CQjAF9QE.js.map +0 -1
  124. package/dist/fundPeginTransaction-BLYXxLBv.js +0 -70
  125. package/dist/fundPeginTransaction-BLYXxLBv.js.map +0 -1
  126. package/dist/fundPeginTransaction-DxNOeyNI.cjs +0 -2
  127. package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +0 -1
  128. package/dist/index-CIuXb72l.cjs +0 -2
  129. package/dist/index-CIuXb72l.cjs.map +0 -1
  130. package/dist/index-D7s2ilf8.js.map +0 -1
  131. package/dist/psbtInputFields-1dXR4hLk.js +0 -237
  132. package/dist/psbtInputFields-1dXR4hLk.js.map +0 -1
  133. package/dist/psbtInputFields-tnAR8tG5.cjs +0 -2
  134. package/dist/psbtInputFields-tnAR8tG5.cjs.map +0 -1
  135. package/dist/types-WrGfwlJd.js +0 -608
  136. package/dist/types-WrGfwlJd.js.map +0 -1
  137. package/dist/types-xU3SBcpH.cjs +0 -2
  138. package/dist/types-xU3SBcpH.cjs.map +0 -1
@@ -0,0 +1,862 @@
1
+ var W = Object.defineProperty;
2
+ var X = (e, t, r) => t in e ? W(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
+ var P = (e, t, r) => X(e, typeof t != "symbol" ? t + "" : t, r);
4
+ import { s as G, B as Y, c as j, a as q, R as Q, d as N, D as b } from "./sha2-ZzfZqQSw.js";
5
+ import { v as A, b as J, s as l, e as Z, p as w, f } from "./bitcoin-B-Y0DlqR.js";
6
+ import * as ee from "bitcoinjs-lib";
7
+ import { Transaction as te, Psbt as B } from "bitcoinjs-lib";
8
+ import { Buffer as V } from "buffer";
9
+ import { c as y } from "./signing-BZigafm0.js";
10
+ import "@babylonlabs-io/babylon-tbv-rust-wasm";
11
+ import { a as H, e as x, b as re } from "./payout-B_fvQU3q.js";
12
+ class oe {
13
+ /**
14
+ * Creates a new PayoutManager instance.
15
+ *
16
+ * @param config - Manager configuration including wallet
17
+ */
18
+ constructor(t) {
19
+ P(this, "config");
20
+ this.config = t;
21
+ }
22
+ /**
23
+ * Signs a Payout transaction and extracts the Schnorr signature.
24
+ *
25
+ * Flow:
26
+ * 1. Vault provider submits Claim transaction
27
+ * 2. Claimer submits Assert transaction to prove validity
28
+ * 3. Payout can be executed (references Assert tx)
29
+ *
30
+ * This method orchestrates the following steps:
31
+ * 1. Get wallet's public key and convert to x-only format
32
+ * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)
33
+ * 3. Build unsigned PSBT using primitives
34
+ * 4. Sign PSBT via btcWallet.signPsbt()
35
+ * 5. Extract 64-byte Schnorr signature using primitives
36
+ *
37
+ * The returned signature can be submitted to the vault provider API.
38
+ *
39
+ * @param params - Payout signing parameters
40
+ * @returns Signature result with 64-byte Schnorr signature and depositor pubkey
41
+ * @throws Error if wallet pubkey doesn't match depositor pubkey
42
+ * @throws Error if wallet operations fail or signature extraction fails
43
+ */
44
+ async signPayoutTransaction(t) {
45
+ this.validatePayoutOutputs(
46
+ t.payoutTxHex,
47
+ t.registeredPayoutScriptPubKey
48
+ );
49
+ const r = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: o } = A(
50
+ r,
51
+ t.depositorBtcPubkey
52
+ ), s = await H({
53
+ payoutTxHex: t.payoutTxHex,
54
+ peginTxHex: t.peginTxHex,
55
+ assertTxHex: t.assertTxHex,
56
+ depositorBtcPubkey: o,
57
+ vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
58
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
59
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
60
+ timelockPegin: t.timelockPegin,
61
+ network: this.config.network
62
+ }), c = await this.config.btcWallet.signPsbt(
63
+ s.psbtHex,
64
+ y(r, 1)
65
+ );
66
+ return {
67
+ signature: x(c, o),
68
+ depositorBtcPubkey: o
69
+ };
70
+ }
71
+ /**
72
+ * Gets the configured Bitcoin network.
73
+ *
74
+ * @returns The Bitcoin network (mainnet, testnet, signet, regtest)
75
+ */
76
+ getNetwork() {
77
+ return this.config.network;
78
+ }
79
+ /**
80
+ * Checks if the wallet supports batch signing (signPsbts).
81
+ *
82
+ * @returns true if batch signing is supported
83
+ */
84
+ supportsBatchSigning() {
85
+ return typeof this.config.btcWallet.signPsbts == "function";
86
+ }
87
+ /**
88
+ * Batch signs multiple payout transactions (1 per claimer).
89
+ * This allows signing all transactions with a single wallet interaction.
90
+ *
91
+ * @param transactions - Array of payout params to sign
92
+ * @returns Array of signature results matching input order
93
+ * @throws Error if wallet doesn't support batch signing
94
+ * @throws Error if any signing operation fails
95
+ */
96
+ async signPayoutTransactionsBatch(t) {
97
+ if (!this.supportsBatchSigning())
98
+ throw new Error(
99
+ "Wallet does not support batch signing (signPsbts method not available)"
100
+ );
101
+ const r = await this.config.btcWallet.getPublicKeyHex(), o = [], s = [], c = [];
102
+ for (const n of t) {
103
+ this.validatePayoutOutputs(
104
+ n.payoutTxHex,
105
+ n.registeredPayoutScriptPubKey
106
+ );
107
+ const { depositorPubkey: u } = A(
108
+ r,
109
+ n.depositorBtcPubkey
110
+ );
111
+ c.push(u);
112
+ const d = await H({
113
+ payoutTxHex: n.payoutTxHex,
114
+ peginTxHex: n.peginTxHex,
115
+ assertTxHex: n.assertTxHex,
116
+ depositorBtcPubkey: u,
117
+ vaultProviderBtcPubkey: n.vaultProviderBtcPubkey,
118
+ vaultKeeperBtcPubkeys: n.vaultKeeperBtcPubkeys,
119
+ universalChallengerBtcPubkeys: n.universalChallengerBtcPubkeys,
120
+ timelockPegin: n.timelockPegin,
121
+ network: this.config.network
122
+ });
123
+ o.push(d.psbtHex), s.push(y(r, 1));
124
+ }
125
+ const a = await this.config.btcWallet.signPsbts(
126
+ o,
127
+ s
128
+ );
129
+ if (a.length !== t.length)
130
+ throw new Error(
131
+ `Expected ${t.length} signed PSBTs but received ${a.length}`
132
+ );
133
+ const i = [];
134
+ for (let n = 0; n < t.length; n++) {
135
+ const u = c[n], d = x(
136
+ a[n],
137
+ u
138
+ );
139
+ i.push({
140
+ payoutSignature: d,
141
+ depositorBtcPubkey: u
142
+ });
143
+ }
144
+ return i;
145
+ }
146
+ /**
147
+ * Validates that the payout transaction's largest output pays to the
148
+ * registered depositor payout address (scriptPubKey).
149
+ *
150
+ * This prevents two attack vectors from a malicious vault provider:
151
+ * 1. Substituting a completely different payout address
152
+ * 2. Including a dust output to the correct address while routing
153
+ * the actual funds to an attacker-controlled address
154
+ *
155
+ * @param payoutTxHex - Raw payout transaction hex
156
+ * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)
157
+ * @throws Error if scriptPubKey is invalid hex
158
+ * @throws Error if the largest output does not pay to the registered address
159
+ */
160
+ validatePayoutOutputs(t, r) {
161
+ if (!J(r))
162
+ throw new Error(
163
+ "Invalid registeredPayoutScriptPubKey: not valid hex"
164
+ );
165
+ const o = V.from(
166
+ l(r),
167
+ "hex"
168
+ ), s = te.fromHex(l(t));
169
+ if (s.outs.length === 0)
170
+ throw new Error("Payout transaction has no outputs");
171
+ if (!s.outs.reduce(
172
+ (a, i) => i.value > a.value ? i : a
173
+ ).script.equals(o))
174
+ throw new Error(
175
+ "Payout transaction does not pay to the registered depositor payout address"
176
+ );
177
+ }
178
+ }
179
+ const I = 66;
180
+ function L(e) {
181
+ if (!e.startsWith("0x") && !e.startsWith("0X"))
182
+ throw new Error("Expected 0x-prefixed hex string");
183
+ const t = e.slice(2);
184
+ if (t.length % 2 !== 0)
185
+ throw new Error(`Hex string has odd length: ${t.length}`);
186
+ if (!/^[0-9a-fA-F]*$/.test(t))
187
+ throw new Error("Hex string contains non-hex characters");
188
+ const r = new Uint8Array(t.length / 2);
189
+ for (let o = 0; o < r.length; o++)
190
+ r[o] = parseInt(t.slice(o * 2, o * 2 + 2), 16);
191
+ return r;
192
+ }
193
+ function ne(e) {
194
+ return `0x${Array.from(e).map((t) => t.toString(16).padStart(2, "0")).join("")}`;
195
+ }
196
+ function S(e, t) {
197
+ if (e.length !== I)
198
+ throw new Error(
199
+ `${t} must be exactly 32 bytes (${I} hex chars with 0x prefix), got ${e.length}`
200
+ );
201
+ }
202
+ function se(e) {
203
+ S(e, "Secret");
204
+ const t = L(e), r = G(t);
205
+ return ne(r);
206
+ }
207
+ function ie(e, t) {
208
+ return S(e, "Secret"), S(t, "Hashlock"), L(t), se(e).toLowerCase() === t.toLowerCase();
209
+ }
210
+ const ae = /^0x[0-9a-fA-F]{64}$/, ue = /^0x[0-9a-fA-F]{40}$/, ce = /^0x([0-9a-fA-F]{2})*$/;
211
+ function E(e, t) {
212
+ if (e.length !== 66)
213
+ throw new Error(
214
+ `${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`
215
+ );
216
+ if (!ae.test(e))
217
+ throw new Error(
218
+ `${t} must contain only hex characters after the 0x prefix`
219
+ );
220
+ }
221
+ function le(e, t) {
222
+ if (!ue.test(e))
223
+ throw new Error(
224
+ `${t} must be a 20-byte 0x-prefixed hex address (42 chars)`
225
+ );
226
+ }
227
+ function de(e, t) {
228
+ if (!ce.test(e))
229
+ throw new Error(
230
+ `${t} must be a 0x-prefixed hex string with an even number of hex chars`
231
+ );
232
+ }
233
+ async function Qe(e) {
234
+ const {
235
+ btcVaultRegistryAddress: t,
236
+ vaultId: r,
237
+ hashlock: o,
238
+ activationMetadata: s,
239
+ writeContract: c,
240
+ signal: a
241
+ } = e;
242
+ a == null || a.throwIfAborted(), le(t, "btcVaultRegistryAddress"), E(r, "vaultId");
243
+ const i = Z(e.secret);
244
+ if (E(i, "secret"), o !== void 0 && (E(o, "hashlock"), !ie(i, o)))
245
+ throw new Error(
246
+ "Invalid secret: SHA256(secret) does not match the provided hashlock"
247
+ );
248
+ return de(s, "activationMetadata"), c({
249
+ address: t,
250
+ abi: Y,
251
+ functionName: "activateVaultWithSecret",
252
+ args: [r, i, s]
253
+ });
254
+ }
255
+ const he = 1e4;
256
+ async function D(e) {
257
+ const {
258
+ statusReader: t,
259
+ peginTxid: r,
260
+ targetStatuses: o,
261
+ timeoutMs: s,
262
+ pollIntervalMs: c = he,
263
+ signal: a
264
+ } = e, i = Date.now();
265
+ for (; ; ) {
266
+ if (a != null && a.aborted)
267
+ throw new Error(
268
+ `Polling aborted for pegin ${r.slice(0, 8)}… (target: ${[...o].join(", ")})`
269
+ );
270
+ if (Date.now() - i >= s)
271
+ throw new Error(
272
+ `Polling timeout after ${s}ms for pegin ${r.slice(0, 8)}… (target: ${[...o].join(", ")})`
273
+ );
274
+ try {
275
+ const u = (await t.getPeginStatus(
276
+ { pegin_txid: r },
277
+ a
278
+ )).status;
279
+ if (o.has(u))
280
+ return u;
281
+ if (j.has(u) && !o.has(u))
282
+ throw new Error(
283
+ `Pegin ${r.slice(0, 8)}… reached terminal status "${u}" while waiting for ${[...o].join(", ")}`
284
+ );
285
+ } catch (n) {
286
+ if (!(n instanceof q && n.code === Q.NOT_FOUND || n instanceof Error && n.message.includes("PegIn not found")))
287
+ throw n;
288
+ }
289
+ await new Promise((n, u) => {
290
+ const d = () => {
291
+ clearTimeout(h), u(
292
+ new Error(
293
+ `Polling aborted for pegin ${r.slice(0, 8)}… (target: ${[...o].join(", ")})`
294
+ )
295
+ );
296
+ }, h = setTimeout(() => {
297
+ a == null || a.removeEventListener("abort", d), n();
298
+ }, c);
299
+ a == null || a.addEventListener("abort", d, { once: !0 });
300
+ });
301
+ }
302
+ }
303
+ const pe = 300 * 1e3, fe = /* @__PURE__ */ new Set([
304
+ b.PENDING_DEPOSITOR_WOTS_PK,
305
+ ...N
306
+ ]);
307
+ async function Je(e) {
308
+ const {
309
+ statusReader: t,
310
+ wotsSubmitter: r,
311
+ peginTxid: o,
312
+ depositorPk: s,
313
+ wotsPublicKeys: c,
314
+ timeoutMs: a = pe,
315
+ signal: i
316
+ } = e;
317
+ i == null || i.throwIfAborted();
318
+ const n = await D({
319
+ statusReader: t,
320
+ peginTxid: o,
321
+ targetStatuses: fe,
322
+ timeoutMs: a,
323
+ signal: i
324
+ });
325
+ N.has(n) || (i == null || i.throwIfAborted(), await r.submitDepositorWotsKey(
326
+ {
327
+ pegin_txid: o,
328
+ depositor_pk: s,
329
+ wots_public_keys: c
330
+ },
331
+ i
332
+ ));
333
+ }
334
+ const $ = 1;
335
+ function ge(e, t, r) {
336
+ const o = B.fromBase64(e), s = o.data.getTransaction().toString("hex").toLowerCase(), c = l(t).toLowerCase();
337
+ if (s !== c)
338
+ throw new Error(
339
+ `PSBT integrity check failed for ${r}: unsigned transaction does not match tx_hex`
340
+ );
341
+ return o;
342
+ }
343
+ function be(e) {
344
+ const t = B.fromHex(e.toHex());
345
+ for (const r of t.data.inputs)
346
+ delete r.tapBip32Derivation, delete r.tapMerkleRoot;
347
+ return t;
348
+ }
349
+ function R(e, t, r) {
350
+ if (!e)
351
+ throw new Error(`Missing ${r} PSBT`);
352
+ const o = ge(e, t, r);
353
+ return be(o).toHex();
354
+ }
355
+ function ye(e, t) {
356
+ const r = [], o = [], s = [], c = R(
357
+ e.payout_psbt,
358
+ e.payout_tx.tx_hex,
359
+ "depositor payout"
360
+ );
361
+ r.push(c), o.push(
362
+ y(t, $)
363
+ );
364
+ for (const a of e.challenger_presign_data) {
365
+ const i = l(a.challenger_pubkey), n = r.length, u = R(
366
+ a.nopayout_psbt,
367
+ a.nopayout_tx.tx_hex,
368
+ `nopayout (challenger ${i})`
369
+ );
370
+ r.push(u), o.push(
371
+ y(t, $)
372
+ ), s.push({
373
+ challengerPubkey: i,
374
+ noPayoutIdx: n
375
+ });
376
+ }
377
+ return { psbtHexes: r, signOptions: o, challengerEntries: s };
378
+ }
379
+ function Pe(e, t, r) {
380
+ const o = x(
381
+ e[0],
382
+ r
383
+ ), s = {};
384
+ for (const c of t)
385
+ s[c.challengerPubkey] = {
386
+ nopayout_signature: x(
387
+ e[c.noPayoutIdx],
388
+ r
389
+ )
390
+ };
391
+ return {
392
+ payout_signatures: {
393
+ payout_signature: o
394
+ },
395
+ per_challenger: s
396
+ };
397
+ }
398
+ async function we(e, t, r) {
399
+ if (typeof e.signPsbts == "function")
400
+ return e.signPsbts(t, r);
401
+ const o = [];
402
+ for (let s = 0; s < t.length; s++)
403
+ o.push(await e.signPsbt(t[s], r == null ? void 0 : r[s]));
404
+ return o;
405
+ }
406
+ async function xe(e) {
407
+ const { depositorGraph: t, depositorBtcPubkey: r, btcWallet: o } = e, s = l(r), c = await o.getPublicKeyHex(), { psbtHexes: a, signOptions: i, challengerEntries: n } = ye(t, c), u = await we(
408
+ o,
409
+ a,
410
+ i
411
+ );
412
+ if (u.length !== a.length)
413
+ throw new Error(
414
+ `Wallet returned ${u.length} signed PSBTs, expected ${a.length}`
415
+ );
416
+ return Pe(
417
+ u,
418
+ n,
419
+ s
420
+ );
421
+ }
422
+ const me = 1200 * 1e3, K = /* @__PURE__ */ new Set([
423
+ b.PENDING_ACKS,
424
+ b.PENDING_ACTIVATION,
425
+ b.ACTIVATED
426
+ ]), ve = /* @__PURE__ */ new Set([
427
+ b.PENDING_DEPOSITOR_SIGNATURES,
428
+ ...K
429
+ ]);
430
+ function Te(e) {
431
+ return e.map((t) => ({
432
+ claimerPubkeyXOnly: w(t.claimer_pubkey),
433
+ payoutTxHex: t.payout_tx.tx_hex,
434
+ assertTxHex: t.assert_tx.tx_hex
435
+ }));
436
+ }
437
+ function Ee(e) {
438
+ const { output: t } = ee.payments.p2tr({
439
+ internalPubkey: V.from(e, "hex")
440
+ });
441
+ if (!t)
442
+ throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");
443
+ return t.toString("hex");
444
+ }
445
+ function ke(e, t) {
446
+ const r = l(e).toLowerCase(), o = l(
447
+ t.vaultProviderBtcPubkey
448
+ ).toLowerCase(), s = l(
449
+ t.depositorBtcPubkey
450
+ ).toLowerCase();
451
+ if (r === o || r === s)
452
+ return t.registeredPayoutScriptPubKey;
453
+ if (!t.vaultKeeperBtcPubkeys.some(
454
+ (i) => l(i).toLowerCase() === r
455
+ ))
456
+ throw new Error(
457
+ `Unknown claimer pubkey ${r}: not VP, depositor, or a registered vault keeper`
458
+ );
459
+ return `0x${Ee(r)}`;
460
+ }
461
+ function C(e, t) {
462
+ return {
463
+ payoutTxHex: e.payoutTxHex,
464
+ peginTxHex: t.peginTxHex,
465
+ assertTxHex: e.assertTxHex,
466
+ vaultProviderBtcPubkey: t.vaultProviderBtcPubkey,
467
+ vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
468
+ universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
469
+ depositorBtcPubkey: t.depositorBtcPubkey,
470
+ timelockPegin: t.timelockPegin,
471
+ registeredPayoutScriptPubKey: ke(
472
+ e.claimerPubkeyXOnly,
473
+ t
474
+ )
475
+ };
476
+ }
477
+ async function Se(e, t, r, o) {
478
+ const s = new oe({
479
+ network: t.network,
480
+ btcWallet: e
481
+ }), c = r.length;
482
+ o == null || o(0, c);
483
+ let a;
484
+ if (s.supportsBatchSigning())
485
+ a = (await s.signPayoutTransactionsBatch(
486
+ r.map((u) => C(u, t))
487
+ )).map((u) => u.payoutSignature);
488
+ else {
489
+ a = [];
490
+ for (let n = 0; n < r.length; n++) {
491
+ o == null || o(n, c);
492
+ const u = await s.signPayoutTransaction(
493
+ C(r[n], t)
494
+ );
495
+ a.push(u.signature);
496
+ }
497
+ }
498
+ const i = {};
499
+ for (let n = 0; n < r.length; n++)
500
+ i[r[n].claimerPubkeyXOnly] = {
501
+ payout_signature: a[n]
502
+ };
503
+ return o == null || o(c, c), i;
504
+ }
505
+ async function Ze(e) {
506
+ const {
507
+ statusReader: t,
508
+ presignClient: r,
509
+ btcWallet: o,
510
+ peginTxid: s,
511
+ depositorPk: c,
512
+ signingContext: a,
513
+ timeoutMs: i = me,
514
+ signal: n,
515
+ onProgress: u
516
+ } = e, d = await D({
517
+ statusReader: t,
518
+ peginTxid: s,
519
+ targetStatuses: ve,
520
+ timeoutMs: i,
521
+ signal: n
522
+ });
523
+ if (K.has(d))
524
+ return;
525
+ n == null || n.throwIfAborted();
526
+ const h = await r.requestDepositorPresignTransactions(
527
+ {
528
+ pegin_txid: s,
529
+ depositor_pk: c
530
+ },
531
+ n
532
+ );
533
+ n == null || n.throwIfAborted();
534
+ const g = w(c), m = h.txs.filter(
535
+ (z) => w(z.claimer_pubkey) !== g
536
+ ), v = Te(m), T = await Se(
537
+ o,
538
+ a,
539
+ v,
540
+ u
541
+ );
542
+ n == null || n.throwIfAborted();
543
+ const p = await xe({
544
+ depositorGraph: h.depositor_graph,
545
+ depositorBtcPubkey: c,
546
+ btcWallet: o
547
+ });
548
+ n == null || n.throwIfAborted();
549
+ const _ = { ...T };
550
+ _[l(c)] = p.payout_signatures, await r.submitDepositorPresignatures(
551
+ {
552
+ pegin_txid: s,
553
+ depositor_pk: c,
554
+ signatures: _,
555
+ depositor_claimer_presignatures: p
556
+ },
557
+ n
558
+ );
559
+ }
560
+ function Be(e) {
561
+ return /^[0-9a-fA-F]{64}$/.test(e);
562
+ }
563
+ function et(e) {
564
+ const {
565
+ amountSats: t,
566
+ minDeposit: r,
567
+ maxDeposit: o,
568
+ btcBalance: s,
569
+ estimatedFeeSats: c,
570
+ depositorClaimValue: a
571
+ } = e;
572
+ return !(t <= 0n || t < r || o && o > 0n && t > o || c == null || a == null || t + c + a > s);
573
+ }
574
+ function tt(e, t, r) {
575
+ return e <= 0n ? {
576
+ valid: !1,
577
+ error: "Deposit amount must be greater than zero"
578
+ } : e < t ? {
579
+ valid: !1,
580
+ error: `Minimum deposit is ${f(t)} BTC`
581
+ } : r && r > 0n && e > r ? {
582
+ valid: !1,
583
+ error: `Maximum deposit is ${f(r)} BTC`
584
+ } : { valid: !0 };
585
+ }
586
+ function rt(e) {
587
+ const { amount: t, effectiveRemaining: r } = e;
588
+ return r === null ? { valid: !0 } : r === 0n ? {
589
+ valid: !1,
590
+ error: "Supply cap reached — deposits temporarily paused"
591
+ } : t > r ? {
592
+ valid: !1,
593
+ error: `Vault size exceeds remaining capacity (${f(r)} BTC)`
594
+ } : { valid: !0 };
595
+ }
596
+ function ot(e, t) {
597
+ if (!e || e.length === 0)
598
+ return {
599
+ valid: !1,
600
+ error: "At least one vault provider must be selected"
601
+ };
602
+ const r = t.map(
603
+ (s) => s.toLowerCase()
604
+ );
605
+ return e.filter(
606
+ (s) => !r.includes(s.toLowerCase())
607
+ ).length > 0 ? {
608
+ valid: !1,
609
+ error: "Invalid vault provider selected"
610
+ } : { valid: !0 };
611
+ }
612
+ function _e(e, t, r) {
613
+ if (!e || e.length === 0)
614
+ return {
615
+ valid: !1,
616
+ error: "At least one vault amount required"
617
+ };
618
+ for (let o = 0; o < e.length; o++) {
619
+ const s = e[o];
620
+ if (s <= 0n)
621
+ return {
622
+ valid: !1,
623
+ error: `Vault ${o + 1} amount must be positive`
624
+ };
625
+ if (t && s < t)
626
+ return {
627
+ valid: !1,
628
+ error: `Vault ${o + 1} amount ${f(s)} BTC is below minimum deposit ${f(t)} BTC`
629
+ };
630
+ if (r && s > r)
631
+ return {
632
+ valid: !1,
633
+ error: `Vault ${o + 1} amount ${f(s)} BTC exceeds maximum deposit ${f(r)} BTC`
634
+ };
635
+ }
636
+ return { valid: !0 };
637
+ }
638
+ function Ae(e) {
639
+ const t = l(e);
640
+ return Be(t) ? { valid: !0 } : {
641
+ valid: !1,
642
+ error: "Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"
643
+ };
644
+ }
645
+ function He(e) {
646
+ if (!e || e.length === 0)
647
+ throw new Error(
648
+ "No vault keepers available. The system requires at least one vault keeper to create a deposit."
649
+ );
650
+ }
651
+ function Ie(e) {
652
+ if (!e || e.length === 0)
653
+ throw new Error(
654
+ "No universal challengers available. The system requires at least one universal challenger to create a deposit."
655
+ );
656
+ }
657
+ function $e(e) {
658
+ if (e.length === 0)
659
+ throw new Error("No spendable UTXOs available");
660
+ }
661
+ function nt(e) {
662
+ const {
663
+ vaultAmounts: t,
664
+ confirmedUTXOs: r,
665
+ vaultProviderBtcPubkey: o,
666
+ vaultKeeperBtcPubkeys: s,
667
+ universalChallengerBtcPubkeys: c,
668
+ minDeposit: a,
669
+ maxDeposit: i,
670
+ htlcSecretHexesLength: n,
671
+ depositorSecretHashesLength: u
672
+ } = e, d = t.length;
673
+ if (n !== d)
674
+ throw new Error(
675
+ `htlcSecretHexes length (${n}) must match vaultAmounts length (${d})`
676
+ );
677
+ if (u !== d)
678
+ throw new Error(
679
+ `depositorSecretHashes length (${u}) must match vaultAmounts length (${d})`
680
+ );
681
+ const h = _e(
682
+ t,
683
+ a,
684
+ i
685
+ );
686
+ if (!h.valid)
687
+ throw new Error(h.error);
688
+ const g = Ae(o);
689
+ if (!g.valid)
690
+ throw new Error(g.error);
691
+ He(s), Ie(c), $e(r);
692
+ }
693
+ var U = /* @__PURE__ */ ((e) => (e.CLAIM_EVENT_RECEIVED = "ClaimEventReceived", e.CLAIM_BROADCAST = "ClaimBroadcast", e.ASSERT_BROADCAST = "AssertBroadcast", e.CHALLENGE_ASSERT_OBSERVED = "ChallengeAssertObserved", e.WRONGLY_CHALLENGED_BROADCAST = "WronglyChallengedBroadcast", e.PAYOUT_BROADCAST = "PayoutBroadcast", e.FAILED = "Failed", e))(U || {});
694
+ const Re = /* @__PURE__ */ new Set([
695
+ "PayoutBroadcast",
696
+ "Failed"
697
+ /* FAILED */
698
+ ]);
699
+ function st(e) {
700
+ return Object.values(U).includes(
701
+ e
702
+ );
703
+ }
704
+ function it(e) {
705
+ return !!e && Re.has(e);
706
+ }
707
+ class Ce extends Error {
708
+ constructor(r, o) {
709
+ super(`Refund not yet mature (BIP68 not final): ${o.message}`);
710
+ P(this, "vaultId");
711
+ P(this, "cause");
712
+ this.name = "BIP68NotMatureError", this.vaultId = r, this.cause = o;
713
+ }
714
+ }
715
+ const Oe = /^0x[0-9a-fA-F]{64}$/, Ne = /^(?:0x)?(?:[0-9a-fA-F]{2})+$/, F = /^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/, Ve = 160, Le = 1, O = 65535, De = /non-BIP68-final/i;
716
+ function M(e, t) {
717
+ if (e.length !== 66)
718
+ throw new Error(
719
+ `${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`
720
+ );
721
+ if (!Oe.test(e))
722
+ throw new Error(
723
+ `${t} must contain only hex characters after the 0x prefix`
724
+ );
725
+ }
726
+ function k(e, t) {
727
+ if (!Number.isInteger(e) || e < 0)
728
+ throw new Error(`${t} must be a non-negative integer, got ${e}`);
729
+ }
730
+ function Ke(e) {
731
+ if (M(e.hashlock, "hashlock"), !Number.isInteger(e.htlcVout) || e.htlcVout < 0 || e.htlcVout > O)
732
+ throw new Error(
733
+ `htlcVout must be an integer 0-${O}, got ${e.htlcVout}`
734
+ );
735
+ if (k(e.offchainParamsVersion, "offchainParamsVersion"), k(e.appVaultKeepersVersion, "appVaultKeepersVersion"), k(
736
+ e.universalChallengersVersion,
737
+ "universalChallengersVersion"
738
+ ), typeof e.unsignedPrePeginTxHex != "string" || e.unsignedPrePeginTxHex.length === 0)
739
+ throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");
740
+ if (!Ne.test(e.unsignedPrePeginTxHex))
741
+ throw new Error(
742
+ "unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)"
743
+ );
744
+ if (!e.depositorBtcPubkey || !F.test(e.depositorBtcPubkey))
745
+ throw new Error(
746
+ "depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)"
747
+ );
748
+ if (typeof e.amount != "bigint" || e.amount <= 0n)
749
+ throw new Error(`amount must be a positive bigint, got ${e.amount}`);
750
+ }
751
+ function Ue(e) {
752
+ if (!e.vaultProviderPubkey || !F.test(e.vaultProviderPubkey))
753
+ throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");
754
+ if (e.vaultKeeperPubkeys.length === 0)
755
+ throw new Error("vaultKeeperPubkeys must be non-empty");
756
+ if (e.universalChallengerPubkeys.length === 0)
757
+ throw new Error("universalChallengerPubkeys must be non-empty");
758
+ if (!Number.isInteger(e.timelockRefund) || e.timelockRefund <= 0)
759
+ throw new Error(
760
+ `timelockRefund must be a positive integer, got ${e.timelockRefund}`
761
+ );
762
+ if (typeof e.feeRate != "bigint" || e.feeRate <= 0n)
763
+ throw new Error(
764
+ `protocol feeRate must be a positive bigint, got ${e.feeRate}`
765
+ );
766
+ if (!Number.isInteger(e.numLocalChallengers) || e.numLocalChallengers < 0)
767
+ throw new Error("numLocalChallengers must be a non-negative integer");
768
+ if (!Number.isInteger(e.councilQuorum) || !Number.isInteger(e.councilSize) || e.councilQuorum <= 0 || e.councilSize <= 0 || e.councilQuorum > e.councilSize)
769
+ throw new Error(
770
+ `councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`
771
+ );
772
+ }
773
+ function Fe(e) {
774
+ const t = B.fromHex(e);
775
+ try {
776
+ t.finalizeAllInputs();
777
+ } catch (r) {
778
+ const o = r instanceof Error ? r.message : String(r);
779
+ if (!o.includes("already finalized"))
780
+ throw new Error(`Failed to finalize refund PSBT: ${o}`);
781
+ }
782
+ return t.extractTransaction().toHex();
783
+ }
784
+ async function at(e) {
785
+ const {
786
+ vaultId: t,
787
+ readVault: r,
788
+ readPrePeginContext: o,
789
+ feeRate: s,
790
+ signPsbt: c,
791
+ broadcastTx: a,
792
+ signal: i
793
+ } = e;
794
+ i == null || i.throwIfAborted(), M(t, "vaultId");
795
+ const n = await r();
796
+ Ke(n), i == null || i.throwIfAborted();
797
+ const u = await o(n);
798
+ if (Ue(u), i == null || i.throwIfAborted(), !Number.isFinite(s) || s <= 0)
799
+ throw new Error(`feeRate must be a positive number, got ${s}`);
800
+ const d = BigInt(Math.ceil(s * Ve));
801
+ i == null || i.throwIfAborted();
802
+ const h = w(
803
+ n.depositorBtcPubkey
804
+ ), { psbtHex: g } = await re({
805
+ prePeginParams: {
806
+ depositorPubkey: h,
807
+ vaultProviderPubkey: l(u.vaultProviderPubkey),
808
+ vaultKeeperPubkeys: u.vaultKeeperPubkeys.map(l),
809
+ universalChallengerPubkeys: u.universalChallengerPubkeys.map(l),
810
+ hashlocks: [l(n.hashlock)],
811
+ timelockRefund: u.timelockRefund,
812
+ pegInAmounts: [n.amount],
813
+ feeRate: u.feeRate,
814
+ numLocalChallengers: u.numLocalChallengers,
815
+ councilQuorum: u.councilQuorum,
816
+ councilSize: u.councilSize,
817
+ network: u.network
818
+ },
819
+ fundedPrePeginTxHex: l(n.unsignedPrePeginTxHex),
820
+ htlcVout: n.htlcVout,
821
+ refundFee: d,
822
+ // buildRefundPsbt's top-level `hashlock` param is documented as "no 0x
823
+ // prefix" and flows into the WASM HTLC connector derivation; a prefixed
824
+ // value would derive the wrong refund script leaf and yield an
825
+ // unspendable PSBT. Match the `hashlocks` array handling above.
826
+ hashlock: l(n.hashlock)
827
+ });
828
+ i == null || i.throwIfAborted();
829
+ const m = y(
830
+ n.depositorBtcPubkey,
831
+ Le
832
+ ), v = await c(g, m), T = Fe(v);
833
+ i == null || i.throwIfAborted();
834
+ try {
835
+ return await a(T);
836
+ } catch (p) {
837
+ throw p instanceof Error && De.test(p.message) ? new Ce(t, p) : p;
838
+ }
839
+ }
840
+ export {
841
+ Ce as B,
842
+ U as C,
843
+ oe as P,
844
+ Qe as a,
845
+ xe as b,
846
+ rt as c,
847
+ ot as d,
848
+ _e as e,
849
+ Ae as f,
850
+ nt as g,
851
+ se as h,
852
+ et as i,
853
+ ie as j,
854
+ st as k,
855
+ it as l,
856
+ at as m,
857
+ Ze as p,
858
+ Je as s,
859
+ tt as v,
860
+ D as w
861
+ };
862
+ //# sourceMappingURL=buildAndBroadcastRefund-BzYJv-Fv.js.map