@babylonlabs-io/ts-sdk 5.0.1 → 5.1.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 (63) 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-Acz637Vf.js} +634 -576
  10. package/dist/{buildAndBroadcastReclaim-rUsFRC5H.js.map → buildAndBroadcastReclaim-Acz637Vf.js.map} +1 -1
  11. package/dist/{buildAndBroadcastReclaim-DtmMg096.cjs → buildAndBroadcastReclaim-Cf05JFP-.cjs} +2 -2
  12. package/dist/{buildAndBroadcastReclaim-DtmMg096.cjs.map → buildAndBroadcastReclaim-Cf05JFP-.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 +90 -87
  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 +92 -89
  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/services/deposit/index.d.ts +1 -1
  35. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  36. package/dist/tbv/core/services/deposit/peginState.d.ts +9 -2
  37. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
  38. package/dist/tbv/core/services/deposit/verifyRegisteredParticipantKeys.d.ts +27 -1
  39. package/dist/tbv/core/services/deposit/verifyRegisteredParticipantKeys.d.ts.map +1 -1
  40. package/dist/tbv/core/services/index.cjs +1 -1
  41. package/dist/tbv/core/services/index.js +85 -82
  42. package/dist/tbv/core/utils/index.cjs +1 -1
  43. package/dist/tbv/core/utils/index.js +1 -1
  44. package/dist/tbv/index.cjs +1 -1
  45. package/dist/tbv/index.js +92 -89
  46. package/dist/{toRefundInputs-4W8aNM6b.cjs → toRefundInputs-BzyN0zvj.cjs} +2 -2
  47. package/dist/{toRefundInputs-4W8aNM6b.cjs.map → toRefundInputs-BzyN0zvj.cjs.map} +1 -1
  48. package/dist/{toRefundInputs-M4IbYwZU.js → toRefundInputs-DwXpKQxN.js} +4 -4
  49. package/dist/{toRefundInputs-M4IbYwZU.js.map → toRefundInputs-DwXpKQxN.js.map} +1 -1
  50. package/dist/types-BnZIbDHb.cjs.map +1 -1
  51. package/dist/types-K_aM5GZO.js.map +1 -1
  52. package/dist/{verifyKeyPathSchnorrSignature-DDi3B6EL.cjs → verifyKeyPathSchnorrSignature-BVrAmVL3.cjs} +2 -2
  53. package/dist/{verifyKeyPathSchnorrSignature-DDi3B6EL.cjs.map → verifyKeyPathSchnorrSignature-BVrAmVL3.cjs.map} +1 -1
  54. package/dist/{verifyKeyPathSchnorrSignature-CAp5zOTX.js → verifyKeyPathSchnorrSignature-CIE3jlVt.js} +2 -2
  55. package/dist/{verifyKeyPathSchnorrSignature-CAp5zOTX.js.map → verifyKeyPathSchnorrSignature-CIE3jlVt.js.map} +1 -1
  56. package/dist/{verifyScriptPathSchnorrSignature-cpUVCwU3.cjs → verifyScriptPathSchnorrSignature-BHskbJJx.cjs} +2 -2
  57. package/dist/{verifyScriptPathSchnorrSignature-cpUVCwU3.cjs.map → verifyScriptPathSchnorrSignature-BHskbJJx.cjs.map} +1 -1
  58. package/dist/{verifyScriptPathSchnorrSignature-BK-bd6w5.js → verifyScriptPathSchnorrSignature-DLNGgm4j.js} +3 -2
  59. package/dist/{verifyScriptPathSchnorrSignature-BK-bd6w5.js.map → verifyScriptPathSchnorrSignature-DLNGgm4j.js.map} +1 -1
  60. package/package.json +1 -1
  61. package/dist/peginState-CIibG9S_.js.map +0 -1
  62. package/dist/peginState-IyE22wWh.cjs +0 -2
  63. 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 E, e as c, g as u } from "./verifyScriptPathSchnorrSignature-DLNGgm4j.js";
