@babylonlabs-io/ts-sdk 0.41.0 → 0.43.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 (93) hide show
  1. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs +2 -0
  2. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs.map +1 -0
  3. package/dist/{ProtocolParams.abi-C2brDWTI.js → ApplicationRegistry.abi-Dn2qk6JG.js} +90 -90
  4. package/dist/ApplicationRegistry.abi-Dn2qk6JG.js.map +1 -0
  5. package/dist/{PayoutManager-B5bovfkD.cjs → PayoutManager-BwYlPF2C.cjs} +2 -2
  6. package/dist/{PayoutManager-B5bovfkD.cjs.map → PayoutManager-BwYlPF2C.cjs.map} +1 -1
  7. package/dist/{PayoutManager-DChODEOJ.js → PayoutManager-CXDccwDN.js} +2 -2
  8. package/dist/{PayoutManager-DChODEOJ.js.map → PayoutManager-CXDccwDN.js.map} +1 -1
  9. package/dist/{PeginManager-D9ZZ8wx2.js → PeginManager-BezsAEDe.js} +161 -166
  10. package/dist/PeginManager-BezsAEDe.js.map +1 -0
  11. package/dist/PeginManager-D-8vmqzq.cjs +2 -0
  12. package/dist/PeginManager-D-8vmqzq.cjs.map +1 -0
  13. package/dist/{assertPsbtUnsignedTxMatches-r1svclbd.cjs → assertPsbtUnsignedTxMatches-CABhEADu.cjs} +2 -2
  14. package/dist/{assertPsbtUnsignedTxMatches-r1svclbd.cjs.map → assertPsbtUnsignedTxMatches-CABhEADu.cjs.map} +1 -1
  15. package/dist/{assertPsbtUnsignedTxMatches-CzVv57QF.js → assertPsbtUnsignedTxMatches-GHobJP-d.js} +2 -2
  16. package/dist/{assertPsbtUnsignedTxMatches-CzVv57QF.js.map → assertPsbtUnsignedTxMatches-GHobJP-d.js.map} +1 -1
  17. package/dist/{buildAndBroadcastRefund-fIHDHiFh.js → buildAndBroadcastRefund-37Bs7-V1.js} +4 -4
  18. package/dist/{buildAndBroadcastRefund-fIHDHiFh.js.map → buildAndBroadcastRefund-37Bs7-V1.js.map} +1 -1
  19. package/dist/{buildAndBroadcastRefund-Cj8JDI7F.cjs → buildAndBroadcastRefund-DbcNEsOv.cjs} +2 -2
  20. package/dist/{buildAndBroadcastRefund-Cj8JDI7F.cjs.map → buildAndBroadcastRefund-DbcNEsOv.cjs.map} +1 -1
  21. package/dist/{challengeAssert-DLEmAhT0.js → challengeAssert-ChqnvtRg.js} +2 -2
  22. package/dist/{challengeAssert-DLEmAhT0.js.map → challengeAssert-ChqnvtRg.js.map} +1 -1
  23. package/dist/{challengeAssert-rpDaS3fH.cjs → challengeAssert-Cmj_OG6V.cjs} +2 -2
  24. package/dist/{challengeAssert-rpDaS3fH.cjs.map → challengeAssert-Cmj_OG6V.cjs.map} +1 -1
  25. package/dist/{fundPeginTransaction-t-6TsHAY.js → fundPeginTransaction-C11tYf6I.js} +32 -33
  26. package/dist/fundPeginTransaction-C11tYf6I.js.map +1 -0
  27. package/dist/fundPeginTransaction-C8qsXxNV.cjs +2 -0
  28. package/dist/fundPeginTransaction-C8qsXxNV.cjs.map +1 -0
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.js +181 -180
  31. package/dist/mempoolApi-CknccHKg.cjs +2 -0
  32. package/dist/mempoolApi-CknccHKg.cjs.map +1 -0
  33. package/dist/mempoolApi-DI9HISqi.js +451 -0
  34. package/dist/mempoolApi-DI9HISqi.js.map +1 -0
  35. package/dist/{noPayout-CS2wnluA.js → noPayout-BtP-R-b-.js} +2 -2
  36. package/dist/{noPayout-CS2wnluA.js.map → noPayout-BtP-R-b-.js.map} +1 -1
  37. package/dist/{noPayout-B06Z9RTe.cjs → noPayout-DliaHuc6.cjs} +2 -2
  38. package/dist/{noPayout-B06Z9RTe.cjs.map → noPayout-DliaHuc6.cjs.map} +1 -1
  39. package/dist/primeVpAuth-Duds3vAO.cjs +2 -0
  40. package/dist/primeVpAuth-Duds3vAO.cjs.map +1 -0
  41. package/dist/primeVpAuth-qEC9TTO_.js +1136 -0
  42. package/dist/primeVpAuth-qEC9TTO_.js.map +1 -0
  43. package/dist/{reservation-hjXStM03.cjs → reservation-Cwf2u4vu.cjs} +2 -2
  44. package/dist/{reservation-hjXStM03.cjs.map → reservation-Cwf2u4vu.cjs.map} +1 -1
  45. package/dist/{reservation-CB-4FBPk.js → reservation-DNOGLBt4.js} +2 -2
  46. package/dist/{reservation-CB-4FBPk.js.map → reservation-DNOGLBt4.js.map} +1 -1
  47. package/dist/tbv/core/clients/eth/types.d.ts +7 -0
  48. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  49. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +8 -0
  50. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  51. package/dist/tbv/core/clients/index.cjs +1 -1
  52. package/dist/tbv/core/clients/index.js +31 -31
  53. package/dist/tbv/core/contracts/index.cjs +1 -1
  54. package/dist/tbv/core/contracts/index.js +1 -1
  55. package/dist/tbv/core/index.cjs +1 -1
  56. package/dist/tbv/core/index.js +183 -182
  57. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  58. package/dist/tbv/core/managers/index.cjs +1 -1
  59. package/dist/tbv/core/managers/index.js +2 -2
  60. package/dist/tbv/core/primitives/index.cjs +1 -1
  61. package/dist/tbv/core/primitives/index.d.ts +2 -1
  62. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  63. package/dist/tbv/core/primitives/index.js +24 -23
  64. package/dist/tbv/core/services/index.cjs +1 -1
  65. package/dist/tbv/core/services/index.js +2 -2
  66. package/dist/tbv/core/utils/fee/constants.d.ts +8 -12
  67. package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -1
  68. package/dist/tbv/core/utils/index.cjs +1 -1
  69. package/dist/tbv/core/utils/index.js +3 -3
  70. package/dist/tbv/index.cjs +1 -1
  71. package/dist/tbv/index.js +183 -182
  72. package/dist/{waitForTransactionReceiptSmartAware-tv1mtSIY.cjs → waitForTransactionReceiptSmartAware-BFMQFEzj.cjs} +2 -2
  73. package/dist/{waitForTransactionReceiptSmartAware-tv1mtSIY.cjs.map → waitForTransactionReceiptSmartAware-BFMQFEzj.cjs.map} +1 -1
  74. package/dist/{waitForTransactionReceiptSmartAware-CmgFXFza.js → waitForTransactionReceiptSmartAware-Dt5VcMK0.js} +2 -2
  75. package/dist/{waitForTransactionReceiptSmartAware-CmgFXFza.js.map → waitForTransactionReceiptSmartAware-Dt5VcMK0.js.map} +1 -1
  76. package/package.json +1 -1
  77. package/dist/PeginManager-D9ZZ8wx2.js.map +0 -1
  78. package/dist/PeginManager-UqbOj2oV.cjs +0 -2
  79. package/dist/PeginManager-UqbOj2oV.cjs.map +0 -1
  80. package/dist/ProtocolParams.abi-C2brDWTI.js.map +0 -1
  81. package/dist/ProtocolParams.abi-DQhcqsNr.cjs +0 -2
  82. package/dist/ProtocolParams.abi-DQhcqsNr.cjs.map +0 -1
  83. package/dist/fundPeginTransaction-BBE3wTjR.cjs +0 -2
  84. package/dist/fundPeginTransaction-BBE3wTjR.cjs.map +0 -1
  85. package/dist/fundPeginTransaction-t-6TsHAY.js.map +0 -1
  86. package/dist/mempoolApi-C7hkVkym.js +0 -214
  87. package/dist/mempoolApi-C7hkVkym.js.map +0 -1
  88. package/dist/mempoolApi-DEAS9wVa.cjs +0 -2
  89. package/dist/mempoolApi-DEAS9wVa.cjs.map +0 -1
  90. package/dist/types-0bvDGR4x.js +0 -1347
  91. package/dist/types-0bvDGR4x.js.map +0 -1
  92. package/dist/types-Be3sAYzr.cjs +0 -2
  93. package/dist/types-Be3sAYzr.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,192 +1,193 @@
