@babylonlabs-io/ts-sdk 5.0.1 → 6.0.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 (73) hide show
  1. package/dist/{PayoutManager-C3p_cNHQ.cjs → PayoutManager-B5nR0x1t.cjs} +2 -2
  2. package/dist/{PayoutManager-C3p_cNHQ.cjs.map → PayoutManager-B5nR0x1t.cjs.map} +1 -1
  3. package/dist/{PayoutManager-CkZ3mGXB.js → PayoutManager-BHeiLQ1j.js} +2 -2
  4. package/dist/{PayoutManager-CkZ3mGXB.js.map → PayoutManager-BHeiLQ1j.js.map} +1 -1
  5. package/dist/{PeginManager-tP0Y-UCv.cjs → PeginManager-6ghglb4r.cjs} +2 -2
  6. package/dist/{PeginManager-tP0Y-UCv.cjs.map → PeginManager-6ghglb4r.cjs.map} +1 -1
  7. package/dist/{PeginManager-BvDlBR13.js → PeginManager-CXNqbgA4.js} +4 -4
  8. package/dist/{PeginManager-BvDlBR13.js.map → PeginManager-CXNqbgA4.js.map} +1 -1
  9. package/dist/{buildAndBroadcastReclaim-rUsFRC5H.js → buildAndBroadcastReclaim-Bs_zdDGN.js} +811 -732
  10. package/dist/{buildAndBroadcastReclaim-rUsFRC5H.js.map → buildAndBroadcastReclaim-Bs_zdDGN.js.map} +1 -1
  11. package/dist/{buildAndBroadcastReclaim-DtmMg096.cjs → buildAndBroadcastReclaim-CXOMHHgK.cjs} +2 -2
  12. package/dist/{buildAndBroadcastReclaim-DtmMg096.cjs.map → buildAndBroadcastReclaim-CXOMHHgK.cjs.map} +1 -1
  13. package/dist/{challengeAssert-ea0EmRKe.cjs → challengeAssert-CuX_8Twt.cjs} +2 -2
  14. package/dist/{challengeAssert-ea0EmRKe.cjs.map → challengeAssert-CuX_8Twt.cjs.map} +1 -1
  15. package/dist/{challengeAssert-CVxCGwBH.js → challengeAssert-D_lRvsO0.js} +2 -2
  16. package/dist/{challengeAssert-CVxCGwBH.js.map → challengeAssert-D_lRvsO0.js.map} +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.js +103 -99
  19. package/dist/peginState-B4t_PDgj.cjs +2 -0
  20. package/dist/peginState-B4t_PDgj.cjs.map +1 -0
  21. package/dist/{peginState-CIibG9S_.js → peginState-CXdbSit3.js} +7 -7
  22. package/dist/peginState-CXdbSit3.js.map +1 -0
  23. package/dist/{reservation-BZQABu4g.js → reservation-BAj5n-H_.js} +2 -2
  24. package/dist/{reservation-BZQABu4g.js.map → reservation-BAj5n-H_.js.map} +1 -1
  25. package/dist/{reservation-CA5knoQ0.cjs → reservation-D9ftyiwP.cjs} +2 -2
  26. package/dist/{reservation-CA5knoQ0.cjs.map → reservation-D9ftyiwP.cjs.map} +1 -1
  27. package/dist/tbv/core/clients/eth/types.d.ts +1 -1
  28. package/dist/tbv/core/index.cjs +1 -1
  29. package/dist/tbv/core/index.js +84 -80
  30. package/dist/tbv/core/managers/index.cjs +1 -1
  31. package/dist/tbv/core/managers/index.js +2 -2
  32. package/dist/tbv/core/primitives/index.cjs +1 -1
  33. package/dist/tbv/core/primitives/index.js +3 -3
  34. package/dist/tbv/core/recovery/reconstructPeginParams.d.ts +6 -0
  35. package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
  36. package/dist/tbv/core/recovery/toRefundInputs.d.ts +0 -2
  37. package/dist/tbv/core/recovery/toRefundInputs.d.ts.map +1 -1
  38. package/dist/tbv/core/services/deposit/index.d.ts +1 -1
  39. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  40. package/dist/tbv/core/services/deposit/peginState.d.ts +9 -2
  41. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
  42. package/dist/tbv/core/services/deposit/verifyRegisteredParticipantKeys.d.ts +27 -1
  43. package/dist/tbv/core/services/deposit/verifyRegisteredParticipantKeys.d.ts.map +1 -1
  44. package/dist/tbv/core/services/index.cjs +1 -1
  45. package/dist/tbv/core/services/index.js +89 -85
  46. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +6 -2
  47. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
  48. package/dist/tbv/core/services/refund/errors.d.ts +15 -0
  49. package/dist/tbv/core/services/refund/errors.d.ts.map +1 -1
  50. package/dist/tbv/core/services/refund/index.d.ts +1 -1
  51. package/dist/tbv/core/services/refund/index.d.ts.map +1 -1
  52. package/dist/tbv/core/utils/index.cjs +1 -1
  53. package/dist/tbv/core/utils/index.js +1 -1
  54. package/dist/tbv/index.cjs +1 -1
  55. package/dist/tbv/index.js +84 -80
  56. package/dist/{toRefundInputs-M4IbYwZU.js → toRefundInputs-Cl4KgzIc.js} +152 -152
  57. package/dist/{toRefundInputs-M4IbYwZU.js.map → toRefundInputs-Cl4KgzIc.js.map} +1 -1
  58. package/dist/{toRefundInputs-4W8aNM6b.cjs → toRefundInputs-DyIgmGJq.cjs} +2 -2
  59. package/dist/{toRefundInputs-4W8aNM6b.cjs.map → toRefundInputs-DyIgmGJq.cjs.map} +1 -1
  60. package/dist/types-BnZIbDHb.cjs.map +1 -1
  61. package/dist/types-K_aM5GZO.js.map +1 -1
  62. package/dist/{verifyKeyPathSchnorrSignature-DDi3B6EL.cjs → verifyKeyPathSchnorrSignature-BVrAmVL3.cjs} +2 -2
  63. package/dist/{verifyKeyPathSchnorrSignature-DDi3B6EL.cjs.map → verifyKeyPathSchnorrSignature-BVrAmVL3.cjs.map} +1 -1
  64. package/dist/{verifyKeyPathSchnorrSignature-CAp5zOTX.js → verifyKeyPathSchnorrSignature-CIE3jlVt.js} +2 -2
  65. package/dist/{verifyKeyPathSchnorrSignature-CAp5zOTX.js.map → verifyKeyPathSchnorrSignature-CIE3jlVt.js.map} +1 -1
  66. package/dist/{verifyScriptPathSchnorrSignature-cpUVCwU3.cjs → verifyScriptPathSchnorrSignature-BHskbJJx.cjs} +2 -2
  67. package/dist/{verifyScriptPathSchnorrSignature-cpUVCwU3.cjs.map → verifyScriptPathSchnorrSignature-BHskbJJx.cjs.map} +1 -1
  68. package/dist/{verifyScriptPathSchnorrSignature-BK-bd6w5.js → verifyScriptPathSchnorrSignature-DLNGgm4j.js} +3 -2
  69. package/dist/{verifyScriptPathSchnorrSignature-BK-bd6w5.js.map → verifyScriptPathSchnorrSignature-DLNGgm4j.js.map} +1 -1
  70. package/package.json +1 -1
  71. package/dist/peginState-CIibG9S_.js.map +0 -1
  72. package/dist/peginState-IyE22wWh.cjs +0 -2
  73. package/dist/peginState-IyE22wWh.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,23 +1,23 @@
1
- import { P as s, h as r, i as t, j as i, f as o, b as n, a as l, c as p, k as P, d as E, e as c, g as d } from "./verifyScriptPathSchnorrSignature-BK-bd6w5.js";
1
+ import { P as s, h as r, i as t, j as i, f as o, b as n, a as l, c as p, k as P, d as c, e as E, g as d } from "./verifyScriptPathSchnorrSignature-DLNGgm4j.js";
2
2
  import { a as g } from "./secp256k1-BuxBFUHm.js";
3
- import { attachFinalizedAssert as R, computeMinClaimValue as A, computeMinPeginFee as _, deriveVaultId as S, expandAuthAnchor as T, expandHashlockSecret as C, expandWotsSeed as I, finalizePayout as f, finalizeWronglyChallenged as h, peginP2aAnchorOutput as V, pinPegoutProof as O, supportedTxGraphVersions as x, validatePeginP2aAnchor as b } from "./tbv/core/wasm/index.js";
4
- import { a as N, c as M, b as y, e as v, f as D } from "./verifyKeyPathSchnorrSignature-CAp5zOTX.js";
5
- import { d as U, c as H, a as L, b as K, e as X, f as G, r as k } from "./challengeAssert-CVxCGwBH.js";
3
+ import { attachFinalizedAssert as R, computeMinClaimValue as A, computeMinPeginFee as _, deriveVaultId as S, expandAuthAnchor as T, expandHashlockSecret as C, expandWotsSeed as f, finalizePayout as I, finalizeWronglyChallenged as h, peginP2aAnchorOutput as V, pinPegoutProof as O, supportedTxGraphVersions as x, validatePeginP2aAnchor as b } from "./tbv/core/wasm/index.js";
4
+ import { a as N, c as y, b as M, e as v, f as D } from "./verifyKeyPathSchnorrSignature-CIE3jlVt.js";
5
+ import { d as U, c as H, a as L, b as K, e as X, f as G, r as k } from "./challengeAssert-D_lRvsO0.js";
6
6
  import { c as w, d as z, a as Y, b as j, e as J, f as Z, k as q, g as Q, h as $, i as aa, j as ea, p as sa, s as ra, t as ta, u as ia, v as oa } from "./bitcoin-C-TuHb-v.js";
7
7
  import { c as la } from "./abortSignals-BPpAUL1Z.js";
8
- import { c as Pa, a as Ea } from "./signing-C1rR4tqs.js";
8
+ import { c as Pa, a as ca } from "./signing-C1rR4tqs.js";
9
9
  import { B as da, C as ua, H as ga, K as ma, M as Ra, T as Aa, X as _a } from "./validation-OSC0xTHB.js";
10
10
  import { waitForTransactionReceiptSmartAware as Ta } from "./tbv/core/utils/eth/index.js";