2
2
  import { a as g } from "./secp256k1-BuxBFUHm.js";
3
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";
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
8
  import { c as Pa, a as Ea } from "./signing-C1rR4tqs.js";
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";
9
+ import { B as ua, C as da, 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 Ia, b as fa, 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
15
  import { V as le, a as pe, b as Pe, r as Ee } from "./signer-set-reader-DiwLeqik.js";
16
- import { C as de, M as ue, V as ge, a as me, c as Re } from "./pegin-registration-client-BlrXyZpF.js";
16
+ import { C as ue, M as de, 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
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";
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 cs, D as us, L as ds, 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 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 Er, a as cr, b as ur, u as dr, 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 yr, k as Mr, q as vr, s as Dr, x as Br } from "./toRefundInputs-DwXpKQxN.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, al as Qr, am as $r, an as at, ao as et, ae as st, af as rt, ag as tt, ah as it, aj as ot, a0 as nt, S as lt, X as pt, V as Pt, a as Et, b as ct, d as ut, e as dt, m as gt, f as mt, g as Rt, t as At, i as _t, B as St, Y as Tt, o as Ct, a4 as It, ak as ft, ac as ht, c as Vt, k as Ot, h as xt, ad as bt, E as Ft, K as Nt, M as yt, a5 as Mt, Z as vt, x as Dt, y as Bt, a1 as Ut, _ as Ht, a6 as Lt, a7 as Kt, p as Xt, r as Gt, ai as kt, a8 as Wt, a9 as wt, aa as zt, F as Yt, q as jt, H as Jt, I as Zt, s as qt, N as Qt, O as $t, L as ai, Q as ei, R as si, T as ri, U as ti, $ as ii, a2 as oi, z as ni, a3 as li } from "./buildAndBroadcastReclaim-Acz637Vf.js";
36
+ import { C as Pi, P as Ei, a as ci, c as ui, g as di, i as gi } from "./peginState-CXdbSit3.js";
37
37
  export {
38
38
  Ks as AUTH_REJECTED_RPC_CODE,
39
39
  Hr as ApplicationEntryPointMismatchError,
@@ -41,21 +41,21 @@ export {
41
41
  Lr as ArtifactsVaultMismatchError,
42
42
  Kr as AssertBindingError,
43
43
  Xr as BIP68NotMatureError,
44
- da as BITCOIN_ADDRESS_RE,
44
+ ua as BITCOIN_ADDRESS_RE,
45
45
  fe as BTCVaultRegistryABI,
46
46
  Ve as BTCVaultRegistryKeyEpochsABI,
47
47
  cs as BTC_DUST_SAT,
48
48
  qe as BitcoinNetworks,
49
49
  es as BitcoinScriptType,
50
- de as COMMISSION_BPS_HEADROOM,
51
- ua as COMPRESSED_PUBKEY_HEX_LEN,
50
+ ue as COMMISSION_BPS_HEADROOM,
51
+ da as COMPRESSED_PUBKEY_HEX_LEN,
52
52
  Oe as CONTRACT_ERRORS,
53
53
  Gr as ChallengerSetMismatchError,
54
54
  Xs as ClaimerPegoutStatusValue,
55
- ni as ContractStatus,
55
+ Pi as ContractStatus,
56
56
  kr as DELEGATED_CLAIM_TX_GRAPH_VERSION,
57
57
  pr as DEPOSIT_TERMS_REJECTED_ERROR_NAME,
58
- ds as DUST_THRESHOLD,
58
+ us as DUST_THRESHOLD,
59
59
  Gs as DaemonStatus,
60
60
  Wr as DelegatedClaimSigningIncompleteError,
61
61
  Pr as DepositTermsRejectedError,
@@ -66,8 +66,8 @@ export {
66
66
  Ws as JsonRpcClient,
67
67
  ws as JsonRpcError,
68
68
  ma as KNOWN_SCRIPT_PREFIXES,
69
- us as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
70
- ue as MAX_ACCEPTABLE_COMMISSION_BPS_CAP,
69
+ ds as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
70
+ de as MAX_ACCEPTABLE_COMMISSION_BPS_CAP,
71
71
  gs as MAX_NON_LEGACY_OUTPUT_SIZE,
72
72
  Ra as MAX_REASONABLE_FEE_SATS,
73
73
  ms as MAX_REASONABLE_PEGIN_VBYTES,
@@ -88,11 +88,11 @@ 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
- dr as PeginFingerprintInputError,
93
+ ur as PeginFingerprintInputError,
94
94
  Ia as PeginManager,
95
- ur as PeginParamsAmbiguousError,
95
+ dr as PeginParamsAmbiguousError,
96
96
  gr as PeginParamsIncompleteSpaceError,
97
97
  mr as PeginParamsNotFoundError,
98
98
  Zr as PeginRegistrationMissingError,
@@ -118,6 +118,7 @@ export {
118
118
  Aa as TXID_RE,
119
119
  Ts as TX_BUFFER_SIZE_OVERHEAD,
120
120
  Ar as UnanchoredPrePeginError,
121
+ pt as UnsupportedPayoutScriptError,
121
122
  xs as UtxoNotAvailableError,
122
123
  ke as VAULT_APP_NAME,
123
124
  Le as VAULT_ERROR_ABI,
@@ -125,7 +126,7 @@ export {
125
126
  Zs as VP_TERMINAL_FAILURE_STATUSES,
126
127
  qs as VP_TRANSIENT_STATUSES,
127
128
  Za as VaultClaimableByNotFoundError,
128
- pt as VaultIdBindingError,
129
+ Pt as VaultIdBindingError,
129
130
  vs as VaultProviderRpcClient,
130
131
  _r as VaultRootMismatchError,
131
132
  le as ViemOperationKeyReader,
@@ -138,39 +139,40 @@ export {
138
139
  rr as VpTokenRegistry,
139
140
  Cs as WALLET_RELAY_FEE_RATE_THRESHOLD,
140
141
  _a as X_ONLY_PUBKEY_HEX_LEN,
141
- Pt as activateVault,
142
- Et as activateVaultAndRedeem,
143
- pi as activationDeadlineBlocksRemaining,
142
+ Et as activateVault,
143
+ ct as activateVaultAndRedeem,
144
+ ci as activationDeadlineBlocksRemaining,
144
145
  ss as applyChangeOutputPolicy,
145
- ct as assembleWatchtowerArtifacts,
146
+ ut as assembleWatchtowerArtifacts,
146
147
  dt as assembleWatchtowerArtifactsFromSignatures,
147
- ut as assertArtifactsUsableForVault,
148
- gt as assertAssertBindsClaimAndPayout,
149
- mt as assertChallengerSetMatchesVault,
148
+ gt as assertArtifactsUsableForVault,
149
+ mt as assertAssertBindsClaimAndPayout,
150
+ Rt as assertChallengerSetMatchesVault,
150
151
  Sr as assertClaimBatchHomogeneous,
151
- Rt as assertClaimSpendsVault,
152
+ At as assertClaimSpendsVault,
152
153
  N as assertKeyPathSchnorrSignature,
153
154
  qa as assertOnChainBtcPubkey,
154
- At as assertPayoutPaysRegisteredScript,
155
+ _t as assertPayoutPaysRegisteredScript,
155
156
  t as assertPsbtUnsignedTxMatches,
156
157
  Qa as assertRegisteredPayoutScriptBounds,
157
- _t as assertReturnedGraphMatchesFingerprint,
158
- M as assertReturnedKeyPathSignatures,
158
+ St as assertReturnedGraphMatchesFingerprint,
159
+ y as assertReturnedKeyPathSignatures,
159
160
  i as assertScriptPathSchnorrSignature,
160
- St as assertTermsMatchVault,
161
+ Tt as assertStandardPayoutScriptsAtEpochs,
162
+ Ct as assertTermsMatchVault,
161
163
  bs as assertUtxosAvailable,
162
164
  g as assertValidVaultCoreVersion,
163
- Tt as assertVaultProviderHintAccepted,
165
+ It as assertVaultProviderHintAccepted,
164
166
  R as attachFinalizedAssert,
165
167
  Bs as batchPollByProvider,
166
- Ct as buildAndBroadcastReclaim,
167
- It as buildAndBroadcastRefund,
168
+ ft as buildAndBroadcastReclaim,
169
+ ht as buildAndBroadcastRefund,
168
170
  U as buildChallengeAssertPsbt,
169
171
  fa as buildDepositTerms,
170
172
  We as buildFundingOutpointsCommitment,
171
173
  H as buildNoPayoutPsbt,
172
174
  o as buildPayoutPsbt,
173
- y as buildPeginInputPsbt,
175
+ M as buildPeginInputPsbt,
174
176
  Tr as buildPeginParamsCandidates,
175
177
  n as buildPeginTxFromFundedPrePegin,
176
178
  l as buildPrePeginPsbt,
@@ -179,10 +181,10 @@ export {
179
181
  we as buildVaultContext,
180
182
  Xe as buildVaultContextInputForClaim,
181
183
  $e as calculateBtcTxHash,
182
- Pi as canPerformAction,
184
+ ui as canPerformAction,
183
185
  w as canonicalizeBtcPubkey,
184
186
  Re as capMaxAcceptableCommissionBps,
185
- ft as claimExpiredVault,
187
+ Vt as claimExpiredVault,
186
188
  la as combineAbortSignals,
187
189
  rs as computeChangeOutputFeeSats,
188
190
  Cr as computeFundedPrePeginFee,
@@ -194,13 +196,13 @@ export {
194
196
  is as computePeginBaseFeeSats,
195
197
  Ir as computePeginFingerprint,
196
198
  ha as computeWotsBlockPublicKeysHash,
197
- ht as copyAssertConnectorLeaf,
199
+ Ot as copyAssertConnectorLeaf,
198
200
  tr as createAuthenticatedVpClient,
199
201
  P as createPayoutScript,
200
202
  Pa as createTaprootScriptPathSignOptions,
201
203
  Ea as createTaprootScriptPathSignOptionsForInput,
202
204
  z as deriveBip86ScriptPubKeyHex,
203
- Vt as deriveClaimerWotsKeypair,
205
+ xt as deriveClaimerWotsKeypair,
204
206
  E as deriveDepositorClaimDescriptor,
205
207
  c as deriveDepositorClaimScriptPubKey,
206
208
  fr as deriveHashlocksFromPrePegin,
@@ -216,13 +218,13 @@ export {
216
218
  J as ensureHexPrefix,
217
219
  Oa as ensurePrePeginTermsApproval,
218
220
  X as estimateReclaimFeeSats,
219
- Ot as estimateRefundFeeSats,
221
+ bt as estimateRefundFeeSats,
220
222
  T as expandAuthAnchor,
221
223
  C as expandHashlockSecret,
222
224
  I as expandWotsSeed,
223
225
  Ne as extractErrorData,
224
226
  Fs as extractInputsFromTransaction,
225
- d as extractPayoutSignature,
227
+ u as extractPayoutSignature,
226
228
  v as extractPeginInputSignature,
227
229
  f as finalizePayout,
228
230
  D as finalizePeginInputPsbt,
@@ -230,20 +232,20 @@ export {
230
232
  h as finalizeWronglyChallenged,
231
233
  Ns as findOverlappingPendingVaults,
232
234
  ae as findRegistrationRecord,
233
- xt as fingerprintReturnedGraph,
235
+ Ft as fingerprintReturnedGraph,
234
236
  Z as formatSatoshisToBtc,
235
237
  Na as forwardDepositApproval,
236
238
  Ye as forwardDeriveContextHash,
237
239
  Is as fundPeginTransaction,
238
240
  Ha as getAddressTxs,
239
241
  La as getAddressUtxos,
240
- Me as getContractErrorMessage,
242
+ ye as getContractErrorMessage,
241
243
  os as getDustThreshold,
242
244
  Ka as getMempoolApiUrl,
243
245
  q as getNetwork,
244
246
  Xa as getNetworkFees,
245
247
  Ga as getOutspend,
246
- Ei as getPeginProtocolState,
248
+ di as getPeginProtocolState,
247
249
  ns as getPsbtInputFields,
248
250
  ls as getScriptType,
249
251
  Q as getSortedXOnlyPubkeys,
@@ -251,89 +253,90 @@ export {
251
253
  Wa as getTxHex,
252
254
  wa as getTxInfo,
253
255
  za as getUtxoInfo,
254
- ye as handleContractError,
256
+ Me as handleContractError,
255
257
  $ as hexToUint8Array,
256
- ci as isActivationDeadlinePassedOnChain,
258
+ gi as isActivationDeadlinePassedOnChain,
257
259
  aa as isAddressFromPublicKey,
258
- bt as isApplicationEntryPointMismatchError,
260
+ Nt as isApplicationEntryPointMismatchError,
259
261
  Qs as isAuthRejectedError,
260
- Ft as isDepositAmountValid,
262
+ yt as isDepositAmountValid,
261
263
  xr as isDepositTermsRejectedError,
262
- Nt as isHintAccepted,
264
+ Mt as isHintAccepted,
263
265
  ve as isKnownContractError,
264
- Mt as isParticipantKeyDriftError,
266
+ vt as isParticipantKeyDriftError,
265
267
  De as isPeginFingerprintChangedError,
266
268
  br as isPeginFingerprintInputError,
267
- yt as isPeginRegistrationMissingError,
268
- vt as isPeginRegistrationNotFinalError,
269
+ Dt as isPeginRegistrationMissingError,
270
+ Bt as isPeginRegistrationNotFinalError,
269
271
  $s as isPegoutTerminalStatus,
270
272
  ar as isRecognizedPegoutStatus,
271
- Dt as isRegisteredVaultVersionMismatchError,
273
+ Ut as isRegisteredVaultVersionMismatchError,
272
274
  ee as isRegistrationLogsUnavailableError,
273
275
  Us as isUnrecognizedDaemonStatusError,
276
+ Ht as isUnsupportedPayoutScriptError,
274
277
  ea as isValidHex,
275
278
  se as isVaultClaimableByNotFoundError,
276
279
  Fr as isWotsMismatchError,
277
- Bt as matchKeyHint,
278
- Ut as matchKeySetHint,
280
+ Lt as matchKeyHint,
281
+ Kt as matchKeySetHint,
279
282
  Nr as orderClaimBatchByHtlcVout,
280
283
  Je as parseFundingOutpointsFromTx,
281
284
  fs as parseUnfundedWasmTransaction,
282
285
  hs as peginOutputCount,
283
286
  V as peginP2aAnchorOutput,
284
287
  O as pinPegoutProof,
285
- Ht as planDelegatedClaimSigning,
288
+ Xt as planDelegatedClaimSigning,
286
289
  ir as primeVpTokenRegistry,
287
290
  sa as processPublicKeyToXOnly,
288
291
  Ya as pushTx,
289
292
  Vs as rateBasedTxBufferFee,
290
- Lt as readDelegatedClaimVaultContext,
291
- Kt as readRefundPrePeginContext,
292
- Xt as readStampedParticipantKeys,
293
- Mr as rebuildDepositTermsCore,
294
- yr as rebuildDepositTermsForClaim,
293
+ Gt as readDelegatedClaimVaultContext,
294
+ kt as readRefundPrePeginContext,
295
+ Wt as readStampedParticipantKeys,
296
+ yr as rebuildDepositTermsCore,
297
+ Mr as rebuildDepositTermsForClaim,
295
298
  k as reclaimVsize,
296
299
  vr as reconstructPeginParams,
297
300
  re as registrationPrePeginTxHash,
298
- Ma as requireChangeAddress,
299
- Gt as resolveCurrentParticipantKeys,
300
- kt as resolveParticipantKeysAtEpochs,
301
+ ya as requireChangeAddress,
302
+ wt as resolveCurrentParticipantKeys,
303
+ zt as resolveParticipantKeysAtEpochs,
301
304
  Ee as resolveProtocolAddresses,
302
- Wt as runDepositorPresignFlow,
305
+ Yt as runDepositorPresignFlow,
303
306
  Dr as selectSiblingRegistrations,
304
307
  ps as selectUtxosForPegin,
305
308
  Ps as shouldAddChangeOutput,
306
- wt as signDelegatedClaimPlan,
307
- zt as signDepositorGraph,
309
+ jt as signDelegatedClaimPlan,
310
+ Jt as signDepositorGraph,
308
311
  ra as stripHexPrefix,
309
- Yt as submitWotsPublicKey,
310
- jt as summarizeWatchtowerArtifacts,
312
+ Zt as submitWotsPublicKey,
313
+ qt as summarizeWatchtowerArtifacts,
311
314
  x as supportedTxGraphVersions,
312
- ya as supportsDepositApproval,
315
+ Ma as supportsDepositApproval,
313
316
  Br as toRefundInputs,
314
317
  ta as toXOnly,
315
318
  ia as uint8ArrayToHex,
316
- Jt as validateDepositAmount,
317
- Zt as validateMultiVaultDepositInputs,
319
+ Qt as validateDepositAmount,
320
+ $t as validateMultiVaultDepositInputs,
318
321
  te as validateOffchainParams,
319
- qt as validateOnChainParticipantKeys,
322
+ ai as validateOnChainParticipantKeys,
320
323
  ie as validatePegInConfiguration,
321
324
  b as validatePeginP2aAnchor,
322
- Qt as validateProviderSelection,
323
- $t as validateRemainingCapacity,
325
+ ei as validateProviderSelection,
326
+ si as validateRemainingCapacity,
324
327
  Hs as validateRequestDepositorClaimerArtifactsResponse,
325
328
  va as validateSecretAgainstHashlock,
326
329
  oe as validateTBVProtocolParams,
327
- Ms as validateUtxosAvailable,
328
- ai as validateVaultAmounts,
329
- ei as validateVaultProviderPubkey,
330
+ ys as validateUtxosAvailable,
331
+ ri as validateVaultAmounts,
332
+ ti as validateVaultProviderPubkey,
330
333
  oa as validateWalletPubkey,
331
- si as verifyRegisteredParticipantKeys,
332
- ri as verifyRegisteredVaultVersions,
334
+ ii as verifyRegisteredParticipantKeys,
335
+ oi as verifyRegisteredVaultVersions,
333
336
  or as verifyServerIdentity,
334
337
  nr as vpTokenRegistry,
335
- ti as waitForPeginRegistrationDepth,
336
- ii as waitForPeginStatus,
338
+ ni as waitForPeginRegistrationDepth,
339
+ li as waitForPeginStatus,
337
340
  Ta as waitForTransactionReceiptSmartAware
338
341
  };
339
342
  //# 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,EAG1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uBAAAC,CAAA,EAA2BH,EAC3DK,EAAkBH,EAAiBC,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,IAAK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IACrC,OAAOA,IAAkBJ,CAAY;AAC9C;"}
@@ -4,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,IA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,WAAO,CAAA;AAAA,EACT;AACF;AAEA,SAASc,EAAYC,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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AAO,MAAM,KAAKN,CAAQ;AAC5B;"}
@@ -1,2 +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