1
- import { a as s, b as t, c as r } from "./challengeAssert-DLEmAhT0.js";
2
- import { computeMinClaimValue as i, deriveVaultId as n, expandAuthAnchor as u, expandHashlockSecret as l, expandWotsSeed as p } from "@babylonlabs-io/babylon-tbv-rust-wasm";
3
- import { P, d as c, c as T, a as E, b as A, f as S, e as R } from "./assertPsbtUnsignedTxMatches-CzVv57QF.js";
4
- import { b as g, e as m, f as x } from "./peginInput-BPRB9tUi.js";
5
- import { a as b, b as I } from "./noPayout-CS2wnluA.js";
6
- import { d as O, a as v, b as F, e as V, f as U, j as h, g as N, h as y, i as D, c as B, p as M, s as H, t as L, u as k, v as X } from "./bitcoin-B5aNKtsk.js";
7
- import { c as w } from "./signing-DaLvGwQe.js";
8
- import { B as G, H as Y, K as Z, M as J, T as j } from "./validation-CxqROCno.js";
9
- import { P as z, V as Q, b as $, a as aa, c as ea, f as sa, d as ta, e as ra } from "./PeginManager-D9ZZ8wx2.js";
10
- import { P as ia, c as na, v as ua } from "./PayoutManager-DChODEOJ.js";
11
- import { A as pa, P as da } from "./ProtocolParams.abi-C2brDWTI.js";
12
- import { B as ca } from "./BTCVaultRegistry.abi-Cq9-JlqT.js";
13
- import { C as Ea, e as Aa, g as Sa, h as Ra, i as _a } from "./errors-CznAK5NB.js";
14
- import { BitcoinNetworks as ma } from "./shared/index.js";
15
- import { B as fa, a as ba, f as Ia, c as Ca, b as Oa, d as va, g as Fa, i as Va, h as Ua, s as ha, e as Na, w as ya } from "./waitForTransactionReceiptSmartAware-CmgFXFza.js";
16
- import { B as Ba, D as Ma, F as Ha, L as La, M as ka, P as Xa, b as Wa, a as wa, S as Ka, T as Ga, W as Ya, f as Za, c as Ja, p as ja, r as qa } from "./fundPeginTransaction-t-6TsHAY.js";
17
- import { U as Qa, a as $a, c as ae, e as ee, s as se, v as te } from "./reservation-CB-4FBPk.js";
18
- import { M as oe, g as ie, a as ne, b as ue, c as le, d as pe, e as de, f as Pe, h as ce, p as Te } from "./mempoolApi-C7hkVkym.js";
19
- import { O as Ae, S as Se, V as Re, j as _e, k as ge, l as me, m as xe, a as fe, d as be, b as Ie, f as Ce, p as Oe, r as ve, g as Fe, h as Ve, v as Ue, i as he, c as Ne, e as ye } from "./types-0bvDGR4x.js";
20
- import { A as Be, D as Me, b as He, J as Le, a as ke, d as Xe, P as We, R as we, e as Ke, c as Ge, V as Ye } from "./types-BqGAMOZM.js";
21
- import { i as Je, p as je } from "./errors-9AkghWyk.js";
22
- import { B as ze, C as Qe, p as $e, q as as, t as es, u as ss, R as ts, a as rs, n as os, o as is, i as ns, m as us, l as ls, j as ps, r as ds, b as Ps, s as cs, v as Ts, g as Es, h as As, d as Ss, c as Rs, e as _s, f as gs, k as ms, w as xs } from "./buildAndBroadcastRefund-fIHDHiFh.js";
23
- import { C as bs, P as Is, c as Cs, g as Os } from "./peginState-CBAlxgXk.js";
1
+ import { a as s, b as t, c as r } from "./challengeAssert-ChqnvtRg.js";
2
+ import { computeMinClaimValue as i, computeMinPeginFee as n, deriveVaultId as u, expandAuthAnchor as l, expandHashlockSecret as p, expandWotsSeed as d } from "@babylonlabs-io/babylon-tbv-rust-wasm";
3
+ import { P as c, d as T, c as E, a as A, b as S, f as R, e as _ } from "./assertPsbtUnsignedTxMatches-GHobJP-d.js";
4
+ import { b as m, e as x, f } from "./peginInput-BPRB9tUi.js";
5
+ import { a as I, b as v } from "./noPayout-BtP-R-b-.js";
6
+ import { d as F, a as O, b as V, e as U, f as h, j as N, g as y, h as D, i as B, c as M, p as H, s as L, t as X, u as k, v as W } from "./bitcoin-B5aNKtsk.js";
7
+ import { c as K } from "./signing-DaLvGwQe.js";
8
+ import { B as Y, H as Z, K as J, M as j, T as q } from "./validation-CxqROCno.js";
9
+ import { P as Q, V as $, b as aa, a as ea, c as sa, f as ta, d as ra, e as oa } from "./PeginManager-BezsAEDe.js";
10
+ import { P as na, c as ua, v as la } from "./PayoutManager-CXDccwDN.js";
11
+ import { A as da, P as Pa } from "./ApplicationRegistry.abi-Dn2qk6JG.js";
12
+ import { B as Ta } from "./BTCVaultRegistry.abi-Cq9-JlqT.js";
13
+ import { C as Aa, e as Sa, g as Ra, h as _a, i as ga } from "./errors-CznAK5NB.js";
14
+ import { BitcoinNetworks as xa } from "./shared/index.js";
15
+ import { B as ba, a as Ia, f as va, c as Ca, b as Fa, d as Oa, g as Va, i as Ua, h as ha, s as Na, e as ya, w as Da } from "./waitForTransactionReceiptSmartAware-Dt5VcMK0.js";
16
+ import { B as Ma, D as Ha, F as La, L as Xa, M as ka, P as Wa, b as wa, a as Ka, S as Ga, T as Ya, W as Za, f as Ja, c as ja, p as qa, r as za } from "./fundPeginTransaction-C11tYf6I.js";
17
+ import { U as $a, a as ae, c as ee, e as se, s as te, v as re } from "./reservation-DNOGLBt4.js";
18
+ import { M as ie, V as ne, g as ue, a as le, b as pe, c as de, d as Pe, e as ce, f as Te, h as Ee, p as Ae, v as Se, i as Re, j as _e } from "./mempoolApi-DI9HISqi.js";
19
+ import { O as me, S as xe, V as fe, g as be, h as Ie, i as ve, a as Ce, d as Fe, b as Oe, f as Ve, p as Ue, r as he, v as Ne, c as ye, e as De } from "./primeVpAuth-qEC9TTO_.js";
20
+ import { A as Me, D as He, b as Le, J as Xe, a as ke, d as We, P as we, R as Ke, e as Ge, c as Ye, V as Ze } from "./types-BqGAMOZM.js";
21
+ import { i as je, p as qe } from "./errors-9AkghWyk.js";
22
+ import { B as Qe, C as $e, p as as, q as es, t as ss, u as ts, R as rs, a as os, n as is, o as ns, i as us, m as ls, l as ps, j as ds, r as Ps, b as cs, s as Ts, v as Es, g as As, h as Ss, d as Rs, c as _s, e as gs, f as ms, k as xs, w as fs } from "./buildAndBroadcastRefund-37Bs7-V1.js";
23
+ import { C as Is, P as vs, c as Cs, g as Fs } from "./peginState-CBAlxgXk.js";
24
24
  export {
25
- Be as AUTH_EXPIRED_DATA_KIND,
26
- pa as ApplicationRegistryABI,
27
- ze as BIP68NotMatureError,
28
- G as BITCOIN_ADDRESS_RE,
29
- ca as BTCVaultRegistryABI,
30
- Ba as BTC_DUST_SAT,
31
- ma as BitcoinNetworks,
32
- fa as BitcoinScriptType,
33
- Ea as CONTRACT_ERRORS,
34
- Qe as ClaimerPegoutStatusValue,
35
- bs as ContractStatus,
36
- Ma as DUST_THRESHOLD,
37
- Me as DaemonStatus,
38
- Ha as FEE_SAFETY_MARGIN,
39
- Y as HEX_RE,
40
- He as JSON_RPC_ERROR_CODES,
41
- Le as JsonRpcClient,
25
+ Me as AUTH_EXPIRED_DATA_KIND,
26
+ da as ApplicationRegistryABI,
27
+ Qe as BIP68NotMatureError,
28
+ Y as BITCOIN_ADDRESS_RE,
29
+ Ta as BTCVaultRegistryABI,
30
+ Ma as BTC_DUST_SAT,
31
+ xa as BitcoinNetworks,
32
+ ba as BitcoinScriptType,
33
+ Aa as CONTRACT_ERRORS,
34
+ $e as ClaimerPegoutStatusValue,
35
+ Is as ContractStatus,
36
+ Ha as DUST_THRESHOLD,
37
+ He as DaemonStatus,
38
+ La as FEE_SAFETY_MARGIN,
39
+ Z as HEX_RE,
40
+ Le as JSON_RPC_ERROR_CODES,
41
+ Xe as JsonRpcClient,
42
42
  ke as JsonRpcError,
43
- Z as KNOWN_SCRIPT_PREFIXES,
44
- La as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
43
+ J as KNOWN_SCRIPT_PREFIXES,
44
+ Xa as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
45
45
  ka as MAX_NON_LEGACY_OUTPUT_SIZE,
46
- J as MAX_REASONABLE_FEE_SATS,
47
- oe as MEMPOOL_API_URLS,
48
- Ae as OnChainBtcVaultStatus,
49
- Xa as P2TR_INPUT_SIZE,
50
- Wa as PEGIN_AUTH_ANCHOR_OUTPUTS,
51
- wa as PEGIN_FIXED_OUTPUTS,
52
- Xe as POST_WOTS_STATUSES,
53
- We as PRE_DEPOSITOR_SIGNATURES_STATES,
54
- ia as PayoutManager,
55
- Is as PeginAction,
56
- z as PeginManager,
57
- da as ProtocolParamsABI,
58
- P as PsbtSubstitutionError,
59
- $e as REFUND_MAX_FEE_FRACTION_DENOMINATOR,
60
- as as REFUND_MAX_FEE_FRACTION_NUMERATOR,
61
- es as REFUND_MAX_FEE_RATE_SATS_VB,
62
- ss as REFUND_VSIZE,
63
- ts as RegisteredVaultVersionMismatchError,
64
- we as RpcErrorCode,
65
- Ka as SPLIT_TX_FEE_SAFETY_MULTIPLIER,
66
- Se as ServerIdentityError,
67
- j as TXID_RE,
68
- Ga as TX_BUFFER_SIZE_OVERHEAD,
69
- Qa as UtxoNotAvailableError,
70
- Q as VAULT_APP_NAME,
71
- Ke as VP_BATCH_MAX_SIZE,
72
- Ge as VP_TERMINAL_FAILURE_STATUSES,
73
- Ye as VP_TRANSIENT_STATUSES,
74
- Re as VaultProviderRpcClient,
75
- _e as ViemProtocolParamsReader,
76
- ge as ViemUniversalChallengerReader,
77
- me as ViemVaultKeeperReader,
78
- xe as ViemVaultRegistryReader,
79
- fe as VpResponseValidationError,
80
- be as VpTokenRegistry,
81
- Ya as WALLET_RELAY_FEE_RATE_THRESHOLD,
82
- rs as activateVault,
83
- ba as applyChangeOutputPolicy,
84
- c as assertPsbtUnsignedTxMatches,
85
- $a as assertUtxosAvailable,
86
- Ie as batchPollByProvider,
87
- os as buildAndBroadcastRefund,
46
+ j as MAX_REASONABLE_FEE_SATS,
47
+ ie as MEMPOOL_API_URLS,
48
+ me as OnChainBtcVaultStatus,
49
+ Wa as P2TR_INPUT_SIZE,
50
+ wa as PEGIN_AUTH_ANCHOR_OUTPUTS,
51
+ Ka as PEGIN_FIXED_OUTPUTS,
52
+ We as POST_WOTS_STATUSES,
53
+ we as PRE_DEPOSITOR_SIGNATURES_STATES,
54
+ na as PayoutManager,
55
+ vs as PeginAction,
56
+ Q as PeginManager,
57
+ Pa as ProtocolParamsABI,
58
+ c as PsbtSubstitutionError,
59
+ as as REFUND_MAX_FEE_FRACTION_DENOMINATOR,
60
+ es as REFUND_MAX_FEE_FRACTION_NUMERATOR,
61
+ ss as REFUND_MAX_FEE_RATE_SATS_VB,
62
+ ts as REFUND_VSIZE,
63
+ rs as RegisteredVaultVersionMismatchError,
64
+ Ke as RpcErrorCode,
65
+ Ga as SPLIT_TX_FEE_SAFETY_MULTIPLIER,
66
+ xe as ServerIdentityError,
67
+ q as TXID_RE,
68
+ Ya as TX_BUFFER_SIZE_OVERHEAD,
69
+ $a as UtxoNotAvailableError,
70
+ $ as VAULT_APP_NAME,
71
+ Ge as VP_BATCH_MAX_SIZE,
72
+ Ye as VP_TERMINAL_FAILURE_STATUSES,
73
+ Ze as VP_TRANSIENT_STATUSES,
74
+ fe as VaultProviderRpcClient,
75
+ be as ViemProtocolParamsReader,
76
+ Ie as ViemUniversalChallengerReader,
77
+ ve as ViemVaultKeeperReader,
78
+ ne as ViemVaultRegistryReader,
79
+ Ce as VpResponseValidationError,
80
+ Fe as VpTokenRegistry,
81
+ Za as WALLET_RELAY_FEE_RATE_THRESHOLD,
82
+ os as activateVault,
83
+ Ia as applyChangeOutputPolicy,
84
+ T as assertPsbtUnsignedTxMatches,
85
+ ae as assertUtxosAvailable,
86
+ Oe as batchPollByProvider,
87
+ is as buildAndBroadcastRefund,
88
88
  s as buildChallengeAssertPsbt,
89
89
  t as buildDepositorPayoutPsbt,
90
- $ as buildFundingOutpointsCommitment,
91
- b as buildNoPayoutPsbt,
92
- T as buildPayoutPsbt,
93
- g as buildPeginInputPsbt,
94
- E as buildPeginTxFromFundedPrePegin,
95
- A as buildPrePeginPsbt,
96
- I as buildRefundPsbt,
97
- aa as buildVaultContext,
98
- Ia as calculateBtcTxHash,
90
+ aa as buildFundingOutpointsCommitment,
91
+ I as buildNoPayoutPsbt,
92
+ E as buildPayoutPsbt,
93
+ m as buildPeginInputPsbt,
94
+ A as buildPeginTxFromFundedPrePegin,
95
+ S as buildPrePeginPsbt,
96
+ v as buildRefundPsbt,
97
+ ea as buildVaultContext,
98
+ va as calculateBtcTxHash,
99
99
  Cs as canPerformAction,
100
- ae as collectReservedUtxoRefs,
100
+ ee as collectReservedUtxoRefs,
101
101
  Ca as computeChangeOutputFeeSats,
102
- na as computeHashlock,
103
- Oa as computeMaxDeposit,
102
+ ua as computeHashlock,
103
+ Fa as computeMaxDeposit,
104
104
  i as computeMinClaimValue,
105
+ n as computeMinPeginFee,
105
106
  r as computeNumLocalChallengers,
106
- va as computePeginBaseFeeSats,
107
- ea as computeWotsBlockPublicKeysHash,
108
- Ce as createAuthenticatedVpClient,
109
- S as createPayoutScript,
110
- w as createTaprootScriptPathSignOptions,
111
- O as deriveBip86ScriptPubKeyHex,
112
- v as deriveNativeSegwitAddress,
113
- F as deriveTaprootAddress,
114
- n as deriveVaultId,
115
- sa as deriveVaultRoot,
116
- ta as deriveWotsBlocksFromSeed,
117
- V as ensureHexPrefix,
118
- is as estimateRefundFeeSats,
119
- ra as estimateSubmitPeginRequestBatchGas,
120
- u as expandAuthAnchor,
121
- l as expandHashlockSecret,
122
- p as expandWotsSeed,
123
- Aa as extractErrorData,
124
- ee as extractInputsFromTransaction,
125
- R as extractPayoutSignature,
126
- m as extractPeginInputSignature,
127
- x as finalizePeginInputPsbt,
128
- U as formatSatoshisToBtc,
129
- Za as fundPeginTransaction,
130
- ie as getAddressTxs,
131
- ne as getAddressUtxos,
132
- Sa as getContractErrorMessage,
133
- Fa as getDustThreshold,
134
- ue as getMempoolApiUrl,
135
- h as getNetwork,
136
- le as getNetworkFees,
137
- Os as getPeginProtocolState,
138
- Va as getPsbtInputFields,
139
- Ua as getScriptType,
140
- N as getSortedXOnlyPubkeys,
141
- pe as getTipHeight,
142
- de as getTxHex,
143
- Pe as getTxInfo,
144
- ce as getUtxoInfo,
145
- Ra as handleContractError,
146
- y as hexToUint8Array,
147
- D as isAddressFromPublicKey,
148
- ns as isDepositAmountValid,
149
- _a as isKnownContractError,
150
- us as isPegoutTerminalStatus,
151
- ls as isRecognizedPegoutStatus,
152
- ps as isRegisteredVaultVersionMismatchError,
153
- B as isValidHex,
154
- Je as isWotsMismatchError,
155
- je as parseFundingOutpointsFromTx,
156
- Ja as parseUnfundedWasmTransaction,
157
- ja as peginOutputCount,
158
- Oe as primeVpTokenRegistry,
159
- M as processPublicKeyToXOnly,
160
- Te as pushTx,
161
- qa as rateBasedTxBufferFee,
162
- ve as resolveProtocolAddresses,
163
- ds as runDepositorPresignFlow,
164
- se as selectUtxosForDeposit,
165
- ha as selectUtxosForPegin,
166
- Na as shouldAddChangeOutput,
167
- Ps as signDepositorGraph,
168
- H as stripHexPrefix,
169
- cs as submitWotsPublicKey,
170
- L as toXOnly,
107
+ Oa as computePeginBaseFeeSats,
108
+ sa as computeWotsBlockPublicKeysHash,
109
+ Ve as createAuthenticatedVpClient,
110
+ R as createPayoutScript,
111
+ K as createTaprootScriptPathSignOptions,
112
+ F as deriveBip86ScriptPubKeyHex,
113
+ O as deriveNativeSegwitAddress,
114
+ V as deriveTaprootAddress,
115
+ u as deriveVaultId,
116
+ ta as deriveVaultRoot,
117
+ ra as deriveWotsBlocksFromSeed,
118
+ U as ensureHexPrefix,
119
+ ns as estimateRefundFeeSats,
120
+ oa as estimateSubmitPeginRequestBatchGas,
121
+ l as expandAuthAnchor,
122
+ p as expandHashlockSecret,
123
+ d as expandWotsSeed,
124
+ Sa as extractErrorData,
125
+ se as extractInputsFromTransaction,
126
+ _ as extractPayoutSignature,
127
+ x as extractPeginInputSignature,
128
+ f as finalizePeginInputPsbt,
129
+ h as formatSatoshisToBtc,
130
+ Ja as fundPeginTransaction,
131
+ ue as getAddressTxs,
132
+ le as getAddressUtxos,
133
+ Ra as getContractErrorMessage,
134
+ Va as getDustThreshold,
135
+ pe as getMempoolApiUrl,
136
+ N as getNetwork,
137
+ de as getNetworkFees,
138
+ Fs as getPeginProtocolState,
139
+ Ua as getPsbtInputFields,
140
+ ha as getScriptType,
141
+ y as getSortedXOnlyPubkeys,
142
+ Pe as getTipHeight,
143
+ ce as getTxHex,
144
+ Te as getTxInfo,
145
+ Ee as getUtxoInfo,
146
+ _a as handleContractError,
147
+ D as hexToUint8Array,
148
+ B as isAddressFromPublicKey,
149
+ us as isDepositAmountValid,
150
+ ga as isKnownContractError,
151
+ ls as isPegoutTerminalStatus,
152
+ ps as isRecognizedPegoutStatus,
153
+ ds as isRegisteredVaultVersionMismatchError,
154
+ M as isValidHex,
155
+ je as isWotsMismatchError,
156
+ qe as parseFundingOutpointsFromTx,
157
+ ja as parseUnfundedWasmTransaction,
158
+ qa as peginOutputCount,
159
+ Ue as primeVpTokenRegistry,
160
+ H as processPublicKeyToXOnly,
161
+ Ae as pushTx,
162
+ za as rateBasedTxBufferFee,
163
+ he as resolveProtocolAddresses,
164
+ Ps as runDepositorPresignFlow,
165
+ te as selectUtxosForDeposit,
166
+ Na as selectUtxosForPegin,
167
+ ya as shouldAddChangeOutput,
168
+ cs as signDepositorGraph,
169
+ L as stripHexPrefix,
170
+ Ts as submitWotsPublicKey,
171
+ X as toXOnly,
171
172
  k as uint8ArrayToHex,
172
- Ts as validateDepositAmount,
173
- Es as validateMultiVaultDepositInputs,
174
- Fe as validateOffchainParams,
175
- As as validateOnChainParticipantKeys,
176
- Ve as validatePegInConfiguration,
177
- Ss as validateProviderSelection,
178
- Rs as validateRemainingCapacity,
179
- Ue as validateRequestDepositorClaimerArtifactsResponse,
180
- ua as validateSecretAgainstHashlock,
181
- he as validateTBVProtocolParams,
182
- te as validateUtxosAvailable,
183
- _s as validateVaultAmounts,
184
- gs as validateVaultProviderPubkey,
185
- X as validateWalletPubkey,
186
- ms as verifyRegisteredVaultVersions,
187
- Ne as verifyServerIdentity,
188
- ye as vpTokenRegistry,
189
- xs as waitForPeginStatus,
190
- ya as waitForTransactionReceiptSmartAware
173
+ Es as validateDepositAmount,
174
+ As as validateMultiVaultDepositInputs,
175
+ Se as validateOffchainParams,
176
+ Ss as validateOnChainParticipantKeys,
177
+ Re as validatePegInConfiguration,
178
+ Rs as validateProviderSelection,
179
+ _s as validateRemainingCapacity,
180
+ Ne as validateRequestDepositorClaimerArtifactsResponse,
181
+ la as validateSecretAgainstHashlock,
182
+ _e as validateTBVProtocolParams,
183
+ re as validateUtxosAvailable,
184
+ gs as validateVaultAmounts,
185
+ ms as validateVaultProviderPubkey,
186
+ W as validateWalletPubkey,
187
+ xs as verifyRegisteredVaultVersions,
188
+ ye as verifyServerIdentity,
189
+ De as vpTokenRegistry,
190
+ fs as waitForPeginStatus,
191
+ Da as waitForTransactionReceiptSmartAware
191
192
  };