11
- import { P as Ia, b as fa, c as ha, d as Va, e as Oa } from "./PeginManager-BvDlBR13.js";
12
- import { P as ba, c as Fa, f as Na, r as Ma, s as ya, v as va } from "./PayoutManager-CkZ3mGXB.js";
11
+ import { P as fa, b as Ia, c as ha, d as Va, e as Oa } from "./PeginManager-CXNqbgA4.js";
12
+ import { P as ba, c as Fa, f as Na, r as ya, s as Ma, v as va } from "./PayoutManager-BHeiLQ1j.js";
13
13
  import { MEMPOOL_API_URLS as Ba, MempoolNotFoundError as Ua, getAddressTxs as Ha, getAddressUtxos as La, getMempoolApiUrl as Ka, getNetworkFees as Xa, getOutspend as Ga, getTipHeight as ka, getTxHex as Wa, getTxInfo as wa, getUtxoInfo as za, pushTx as Ya } from "./tbv/core/clients/mempool/index.js";
14
14
  import { R as Ja, V as Za, a as qa, f as Qa, d as $a, g as ae, e as ee, i as se, r as re, v as te, b as ie, c as oe } from "./registration-records-D39ApuHS.js";
15
- import { V as le, a as pe, b as Pe, r as Ee } from "./signer-set-reader-DiwLeqik.js";
15
+ import { V as le, a as pe, b as Pe, r as ce } from "./signer-set-reader-DiwLeqik.js";
16
16
  import { C as de, M as ue, V as ge, a as me, c as Re } from "./pegin-registration-client-BlrXyZpF.js";
17
17
  import { O as _e, V as Se } from "./types-K_aM5GZO.js";
18
18
  import { A as Ce } from "./ApplicationRegistry.abi-s8cQ1ooR.js";
19
- import { B as fe } from "./BTCVaultRegistry.abi-DnP4UkB5.js";
20
- import { B as Ve, C as Oe, E as xe, P as be, a as Fe, e as Ne, g as Me, h as ye, i as ve, b as De } from "./BTCVaultRegistryKeyEpochs.abi-Btg0nBz1.js";
19
+ import { B as Ie } from "./BTCVaultRegistry.abi-DnP4UkB5.js";
20
+ import { B as Ve, C as Oe, E as xe, P as be, a as Fe, e as Ne, g as ye, h as Me, i as ve, b as De } from "./BTCVaultRegistryKeyEpochs.abi-Btg0nBz1.js";
21
21
  import { P as Ue } from "./ProtocolParams.abi-CuDl7AuC.js";
22
22
  import { V as Le } from "./VaultErrors.abi-Dc3UnB_h.js";
23
23
  import { b as Xe } from "./buildVaultContextInputForClaim-DhBoQKyN.js";
@@ -26,14 +26,14 @@ import { p as Je } from "./parseFundingOutpoints-GSM-IaaK.js";
26
26
  import { BitcoinNetworks as qe } from "./shared/index.js";
27
27
  import { c as $e } from "./btcTxHash-BRZ8_EZq.js";
28
28
  import { B as es, a as ss, c as rs, b as ts, d as is, g as os, h as ns, f as ls, s as ps, e as Ps } from "./psbtInputFields-CCVyaQMi.js";
29
- import { B as cs, D as ds, L as us, M as gs, c as ms, P as Rs, b as As, a as _s, S as Ss, T as Ts, W as Cs, f as Is, d as fs, p as hs, r as Vs } from "./fundPeginTransaction-CwhRbCQC.js";
30
- import { U as xs, a as bs, e as Fs, f as Ns, v as Ms } from "./reservation-BZQABu4g.js";
29
+ import { B as Es, D as ds, L as us, M as gs, c as ms, P as Rs, b as As, a as _s, S as Ss, T as Ts, W as Cs, f as fs, d as Is, p as hs, r as Vs } from "./fundPeginTransaction-CwhRbCQC.js";
30
+ import { U as xs, a as bs, e as Fs, f as Ns, v as ys } from "./reservation-BAj5n-H_.js";
31
31
  import { V as vs, a as Ds, b as Bs, i as Us, v as Hs } from "./index-B-9aXMxk.js";
32
32
  import { A as Ks, C as Xs, D as Gs, J as ks, a as Ws, b as ws, d as zs, P as Ys, R as js, e as Js, c as Zs, V as qs, i as Qs, g as $s, f as ar } from "./state-CFn1rT74.js";
33
33
  import { S as sr, V as rr, c as tr, p as ir, v as or, a as nr } from "./primeVpAuth-B0noJdcy.js";
34
- import { D as pr, g as Pr, P as Er, a as cr, b as dr, u as ur, v as gr, t as mr, w as Rr, U as Ar, V as _r, f as Sr, m as Tr, j as Cr, c as Ir, l as fr, p as hr, n as Vr, e as Or, h as xr, d as br, i as Fr, o as Nr, r as Mr, k as yr, q as vr, s as Dr, x as Br } from "./toRefundInputs-M4IbYwZU.js";
35
- import { J as Hr, l as Lr, A as Kr, a8 as Xr, C as Gr, D as kr, n as Wr, G as wr, u as zr, W as Yr, P as jr, j as Jr, v as Zr, w as qr, ai as Qr, aj as $r, ak as at, al as et, ab as st, ac as rt, ad as tt, ae as it, ag as ot, Z as nt, S as lt, V as pt, a as Pt, b as Et, d as ct, e as dt, m as ut, f as gt, g as mt, t as Rt, i as At, B as _t, o as St, a1 as Tt, ah as Ct, a9 as It, c as ft, k as ht, h as Vt, aa as Ot, E as xt, K as bt, M as Ft, a2 as Nt, X as Mt, x as yt, y as vt, _ as Dt, a3 as Bt, a4 as Ut, p as Ht, r as Lt, af as Kt, a5 as Xt, a6 as Gt, a7 as kt, F as Wt, q as wt, H as zt, I as Yt, s as jt, N as Jt, O as Zt, L as qt, Q as Qt, R as $t, T as ai, U as ei, Y as si, $ as ri, z as ti, a0 as ii } from "./buildAndBroadcastReclaim-rUsFRC5H.js";
36
- import { C as ni, P as li, a as pi, c as Pi, g as Ei, i as ci } from "./peginState-CIibG9S_.js";
34
+ import { D as pr, g as Pr, P as cr, a as Er, b as dr, u as ur, v as gr, t as mr, w as Rr, U as Ar, V as _r, f as Sr, m as Tr, j as Cr, c as fr, l as Ir, p as hr, n as Vr, e as Or, h as xr, d as br, i as Fr, o as Nr, r as yr, k as Mr, q as vr, s as Dr, x as Br } from "./toRefundInputs-Cl4KgzIc.js";
35
+ import { J as Hr, l as Lr, A as Kr, ab as Xr, C as Gr, D as kr, n as Wr, G as wr, u as zr, W as Yr, P as jr, j as Jr, v as Zr, w as qr, am as Qr, an as $r, ao as at, ap as et, af as st, ag as rt, ah as tt, ai as it, ak as ot, ac as nt, a0 as lt, S as pt, X as Pt, V as ct, a as Et, b as dt, d as ut, e as gt, m as mt, f as Rt, g as At, t as _t, i as St, B as Tt, Y as Ct, o as ft, a4 as It, al as ht, ad as Vt, c as Ot, k as xt, h as bt, ae as Ft, E as Nt, K as yt, M as Mt, a5 as vt, Z as Dt, x as Bt, y as Ut, a1 as Ht, _ as Lt, a6 as Kt, a7 as Xt, p as Gt, r as kt, aj as Wt, a8 as wt, a9 as zt, aa as Yt, F as jt, q as Jt, H as Zt, I as qt, s as Qt, N as $t, O as ai, L as ei, Q as si, R as ri, T as ti, U as ii, $ as oi, a2 as ni, z as li, a3 as pi } from "./buildAndBroadcastReclaim-Bs_zdDGN.js";
36
+ import { C as ci, P as Ei, a as di, c as ui, g as gi, i as mi } from "./peginState-CXdbSit3.js";
37
37
  export {
38
38
  Ks as AUTH_REJECTED_RPC_CODE,
39
39
  Hr as ApplicationEntryPointMismatchError,
@@ -42,9 +42,9 @@ export {
42
42
  Kr as AssertBindingError,
43
43
  Xr as BIP68NotMatureError,
44
44
  da as BITCOIN_ADDRESS_RE,
45
- fe as BTCVaultRegistryABI,
45
+ Ie as BTCVaultRegistryABI,
46
46
  Ve as BTCVaultRegistryKeyEpochsABI,
47
- cs as BTC_DUST_SAT,
47
+ Es as BTC_DUST_SAT,
48
48
  qe as BitcoinNetworks,
49
49
  es as BitcoinScriptType,
50
50
  de as COMMISSION_BPS_HEADROOM,
@@ -52,7 +52,7 @@ export {
52
52
  Oe as CONTRACT_ERRORS,
53
53
  Gr as ChallengerSetMismatchError,
54
54
  Xs as ClaimerPegoutStatusValue,
55
- ni as ContractStatus,
55
+ ci as ContractStatus,
56
56
  kr as DELEGATED_CLAIM_TX_GRAPH_VERSION,
57
57
  pr as DEPOSIT_TERMS_REJECTED_ERROR_NAME,
58
58
  ds as DUST_THRESHOLD,
@@ -79,8 +79,8 @@ export {
79
79
  s as PEGIN_DEPOSITOR_CLAIM_VOUT,
80
80
  zr as PEGIN_ETH_CONFIRMATIONS,
81
81
  be as PEGIN_FINGERPRINT_CHANGED_SELECTOR,
82
- Er as PEGIN_FINGERPRINT_DOMAIN,
83
- cr as PEGIN_FINGERPRINT_DOMAIN_PREIMAGE,
82
+ cr as PEGIN_FINGERPRINT_DOMAIN,
83
+ Er as PEGIN_FINGERPRINT_DOMAIN_PREIMAGE,
84
84
  _s as PEGIN_FIXED_OUTPUTS,
85
85
  zs as POST_WOTS_STATUSES,
86
86
  Ys as PRE_DEPOSITOR_SIGNATURES_STATES,
@@ -88,10 +88,10 @@ export {
88
88
  jr as PayoutDestinationError,
89
89
  Jr as PayoutInputLeafError,
90
90
  ba as PayoutManager,
91
- li as PeginAction,
91
+ Ei as PeginAction,
92
92
  Fe as PeginFingerprintChangedError,
93
93
  dr as PeginFingerprintInputError,
94
- Ia as PeginManager,
94
+ fa as PeginManager,
95
95
  ur as PeginParamsAmbiguousError,
96
96
  gr as PeginParamsIncompleteSpaceError,
97
97
  mr as PeginParamsNotFoundError,
@@ -109,15 +109,17 @@ export {
109
109
  tt as REFUND_MAX_FEE_RATE_SATS_VB,
110
110
  it as REFUND_VSIZE,
111
111
  ot as ReclaimUneconomicalError,
112
- nt as RegisteredVaultVersionMismatchError,
112
+ nt as RefundBroadcastRejectedError,
113
+ lt as RegisteredVaultVersionMismatchError,
113
114
  Ja as RegistrationLogsUnavailableError,
114
115
  js as RpcErrorCode,
115
116
  Ss as SPLIT_TX_FEE_SAFETY_MULTIPLIER,
116
117
  sr as ServerIdentityError,
117
- lt as SigningPlanMismatchError,
118
+ pt as SigningPlanMismatchError,
118
119
  Aa as TXID_RE,
119
120
  Ts as TX_BUFFER_SIZE_OVERHEAD,
120
121
  Ar as UnanchoredPrePeginError,
122
+ Pt as UnsupportedPayoutScriptError,
121
123
  xs as UtxoNotAvailableError,
122
124
  ke as VAULT_APP_NAME,
123
125
  Le as VAULT_ERROR_ABI,
@@ -125,7 +127,7 @@ export {
125
127
  Zs as VP_TERMINAL_FAILURE_STATUSES,
126
128
  qs as VP_TRANSIENT_STATUSES,
127
129
  Za as VaultClaimableByNotFoundError,
128
- pt as VaultIdBindingError,
130
+ ct as VaultIdBindingError,
129
131
  vs as VaultProviderRpcClient,
130
132
  _r as VaultRootMismatchError,
131
133
  le as ViemOperationKeyReader,
@@ -138,39 +140,40 @@ export {
138
140
  rr as VpTokenRegistry,
139
141
  Cs as WALLET_RELAY_FEE_RATE_THRESHOLD,
140
142
  _a as X_ONLY_PUBKEY_HEX_LEN,
141
- Pt as activateVault,
142
- Et as activateVaultAndRedeem,
143
- pi as activationDeadlineBlocksRemaining,
143
+ Et as activateVault,
144
+ dt as activateVaultAndRedeem,
145
+ di as activationDeadlineBlocksRemaining,
144
146
  ss as applyChangeOutputPolicy,
145
- ct as assembleWatchtowerArtifacts,
146
- dt as assembleWatchtowerArtifactsFromSignatures,
147
- ut as assertArtifactsUsableForVault,
148
- gt as assertAssertBindsClaimAndPayout,
149
- mt as assertChallengerSetMatchesVault,
147
+ ut as assembleWatchtowerArtifacts,
148
+ gt as assembleWatchtowerArtifactsFromSignatures,
149
+ mt as assertArtifactsUsableForVault,
150
+ Rt as assertAssertBindsClaimAndPayout,
151
+ At as assertChallengerSetMatchesVault,
150
152
  Sr as assertClaimBatchHomogeneous,
151
- Rt as assertClaimSpendsVault,
153
+ _t as assertClaimSpendsVault,
152
154
  N as assertKeyPathSchnorrSignature,
153
155
  qa as assertOnChainBtcPubkey,
154
- At as assertPayoutPaysRegisteredScript,
156
+ St as assertPayoutPaysRegisteredScript,
155
157
  t as assertPsbtUnsignedTxMatches,
156
158
  Qa as assertRegisteredPayoutScriptBounds,
157
- _t as assertReturnedGraphMatchesFingerprint,
158
- M as assertReturnedKeyPathSignatures,
159
+ Tt as assertReturnedGraphMatchesFingerprint,
160
+ y as assertReturnedKeyPathSignatures,
159
161
  i as assertScriptPathSchnorrSignature,
160
- St as assertTermsMatchVault,
162
+ Ct as assertStandardPayoutScriptsAtEpochs,
163
+ ft as assertTermsMatchVault,
161
164
  bs as assertUtxosAvailable,
162
165
  g as assertValidVaultCoreVersion,
163
- Tt as assertVaultProviderHintAccepted,
166
+ It as assertVaultProviderHintAccepted,
164
167
  R as attachFinalizedAssert,
165
168
  Bs as batchPollByProvider,
166
- Ct as buildAndBroadcastReclaim,
167
- It as buildAndBroadcastRefund,
169
+ ht as buildAndBroadcastReclaim,
170
+ Vt as buildAndBroadcastRefund,
168
171
  U as buildChallengeAssertPsbt,
169
- fa as buildDepositTerms,
172
+ Ia as buildDepositTerms,
170
173
  We as buildFundingOutpointsCommitment,
171
174
  H as buildNoPayoutPsbt,
172
175
  o as buildPayoutPsbt,
173
- y as buildPeginInputPsbt,
176
+ M as buildPeginInputPsbt,
174
177
  Tr as buildPeginParamsCandidates,
175
178
  n as buildPeginTxFromFundedPrePegin,
176
179
  l as buildPrePeginPsbt,
@@ -179,10 +182,10 @@ export {
179
182
  we as buildVaultContext,
180
183
  Xe as buildVaultContextInputForClaim,
181
184
  $e as calculateBtcTxHash,
182
- Pi as canPerformAction,
185
+ ui as canPerformAction,
183
186
  w as canonicalizeBtcPubkey,
184
187
  Re as capMaxAcceptableCommissionBps,
185
- ft as claimExpiredVault,
188
+ Ot as claimExpiredVault,
186
189
  la as combineAbortSignals,
187
190
  rs as computeChangeOutputFeeSats,
188
191
  Cr as computeFundedPrePeginFee,
@@ -192,18 +195,18 @@ export {
192
195
  _ as computeMinPeginFee,
193
196
  p as computeNumLocalChallengers,
194
197
  is as computePeginBaseFeeSats,
195
- Ir as computePeginFingerprint,
198
+ fr as computePeginFingerprint,
196
199
  ha as computeWotsBlockPublicKeysHash,
197
- ht as copyAssertConnectorLeaf,
200
+ xt as copyAssertConnectorLeaf,
198
201
  tr as createAuthenticatedVpClient,
199
202
  P as createPayoutScript,
200
203
  Pa as createTaprootScriptPathSignOptions,
201
- Ea as createTaprootScriptPathSignOptionsForInput,
204
+ ca as createTaprootScriptPathSignOptionsForInput,
202
205
  z as deriveBip86ScriptPubKeyHex,
203
- Vt as deriveClaimerWotsKeypair,
204
- E as deriveDepositorClaimDescriptor,
205
- c as deriveDepositorClaimScriptPubKey,
206
- fr as deriveHashlocksFromPrePegin,
206
+ bt as deriveClaimerWotsKeypair,
207
+ c as deriveDepositorClaimDescriptor,
208
+ E as deriveDepositorClaimScriptPubKey,
209
+ Ir as deriveHashlocksFromPrePegin,
207
210
  Y as deriveNativeSegwitAddress,
208
211
  $a as derivePeginVaultId,
209
212
  j as deriveTaprootAddress,
@@ -216,34 +219,34 @@ export {
216
219
  J as ensureHexPrefix,
217
220
  Oa as ensurePrePeginTermsApproval,
218
221
  X as estimateReclaimFeeSats,
219
- Ot as estimateRefundFeeSats,
222
+ Ft as estimateRefundFeeSats,
220
223
  T as expandAuthAnchor,
221
224
  C as expandHashlockSecret,
222
- I as expandWotsSeed,
225
+ f as expandWotsSeed,
223
226
  Ne as extractErrorData,
224
227
  Fs as extractInputsFromTransaction,
225
228
  d as extractPayoutSignature,
226
229
  v as extractPeginInputSignature,
227
- f as finalizePayout,
230
+ I as finalizePayout,
228
231
  D as finalizePeginInputPsbt,
229
232
  G as finalizeScriptPathWithSignatures,
230
233
  h as finalizeWronglyChallenged,
231
234
  Ns as findOverlappingPendingVaults,
232
235
  ae as findRegistrationRecord,
233
- xt as fingerprintReturnedGraph,
236
+ Nt as fingerprintReturnedGraph,
234
237
  Z as formatSatoshisToBtc,
235
238
  Na as forwardDepositApproval,
236
239
  Ye as forwardDeriveContextHash,
237
- Is as fundPeginTransaction,
240
+ fs as fundPeginTransaction,
238
241
  Ha as getAddressTxs,
239
242
  La as getAddressUtxos,
240
- Me as getContractErrorMessage,
243
+ ye as getContractErrorMessage,
241
244
  os as getDustThreshold,
242
245
  Ka as getMempoolApiUrl,
243
246
  q as getNetwork,
244
247
  Xa as getNetworkFees,
245
248
  Ga as getOutspend,
246
- Ei as getPeginProtocolState,
249
+ gi as getPeginProtocolState,
247
250
  ns as getPsbtInputFields,
248
251
  ls as getScriptType,
249
252
  Q as getSortedXOnlyPubkeys,
@@ -251,89 +254,90 @@ export {
251
254
  Wa as getTxHex,
252
255
  wa as getTxInfo,
253
256
  za as getUtxoInfo,
254
- ye as handleContractError,
257
+ Me as handleContractError,
255
258
  $ as hexToUint8Array,
256
- ci as isActivationDeadlinePassedOnChain,
259
+ mi as isActivationDeadlinePassedOnChain,
257
260
  aa as isAddressFromPublicKey,
258
- bt as isApplicationEntryPointMismatchError,
261
+ yt as isApplicationEntryPointMismatchError,
259
262
  Qs as isAuthRejectedError,
260
- Ft as isDepositAmountValid,
263
+ Mt as isDepositAmountValid,
261
264
  xr as isDepositTermsRejectedError,
262
- Nt as isHintAccepted,
265
+ vt as isHintAccepted,
263
266
  ve as isKnownContractError,
264
- Mt as isParticipantKeyDriftError,
267
+ Dt as isParticipantKeyDriftError,
265
268
  De as isPeginFingerprintChangedError,
266
269
  br as isPeginFingerprintInputError,
267
- yt as isPeginRegistrationMissingError,
268
- vt as isPeginRegistrationNotFinalError,
270
+ Bt as isPeginRegistrationMissingError,
271
+ Ut as isPeginRegistrationNotFinalError,
269
272
  $s as isPegoutTerminalStatus,
270
273
  ar as isRecognizedPegoutStatus,
271
- Dt as isRegisteredVaultVersionMismatchError,
274
+ Ht as isRegisteredVaultVersionMismatchError,
272
275
  ee as isRegistrationLogsUnavailableError,
273
276
  Us as isUnrecognizedDaemonStatusError,
277
+ Lt as isUnsupportedPayoutScriptError,
274
278
  ea as isValidHex,
275
279
  se as isVaultClaimableByNotFoundError,
276
280
  Fr as isWotsMismatchError,
277
- Bt as matchKeyHint,
278
- Ut as matchKeySetHint,
281
+ Kt as matchKeyHint,
282
+ Xt as matchKeySetHint,
279
283
  Nr as orderClaimBatchByHtlcVout,
280
284
  Je as parseFundingOutpointsFromTx,
281
- fs as parseUnfundedWasmTransaction,
285
+ Is as parseUnfundedWasmTransaction,
282
286
  hs as peginOutputCount,
283
287
  V as peginP2aAnchorOutput,
284
288
  O as pinPegoutProof,
285
- Ht as planDelegatedClaimSigning,
289
+ Gt as planDelegatedClaimSigning,
286
290
  ir as primeVpTokenRegistry,
287
291
  sa as processPublicKeyToXOnly,
288
292
  Ya as pushTx,
289
293
  Vs as rateBasedTxBufferFee,
290
- Lt as readDelegatedClaimVaultContext,
291
- Kt as readRefundPrePeginContext,
292
- Xt as readStampedParticipantKeys,
293
- Mr as rebuildDepositTermsCore,
294
- yr as rebuildDepositTermsForClaim,
294
+ kt as readDelegatedClaimVaultContext,
295
+ Wt as readRefundPrePeginContext,
296
+ wt as readStampedParticipantKeys,
297
+ yr as rebuildDepositTermsCore,
298
+ Mr as rebuildDepositTermsForClaim,
295
299
  k as reclaimVsize,
296
300
  vr as reconstructPeginParams,
297
301
  re as registrationPrePeginTxHash,
298
- Ma as requireChangeAddress,
299
- Gt as resolveCurrentParticipantKeys,
300
- kt as resolveParticipantKeysAtEpochs,
301
- Ee as resolveProtocolAddresses,
302
- Wt as runDepositorPresignFlow,
302
+ ya as requireChangeAddress,
303
+ zt as resolveCurrentParticipantKeys,
304
+ Yt as resolveParticipantKeysAtEpochs,
305
+ ce as resolveProtocolAddresses,
306
+ jt as runDepositorPresignFlow,
303
307
  Dr as selectSiblingRegistrations,
304
308
  ps as selectUtxosForPegin,
305
309
  Ps as shouldAddChangeOutput,
306
- wt as signDelegatedClaimPlan,
307
- zt as signDepositorGraph,
310
+ Jt as signDelegatedClaimPlan,
311
+ Zt as signDepositorGraph,
308
312
  ra as stripHexPrefix,
309
- Yt as submitWotsPublicKey,
310
- jt as summarizeWatchtowerArtifacts,
313
+ qt as submitWotsPublicKey,
314
+ Qt as summarizeWatchtowerArtifacts,
311
315
  x as supportedTxGraphVersions,
312
- ya as supportsDepositApproval,
316
+ Ma as supportsDepositApproval,
313
317
  Br as toRefundInputs,
314
318
  ta as toXOnly,
315
319
  ia as uint8ArrayToHex,
316
- Jt as validateDepositAmount,
317
- Zt as validateMultiVaultDepositInputs,
320
+ $t as validateDepositAmount,
321
+ ai as validateMultiVaultDepositInputs,
318
322
  te as validateOffchainParams,
319
- qt as validateOnChainParticipantKeys,
323
+ ei as validateOnChainParticipantKeys,
320
324
  ie as validatePegInConfiguration,
321
325
  b as validatePeginP2aAnchor,
322
- Qt as validateProviderSelection,
323
- $t as validateRemainingCapacity,
326
+ si as validateProviderSelection,
327
+ ri as validateRemainingCapacity,
324
328
  Hs as validateRequestDepositorClaimerArtifactsResponse,
325
329
  va as validateSecretAgainstHashlock,
326
330
  oe as validateTBVProtocolParams,
327
- Ms as validateUtxosAvailable,
328
- ai as validateVaultAmounts,
329
- ei as validateVaultProviderPubkey,
331
+ ys as validateUtxosAvailable,
332
+ ti as validateVaultAmounts,
333
+ ii as validateVaultProviderPubkey,
330
334
  oa as validateWalletPubkey,
331
- si as verifyRegisteredParticipantKeys,
332
- ri as verifyRegisteredVaultVersions,
335
+ oi as verifyRegisteredParticipantKeys,
336
+ ni as verifyRegisteredVaultVersions,
333
337
  or as verifyServerIdentity,
334
338
  nr as vpTokenRegistry,
335
- ti as waitForPeginRegistrationDepth,
336
- ii as waitForPeginStatus,
339
+ li as waitForPeginRegistrationDepth,
340
+ pi as waitForPeginStatus,
337
341
  Ta as waitForTransactionReceiptSmartAware
338
342
  };
339
343
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";var l=(i=>(i[i.PENDING=0]="PENDING",i[i.VERIFIED=1]="VERIFIED",i[i.ACTIVE=2]="ACTIVE",i[i.REDEEMED=3]="REDEEMED",i[i.LIQUIDATED=4]="LIQUIDATED",i[i.INVALID=5]="INVALID",i[i.DEPOSITOR_WITHDRAWN=6]="DEPOSITOR_WITHDRAWN",i[i.EXPIRED=7]="EXPIRED",i[i.NON_DEPOSITOR_SPEND=8]="NON_DEPOSITOR_SPEND",i))(l||{}),E=(i=>(i.SUBMIT_WOTS_KEY="SUBMIT_WOTS_KEY",i.SIGN_PAYOUT_TRANSACTIONS="SIGN_PAYOUT_TRANSACTIONS",i.SIGN_AND_BROADCAST_TO_BITCOIN="SIGN_AND_BROADCAST_TO_BITCOIN",i.ACTIVATE_VAULT="ACTIVATE_VAULT",i.ACTIVATE_AND_REDEEM="ACTIVATE_AND_REDEEM",i.REFUND_HTLC="REFUND_HTLC",i.CLAIM_EXPIRED_VAULT="CLAIM_EXPIRED_VAULT",i))(E||{});function R(i,e={}){const{transactionsReady:A,needsWotsKey:T,pendingIngestion:I,canRefund:_,hasProviderTerminalFailure:D,htlcSpentByPeginTx:n,canClaimExpired:N}=e;return i===0?D?{contractStatus:i,availableActions:[]}:T?{contractStatus:i,availableActions:["SUBMIT_WOTS_KEY"]}:I===!0&&!A?{contractStatus:i,availableActions:["SIGN_AND_BROADCAST_TO_BITCOIN"]}:I===void 0&&!A?{contractStatus:i,availableActions:[]}:A?{contractStatus:i,availableActions:["SIGN_PAYOUT_TRANSACTIONS"]}:{contractStatus:i,availableActions:[]}:i===1?n?{contractStatus:i,availableActions:["ACTIVATE_AND_REDEEM"]}:{contractStatus:i,availableActions:["ACTIVATE_VAULT"]}:i===2?{contractStatus:i,availableActions:[]}:i===3?{contractStatus:i,availableActions:[]}:i===4?{contractStatus:i,availableActions:[]}:i===7?N?{contractStatus:i,availableActions:["CLAIM_EXPIRED_VAULT"]}:{contractStatus:i,availableActions:_?["REFUND_HTLC"]:[]}:i===5?{contractStatus:i,availableActions:[]}:i===6?{contractStatus:i,availableActions:[]}:i===8?{contractStatus:i,availableActions:[]}:{contractStatus:i,availableActions:[]}}function O(i,e){return i.availableActions.includes(e)}function r(i){const{currentBlock:e,createdAtBlock:A,pegInActivationTimeout:T}=i;return e>A+T}function v(i){const{currentBlock:e,createdAtBlock:A,pegInActivationTimeout:T}=i,I=A+T;return e>=I?0:Number(I-e)}exports.ContractStatus=l;exports.PeginAction=E;exports.activationDeadlineBlocksRemaining=v;exports.canPerformAction=O;exports.getPeginProtocolState=R;exports.isActivationDeadlinePassedOnChain=r;
2
+ //# sourceMappingURL=peginState-B4t_PDgj.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginState-B4t_PDgj.cjs","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-8). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n /**\n * Status 8 (indexer-only): a redeemed vault's BTC was spent on Bitcoin to a\n * script other than the depositor's payout script, in practice a vault\n * keeper's claim that no challenger blocked. The vault's BTC is gone; only\n * the depositor's PegIn output 1 reserve may remain.\n */\n NON_DEPOSITOR_SPEND = 8,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /**\n * Escape hatch: reveal the HTLC secret and immediately redeem the vault for\n * the depositor (`activateVaultWithSecretAndRedeem`), skipping application\n * activation. Recovery path when the peg-in was swept on Bitcoin but the\n * vault could not be activated (application paused / activation revert).\n */\n ACTIVATE_AND_REDEEM = \"ACTIVATE_AND_REDEEM\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n /**\n * Reveal the HTLC secret for a vault that expired after reaching Verified\n * (`claimExpiredVault`), so the BTC the PegIn swept into the vault is\n * claimed out to the keys recorded on chain. The only exit once the PegIn\n * has spent the HTLC; the contract accepts it until the vault's\n * `claimExpiredUntil` block.\n */\n CLAIM_EXPIRED_VAULT = \"CLAIM_EXPIRED_VAULT\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n /**\n * VERIFIED only: the Pre-PegIn HTLC outpoint has been spent on Bitcoin BY\n * THE PEGIN TRANSACTION while the vault is still Verified on Ethereum. The\n * secret was revealed (e.g. in the calldata of a reverted activation) and\n * the peg-in swept without the vault activating, so the normal activation\n * no longer returns value to the depositor and the CSV refund can never\n * broadcast. The remaining recovery is the activate-and-redeem escape\n * hatch.\n *\n * The caller MUST prove the spender by comparing the outspend's\n * `spendingTxid` against the vault's PegIn txid before setting this. A\n * bare \"spent\" observation is not sufficient: the spend may be the\n * depositor's own CSV refund, and offering the secret-revealing hatch\n * against a refund burns the secret for a vault whose funds already\n * returned.\n */\n htlcSpentByPeginTx?: boolean;\n /**\n * EXPIRED only: the vault expired after reaching Verified, the PegIn\n * transaction has spent the Pre-PegIn HTLC, and the claim window has not\n * elapsed. The CSV refund is gone, so the claim is the remaining exit.\n *\n * The same spender proof as `htlcSpentByPeginTx` applies: offering the claim\n * while the HTLC is unspent reveals the secret and lets anyone broadcast the\n * PegIn ahead of the depositor's refund. When set, it takes precedence over\n * `canRefund`, which a proven PegIn spend makes impossible.\n */\n canClaimExpired?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n htlcSpentByPeginTx,\n canClaimExpired,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n // A spent HTLC while still Verified means the peg-in was swept without\n // activation: activating normally would hand the collateral to an\n // application flow that already failed once, and refunding is impossible\n // (the outpoint is gone). Surface only the escape hatch.\n if (htlcSpentByPeginTx) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_AND_REDEEM],\n };\n }\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n if (canClaimExpired) {\n return {\n contractStatus,\n availableActions: [PeginAction.CLAIM_EXPIRED_VAULT],\n };\n }\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n // Terminal like DEPOSITOR_WITHDRAWN: the vault output is spent. The reserve\n // reclaim is decided by the app from Bitcoin reads, not offered here.\n if (contractStatus === ContractStatus.NON_DEPOSITOR_SPEND) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n\n// ============================================================================\n// Activation deadline\n// ============================================================================\n\n/**\n * Whether a vault's on-chain activation window has closed. Mirrors the\n * BTCVaultRegistry check that reverts `ActivationDeadlineExpired`:\n * `block.number > createdAt + pegInActivationTimeout` — strict `>`, so a\n * boundary-equal block is NOT expired. All values are Ethereum block numbers.\n */\nexport function isActivationDeadlinePassedOnChain(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): boolean {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n return currentBlock > createdAtBlock + pegInActivationTimeout;\n}\n\n/**\n * Blocks still available for an activation transaction to be mined; `0` once\n * the window has closed.\n *\n * `isActivationDeadlinePassedOnChain` answers whether the window is already\n * shut, which is the right question for a badge but the wrong one for a\n * secret-bearing call. An activation submitted in the last block before the\n * deadline reverts if it lands one block late, and by then `s` is public\n * calldata: the vault expires with `ActivationTimeout`, and the vault\n * provider, which holds the rest of the HTLC signature set, can broadcast the\n * PegIn with that secret. The caller therefore needs the remaining margin,\n * not a boolean.\n *\n * The contract accepts a transaction mined at `block.number <= createdAt +\n * timeout`. `currentBlock` is the chain head, which is already mined, so a new\n * transaction lands at `currentBlock + 1` at the earliest: at\n * `currentBlock === createdAt + timeout` no usable block remains.\n */\nexport function activationDeadlineBlocksRemaining(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): number {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n const lastUsableBlock = createdAtBlock + pegInActivationTimeout;\n if (currentBlock >= lastUsableBlock) return 0;\n return Number(lastUsableBlock - currentBlock);\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","htlcSpentByPeginTx","canClaimExpired","canPerformAction","state","action","isActivationDeadlinePassedOnChain","params","currentBlock","createdAtBlock","pegInActivationTimeout","activationDeadlineBlocksRemaining","lastUsableBlock"],"mappings":"aAeO,IAAKA,GAAAA,IAEVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SAEAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WAEAA,EAAAA,EAAA,WAAa,CAAA,EAAb,aAEAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAEAA,EAAAA,EAAA,oBAAsB,CAAA,EAAtB,sBAEAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UAOAA,EAAAA,EAAA,oBAAsB,CAAA,EAAtB,sBAvBUA,IAAAA,GAAA,CAAA,CAAA,EAuCAC,GAAAA,IAEVA,EAAA,gBAAkB,kBAElBA,EAAA,yBAA2B,2BAE3BA,EAAA,8BAAgC,gCAEhCA,EAAA,eAAiB,iBAOjBA,EAAA,oBAAsB,sBAEtBA,EAAA,YAAc,cAQdA,EAAA,oBAAsB,sBAzBZA,IAAAA,GAAA,CAAA,CAAA,EAuGL,SAASC,EACdC,EACAC,EAAwC,GACpB,CACpB,KAAM,CACJ,kBAAAC,EACA,aAAAC,EACA,iBAAAC,EACA,UAAAC,EACA,2BAAAC,EACA,mBAAAC,EACA,gBAAAC,CAAA,EACEP,EAEJ,OAAID,IAAmB,EACjBM,EACK,CAAE,eAAAN,EAAgB,iBAAkB,EAAC,EAG1CG,EACK,CACL,eAAAH,EACA,iBAAkB,CAAC,iBAAA,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,EACzC,OAAIF,GAAgBI,EAAwB,EACrC,OAAOA,EAAkBJ,CAAY,CAC9C"}
@@ -1,4 +1,4 @@
1
- var N = /* @__PURE__ */ ((i) => (i[i.PENDING = 0] = "PENDING", i[i.VERIFIED = 1] = "VERIFIED", i[i.ACTIVE = 2] = "ACTIVE", i[i.REDEEMED = 3] = "REDEEMED", i[i.LIQUIDATED = 4] = "LIQUIDATED", i[i.INVALID = 5] = "INVALID", i[i.DEPOSITOR_WITHDRAWN = 6] = "DEPOSITOR_WITHDRAWN", i[i.EXPIRED = 7] = "EXPIRED", i))(N || {}), n = /* @__PURE__ */ ((i) => (i.SUBMIT_WOTS_KEY = "SUBMIT_WOTS_KEY", i.SIGN_PAYOUT_TRANSACTIONS = "SIGN_PAYOUT_TRANSACTIONS", i.SIGN_AND_BROADCAST_TO_BITCOIN = "SIGN_AND_BROADCAST_TO_BITCOIN", i.ACTIVATE_VAULT = "ACTIVATE_VAULT", i.ACTIVATE_AND_REDEEM = "ACTIVATE_AND_REDEEM", i.REFUND_HTLC = "REFUND_HTLC", i.CLAIM_EXPIRED_VAULT = "CLAIM_EXPIRED_VAULT", i))(n || {});
1
+ var N = /* @__PURE__ */ ((i) => (i[i.PENDING = 0] = "PENDING", i[i.VERIFIED = 1] = "VERIFIED", i[i.ACTIVE = 2] = "ACTIVE", i[i.REDEEMED = 3] = "REDEEMED", i[i.LIQUIDATED = 4] = "LIQUIDATED", i[i.INVALID = 5] = "INVALID", i[i.DEPOSITOR_WITHDRAWN = 6] = "DEPOSITOR_WITHDRAWN", i[i.EXPIRED = 7] = "EXPIRED", i[i.NON_DEPOSITOR_SPEND = 8] = "NON_DEPOSITOR_SPEND", i))(N || {}), n = /* @__PURE__ */ ((i) => (i.SUBMIT_WOTS_KEY = "SUBMIT_WOTS_KEY", i.SIGN_PAYOUT_TRANSACTIONS = "SIGN_PAYOUT_TRANSACTIONS", i.SIGN_AND_BROADCAST_TO_BITCOIN = "SIGN_AND_BROADCAST_TO_BITCOIN", i.ACTIVATE_VAULT = "ACTIVATE_VAULT", i.ACTIVATE_AND_REDEEM = "ACTIVATE_AND_REDEEM", i.REFUND_HTLC = "REFUND_HTLC", i.CLAIM_EXPIRED_VAULT = "CLAIM_EXPIRED_VAULT", i))(n || {});
2
2
  function R(i, e = {}) {
3
3
  const {
4
4
  transactionsReady: A,
@@ -51,25 +51,25 @@ function R(i, e = {}) {
51
51
  "REFUND_HTLC"
52
52
  /* REFUND_HTLC */
53
53
  ] : []
54
- } : i === 5 ? { contractStatus: i, availableActions: [] } : i === 6 ? { contractStatus: i, availableActions: [] } : { contractStatus: i, availableActions: [] };
54
+ } : i === 5 ? { contractStatus: i, availableActions: [] } : i === 6 ? { contractStatus: i, availableActions: [] } : i === 8 ? { contractStatus: i, availableActions: [] } : { contractStatus: i, availableActions: [] };
55
55
  }
56
- function r(i, e) {
56
+ function O(i, e) {
57
57
  return i.availableActions.includes(e);
58
58
  }
59
59
  function v(i) {
60
60
  const { currentBlock: e, createdAtBlock: A, pegInActivationTimeout: T } = i;
61
61
  return e > A + T;
62
62
  }
63
- function O(i) {
63
+ function r(i) {
64
64
  const { currentBlock: e, createdAtBlock: A, pegInActivationTimeout: T } = i, I = A + T;
65
65
  return e >= I ? 0 : Number(I - e);
66
66
  }
67
67
  export {
68
68
  N as C,
69
69
  n as P,
70
- O as a,
71
- r as c,
70
+ r as a,
71
+ O as c,
72
72
  R as g,
73
73
  v as i
74
74
  };
75
- //# sourceMappingURL=peginState-CIibG9S_.js.map
75
+ //# sourceMappingURL=peginState-CXdbSit3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginState-CXdbSit3.js","sources":["../src/tbv/core/services/deposit/peginState.ts"],"sourcesContent":["// ============================================================================\n// State Definitions\n// ============================================================================\n\n/**\n * Vault status — combines on-chain contract status (0-4) with indexer-derived\n * statuses (5-8). The contract enum (BTCVaultRegistry.sol BTCVaultStatus) only\n * has: Pending(0), Verified(1), Active(2), Redeemed(3), Expired(4).\n * The indexer maps these and adds extra statuses for UI display.\n *\n * IMPORTANT: With the new contract architecture:\n * - Core vault status (BTCVaultRegistry) does NOT change when used by applications\n * - Vaults remain at ACTIVE status even when used in DeFi positions\n * - Application usage status is tracked separately by each integration controller\n */\nexport enum ContractStatus {\n /** Status 0: Request submitted, waiting for ACKs */\n PENDING = 0,\n /** Status 1: All ACKs collected, ready for secret activation */\n VERIFIED = 1,\n /** Status 2: HTLC secret revealed, vault is active and usable (stays here even when used by apps) */\n ACTIVE = 2,\n /** Status 3: Vault has been redeemed, BTC is claimable */\n REDEEMED = 3,\n /** Status 4 (indexer-only): Vault was liquidated (collateral seized due to unpaid debt) */\n LIQUIDATED = 4,\n /** Status 5 (indexer-only): Vault is invalid — BTC UTXOs were spent in a different transaction */\n INVALID = 5,\n /** Status 6 (indexer-only): Depositor has withdrawn their BTC (redemption complete) */\n DEPOSITOR_WITHDRAWN = 6,\n /** Status 7 (indexer-only): Vault expired due to AckTimeout or ActivationTimeout */\n EXPIRED = 7,\n /**\n * Status 8 (indexer-only): a redeemed vault's BTC was spent on Bitcoin to a\n * script other than the depositor's payout script, in practice a vault\n * keeper's claim that no challenger blocked. The vault's BTC is gone; only\n * the depositor's PegIn output 1 reserve may remain.\n */\n NON_DEPOSITOR_SPEND = 8,\n}\n\n/** Reason why a vault expired */\nexport type ExpirationReason =\n | \"ack_timeout\"\n | \"proof_timeout\"\n | \"activation_timeout\";\n\n// ============================================================================\n// Protocol State Model\n// ============================================================================\n\n/**\n * Available actions user can take\n */\nexport enum PeginAction {\n /** Submit WOTS key (re-derives via wallet `deriveContextHash`) */\n SUBMIT_WOTS_KEY = \"SUBMIT_WOTS_KEY\",\n /** Sign payout transactions */\n SIGN_PAYOUT_TRANSACTIONS = \"SIGN_PAYOUT_TRANSACTIONS\",\n /** Sign and broadcast peg-in transaction to Bitcoin */\n SIGN_AND_BROADCAST_TO_BITCOIN = \"SIGN_AND_BROADCAST_TO_BITCOIN\",\n /** Reveal HTLC secret on Ethereum to activate vault */\n ACTIVATE_VAULT = \"ACTIVATE_VAULT\",\n /**\n * Escape hatch: reveal the HTLC secret and immediately redeem the vault for\n * the depositor (`activateVaultWithSecretAndRedeem`), skipping application\n * activation. Recovery path when the peg-in was swept on Bitcoin but the\n * vault could not be activated (application paused / activation revert).\n */\n ACTIVATE_AND_REDEEM = \"ACTIVATE_AND_REDEEM\",\n /** Sign and broadcast HTLC refund transaction for an expired vault */\n REFUND_HTLC = \"REFUND_HTLC\",\n /**\n * Reveal the HTLC secret for a vault that expired after reaching Verified\n * (`claimExpiredVault`), so the BTC the PegIn swept into the vault is\n * claimed out to the keys recorded on chain. The only exit once the PegIn\n * has spent the HTLC; the contract accepts it until the vault's\n * `claimExpiredUntil` block.\n */\n CLAIM_EXPIRED_VAULT = \"CLAIM_EXPIRED_VAULT\",\n}\n\n/**\n * Protocol-level peg-in state (framework-agnostic)\n */\nexport interface PeginProtocolState {\n /** Smart contract status (source of truth for on-chain state) */\n contractStatus: ContractStatus;\n /** Available user actions (empty array when no action is available) */\n availableActions: PeginAction[];\n}\n\n/**\n * Options for getPeginProtocolState function.\n *\n * All fields represent protocol-level state from the vault provider or\n * on-chain contracts. Client-side tracking (localStorage, polling state)\n * is NOT included — consumers handle that in their own layer.\n */\nexport interface GetPeginProtocolStateOptions {\n /** Whether claim/payout transactions are ready from VP */\n transactionsReady?: boolean;\n /** Whether the vault provider is waiting for the depositor's WOTS public key */\n needsWotsKey?: boolean;\n /** Whether the vault provider hasn't ingested this peg-in yet */\n pendingIngestion?: boolean;\n /** Whether the depositor can refund the HTLC (Pre-PegIn tx available) */\n canRefund?: boolean;\n /** Whether the vault provider reported a terminal failure */\n hasProviderTerminalFailure?: boolean;\n /**\n * VERIFIED only: the Pre-PegIn HTLC outpoint has been spent on Bitcoin BY\n * THE PEGIN TRANSACTION while the vault is still Verified on Ethereum. The\n * secret was revealed (e.g. in the calldata of a reverted activation) and\n * the peg-in swept without the vault activating, so the normal activation\n * no longer returns value to the depositor and the CSV refund can never\n * broadcast. The remaining recovery is the activate-and-redeem escape\n * hatch.\n *\n * The caller MUST prove the spender by comparing the outspend's\n * `spendingTxid` against the vault's PegIn txid before setting this. A\n * bare \"spent\" observation is not sufficient: the spend may be the\n * depositor's own CSV refund, and offering the secret-revealing hatch\n * against a refund burns the secret for a vault whose funds already\n * returned.\n */\n htlcSpentByPeginTx?: boolean;\n /**\n * EXPIRED only: the vault expired after reaching Verified, the PegIn\n * transaction has spent the Pre-PegIn HTLC, and the claim window has not\n * elapsed. The CSV refund is gone, so the claim is the remaining exit.\n *\n * The same spender proof as `htlcSpentByPeginTx` applies: offering the claim\n * while the HTLC is unspent reveals the secret and lets anyone broadcast the\n * PegIn ahead of the depositor's refund. When set, it takes precedence over\n * `canRefund`, which a proven PegIn spend makes impossible.\n */\n canClaimExpired?: boolean;\n}\n\n// ============================================================================\n// State Machine Logic\n// ============================================================================\n\n/**\n * Determine the current protocol state and available actions based on contract\n * status and vault provider state. Framework-agnostic: returns only\n * protocol-level data with no display labels, messages, or UI concerns.\n *\n * Client-side tracking overrides (e.g. suppressing actions after the user\n * has already acted but on-chain state hasn't caught up) are the caller's\n * responsibility.\n *\n * @param contractStatus - On-chain contract status (source of truth)\n * @param options - Vault provider state\n * @returns Protocol state with available actions\n */\nexport function getPeginProtocolState(\n contractStatus: ContractStatus,\n options: GetPeginProtocolStateOptions = {},\n): PeginProtocolState {\n const {\n transactionsReady,\n needsWotsKey,\n pendingIngestion,\n canRefund,\n hasProviderTerminalFailure,\n htlcSpentByPeginTx,\n canClaimExpired,\n } = options;\n\n if (contractStatus === ContractStatus.PENDING) {\n if (hasProviderTerminalFailure) {\n return { contractStatus, availableActions: [] };\n }\n\n if (needsWotsKey) {\n return {\n contractStatus,\n availableActions: [PeginAction.SUBMIT_WOTS_KEY],\n };\n }\n\n if (pendingIngestion === true && !transactionsReady) {\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_AND_BROADCAST_TO_BITCOIN],\n };\n }\n\n if (pendingIngestion === undefined && !transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n if (!transactionsReady) {\n return { contractStatus, availableActions: [] };\n }\n\n return {\n contractStatus,\n availableActions: [PeginAction.SIGN_PAYOUT_TRANSACTIONS],\n };\n }\n\n if (contractStatus === ContractStatus.VERIFIED) {\n // A spent HTLC while still Verified means the peg-in was swept without\n // activation: activating normally would hand the collateral to an\n // application flow that already failed once, and refunding is impossible\n // (the outpoint is gone). Surface only the escape hatch.\n if (htlcSpentByPeginTx) {\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_AND_REDEEM],\n };\n }\n return {\n contractStatus,\n availableActions: [PeginAction.ACTIVATE_VAULT],\n };\n }\n\n if (contractStatus === ContractStatus.ACTIVE) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.REDEEMED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.LIQUIDATED) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.EXPIRED) {\n if (canClaimExpired) {\n return {\n contractStatus,\n availableActions: [PeginAction.CLAIM_EXPIRED_VAULT],\n };\n }\n return {\n contractStatus,\n availableActions: canRefund ? [PeginAction.REFUND_HTLC] : [],\n };\n }\n\n if (contractStatus === ContractStatus.INVALID) {\n return { contractStatus, availableActions: [] };\n }\n\n if (contractStatus === ContractStatus.DEPOSITOR_WITHDRAWN) {\n return { contractStatus, availableActions: [] };\n }\n\n // Terminal like DEPOSITOR_WITHDRAWN: the vault output is spent. The reserve\n // reclaim is decided by the app from Bitcoin reads, not offered here.\n if (contractStatus === ContractStatus.NON_DEPOSITOR_SPEND) {\n return { contractStatus, availableActions: [] };\n }\n\n return { contractStatus, availableActions: [] };\n}\n\n/**\n * Check if a specific action is available in the current state\n */\nexport function canPerformAction(\n state: PeginProtocolState,\n action: PeginAction,\n): boolean {\n return state.availableActions.includes(action);\n}\n\n// ============================================================================\n// Activation deadline\n// ============================================================================\n\n/**\n * Whether a vault's on-chain activation window has closed. Mirrors the\n * BTCVaultRegistry check that reverts `ActivationDeadlineExpired`:\n * `block.number > createdAt + pegInActivationTimeout` — strict `>`, so a\n * boundary-equal block is NOT expired. All values are Ethereum block numbers.\n */\nexport function isActivationDeadlinePassedOnChain(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): boolean {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n return currentBlock > createdAtBlock + pegInActivationTimeout;\n}\n\n/**\n * Blocks still available for an activation transaction to be mined; `0` once\n * the window has closed.\n *\n * `isActivationDeadlinePassedOnChain` answers whether the window is already\n * shut, which is the right question for a badge but the wrong one for a\n * secret-bearing call. An activation submitted in the last block before the\n * deadline reverts if it lands one block late, and by then `s` is public\n * calldata: the vault expires with `ActivationTimeout`, and the vault\n * provider, which holds the rest of the HTLC signature set, can broadcast the\n * PegIn with that secret. The caller therefore needs the remaining margin,\n * not a boolean.\n *\n * The contract accepts a transaction mined at `block.number <= createdAt +\n * timeout`. `currentBlock` is the chain head, which is already mined, so a new\n * transaction lands at `currentBlock + 1` at the earliest: at\n * `currentBlock === createdAt + timeout` no usable block remains.\n */\nexport function activationDeadlineBlocksRemaining(params: {\n currentBlock: bigint;\n createdAtBlock: bigint;\n pegInActivationTimeout: bigint;\n}): number {\n const { currentBlock, createdAtBlock, pegInActivationTimeout } = params;\n const lastUsableBlock = createdAtBlock + pegInActivationTimeout;\n if (currentBlock >= lastUsableBlock) return 0;\n return Number(lastUsableBlock - currentBlock);\n}\n"],"names":["ContractStatus","PeginAction","getPeginProtocolState","contractStatus","options","transactionsReady","needsWotsKey","pendingIngestion","canRefund","hasProviderTerminalFailure","htlcSpentByPeginTx","canClaimExpired","canPerformAction","state","action","isActivationDeadlinePassedOnChain","params","currentBlock","createdAtBlock","pegInActivationTimeout","activationDeadlineBlocksRemaining","lastUsableBlock"],"mappings":"AAeO,IAAKA,sBAAAA,OAEVA,EAAAA,EAAA,UAAU,CAAA,IAA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7 +4,7 @@ var f = (e, n, t) => g(e, typeof n != "symbol" ? n + "" : n, t);
4
4
  import { Transaction as p } from "bitcoinjs-lib";
5
5
  import { Buffer as d } from "buffer";
6
6
  import { s as w } from "./bitcoin-C-TuHb-v.js";
7
- import { C as T } from "./peginState-CIibG9S_.js";
7
+ import { C as T } from "./peginState-CXdbSit3.js";
8
8
  class U extends Error {
9
9
  constructor(t) {
10
10
  const r = t.length, a = r === 1 ? "The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO." : `${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;
@@ -104,4 +104,4 @@ export {
104
104
  L as f,
105
105
  b as v
106
106
  };
107
- //# sourceMappingURL=reservation-BZQABu4g.js.map
107
+ //# sourceMappingURL=reservation-BAj5n-H_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reservation-BZQABu4g.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport type { UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":";;;;;;;AAoDO,MAAMA,UAA8B,MAAM;AAAA,EAG/C,YAAYC,GAAiC;AAC3C,UAAMC,IAAQD,EAAa,QACrBE,IACJD,MAAU,IACN,8JACA,GAAGA,CAAK;AAEd,UAAMC,CAAO;AATC,IAAAC,EAAA;AAUd,SAAK,OAAO,yBACZ,KAAK,eAAeH;AAAA,EACtB;AACF;AAQO,SAASI,EACdC,GACuC;AACvC,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAAM,CAAC,IACrBA;AAEJ,MAAIE;AACJ,MAAI;AACF,IAAAA,IAAKC,EAAY,QAAQF,CAAQ;AAAA,EACnC,SAASG,GAAO;AACd,UAAM,IAAI;AAAA,MACR,oCAAoCA,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK,CAAC;AAAA,IAAA;AAAA,EAE9F;AAEA,SAAOF,EAAG,IAAI,IAAI,CAACG,OAAW;AAAA;AAAA,IAE5B,MAAMC,EAAO,KAAKD,EAAM,IAAI,EAAE,QAAA,EAAU,SAAS,KAAK;AAAA,IACtD,MAAMA,EAAM;AAAA,EAAA,EACZ;AACJ;AAaO,SAASE,EACdP,GACAQ,GACsB;AACtB,QAAMC,IAASV,EAA6BC,CAAa;AAEzD,MAAIS,EAAO,WAAW;AAC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,GAAoB;AACvC,SAAO,GAAGA,EAAE,KAAK,aAAa,IAAIA,EAAE,IAAI;AAC1C;AAOO,SAASC,EACdC,GACU;AACV,QAAM,EAAE,mBAAAC,GAAmB,QAAAC,IAAS,CAAA,GAAI,eAAAC,IAAgB,CAAA,MAAOH,GAEzDI,IAAc,IAAI,IAAIH,EAAkB,IAAIJ,CAAW,CAAC;AAC9D,MAAIO,EAAY,SAAS,EAAG,QAAO,CAAA;AAEnC,QAAMC,wBAAc,IAAA,GACdC,wBAAe,IAAA,GAEfC,IAAW,CAACC,GAAwBb,MAAwB;AAChE,QAAI,CAACa,EAAI;AACT,UAAMC,IAAUD,EAAG,YAAA;AACnB,QAAIH,EAAQ,IAAII,CAAO,EAAG;AAC1B,IAAAJ,EAAQ,IAAII,CAAO;AACnB,UAAMtB,IAASO,EAAqBC,CAAK;AACzC,eAAWZ,KAASI;AAClB,UAAIiB,EAAY,IAAIP,EAAYd,CAAK,CAAC,GAAG;AACvC,QAAAuB,EAAS,IAAIE,CAAE;AACf;AAAA,MACF;AAAA,EAEJ;AAGA,aAAWE,KAAKR;AACd,IAAIQ,EAAE,WAAWC,EAAe,WAChCJ,EAASG,EAAE,IAAIA,EAAE,kBAAkB;AAErC,aAAWE,KAAKT;AACd,IAAKS,EAAE,iBACPL,EAASK,EAAE,IAAIA,EAAE,aAAa;AAGhC,SAAO,MAAM,KAAKN,CAAQ;AAC5B;"}
1
+ {"version":3,"file":"reservation-BAj5n-H_.js","sources":["../src/tbv/core/utils/utxo/availability.ts","../src/tbv/core/utils/utxo/reservation.ts"],"sourcesContent":["/**\n * UTXO Availability Validation\n *\n * Validates that UTXOs referenced in a pre-pegin transaction are still unspent\n * BEFORE asking the user to sign. This prevents wasted signing effort when\n * UTXOs have already been spent by unrelated transactions.\n *\n * These functions are pure — they accept pre-fetched UTXOs and perform no I/O.\n * The vault service wrapper is responsible for fetching UTXOs from the mempool.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Reference to a Bitcoin UTXO by its outpoint (txid + vout).\n *\n * Used by the availability check to compare a Pre-PegIn transaction's\n * declared inputs against the wallet's current spendable set. Txids are\n * compared case-insensitively; callers should treat the txid as opaque\n * lowercase hex.\n */\nexport interface UtxoRef {\n txid: string;\n vout: number;\n}\n\n/**\n * Information about a missing/spent UTXO.\n */\nexport interface MissingUtxoInfo {\n /** Transaction ID of the missing UTXO */\n txid: string;\n /** Output index of the missing UTXO */\n vout: number;\n}\n\n/**\n * Result of UTXO validation.\n */\nexport interface UtxoValidationResult {\n /** Whether all UTXOs are still available */\n allAvailable: boolean;\n /** List of missing UTXOs (if any) */\n missingUtxos: MissingUtxoInfo[];\n /** Total number of inputs checked */\n totalInputs: number;\n}\n\n/**\n * Error thrown when UTXOs are not available.\n */\nexport class UtxoNotAvailableError extends Error {\n public readonly missingUtxos: MissingUtxoInfo[];\n\n constructor(missingUtxos: MissingUtxoInfo[]) {\n const count = missingUtxos.length;\n const message =\n count === 1\n ? \"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.\"\n : `${count} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;\n\n super(message);\n this.name = \"UtxoNotAvailableError\";\n this.missingUtxos = missingUtxos;\n }\n}\n\n/**\n * Extract input references (txid:vout) from an unsigned transaction.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @returns Array of input references\n */\nexport function extractInputsFromTransaction(\n unsignedTxHex: string,\n): Array<{ txid: string; vout: number }> {\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n\n let tx: Transaction;\n try {\n tx = Transaction.fromHex(cleanHex);\n } catch (error) {\n throw new Error(\n `Failed to parse BTC transaction: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n return tx.ins.map((input) => ({\n // Bitcoin stores txid in reverse byte order\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n}\n\n/**\n * Validate that all UTXOs in a transaction are still available.\n *\n * Pure function — accepts pre-fetched UTXOs instead of making network calls.\n * This should be called BEFORE signing to avoid wasting user effort\n * signing a transaction that will fail to broadcast.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @returns Validation result with missing UTXO details\n */\nexport function validateUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): UtxoValidationResult {\n const inputs = extractInputsFromTransaction(unsignedTxHex);\n\n if (inputs.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Detect duplicate inputs (same txid:vout referenced more than once).\n // This would produce an invalid Bitcoin transaction.\n const inputKeys = new Set<string>();\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (inputKeys.has(key)) {\n throw new Error(\n `Transaction contains duplicate input ${input.txid}:${input.vout}. ` +\n `This would produce an invalid Bitcoin transaction.`,\n );\n }\n inputKeys.add(key);\n }\n\n // Set of available outpoints for O(1) lookup. Lowercased so the comparison\n // is case-insensitive against whatever case the wallet returned.\n const availableSet = new Set(\n availableUtxos.map((utxo) => `${utxo.txid.toLowerCase()}:${utxo.vout}`),\n );\n\n // Check which inputs are missing\n const missingUtxos: MissingUtxoInfo[] = [];\n for (const input of inputs) {\n const key = `${input.txid.toLowerCase()}:${input.vout}`;\n if (!availableSet.has(key)) {\n missingUtxos.push({\n txid: input.txid,\n vout: input.vout,\n });\n }\n }\n\n return {\n allAvailable: missingUtxos.length === 0,\n missingUtxos,\n totalInputs: inputs.length,\n };\n}\n\n/**\n * Validate UTXOs and throw if any are not available.\n *\n * Pure convenience function that combines validation and error throwing.\n *\n * @param unsignedTxHex - Unsigned transaction hex\n * @param availableUtxos - Pre-fetched list of available UTXOs for the depositor\n * @throws UtxoNotAvailableError if any UTXOs are not available\n * @throws Error if validation fails\n */\nexport function assertUtxosAvailable(\n unsignedTxHex: string,\n availableUtxos: UtxoRef[],\n): void {\n const result = validateUtxosAvailable(unsignedTxHex, availableUtxos);\n\n if (!result.allAvailable) {\n throw new UtxoNotAvailableError(result.missingUtxos);\n }\n}\n","/**\n * Pending-vault outpoint overlap detection.\n *\n * Given the depositor's pending vaults (indexer + local cache) and the\n * outpoints a new deposit's coin selector picked, return the set of\n * pending vault ids whose Pre-PegIn BTC tx shares an input. Advisory\n * only — used to warn the user before signing.\n *\n * Only `PENDING` vaults contribute: VERIFIED+ have their Pre-PegIn\n * already confirmed on-chain, so those inputs cannot still appear in\n * the wallet's spendable set.\n */\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\nimport { ContractStatus } from \"../../services/deposit/peginState\";\n\nimport type { UtxoRef } from \"./availability\";\n\n/** Locally-known pending pegin. `id` is the bytes32 vault id. */\nexport interface PendingPeginLike {\n id?: string;\n unsignedTxHex?: string;\n}\n\n/** On-chain vault row from the indexer. */\nexport interface VaultLike {\n id?: string;\n status: number;\n unsignedPrePeginTx: string;\n}\n\nexport interface FindOverlappingPendingVaultsParams {\n selectedOutpoints: ReadonlyArray<UtxoRef>;\n vaults?: ReadonlyArray<VaultLike>;\n pendingPegins?: ReadonlyArray<PendingPeginLike>;\n}\n\nfunction extractInputUtxoRefs(txHex: string): UtxoRef[] {\n try {\n const tx = Transaction.fromHex(stripHexPrefix(txHex));\n return tx.ins.map((input) => ({\n txid: Buffer.from(input.hash).reverse().toString(\"hex\"),\n vout: input.index,\n }));\n } catch {\n return [];\n }\n}\n\nfunction outpointKey(o: UtxoRef): string {\n return `${o.txid.toLowerCase()}:${o.vout}`;\n}\n\n/**\n * Return the ids of pending vaults whose committed Pre-PegIn inputs\n * overlap any of the just-selected outpoints. On-chain `PENDING` vaults\n * take precedence over a same-id local pegin entry.\n */\nexport function findOverlappingPendingVaults(\n params: FindOverlappingPendingVaultsParams,\n): string[] {\n const { selectedOutpoints, vaults = [], pendingPegins = [] } = params;\n\n const selectedSet = new Set(selectedOutpoints.map(outpointKey));\n if (selectedSet.size === 0) return [];\n\n const seenIds = new Set<string>();\n const impacted = new Set<string>();\n\n const consider = (id: string | undefined, txHex: string): void => {\n if (!id) return;\n const idLower = id.toLowerCase();\n if (seenIds.has(idLower)) return;\n seenIds.add(idLower);\n const inputs = extractInputUtxoRefs(txHex);\n for (const input of inputs) {\n if (selectedSet.has(outpointKey(input))) {\n impacted.add(id);\n return;\n }\n }\n };\n\n // On-chain wins on id collision.\n for (const v of vaults) {\n if (v.status !== ContractStatus.PENDING) continue;\n consider(v.id, v.unsignedPrePeginTx);\n }\n for (const p of pendingPegins) {\n if (!p.unsignedTxHex) continue;\n consider(p.id, p.unsignedTxHex);\n }\n\n return Array.from(impacted);\n}\n"],"names":["UtxoNotAvailableError","missingUtxos","count","message","__publicField","extractInputsFromTransaction","unsignedTxHex","cleanHex","tx","Transaction","error","input","Buffer","validateUtxosAvailable","availableUtxos","inputs","inputKeys","key","availableSet","utxo","assertUtxosAvailable","result","extractInputUtxoRefs","txHex","stripHexPrefix","outpointKey","o","findOverlappingPendingVaults","params","selectedOutpoints","vaults","pendingPegins","selectedSet","seenIds","impacted","consider","id","idLower","v","ContractStatus","p"],"mappings":";;;;;;;AAoDO,MAAMA,UAA8B,MAAM;AAAA,EAG/C,YAAYC,GAAiC;AAC3C,UAAMC,IAAQD,EAAa,QACrBE,IACJD,MAAU,IACN,8JACA,GAAGA,CAAK;AAEd,UAAMC,CAAO;AATC,IAAAC,EAAA;AAUd,SAAK,OAAO,yBACZ,KAAK,eAAeH;AAAA,EACtB;AACF;AAQO,SAASI,EACdC,GACuC;AACvC,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAAM,CAAC,IACrBA;AAEJ,MAAIE;AACJ,MAAI;AACF,IAAAA,IAAKC,EAAY,QAAQF,CAAQ;AAAA,EACnC,SAASG,GAAO;AACd,UAAM,IAAI;AAAA,MACR,oCAAo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1,2 @@
1
- "use strict";var b=Object.defineProperty;var T=(e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var l=(e,n,t)=>T(e,typeof n!="symbol"?n+"":n,t);const d=require("bitcoinjs-lib"),x=require("buffer"),U=require("./bitcoin-D-O2GjbC.cjs"),$=require("./peginState-IyE22wWh.cjs");class p extends Error{constructor(t){const r=t.length,a=r===1?"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.":`${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;super(a);l(this,"missingUtxos");this.name="UtxoNotAvailableError",this.missingUtxos=t}}function h(e){const n=e.startsWith("0x")?e.slice(2):e;let t;try{t=d.Transaction.fromHex(n)}catch(r){throw new Error(`Failed to parse BTC transaction: ${r instanceof Error?r.message:String(r)}`)}return t.ins.map(r=>({txid:x.Buffer.from(r.hash).reverse().toString("hex"),vout:r.index}))}function v(e,n){const t=h(e);if(t.length===0)throw new Error("Transaction has no inputs");const r=new Set;for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;if(r.has(i))throw new Error(`Transaction contains duplicate input ${o.txid}:${o.vout}. This would produce an invalid Bitcoin transaction.`);r.add(i)}const a=new Set(n.map(o=>`${o.txid.toLowerCase()}:${o.vout}`)),c=[];for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;a.has(i)||c.push({txid:o.txid,vout:o.vout})}return{allAvailable:c.length===0,missingUtxos:c,totalInputs:t.length}}function S(e,n){const t=v(e,n);if(!t.allAvailable)throw new p(t.missingUtxos)}function y(e){try{return d.Transaction.fromHex(U.stripHexPrefix(e)).ins.map(t=>({txid:x.Buffer.from(t.hash).reverse().toString("hex"),vout:t.index}))}catch{return[]}}function f(e){return`${e.txid.toLowerCase()}:${e.vout}`}function A(e){const{selectedOutpoints:n,vaults:t=[],pendingPegins:r=[]}=e,a=new Set(n.map(f));if(a.size===0)return[];const c=new Set,o=new Set,i=(s,g)=>{if(!s)return;const u=s.toLowerCase();if(c.has(u))return;c.add(u);const w=y(g);for(const m of w)if(a.has(f(m))){o.add(s);return}};for(const s of t)s.status===$.ContractStatus.PENDING&&i(s.id,s.unsignedPrePeginTx);for(const s of r)s.unsignedTxHex&&i(s.id,s.unsignedTxHex);return Array.from(o)}exports.UtxoNotAvailableError=p;exports.assertUtxosAvailable=S;exports.extractInputsFromTransaction=h;exports.findOverlappingPendingVaults=A;exports.validateUtxosAvailable=v;
2
- //# sourceMappingURL=reservation-CA5knoQ0.cjs.map
1
+ "use strict";var b=Object.defineProperty;var T=(e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var l=(e,n,t)=>T(e,typeof n!="symbol"?n+"":n,t);const d=require("bitcoinjs-lib"),x=require("buffer"),U=require("./bitcoin-D-O2GjbC.cjs"),$=require("./peginState-B4t_PDgj.cjs");class p extends Error{constructor(t){const r=t.length,a=r===1?"The UTXO for this peg-in is no longer available. It may have been spent in another transaction. Please create a new peg-in request with a different UTXO.":`${r} UTXOs for this peg-in are no longer available. They may have been spent. Please create a new peg-in request with different UTXOs.`;super(a);l(this,"missingUtxos");this.name="UtxoNotAvailableError",this.missingUtxos=t}}function h(e){const n=e.startsWith("0x")?e.slice(2):e;let t;try{t=d.Transaction.fromHex(n)}catch(r){throw new Error(`Failed to parse BTC transaction: ${r instanceof Error?r.message:String(r)}`)}return t.ins.map(r=>({txid:x.Buffer.from(r.hash).reverse().toString("hex"),vout:r.index}))}function v(e,n){const t=h(e);if(t.length===0)throw new Error("Transaction has no inputs");const r=new Set;for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;if(r.has(i))throw new Error(`Transaction contains duplicate input ${o.txid}:${o.vout}. This would produce an invalid Bitcoin transaction.`);r.add(i)}const a=new Set(n.map(o=>`${o.txid.toLowerCase()}:${o.vout}`)),c=[];for(const o of t){const i=`${o.txid.toLowerCase()}:${o.vout}`;a.has(i)||c.push({txid:o.txid,vout:o.vout})}return{allAvailable:c.length===0,missingUtxos:c,totalInputs:t.length}}function S(e,n){const t=v(e,n);if(!t.allAvailable)throw new p(t.missingUtxos)}function y(e){try{return d.Transaction.fromHex(U.stripHexPrefix(e)).ins.map(t=>({txid:x.Buffer.from(t.hash).reverse().toString("hex"),vout:t.index}))}catch{return[]}}function f(e){return`${e.txid.toLowerCase()}:${e.vout}`}function A(e){const{selectedOutpoints:n,vaults:t=[],pendingPegins:r=[]}=e,a=new Set(n.map(f));if(a.size===0)return[];const c=new Set,o=new Set,i=(s,g)=>{if(!s)return;const u=s.toLowerCase();if(c.has(u))return;c.add(u);const w=y(g);for(const m of w)if(a.has(f(m))){o.add(s);return}};for(const s of t)s.status===$.ContractStatus.PENDING&&i(s.id,s.unsignedPrePeginTx);for(const s of r)s.unsignedTxHex&&i(s.id,s.unsignedTxHex);return Array.from(o)}exports.UtxoNotAvailableError=p;exports.assertUtxosAvailable=S;exports.extractInputsFromTransaction=h;exports.findOverlappingPendingVaults=A;exports.validateUtxosAvailable=v;
2
+ //# sourceMappingURL=reservation-D9ftyiwP.cjs.map