192
193
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";const C=require("@bitcoin-js/tiny-secp256k1-asmjs"),E=require("./bitcoin-CHfKAhcI.cjs"),s=require("./BTCVaultRegistry.abi-CHFGevwa.cjs"),l=require("./validation-u8W7Lp2x.cjs");function B(e){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(o,t,r.get?r:{enumerable:!0,get:()=>e[t]})}}return o.default=e,Object.freeze(o)}const F=B(C),m=65535,d=1e4,f=4294967295,p=255;function u(e){if(!Number.isInteger(e)||e<0||e>f)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`)}function b(e){const o=[];if(e.timelockAssert<=0n&&o.push(`timelockAssert must be positive, got ${e.timelockAssert}`),e.timelockAssert>BigInt(m)&&o.push(`timelockAssert ${e.timelockAssert} exceeds uint16 max (${m})`),e.timelockChallengeAssert<=0n&&o.push(`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`),e.tRefund<=0&&o.push(`tRefund must be positive, got ${e.tRefund}`),e.tStale<=0&&o.push(`tStale must be positive, got ${e.tStale}`),e.securityCouncilKeys.length===0&&o.push("securityCouncilKeys must not be empty"),e.councilQuorum<=0&&o.push(`councilQuorum must be positive, got ${e.councilQuorum}`),e.councilQuorum>e.securityCouncilKeys.length&&o.push(`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`),e.feeRate<=0n&&o.push(`feeRate must be positive, got ${e.feeRate}`),e.minPeginFeeRate<=0n&&o.push(`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`),(!Number.isInteger(e.proverCircuitVersion)||e.proverCircuitVersion<0||e.proverCircuitVersion>m)&&o.push(`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`),(!Number.isInteger(e.minPrepeginDepth)||e.minPrepeginDepth<=0||e.minPrepeginDepth>f)&&o.push(`minPrepeginDepth must be a uint32 in [1, ${f}], got ${e.minPrepeginDepth}`),e.babeTotalInstances<=0&&o.push(`babeTotalInstances must be positive, got ${e.babeTotalInstances}`),e.babeInstancesToFinalize<=0&&o.push(`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`),e.babeInstancesToFinalize>e.babeTotalInstances&&o.push(`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`),(e.minVpCommissionBps<0||e.minVpCommissionBps>d)&&o.push(`minVpCommissionBps must be in [0, ${d}], got ${e.minVpCommissionBps}`),o.length>0)throw new Error(`Invalid offchain protocol parameters: ${o.join("; ")}`)}function I(e){const o=[];if(e.minimumPegInAmount<=0n&&o.push(`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`),e.maxPegInAmount<e.minimumPegInAmount&&o.push(`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`),e.pegInAckTimeout<=0n&&o.push(`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`),e.pegInActivationTimeout<=0n&&o.push(`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`),(!Number.isInteger(e.maxHtlcOutputCount)||e.maxHtlcOutputCount<=0||e.maxHtlcOutputCount>p)&&o.push(`maxHtlcOutputCount must be an integer in [1, ${p}], got ${e.maxHtlcOutputCount}`),(typeof e.expiredPegInGraceBlocks!="bigint"||e.expiredPegInGraceBlocks<=0n)&&o.push(`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`),o.length>0)throw new Error(`Invalid TBV protocol parameters: ${o.join("; ")}`)}function k(e){if(I(e),b(e.offchainParams),!Number.isInteger(e.offchainParamsVersion)||e.offchainParamsVersion<0||e.offchainParamsVersion>f)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`)}const P=9999;class S{constructor(o,t){this.publicClient=o,this.contractAddress=t}async getVaultProviderBtcPubKey(o){const r=(await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderBTCKey",args:[o]})).toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`getVaultProviderBTCKey returned an unexpected value (vp=${o}, length ${r.length}, prefix "${r.slice(0,2)}")`);const i=r.slice(2);if(!F.isXOnlyPoint(E.hexToUint8Array(i)))throw new Error(`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${o})`);return i}async getVaultBasicInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[o]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]}),r=Number(t.offchainParamsVersion);return u(r),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:r,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,claimExpiredUntil:t.claimExpiredUntil,vaultCoreVersion:t.vaultCoreVersion}}async getProtocolInfoBatch(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map((r,i)=>{const n=r;if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o[i]} not found on-chain or has no pegin transaction`);const a=Number(n.offchainParamsVersion);return u(a),{depositorSignedPeginTx:n.depositorSignedPeginTx,universalChallengersVersion:n.universalChallengersVersion,appVaultKeepersVersion:n.appVaultKeepersVersion,offchainParamsVersion:a,verifiedAt:n.verifiedAt,depositorWotsPkHash:n.depositorWotsPkHash,hashlock:n.hashlock,htlcVout:n.htlcVout,depositorPopSignature:n.depositorPopSignature,prePeginTxHash:n.prePeginTxHash,vaultProviderCommissionBps:n.vaultProviderCommissionBps,claimExpiredUntil:n.claimExpiredUntil,vaultCoreVersion:n.vaultCoreVersion}})}async getPegInFee(o){return await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}async getVaultProviderCommission(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[o]});if(!Number.isInteger(t)||t<0||t>P)throw new Error(`getVaultProviderCommission returned ${t} bps for ${o}, outside the protocol range [0, ${P}]`);return t}async getVaultData(o){const[t,r]=await Promise.all([this.getVaultBasicInfo(o),this.getVaultProtocolInfo(o)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}async getOffchainParamsVersionsByVaultIds(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map(r=>{const i=r;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error("Vault not found on-chain or has no pegin transaction while reading offchain params version");const n=Number(i.offchainParamsVersion);return u(n),n})}}const O=21e6*1e8,w=3e4;async function h(e,o){const t=new AbortController,r=setTimeout(()=>t.abort(),w),i=[t.signal,o==null?void 0:o.signal].filter(Boolean);try{return await fetch(e,{...o,signal:AbortSignal.any(i)})}catch(n){throw clearTimeout(r),n!=null&&typeof n=="object"&&"name"in n&&n.name==="AbortError"?new Error(`Mempool API request timed out after ${w}ms: ${e}`):n}}const $=1e4;function T(e){return Number.isInteger(e)&&e>0&&e<=O}function N(e){return Number.isInteger(e)&&e>0&&e<=$}function v(e,o){return!Number.isInteger(e)||e<0?!1:o===void 0||e<o}function g(e){if(!l.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function V(e){if(!l.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function y(e,o){if(!l.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${o}`);if(!l.KNOWN_SCRIPT_PREFIXES.some(r=>e.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${o}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const x={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(e,o){try{const t=await h(e,o);if(!t.ok){const i=await t.text();throw new Error(`Mempool API error (${t.status}): ${i||t.statusText}`)}const r=t.headers.get("content-type");return r!=null&&r.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function R(e,o){try{const t=await h(`${o}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!t.ok){const i=await t.text();let n;try{n=JSON.parse(i).message}catch{n=i}throw new Error(n||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function A(e,o){return g(e),c(`${o}/tx/${e}`)}async function U(e){const o=await c(`${e}/blocks/tip/height`),t=o.trim();if(!/^\d+$/.test(t))throw new Error(`Mempool API returned an invalid block tip height: "${o}"`);return Number.parseInt(t,10)}async function _(e,o){g(e);try{const t=await h(`${o}/tx/${e}/hex`);if(!t.ok){const r=await t.text();throw new Error(`Mempool API error (${t.status}): ${r||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${t.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function M(e,o,t){g(e);const r=await A(e,t);if(!v(o,r.vout.length))throw new Error(`Invalid vout ${o} for transaction ${e} (has ${r.vout.length} outputs)`);const i=r.vout[o];if(!T(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${e}:${o}`);return y(i.scriptpubkey,`${e}:${o}`),{txid:e,vout:o,value:i.value,scriptPubKey:i.scriptpubkey}}async function H(e,o){V(e);try{const t=await c(`${o}/address/${e}/utxo`),r=await c(`${o}/v1/validate-address/${e}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);y(r.scriptPubKey,e);for(const n of t){if(g(n.txid),!v(n.vout))throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);if(!T(n.value))throw new Error(`Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`)}return t.sort((n,a)=>a.value-n.value).map(n=>({txid:n.txid,vout:n.vout,value:n.value,scriptPubKey:r.scriptPubKey,confirmed:n.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${t.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function K(e){return x[e]}async function X(e,o){return V(e),c(`${o}/address/${e}/txs`)}async function D(e){const o=await h(`${e}/v1/fees/recommended`);if(!o.ok)throw new Error(`Failed to fetch network fees: ${o.status} ${o.statusText}`);const t=await o.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of r)if(!N(t[i]))throw new Error(`Invalid fee rate ${i}=${t[i]} from mempool API: expected a positive number ≤ ${$}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}exports.MEMPOOL_API_URLS=x;exports.ViemVaultRegistryReader=S;exports.assertValidOffchainParamsVersion=u;exports.getAddressTxs=X;exports.getAddressUtxos=H;exports.getMempoolApiUrl=K;exports.getNetworkFees=D;exports.getTipHeight=U;exports.getTxHex=_;exports.getTxInfo=A;exports.getUtxoInfo=M;exports.pushTx=R;exports.validateOffchainParams=b;exports.validatePegInConfiguration=k;exports.validateTBVProtocolParams=I;
2
+ //# sourceMappingURL=mempoolApi-CknccHKg.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-CknccHKg.cjs","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n };\n\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","MAX_VP_COMMISSION_BPS","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","result","offchainParamsVersion","vaultIds","info","vaultProvider","bps","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTipHeight","raw","trimmed","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"udAsBMA,EAAa,MAGbC,EAAmB,IAGnBC,EAAa,WAGbC,EAAY,IAQX,SAASC,EAAiCC,EAAuB,CACtE,GACE,CAAC,OAAO,UAAUA,CAAO,GACzBA,EAAU,GACVA,EAAUH,EAEV,MAAM,IAAI,MACR,sEAAsEG,CAAO,EAAA,CAGnF,CAMO,SAASC,EAAuBC,EAAuC,CAC5E,MAAMC,EAAmB,CAAA,EA+FzB,GA7FID,EAAO,gBAAkB,IAC3BC,EAAO,KACL,wCAAwCD,EAAO,cAAc,EAAA,EAG7DA,EAAO,eAAiB,OAAOP,CAAU,GAC3CQ,EAAO,KACL,kBAAkBD,EAAO,cAAc,wBAAwBP,CAAU,GAAA,EAIzEO,EAAO,yBAA2B,IACpCC,EAAO,KACL,iDAAiDD,EAAO,uBAAuB,EAAA,EAI/EA,EAAO,SAAW,GACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,EAG3DA,EAAO,QAAU,GACnBC,EAAO,KAAK,gCAAgCD,EAAO,MAAM,EAAE,EAGzDA,EAAO,oBAAoB,SAAW,GACxCC,EAAO,KAAK,uCAAuC,EAGjDD,EAAO,eAAiB,GAC1BC,EAAO,KAAK,uCAAuCD,EAAO,aAAa,EAAE,EAEvEA,EAAO,cAAgBA,EAAO,oBAAoB,QACpDC,EAAO,KACL,kBAAkBD,EAAO,aAAa,wCAAwCA,EAAO,oBAAoB,MAAM,GAAA,EAI/GA,EAAO,SAAW,IACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,EAG3DA,EAAO,iBAAmB,IAC5BC,EAAO,KACL,yCA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