@babylonlabs-io/ts-sdk 3.2.1 → 3.3.1

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 (70) hide show
  1. package/dist/{PeginManager-sizm3dlw.js → PeginManager-CQ9bVPR3.js} +116 -105
  2. package/dist/{PeginManager-sizm3dlw.js.map → PeginManager-CQ9bVPR3.js.map} +1 -1
  3. package/dist/PeginManager-D2R4Q1bN.cjs +2 -0
  4. package/dist/{PeginManager-BCRtUqyX.cjs.map → PeginManager-D2R4Q1bN.cjs.map} +1 -1
  5. package/dist/ProtocolParams.abi-BgEZaQ2I.cjs +2 -0
  6. package/dist/ProtocolParams.abi-BgEZaQ2I.cjs.map +1 -0
  7. package/dist/{ProtocolParams.abi-CKOVqFJP.js → ProtocolParams.abi-Cv77fsUe.js} +15 -9
  8. package/dist/ProtocolParams.abi-Cv77fsUe.js.map +1 -0
  9. package/dist/{buildAndBroadcastReclaim-rQyAiAUS.js → buildAndBroadcastReclaim-CQANDXVJ.js} +3 -3
  10. package/dist/{buildAndBroadcastReclaim-rQyAiAUS.js.map → buildAndBroadcastReclaim-CQANDXVJ.js.map} +1 -1
  11. package/dist/{buildAndBroadcastReclaim-CE77jzTp.cjs → buildAndBroadcastReclaim-DPk36Uhp.cjs} +2 -2
  12. package/dist/{buildAndBroadcastReclaim-CE77jzTp.cjs.map → buildAndBroadcastReclaim-DPk36Uhp.cjs.map} +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +8 -8
  15. package/dist/{pegin-registration-client-Bmkh1OZ9.cjs → pegin-registration-client-CdRyXP3j.cjs} +2 -2
  16. package/dist/{pegin-registration-client-Bmkh1OZ9.cjs.map → pegin-registration-client-CdRyXP3j.cjs.map} +1 -1
  17. package/dist/{pegin-registration-client-8tzSRDaq.js → pegin-registration-client-Cvjk4ILq.js} +2 -2
  18. package/dist/{pegin-registration-client-8tzSRDaq.js.map → pegin-registration-client-Cvjk4ILq.js.map} +1 -1
  19. package/dist/{registration-records-BBOz21Dm.js → registration-records-DJJC2NiO.js} +81 -79
  20. package/dist/{registration-records-BBOz21Dm.js.map → registration-records-DJJC2NiO.js.map} +1 -1
  21. package/dist/{registration-records-DaBufozs.cjs → registration-records-XQMIKjGV.cjs} +2 -2
  22. package/dist/{registration-records-DaBufozs.cjs.map → registration-records-XQMIKjGV.cjs.map} +1 -1
  23. package/dist/shared/index.cjs.map +1 -1
  24. package/dist/shared/index.js.map +1 -1
  25. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts +5 -0
  26. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -1
  27. package/dist/{signer-set-reader-DFF9MgQN.js → signer-set-reader-CSUe92zE.js} +2 -2
  28. package/dist/{signer-set-reader-DFF9MgQN.js.map → signer-set-reader-CSUe92zE.js.map} +1 -1
  29. package/dist/{signer-set-reader-D-CyIYR5.cjs → signer-set-reader-GrFe_rsW.cjs} +2 -2
  30. package/dist/{signer-set-reader-D-CyIYR5.cjs.map → signer-set-reader-GrFe_rsW.cjs.map} +1 -1
  31. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  32. package/dist/tbv/core/clients/eth/index.js +4 -4
  33. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +1 -0
  34. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  35. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
  36. package/dist/tbv/core/clients/eth/types.d.ts +12 -6
  37. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  38. package/dist/tbv/core/clients/index.cjs +1 -1
  39. package/dist/tbv/core/clients/index.js +4 -4
  40. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +8 -0
  41. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
  42. package/dist/tbv/core/contracts/index.cjs +1 -1
  43. package/dist/tbv/core/contracts/index.js +1 -1
  44. package/dist/tbv/core/index.cjs +1 -1
  45. package/dist/tbv/core/index.js +8 -8
  46. package/dist/tbv/core/managers/PeginManager.d.ts +2 -1
  47. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  48. package/dist/tbv/core/managers/index.cjs +1 -1
  49. package/dist/tbv/core/managers/index.js +1 -1
  50. package/dist/tbv/core/services/index.cjs +1 -1
  51. package/dist/tbv/core/services/index.js +1 -1
  52. package/dist/tbv/index.cjs +1 -1
  53. package/dist/tbv/index.js +8 -8
  54. package/dist/{toRefundInputs-Dso_QEr-.js → toRefundInputs-DH-1bRNY.js} +3 -3
  55. package/dist/{toRefundInputs-Dso_QEr-.js.map → toRefundInputs-DH-1bRNY.js.map} +1 -1
  56. package/dist/{toRefundInputs-DOCLxqC1.cjs → toRefundInputs-DRmK83fv.cjs} +2 -2
  57. package/dist/{toRefundInputs-DOCLxqC1.cjs.map → toRefundInputs-DRmK83fv.cjs.map} +1 -1
  58. package/dist/types-24A9Qoxb.js +274 -0
  59. package/dist/types-24A9Qoxb.js.map +1 -0
  60. package/dist/types-BC2TGzcp.cjs +2 -0
  61. package/dist/types-BC2TGzcp.cjs.map +1 -0
  62. package/package.json +2 -2
  63. package/dist/PeginManager-BCRtUqyX.cjs +0 -2
  64. package/dist/ProtocolParams.abi-CKOVqFJP.js.map +0 -1
  65. package/dist/ProtocolParams.abi-CjrT0545.cjs +0 -2
  66. package/dist/ProtocolParams.abi-CjrT0545.cjs.map +0 -1
  67. package/dist/types-DGr5HWwD.cjs +0 -2
  68. package/dist/types-DGr5HWwD.cjs.map +0 -1
  69. package/dist/types-Dbs--c2M.js +0 -198
  70. package/dist/types-Dbs--c2M.js.map +0 -1
@@ -0,0 +1,274 @@
1
+ import { P as s } from "./ProtocolParams.abi-Cv77fsUe.js";
2
+ import { c as A, v as f, j as h, b } from "./registration-records-DJJC2NiO.js";
3
+ const p = 65535, y = [
4
+ {
5
+ type: "function",
6
+ name: "getTBVProtocolParams",
7
+ inputs: [],
8
+ outputs: [
9
+ {
10
+ name: "",
11
+ type: "tuple",
12
+ internalType: "struct IProtocolParams.TBVProtocolParams",
13
+ components: [
14
+ {
15
+ name: "minimumPegInAmount",
16
+ type: "uint64",
17
+ internalType: "uint64"
18
+ },
19
+ {
20
+ name: "maxPegInAmount",
21
+ type: "uint64",
22
+ internalType: "uint64"
23
+ },
24
+ {
25
+ name: "pegInAckTimeout",
26
+ type: "uint64",
27
+ internalType: "uint64"
28
+ },
29
+ {
30
+ name: "pegInActivationTimeout",
31
+ type: "uint64",
32
+ internalType: "uint64"
33
+ },
34
+ {
35
+ name: "maxHtlcOutputCount",
36
+ type: "uint8",
37
+ internalType: "uint8"
38
+ },
39
+ {
40
+ name: "expiredPegInGraceBlocks",
41
+ type: "uint64",
42
+ internalType: "uint64"
43
+ }
44
+ ]
45
+ }
46
+ ],
47
+ stateMutability: "view"
48
+ }
49
+ ];
50
+ function P(t) {
51
+ if (t.status === "failure")
52
+ throw t.error;
53
+ return t.result;
54
+ }
55
+ function m(t) {
56
+ return {
57
+ timelockAssert: t.timelockAssert,
58
+ timelockChallengeAssert: t.timelockChallengeAssert,
59
+ securityCouncilKeys: [...t.securityCouncilKeys],
60
+ councilQuorum: t.councilQuorum,
61
+ feeRate: t.feeRate,
62
+ babeTotalInstances: t.babeTotalInstances,
63
+ babeInstancesToFinalize: t.babeInstancesToFinalize,
64
+ minVpCommissionBps: t.minVpCommissionBps,
65
+ tRefund: t.tRefund,
66
+ tStale: t.tStale,
67
+ minPeginFeeRate: t.minPeginFeeRate,
68
+ proverCircuitVersion: t.proverCircuitVersion,
69
+ minPrepeginDepth: t.minPrepeginDepth
70
+ };
71
+ }
72
+ function g(t, e) {
73
+ return {
74
+ minimumPegInAmount: t.minimumPegInAmount,
75
+ maxPegInAmount: t.maxPegInAmount,
76
+ pegInAckTimeout: t.pegInAckTimeout,
77
+ pegInActivationTimeout: t.pegInActivationTimeout,
78
+ maxHtlcOutputCount: t.maxHtlcOutputCount,
79
+ expiredPegInGraceBlocks: t.expiredPegInGraceBlocks,
80
+ maxFundingInputCount: e
81
+ };
82
+ }
83
+ function d(t, e) {
84
+ if (t.status === "success") {
85
+ const n = t.result;
86
+ return g(n, n.maxFundingInputCount);
87
+ }
88
+ if (e.status === "success")
89
+ return g(
90
+ e.result,
91
+ null
92
+ );
93
+ throw t.error;
94
+ }
95
+ function I(t) {
96
+ if (t > BigInt(p))
97
+ throw new Error(
98
+ `timelockAssert value ${t} exceeds uint16 max (${p})`
99
+ );
100
+ return Number(t);
101
+ }
102
+ class V {
103
+ constructor(e, n) {
104
+ this.publicClient = e, this.contractAddress = n;
105
+ }
106
+ async getTBVProtocolParams() {
107
+ const [e, n] = await this.publicClient.multicall({
108
+ contracts: this.tbvParamsCalls(),
109
+ allowFailure: !0
110
+ }), a = d(e, n);
111
+ return A(a), a;
112
+ }
113
+ tbvParamsCalls() {
114
+ return [
115
+ {
116
+ address: this.contractAddress,
117
+ abi: s,
118
+ functionName: "getTBVProtocolParams"
119
+ },
120
+ {
121
+ address: this.contractAddress,
122
+ abi: y,
123
+ functionName: "getTBVProtocolParams"
124
+ }
125
+ ];
126
+ }
127
+ async getLatestOffchainParams() {
128
+ const e = await this.publicClient.readContract({
129
+ address: this.contractAddress,
130
+ abi: s,
131
+ functionName: "getLatestOffchainParams"
132
+ }), n = m(e);
133
+ return f(n), n;
134
+ }
135
+ async getOffchainParamsByVersion(e) {
136
+ const n = await this.publicClient.readContract({
137
+ address: this.contractAddress,
138
+ abi: s,
139
+ functionName: "getOffchainParamsByVersion",
140
+ args: [e]
141
+ }), a = m(n);
142
+ return f(a), a;
143
+ }
144
+ async getLatestOffchainParamsVersion() {
145
+ const e = await this.publicClient.readContract({
146
+ address: this.contractAddress,
147
+ abi: s,
148
+ functionName: "latestOffchainParamsVersion"
149
+ }), n = Number(e);
150
+ return h(n), n;
151
+ }
152
+ async getTimelockPeginByVersion(e) {
153
+ const n = await this.getOffchainParamsByVersion(e);
154
+ return I(n.timelockAssert);
155
+ }
156
+ /**
157
+ * Returned as `bigint` with no `Number` narrowing: the registry compares it
158
+ * against `block.number`, so callers must do the same arithmetic the
159
+ * contract does. `0` is the documented "disabled" case and is returned as
160
+ * `0n`. A missing getter or a non-bigint payload throws — never coerced to
161
+ * `0`, which would fail open and skip the observation window.
162
+ *
163
+ * @throws If the deployment does not expose `peginActivationDelay()`, or
164
+ * the decoded payload is not a `bigint`.
165
+ */
166
+ async getPeginActivationDelay() {
167
+ const e = await this.publicClient.readContract({
168
+ address: this.contractAddress,
169
+ abi: s,
170
+ functionName: "peginActivationDelay"
171
+ });
172
+ if (typeof e != "bigint")
173
+ throw new Error(
174
+ `Invalid peginActivationDelay from contract: must be a bigint, got ${typeof e}`
175
+ );
176
+ return e;
177
+ }
178
+ /**
179
+ * Read TBV protocol params, latest offchain params, and the latest version
180
+ * label atomically via multicall. The version is paired with the params so
181
+ * that a governance update between separate reads cannot let JS build BTC
182
+ * scripts with version N params while the contract registers the vault
183
+ * under version N+1.
184
+ *
185
+ * That guarantee holds only within this multicall. A caller that also reads
186
+ * participant keys — every fresh peg-in build does — must pass the same
187
+ * `blockNumber` here and to those reads, or the two describe different
188
+ * blocks and the pairing above buys nothing across the seam.
189
+ */
190
+ async getPegInConfiguration(e) {
191
+ const n = await this.publicClient.multicall({
192
+ blockNumber: e,
193
+ contracts: [
194
+ ...this.tbvParamsCalls(),
195
+ {
196
+ address: this.contractAddress,
197
+ abi: s,
198
+ functionName: "getLatestOffchainParams"
199
+ },
200
+ {
201
+ address: this.contractAddress,
202
+ abi: s,
203
+ functionName: "latestOffchainParamsVersion"
204
+ },
205
+ {
206
+ address: this.contractAddress,
207
+ abi: s,
208
+ functionName: "activeVaultCoreVersion"
209
+ }
210
+ ],
211
+ allowFailure: !0
212
+ }), a = d(n[0], n[1]), r = m(
213
+ P(n[2])
214
+ ), u = Number(P(n[3])), o = Number(P(n[4])), i = {
215
+ minimumPegInAmount: a.minimumPegInAmount,
216
+ maxPegInAmount: a.maxPegInAmount,
217
+ pegInAckTimeout: a.pegInAckTimeout,
218
+ pegInActivationTimeout: a.pegInActivationTimeout,
219
+ maxHtlcOutputCount: a.maxHtlcOutputCount,
220
+ expiredPegInGraceBlocks: a.expiredPegInGraceBlocks,
221
+ maxFundingInputCount: a.maxFundingInputCount,
222
+ timelockPegin: I(r.timelockAssert),
223
+ timelockRefund: r.tRefund,
224
+ minVpCommissionBps: r.minVpCommissionBps,
225
+ offchainParams: r,
226
+ offchainParamsVersion: u,
227
+ activeVaultCoreVersion: o
228
+ };
229
+ return b(i), i;
230
+ }
231
+ /**
232
+ * Fetch every historical offchain params version in a single multicall.
233
+ * Iterates 1..latestVersion and calls `getOffchainParamsByVersion` for each.
234
+ * Versions whose payload fails validation are skipped (not included in the
235
+ * returned map) so a single bad historical version doesn't block the
236
+ * lookup of the rest.
237
+ *
238
+ * @param onSkippedVersion - optional observer invoked once per skipped
239
+ * version. Use to log/telemeter without coupling the SDK to a logger.
240
+ */
241
+ async fetchAllOffchainParams(e) {
242
+ const n = await this.getLatestOffchainParamsVersion();
243
+ if (n === 0)
244
+ return { byVersion: /* @__PURE__ */ new Map(), latestVersion: 0 };
245
+ const a = Array.from({ length: n }, (i, c) => c + 1), r = a.map((i) => ({
246
+ address: this.contractAddress,
247
+ abi: s,
248
+ functionName: "getOffchainParamsByVersion",
249
+ args: [i]
250
+ })), u = await this.publicClient.multicall({
251
+ contracts: r,
252
+ allowFailure: !1
253
+ }), o = /* @__PURE__ */ new Map();
254
+ for (let i = 0; i < a.length; i++) {
255
+ const c = m(u[i]);
256
+ try {
257
+ f(c), o.set(a[i], c);
258
+ } catch (l) {
259
+ e == null || e(
260
+ a[i],
261
+ l instanceof Error ? l : new Error(String(l))
262
+ );
263
+ }
264
+ }
265
+ return { byVersion: o, latestVersion: n };
266
+ }
267
+ }
268
+ var T = /* @__PURE__ */ ((t) => (t[t.PENDING = 0] = "PENDING", t[t.VERIFIED = 1] = "VERIFIED", t[t.ACTIVE = 2] = "ACTIVE", t[t.REDEEMED = 3] = "REDEEMED", t[t.EXPIRED = 4] = "EXPIRED", t))(T || {});
269
+ export {
270
+ T as O,
271
+ V,
272
+ I as d
273
+ };
274
+ //# sourceMappingURL=types-24A9Qoxb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-24A9Qoxb.js","sources":["../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/types.ts"],"sourcesContent":["/**\n * Concrete ProtocolParams reader using viem's readContract and multicall.\n *\n * This is an optional utility — callers can use their own implementation\n * of the ProtocolParamsReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport {\n assertValidOffchainParamsVersion,\n validateOffchainParams,\n validatePegInConfiguration,\n validateTBVProtocolParams,\n} from \"./protocol-params-validation\";\nimport type {\n AllOffchainParamsData,\n OnSkippedOffchainParamsVersion,\n PegInConfiguration,\n ProtocolParamsReader,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16. btc-vault carries the PegIn timelock as\n * a `NonZeroU16` (`transactions/pegin.rs:33` @ ac4954e7), so a larger\n * `timelockAssert` has no protocol-side representation.\n */\nconst UINT16_MAX = 65535;\n\n// Decodes deployments that predate `maxFundingInputCount`, including those that also predate `peginActivationDelay`; delete it once every network returns 8 fields.\nconst PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI = [\n {\n type: \"function\",\n name: \"getTBVProtocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct IProtocolParams.TBVProtocolParams\",\n components: [\n {\n name: \"minimumPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInAckTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInActivationTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxHtlcOutputCount\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"expiredPegInGraceBlocks\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n\n/**\n * Raw shape viem returns for VersionedOffchainParams struct.\n * viem resolves ABI struct outputs to named objects (not tuples).\n */\ninterface RawOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: readonly Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/** Raw shape viem returns for TBVProtocolParams struct. */\ninterface RawTBVParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n maxFundingInputCount: number;\n}\n\ntype RawPreFundingInputCapTBVParams = Omit<\n RawTBVParams,\n \"maxFundingInputCount\"\n>;\n\ntype MulticallEntry =\n | { status: \"success\"; result: unknown }\n | { status: \"failure\"; error: Error };\n\nfunction requireSuccess(entry: MulticallEntry): unknown {\n if (entry.status === \"failure\") {\n throw entry.error;\n }\n return entry.result;\n}\n\n/** Map viem struct result to VersionedOffchainParams. */\nfunction mapOffchainParams(result: RawOffchainParams): VersionedOffchainParams {\n return {\n timelockAssert: result.timelockAssert,\n timelockChallengeAssert: result.timelockChallengeAssert,\n securityCouncilKeys: [...result.securityCouncilKeys],\n councilQuorum: result.councilQuorum,\n feeRate: result.feeRate,\n babeTotalInstances: result.babeTotalInstances,\n babeInstancesToFinalize: result.babeInstancesToFinalize,\n minVpCommissionBps: result.minVpCommissionBps,\n tRefund: result.tRefund,\n tStale: result.tStale,\n minPeginFeeRate: result.minPeginFeeRate,\n proverCircuitVersion: result.proverCircuitVersion,\n minPrepeginDepth: result.minPrepeginDepth,\n };\n}\n\n/** Map viem struct result to TBVProtocolParams. */\nfunction mapTBVParams(\n result: RawPreFundingInputCapTBVParams,\n maxFundingInputCount: number | null,\n): TBVProtocolParams {\n return {\n minimumPegInAmount: result.minimumPegInAmount,\n maxPegInAmount: result.maxPegInAmount,\n pegInAckTimeout: result.pegInAckTimeout,\n pegInActivationTimeout: result.pegInActivationTimeout,\n maxHtlcOutputCount: result.maxHtlcOutputCount,\n expiredPegInGraceBlocks: result.expiredPegInGraceBlocks,\n maxFundingInputCount,\n };\n}\n\nfunction resolveTBVParams(\n withFundingInputCap: MulticallEntry,\n preFundingInputCap: MulticallEntry,\n): TBVProtocolParams {\n if (withFundingInputCap.status === \"success\") {\n const raw = withFundingInputCap.result as RawTBVParams;\n return mapTBVParams(raw, raw.maxFundingInputCount);\n }\n if (preFundingInputCap.status === \"success\") {\n return mapTBVParams(\n preFundingInputCap.result as RawPreFundingInputCapTBVParams,\n null,\n );\n }\n throw withFundingInputCap.error;\n}\n\n/**\n * Derive timelockPegin from timelockAssert.\n *\n * btc-vault uses `timelock_assert` as the PegIn timelock (vaultd\n * `pegin_babe_setup.rs:794` @ ac4954e7) and carries it as a `NonZeroU16`\n * (`transactions/pegin.rs:33`).\n * `ProtocolParams.sol:510-512` @ c559f5c2 rejects a zero or above-uint16\n * `timelockAssert` on write; the upper bound is enforced again here so a bad\n * read fails early instead of truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nexport function deriveTimelockPegin(timelockAssert: bigint): number {\n if (timelockAssert > BigInt(UINT16_MAX)) {\n throw new Error(\n `timelockAssert value ${timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n return Number(timelockAssert);\n}\n\n/**\n * Concrete protocol params reader using viem.\n *\n * Every read method runs the matching validator from\n * `protocol-params-validation` before returning, so callers don't have to\n * remember to validate.\n *\n * Usage:\n * ```ts\n * const reader = new ViemProtocolParamsReader(publicClient, protocolParamsAddress);\n * const config = await reader.getPegInConfiguration();\n * ```\n */\nexport class ViemProtocolParamsReader implements ProtocolParamsReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getTBVProtocolParams(): Promise<TBVProtocolParams> {\n const [withFundingInputCap, preFundingInputCap] =\n await this.publicClient.multicall({\n contracts: this.tbvParamsCalls(),\n allowFailure: true,\n });\n\n const params = resolveTBVParams(withFundingInputCap, preFundingInputCap);\n validateTBVProtocolParams(params);\n return params;\n }\n\n private tbvParamsCalls() {\n return [\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\n {\n address: this.contractAddress,\n abi: PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI,\n functionName: \"getTBVProtocolParams\",\n },\n ] as const;\n }\n\n async getLatestOffchainParams(): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getOffchainParamsByVersion(\n version: number,\n ): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getOffchainParamsByVersion\",\n args: [version],\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getLatestOffchainParamsVersion(): Promise<number> {\n const raw = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n });\n const version = Number(raw);\n assertValidOffchainParamsVersion(version);\n return version;\n }\n\n async getTimelockPeginByVersion(version: number): Promise<number> {\n const params = await this.getOffchainParamsByVersion(version);\n return deriveTimelockPegin(params.timelockAssert);\n }\n\n /**\n * Returned as `bigint` with no `Number` narrowing: the registry compares it\n * against `block.number`, so callers must do the same arithmetic the\n * contract does. `0` is the documented \"disabled\" case and is returned as\n * `0n`. A missing getter or a non-bigint payload throws — never coerced to\n * `0`, which would fail open and skip the observation window.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n async getPeginActivationDelay(): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"peginActivationDelay\",\n });\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid peginActivationDelay from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n }\n\n /**\n * Read TBV protocol params, latest offchain params, and the latest version\n * label atomically via multicall. The version is paired with the params so\n * that a governance update between separate reads cannot let JS build BTC\n * scripts with version N params while the contract registers the vault\n * under version N+1.\n *\n * That guarantee holds only within this multicall. A caller that also reads\n * participant keys — every fresh peg-in build does — must pass the same\n * `blockNumber` here and to those reads, or the two describe different\n * blocks and the pairing above buys nothing across the seam.\n */\n async getPegInConfiguration(\n blockNumber?: bigint,\n ): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\n blockNumber,\n contracts: [\n ...this.tbvParamsCalls(),\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"activeVaultCoreVersion\",\n },\n ],\n allowFailure: true,\n });\n\n const tbvParams = resolveTBVParams(results[0], results[1]);\n const offchainParams = mapOffchainParams(\n requireSuccess(results[2]) as RawOffchainParams,\n );\n const offchainParamsVersion = Number(requireSuccess(results[3]));\n const activeVaultCoreVersion = Number(requireSuccess(results[4]));\n\n const config: PegInConfiguration = {\n minimumPegInAmount: tbvParams.minimumPegInAmount,\n maxPegInAmount: tbvParams.maxPegInAmount,\n pegInAckTimeout: tbvParams.pegInAckTimeout,\n pegInActivationTimeout: tbvParams.pegInActivationTimeout,\n maxHtlcOutputCount: tbvParams.maxHtlcOutputCount,\n expiredPegInGraceBlocks: tbvParams.expiredPegInGraceBlocks,\n maxFundingInputCount: tbvParams.maxFundingInputCount,\n timelockPegin: deriveTimelockPegin(offchainParams.timelockAssert),\n timelockRefund: offchainParams.tRefund,\n minVpCommissionBps: offchainParams.minVpCommissionBps,\n offchainParams,\n offchainParamsVersion,\n activeVaultCoreVersion,\n };\n\n validatePegInConfiguration(config);\n return config;\n }\n\n /**\n * Fetch every historical offchain params version in a single multicall.\n * Iterates 1..latestVersion and calls `getOffchainParamsByVersion` for each.\n * Versions whose payload fails validation are skipped (not included in the\n * returned map) so a single bad historical version doesn't block the\n * lookup of the rest.\n *\n * @param onSkippedVersion - optional observer invoked once per skipped\n * version. Use to log/telemeter without coupling the SDK to a logger.\n */\n async fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData> {\n const latestVersion = await this.getLatestOffchainParamsVersion();\n if (latestVersion === 0) {\n return { byVersion: new Map(), latestVersion: 0 };\n }\n\n const versions = Array.from({ length: latestVersion }, (_, i) => i + 1);\n const contracts = versions.map((v) => ({\n address: this.contractAddress,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOffchainParamsByVersion\" as const,\n args: [v] as const,\n }));\n\n const results = await this.publicClient.multicall({\n contracts,\n allowFailure: false,\n });\n\n const byVersion = new Map<number, VersionedOffchainParams>();\n for (let i = 0; i < versions.length; i++) {\n const params = mapOffchainParams(results[i] as RawOffchainParams);\n try {\n validateOffchainParams(params);\n byVersion.set(versions[i], params);\n } catch (error) {\n // A malformed historical version mustn't block lookup of the rest.\n // Surface the skip to the caller's observer if one was supplied.\n onSkippedVersion?.(\n versions[i],\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n\n return { byVersion, latestVersion };\n }\n}\n","/**\n * Types and interfaces for ETH contract readers.\n *\n * These are optional utilities — callers can use them or build their own.\n * Core service functions never import from this module.\n */\n\nimport type { Address, Hex } from \"viem\";\n\n// ============================================================================\n// Vault Registry Types\n// ============================================================================\n\ndeclare const onChainBtcPubkeyBrand: unique symbol;\n\n/**\n * 64-char lowercase hex (no `0x`) x-only BTC pubkey sourced from an on-chain\n * registry. Minted only by `assertOnChainBtcPubkey`, which is the shared\n * validator behind both producers:\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey} (the fixed\n * registration key) and {@link OperationKeyReader} (RFC-006 operation keys,\n * resolved current or at a vault's frozen epoch).\n *\n * @stability frozen\n */\nexport type OnChainBtcPubkey = string & {\n readonly [onChainBtcPubkeyBrand]: true;\n};\n\n/**\n * Mirrors `IBTCVaultRegistry.BTCVaultStatus` in BTCVaultRegistry.sol exactly.\n * Use this when consuming `status` from `getVaultBasicInfo` /\n * `getBtcVaultBasicInfo`.\n *\n * Do NOT confuse with the app-side `ContractStatus` enum\n * (`services/deposit/peginState.ts`) — that one is for the indexer and\n * extends this with values 5-7, reassigning 4 to LIQUIDATED. Reading an\n * on-chain status through `ContractStatus[n]` for labels will mislabel\n * Expired(4) as LIQUIDATED.\n */\nexport enum OnChainBtcVaultStatus {\n PENDING = 0,\n VERIFIED = 1,\n ACTIVE = 2,\n REDEEMED = 3,\n EXPIRED = 4,\n}\n\n/** Basic vault info from BTCVaultRegistry.getBtcVaultBasicInfo */\nexport interface VaultBasicInfo {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n}\n\n/** Protocol info from BTCVaultRegistry.getBtcVaultProtocolInfo */\nexport interface VaultProtocolInfo {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n /**\n * ETH block number stamped at the Pending→Verified transition.\n * Compared against `block.number` (inclusive:\n * `block.number >= verifiedAt + peginActivationDelay`), never a unix timestamp.\n */\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n /**\n * Last ETH block (inclusive) at which `claimExpiredVault` is accepted for\n * this vault. Frozen when the vault is reported expired, as that block plus\n * `expiredPegInGraceBlocks`; zero until then. Only meaningful for a vault\n * that expired after reaching Verified (`verifiedAt > 0`) — the contract\n * rejects the claim for any other.\n */\n claimExpiredUntil: bigint;\n /** Vault core version (uint16) stamped at registration. VP-side gating only — see #1690. */\n vaultCoreVersion: number;\n}\n\n/** Combined vault data (basic + protocol) */\nexport interface VaultData {\n basic: VaultBasicInfo;\n protocol: VaultProtocolInfo;\n}\n\n/**\n * One vault's `PegInSubmittedV2` registration log, decoded.\n *\n * The registry discards several of these values after using them\n * (`maxAcceptableCommissionBps` is bound-checked and dropped), so the log is\n * their only on-chain source. Decoded leniently — no transaction is parsed and\n * no script is bound-checked here, so one malformed registration elsewhere in\n * the block cannot fail an unrelated caller's read; the strict per-record\n * checks live in `registration-records.ts` and run on selected records only.\n * That leniency stops at duplicates: a vault registers once, so two logs for\n * any vault id are an inconsistent node and fail the whole block's read\n * closed.\n *\n * @experimental\n */\nexport interface PeginRegistrationRecord {\n /** Lowercase, `0x`-prefixed. */\n vaultId: Hex;\n depositor: Address;\n vaultProvider: Address;\n /** btc-vault `pegin_amount`, satoshis. */\n amount: bigint;\n vaultCoreVersion: number;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n proverCircuitVersion: number;\n offchainParamsVersion: number;\n /**\n * The event's own `peginTxHash`: the txid of this vault's depositor-signed\n * PegIn, which with `depositor` re-derives the vault id. Per-vault, unlike\n * {@link PeginRegistrationRecord.unsignedPrePeginTx}, which siblings share.\n */\n peginTxHash: Hex;\n /**\n * The event's `depositorPayoutBtcAddress` bytes: the depositor's payout\n * scriptPubKey as `submitPeginRequest` received it (BTCVaultRegistry.sol\n * documents the parameter as \"BTC payout address (scriptPubKey)\"; the SDK\n * registers the validated scriptPubKey there). Lowercase, `0x`-prefixed.\n */\n depositorPayoutScriptPubKey: Hex;\n /**\n * The log's `unsignedPrePeginTx`, verbatim. Its txid\n * (`registrationPrePeginTxHash`) equals\n * {@link VaultProtocolInfo.prePeginTxHash}; siblings of one batch share it,\n * while the event's own `peginTxHash` is the per-vault PegIn id.\n */\n unsignedPrePeginTx: Hex;\n maxAcceptableCommissionBps: number;\n blockNumber: bigint;\n}\n\n/**\n * A vault's finalized `VaultClaimableBy` log for one claimer key.\n *\n * `blockNumber` is what the artifacts file records as\n * `claimable_event_block_number`, the block the prover proves against.\n *\n * @experimental\n */\nexport interface VaultClaimableByEvent {\n blockNumber: bigint;\n /** The `claimerPK` topic, validated as an x-only key. */\n claimerPk: OnChainBtcPubkey;\n peginTxHash: Hex;\n vaultCoreVersion: number;\n proverCircuitVersion: number;\n offchainParamsVersion: number;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n}\n\n/**\n * RFC-006 operation-key epochs a vault froze at `submitPeginRequest`.\n *\n * Each registry keeps a monotonic epoch counter that every key/payout setter\n * pre-increments. A vault stamps the counters live at its creation, and every\n * participant resolves \"which key did this vault bond?\" by asking the registry\n * for the key whose appended version is the latest stamped `<=` this epoch. A\n * rotation after the vault was created therefore never moves its keys.\n *\n * `uint64` — kept as `bigint` end-to-end and passed straight back to the\n * `...AtEpoch` getters, never narrowed through `Number`.\n *\n * Only ever read through {@link VaultRegistryReader.getVaultKeyEpochs}, which\n * uses the extended ABI. See `BTCVaultRegistryKeyEpochs.abi.ts` for why that\n * read is quarantined to its own ABI.\n */\nexport interface KeyEpochs {\n vpKeyEpoch: bigint;\n appKeeperKeyEpoch: bigint;\n ucKeyEpoch: bigint;\n}\n\n/** Interface for reading vault data from the BTCVaultRegistry contract. */\nexport interface VaultRegistryReader {\n getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo>;\n getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo>;\n getProtocolInfoBatch(vaultIds: readonly Hex[]): Promise<VaultProtocolInfo[]>;\n getVaultData(vaultId: Hex): Promise<VaultData>;\n /**\n * Read a vault provider's *genesis* (registration) BTC key — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Used only as the genesis fallback for epoch-based resolution and as a\n * candidate when cross-checking an indexer hint. Never the key to build a\n * Bitcoin lock with; that comes from `OperationKeyReader`.\n *\n * Resolves via `getOperationBtcKeyAtEpoch` at epoch 0, so it requires an\n * RFC-006 registry — as does every caller.\n */\n getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the vault provider operation key selected by an RFC-006 epoch.\n * Existing-vault consumers pass the vault's frozen `vpKeyEpoch` here so a\n * later rotation cannot move the result.\n */\n getVaultProviderOperationBtcKeyAtEpoch(\n vpAddress: Address,\n epoch: bigint,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /** Read the protocol pegin fee (in wei) for a given vault provider. */\n getPegInFee(vaultProvider: Address): Promise<bigint>;\n /**\n * Read a vault provider's current commission in basis points.\n *\n * Validates the contract-enforced `[0, 9999]` range — an out-of-range\n * value signals a wrong contract address or ABI drift, not a real rate.\n */\n getVaultProviderCommission(vaultProvider: Address): Promise<number>;\n /**\n * Read a vault's frozen RFC-006 key epochs.\n *\n * Uses the extended `getBtcVaultProtocolInfo` ABI. Against a registry whose\n * `BTCVaultProtocolInfo` struct is not extended this returns silent garbage\n * for a populated vault rather than throwing, so it must only be called\n * against an RFC-006 registry — a deployment invariant, not something this\n * call can detect. A registry missing the operation-key getters altogether is\n * the safer case: key resolution reverts downstream and these epochs are never\n * used. See `BTCVaultRegistryKeyEpochs.abi.ts`.\n */\n getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs>;\n /** {@link getVaultKeyEpochs} for many vaults in one multicall. */\n getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]>;\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key — the key its\n * server uses for the JSON-RPC token subject. Falls back to the registration\n * key when the provider has never rotated.\n */\n getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the depositor's commission ceiling (`maxAcceptableCommissionBps`)\n * for vaults registered in the same block `createdAt`, from their\n * `PegInSubmittedV2` logs, in `vaultIds` order. The contract discards the\n * ceiling after bound-checking it, so the log is its only on-chain source.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all, with none\n * for a vault asked for, or with V1 logs only — the registry emits both\n * shapes together, so every one of those can be a partial answer.\n * @throws when a vault has more than one V2 log.\n */\n getMaxAcceptableCommissionBpsBatch(\n vaultIds: readonly Hex[],\n createdAt: bigint,\n ): Promise<number[]>;\n /**\n * Decode every `PegInSubmittedV2` registration in block `createdAt`, the\n * `block.number` stamped on the vault at registration. One query at exactly\n * that block, so no range scan is needed and public-RPC range caps do not\n * apply. Records are keyed by lowercase vault id; use\n * `findRegistrationRecord` to pick one.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all, or with V1\n * registrations only — the registry emits both shapes together, so either\n * can be a partial answer.\n * @throws when a vault has more than one V2 log. Records are decoded\n * leniently: no transaction is parsed and no script is bound-checked here\n * (see `registration-records.ts`).\n */\n getRegistrationRecordsAtBlock(\n createdAt: bigint,\n ): Promise<PeginRegistrationRecord[]>;\n /**\n * The vault's finalized `VaultClaimableBy` log for `claimerPk` — the\n * redemption that authorized that key to claim, and the block the prover\n * proves against.\n *\n * The event's block is not stored in contract state, so it is found by\n * scanning `eth_getLogs` newest-first from the finalized block\n * (`eth_getBlockByNumber(\"finalized\")`) down to the vault's `createdAt`, in\n * chunks of `VAULT_CLAIMABLE_BY_QUERY_CHUNK_BLOCKS`, filtered on the indexed\n * `vaultId` and `claimerPK` topics. A redeem in the last chunk costs one\n * request; an older one costs one request per chunk. The bound is\n * finalized, not latest, because the block returned is what the prover\n * proves against (`claimable_event_block_number`) and an unfinalized redeem\n * can reorg away — the same bound btc-vault's reader uses\n * (`eth-client/src/client.rs:5989-6040`, `FinalityLevel::Finalized` default\n * `config.rs:11-21`).\n *\n * A REDEEMED vault can legitimately have no log for the depositor:\n * `redeemForAVK` (RedeemLogic.sol) authorizes the vault keeper alone.\n *\n * @throws {VaultClaimableByNotFoundError} (typed) when no log exists in\n * `createdAt..finalized` — the vault is not redeemed for that key, the\n * redeem is not finalized yet, or the node did not serve the block. The\n * last case is indistinguishable here, so a caller that knows the vault is\n * redeemed for this key owns the retry (as\n * `getMaxAcceptableCommissionBpsFromChainWithGrace` does in the vault app);\n * point the read at a node that serves whole blocks, not a load balancer.\n * @throws when matching logs span more than one transaction (a vault is\n * redeemed once), or `claimerPk` is not an x-only key on the curve.\n */\n getVaultClaimableBy(\n vaultId: Hex,\n claimerPk: Hex,\n createdAt: bigint,\n ): Promise<VaultClaimableByEvent>;\n /**\n * Read the application entry point a vault provider is registered for.\n *\n * The peg-in submit path resolves this internally and uses it to pick the\n * keeper roster, the roster version and the keeper key epoch a deposit is\n * bonded to. Pass `blockNumber` when the result will shape a Bitcoin lock,\n * so it describes the same block as the roster reads that follow it.\n */\n getVaultProviderApplication(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<Address>;\n}\n\n// ============================================================================\n// Protocol Params Types (from IProtocolParams.sol)\n// ============================================================================\n\n/**\n * TBV protocol parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.TBVProtocolParams`, except\n * `peginActivationDelay`, which is surfaced via `getPeginActivationDelay()`\n * rather than on this type.\n *\n * All uint64 amounts use bigint (satoshi values can exceed 2^53).\n * uint8 uses number (bounded, max 255).\n */\nexport interface TBVProtocolParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n /**\n * Number of blocks added to the activation deadline as a grace window\n * during which a depositor may still reclaim an expired pegin via the\n * HTLC preimage. Source: `IProtocolParams.TBVProtocolParams.expiredPegInGraceBlocks`.\n */\n expiredPegInGraceBlocks: bigint;\n /**\n * Maximum number of funding inputs one Pre-PegIn may spend; the contract\n * rejects a Pre-PegIn with more. Source:\n * `IProtocolParams.TBVProtocolParams.maxFundingInputCount`. `null` means the\n * deployed ProtocolParams predates `maxFundingInputCount` and enforces no\n * funding-input bound.\n */\n maxFundingInputCount: number | null;\n}\n\n/**\n * Versioned offchain parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.VersionedOffchainParams` exactly.\n *\n * bigint for: uint256 timelocks, uint64 fee rates/amounts.\n * number for: uint8/uint16/uint32 fields (bounded, safe for JS arithmetic).\n */\nexport interface VersionedOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/**\n * Combined peg-in configuration read atomically via multicall.\n * Prevents TOCTOU inconsistency if governance updates params between reads.\n */\nexport interface PegInConfiguration {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n maxFundingInputCount: number | null;\n timelockPegin: number;\n timelockRefund: number;\n minVpCommissionBps: number;\n offchainParams: VersionedOffchainParams;\n /**\n * Version label paired atomically with `offchainParams`.\n * Read in the same multicall as the params struct so that, if a parameter\n * update lands between separate reads, the script-construction code and\n * the version label stay consistent.\n */\n offchainParamsVersion: number;\n /**\n * Currently-active vault core (tx-graph) version\n * (`ProtocolParams.activeVaultCoreVersion()`, uint16 ≥ 1). Stamped onto\n * every new vault at peg-in submission; fresh deposits must build this\n * graph version. Read in the same multicall so a governance version bump\n * can't land between reading the params and reading the version.\n */\n activeVaultCoreVersion: number;\n}\n\n/**\n * All offchain params snapshots indexed by version, plus the latest version\n * number known when the snapshot was taken. Used by consumers that need to\n * resolve any historical version (e.g. signing for an existing vault locked\n * to an older version).\n */\nexport interface AllOffchainParamsData {\n byVersion: Map<number, VersionedOffchainParams>;\n latestVersion: number;\n}\n\n/**\n * Optional observer invoked by `fetchAllOffchainParams` when a historical\n * version fails validation. Called once per skipped version so callers can\n * log/telemeter without coupling the SDK to a specific logger.\n */\nexport type OnSkippedOffchainParamsVersion = (\n version: number,\n error: Error,\n) => void;\n\n/** Interface for reading protocol parameters from the ProtocolParams contract. */\nexport interface ProtocolParamsReader {\n getTBVProtocolParams(): Promise<TBVProtocolParams>;\n getOffchainParamsByVersion(version: number): Promise<VersionedOffchainParams>;\n getLatestOffchainParams(): Promise<VersionedOffchainParams>;\n getLatestOffchainParamsVersion(): Promise<number>;\n getTimelockPeginByVersion(version: number): Promise<number>;\n /**\n * Pass `blockNumber` when the result will shape a Bitcoin lock, so this\n * multicall and the participant-key reads describe the same block. Omit it\n * for display-only reads, where a slightly stale value is harmless.\n */\n getPegInConfiguration(blockNumber?: bigint): Promise<PegInConfiguration>;\n /**\n * Observation window enforced between a vault's final ACK and its\n * activation, in ETH blocks measured from `verifiedAt`. `0` disables it.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n getPeginActivationDelay(): Promise<bigint>;\n fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData>;\n}\n\n// ============================================================================\n// Signer-Set Types (from BTCVaultTypes.sol)\n// ============================================================================\n\n/**\n * Matches Solidity struct `BTCVaultTypes.AddressBTCKeyPair` exactly.\n * Used for vault keepers and universal challengers.\n */\nexport interface AddressBTCKeyPair {\n ethAddress: Address;\n btcPubKey: Hex;\n}\n\n/**\n * Interface for reading vault keepers from the ApplicationRegistry contract.\n *\n * The reads used to build a peg-in — here and on the sibling reader interfaces\n * — take an optional `blockNumber` that pins them to one block instead of\n * `latest`. Omitting it, the historical behaviour, is correct for every read\n * that resolves against a vault's already-frozen epochs, because those are\n * immutable once stamped. It is NOT correct for a fresh peg-in build: the\n * participant keys, roster versions and protocol params that shape the Bitcoin\n * lock must all describe the same block, or the lock commits to a mixture of\n * chain states that never existed at once. See\n * `services/deposit/validateOnChainParticipantKeys`.\n *\n * The `getCurrent*` roster reads are the exception and take no block. Nothing\n * on the build path uses them — it resolves rosters by version instead — so\n * they were left alone rather than given a pin no caller would pass.\n */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number>;\n /**\n * Read the application's current vault-keeper operation-key epoch.\n *\n * One counter for the whole application, bumped by any keeper's\n * operation-key or payout-script append. The peg-in config fingerprint\n * commits to it in place of the N resolved keeper keys, so it must be read\n * at the same block as the roster it labels. Returned as `bigint`; the\n * contract encodes it as `uint64` and a `Number` would truncate.\n */\n getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(blockNumber?: bigint): Promise<number>;\n /**\n * Read the protocol's current universal-challenger operation-key epoch.\n *\n * The challenger-axis counterpart to\n * {@link VaultKeeperReader.getCurrentAppKeeperKeyEpoch}: one protocol-wide\n * counter the fingerprint commits to in place of the M resolved challenger\n * keys. Returned as `bigint` for the same `uint64` reason.\n */\n getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint>;\n}\n\n// ============================================================================\n// RFC-006 Operation-Key Types\n// ============================================================================\n\n/**\n * The participants whose operation keys are being resolved, and the roster\n * they are resolved against.\n *\n * A roster entry's `ethAddress` is the operator's **admin** address — the\n * lookup key for its key history — and its `btcPubKey` is the operator's\n * **genesis** key. Both are needed: the `...AtEpochOrGenesis` getters take the\n * roster key explicitly because the correct genesis for a keeper/challenger is\n * its key in the vault's *frozen membership version*, which an operator that\n * was later dropped from the roster no longer has a current entry for.\n */\nexport interface OperationKeyQuery {\n vaultProviderEthAddress: Address;\n /**\n * The VP's genesis (registration) key, from\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey}.\n *\n * The VP has no roster entry to carry a genesis key the way keepers and\n * challengers do, so it is supplied here. Every call site already reads it:\n * it is what the indexer hint is compared against, and what makes the VP's\n * `rotated` flag mean the same thing as everyone else's.\n */\n vaultProviderGenesisBtcPubkey: Hex;\n applicationEntryPoint: Address;\n /** Keeper roster at the membership version being resolved against. */\n vaultKeepers: readonly AddressBTCKeyPair[];\n /** Challenger roster at the membership version being resolved against. */\n universalChallengers: readonly AddressBTCKeyPair[];\n}\n\n/** Raw registry-returned operation keys, index-aligned with the query rosters. */\nexport interface RawOperationKeys {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n universalChallengers: Hex[];\n}\n\n/**\n * Registry-returned payout scriptPubKeys, index-aligned with the query\n * rosters. `universalChallengers` has no counterpart: a UC is never a claimer,\n * so it has no payout script.\n */\nexport interface RawPayoutScripts {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts across all three registries\n * (BTCVaultRegistry, ApplicationRegistry, ProtocolParams).\n *\n * Every method resolves the whole participant set in a **single** multicall so\n * the keys are pinned to one block. That atomicity is load-bearing: a rotation\n * landing between two `eth_call`s would yield a self-inconsistent key set that\n * builds a lock no counterparty agrees with.\n */\nexport interface OperationKeyReader {\n /**\n * Resolve every participant's *current* operation key.\n *\n * Used for new peg-ins. The VP-only current getter separately supplies the\n * JSON-RPC auth pin. Needs no epoch read at all — each registry's\n * `getCurrentOperationBtcKey` resolves its own genesis fallback, so an\n * operator that never rotated yields its registration key.\n */\n getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve every participant's operation key bonded at a vault's frozen\n * epochs. Used for every existing-vault path (resume, payout, refund).\n */\n getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve the VP's commission payout script and each keeper's payout script\n * at a vault's frozen epochs.\n *\n * The registry backfills BIP-86 P2TR of the epoch's operation key for any\n * operator that never called `setPayoutScript`, so this returns byte-identical\n * results to local BIP-86 derivation until an operator registers a custom\n * script.\n */\n getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts>;\n}\n"],"names":["UINT16_MAX","PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI","requireSuccess","entry","mapOffchainParams","result","mapTBVParams","maxFundingInputCount","resolveTBVParams","withFundingInputCap","preFundingInputCap","raw","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","params","validateTBVProtocolParams","ProtocolParamsABI","validateOffchainParams","version","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":";;AA8BA,MAAMA,IAAa,OAGbC,IAAuC;AAAA,EAC3C;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,QAAQ,CAAA;AAAA,IACR,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,QACd,YAAY;AAAA,UACV;AAAA,YACE,MAAM;AAAA,YACN,MAA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AAK;AAAA,MACd,KAAKlB;AAAA,MACL,cAAc;AAAA,MACd,MAAM,CAACkB,CAAC;AAAA,IAAA,EACR,GAEIb,IAAU,MAAM,KAAK,aAAa,UAAU;AAAA,MAChD,WAAAY;AAAA,MACA,cAAc;AAAA,IAAA,CACf,GAEKE,wBAAgB,IAAA;AACtB,aAAS,IAAI,GAAG,IAAIL,EAAS,QAAQ,KAAK;AACxC,YAAMhB,IAASb,EAAkBoB,EAAQ,CAAC,CAAsB;AAChE,UAAI;AACF,QAAAJ,EAAuBH,CAAM,GAC7BqB,EAAU,IAAIL,EAAS,CAAC,GAAGhB,CAAM;AAAA,MACnC,SAASsB,GAAO;AAGd,QAAAR,KAAA,QAAAA;AAAA,UACEE,EAAS,CAAC;AAAA,UACVM,aAAiB,QAAQA,IAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC;AAAA;AAAA,MAE5D;AAAA,IACF;AAEA,WAAO,EAAE,WAAAD,GAAW,eAAAN,EAAA;AAAA,EACtB;AACF;ACpYO,IAAKQ,sBAAAA,OACVA,EAAAA,EAAA,UAAU,CAAA,IAAV,WACAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YACAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UACAA,EAAAA,EAAA,WAAW,CAAA,IAAX,YACAA,EAAAA,EAAA,UAAU,CAAA,IAAV,WALUA,IAAAA,KAAA,CAAA,CAAA;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const r=require("./ProtocolParams.abi-BgEZaQ2I.cjs"),s=require("./registration-records-XQMIKjGV.cjs"),p=65535,h=[{type:"function",name:"getTBVProtocolParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.TBVProtocolParams",components:[{name:"minimumPegInAmount",type:"uint64",internalType:"uint64"},{name:"maxPegInAmount",type:"uint64",internalType:"uint64"},{name:"pegInAckTimeout",type:"uint64",internalType:"uint64"},{name:"pegInActivationTimeout",type:"uint64",internalType:"uint64"},{name:"maxHtlcOutputCount",type:"uint8",internalType:"uint8"},{name:"expiredPegInGraceBlocks",type:"uint64",internalType:"uint64"}]}],stateMutability:"view"}];function f(t){if(t.status==="failure")throw t.error;return t.result}function u(t){return{timelockAssert:t.timelockAssert,timelockChallengeAssert:t.timelockChallengeAssert,securityCouncilKeys:[...t.securityCouncilKeys],councilQuorum:t.councilQuorum,feeRate:t.feeRate,babeTotalInstances:t.babeTotalInstances,babeInstancesToFinalize:t.babeInstancesToFinalize,minVpCommissionBps:t.minVpCommissionBps,tRefund:t.tRefund,tStale:t.tStale,minPeginFeeRate:t.minPeginFeeRate,proverCircuitVersion:t.proverCircuitVersion,minPrepeginDepth:t.minPrepeginDepth}}function d(t,e){return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,maxFundingInputCount:e}}function I(t,e){if(t.status==="success"){const a=t.result;return d(a,a.maxFundingInputCount)}if(e.status==="success")return d(e.result,null);throw t.error}function g(t){if(t>BigInt(p))throw new Error(`timelockAssert value ${t} exceeds uint16 max (${p})`);return Number(t)}class b{constructor(e,a){this.publicClient=e,this.contractAddress=a}async getTBVProtocolParams(){const[e,a]=await this.publicClient.multicall({contracts:this.tbvParamsCalls(),allowFailure:!0}),n=I(e,a);return s.validateTBVProtocolParams(n),n}tbvParamsCalls(){return[{address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:h,functionName:"getTBVProtocolParams"}]}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),a=u(e);return s.validateOffchainParams(a),a}async getOffchainParamsByVersion(e){const a=await this.publicClient.readContract({address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=u(a);return s.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),a=Number(e);return s.assertValidOffchainParamsVersion(a),a}async getTimelockPeginByVersion(e){const a=await this.getOffchainParamsByVersion(e);return g(a.timelockAssert)}async getPeginActivationDelay(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"peginActivationDelay"});if(typeof e!="bigint")throw new Error(`Invalid peginActivationDelay from contract: must be a bigint, got ${typeof e}`);return e}async getPegInConfiguration(e){const a=await this.publicClient.multicall({blockNumber:e,contracts:[...this.tbvParamsCalls(),{address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"},{address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"activeVaultCoreVersion"}],allowFailure:!0}),n=I(a[0],a[1]),o=u(f(a[2])),l=Number(f(a[3])),c=Number(f(a[4])),i={minimumPegInAmount:n.minimumPegInAmount,maxPegInAmount:n.maxPegInAmount,pegInAckTimeout:n.pegInAckTimeout,pegInActivationTimeout:n.pegInActivationTimeout,maxHtlcOutputCount:n.maxHtlcOutputCount,expiredPegInGraceBlocks:n.expiredPegInGraceBlocks,maxFundingInputCount:n.maxFundingInputCount,timelockPegin:g(o.timelockAssert),timelockRefund:o.tRefund,minVpCommissionBps:o.minVpCommissionBps,offchainParams:o,offchainParamsVersion:l,activeVaultCoreVersion:c};return s.validatePegInConfiguration(i),i}async fetchAllOffchainParams(e){const a=await this.getLatestOffchainParamsVersion();if(a===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:a},(i,m)=>m+1),o=n.map(i=>({address:this.contractAddress,abi:r.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[i]})),l=await this.publicClient.multicall({contracts:o,allowFailure:!1}),c=new Map;for(let i=0;i<n.length;i++){const m=u(l[i]);try{s.validateOffchainParams(m),c.set(n[i],m)}catch(P){e==null||e(n[i],P instanceof Error?P:new Error(String(P)))}}return{byVersion:c,latestVersion:a}}}var A=(t=>(t[t.PENDING=0]="PENDING",t[t.VERIFIED=1]="VERIFIED",t[t.ACTIVE=2]="ACTIVE",t[t.REDEEMED=3]="REDEEMED",t[t.EXPIRED=4]="EXPIRED",t))(A||{});exports.OnChainBtcVaultStatus=A;exports.ViemProtocolParamsReader=b;exports.deriveTimelockPegin=g;
2
+ //# sourceMappingURL=types-BC2TGzcp.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BC2TGzcp.cjs","sources":["../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/types.ts"],"sourcesContent":["/**\n * Concrete ProtocolParams reader using viem's readContract and multicall.\n *\n * This is an optional utility — callers can use their own implementation\n * of the ProtocolParamsReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport {\n assertValidOffchainParamsVersion,\n validateOffchainParams,\n validatePegInConfiguration,\n validateTBVProtocolParams,\n} from \"./protocol-params-validation\";\nimport type {\n AllOffchainParamsData,\n OnSkippedOffchainParamsVersion,\n PegInConfiguration,\n ProtocolParamsReader,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16. btc-vault carries the PegIn timelock as\n * a `NonZeroU16` (`transactions/pegin.rs:33` @ ac4954e7), so a larger\n * `timelockAssert` has no protocol-side representation.\n */\nconst UINT16_MAX = 65535;\n\n// Decodes deployments that predate `maxFundingInputCount`, including those that also predate `peginActivationDelay`; delete it once every network returns 8 fields.\nconst PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI = [\n {\n type: \"function\",\n name: \"getTBVProtocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct IProtocolParams.TBVProtocolParams\",\n components: [\n {\n name: \"minimumPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInAckTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInActivationTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxHtlcOutputCount\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"expiredPegInGraceBlocks\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n\n/**\n * Raw shape viem returns for VersionedOffchainParams struct.\n * viem resolves ABI struct outputs to named objects (not tuples).\n */\ninterface RawOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: readonly Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/** Raw shape viem returns for TBVProtocolParams struct. */\ninterface RawTBVParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n maxFundingInputCount: number;\n}\n\ntype RawPreFundingInputCapTBVParams = Omit<\n RawTBVParams,\n \"maxFundingInputCount\"\n>;\n\ntype MulticallEntry =\n | { status: \"success\"; result: unknown }\n | { status: \"failure\"; error: Error };\n\nfunction requireSuccess(entry: MulticallEntry): unknown {\n if (entry.status === \"failure\") {\n throw entry.error;\n }\n return entry.result;\n}\n\n/** Map viem struct result to VersionedOffchainParams. */\nfunction mapOffchainParams(result: RawOffchainParams): VersionedOffchainParams {\n return {\n timelockAssert: result.timelockAssert,\n timelockChallengeAssert: result.timelockChallengeAssert,\n securityCouncilKeys: [...result.securityCouncilKeys],\n councilQuorum: result.councilQuorum,\n feeRate: result.feeRate,\n babeTotalInstances: result.babeTotalInstances,\n babeInstancesToFinalize: result.babeInstancesToFinalize,\n minVpCommissionBps: result.minVpCommissionBps,\n tRefund: result.tRefund,\n tStale: result.tStale,\n minPeginFeeRate: result.minPeginFeeRate,\n proverCircuitVersion: result.proverCircuitVersion,\n minPrepeginDepth: result.minPrepeginDepth,\n };\n}\n\n/** Map viem struct result to TBVProtocolParams. */\nfunction mapTBVParams(\n result: RawPreFundingInputCapTBVParams,\n maxFundingInputCount: number | null,\n): TBVProtocolParams {\n return {\n minimumPegInAmount: result.minimumPegInAmount,\n maxPegInAmount: result.maxPegInAmount,\n pegInAckTimeout: result.pegInAckTimeout,\n pegInActivationTimeout: result.pegInActivationTimeout,\n maxHtlcOutputCount: result.maxHtlcOutputCount,\n expiredPegInGraceBlocks: result.expiredPegInGraceBlocks,\n maxFundingInputCount,\n };\n}\n\nfunction resolveTBVParams(\n withFundingInputCap: MulticallEntry,\n preFundingInputCap: MulticallEntry,\n): TBVProtocolParams {\n if (withFundingInputCap.status === \"success\") {\n const raw = withFundingInputCap.result as RawTBVParams;\n return mapTBVParams(raw, raw.maxFundingInputCount);\n }\n if (preFundingInputCap.status === \"success\") {\n return mapTBVParams(\n preFundingInputCap.result as RawPreFundingInputCapTBVParams,\n null,\n );\n }\n throw withFundingInputCap.error;\n}\n\n/**\n * Derive timelockPegin from timelockAssert.\n *\n * btc-vault uses `timelock_assert` as the PegIn timelock (vaultd\n * `pegin_babe_setup.rs:794` @ ac4954e7) and carries it as a `NonZeroU16`\n * (`transactions/pegin.rs:33`).\n * `ProtocolParams.sol:510-512` @ c559f5c2 rejects a zero or above-uint16\n * `timelockAssert` on write; the upper bound is enforced again here so a bad\n * read fails early instead of truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nexport function deriveTimelockPegin(timelockAssert: bigint): number {\n if (timelockAssert > BigInt(UINT16_MAX)) {\n throw new Error(\n `timelockAssert value ${timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n return Number(timelockAssert);\n}\n\n/**\n * Concrete protocol params reader using viem.\n *\n * Every read method runs the matching validator from\n * `protocol-params-validation` before returning, so callers don't have to\n * remember to validate.\n *\n * Usage:\n * ```ts\n * const reader = new ViemProtocolParamsReader(publicClient, protocolParamsAddress);\n * const config = await reader.getPegInConfiguration();\n * ```\n */\nexport class ViemProtocolParamsReader implements ProtocolParamsReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getTBVProtocolParams(): Promise<TBVProtocolParams> {\n const [withFundingInputCap, preFundingInputCap] =\n await this.publicClient.multicall({\n contracts: this.tbvParamsCalls(),\n allowFailure: true,\n });\n\n const params = resolveTBVParams(withFundingInputCap, preFundingInputCap);\n validateTBVProtocolParams(params);\n return params;\n }\n\n private tbvParamsCalls() {\n return [\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\n {\n address: this.contractAddress,\n abi: PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI,\n functionName: \"getTBVProtocolParams\",\n },\n ] as const;\n }\n\n async getLatestOffchainParams(): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getOffchainParamsByVersion(\n version: number,\n ): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getOffchainParamsByVersion\",\n args: [version],\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getLatestOffchainParamsVersion(): Promise<number> {\n const raw = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n });\n const version = Number(raw);\n assertValidOffchainParamsVersion(version);\n return version;\n }\n\n async getTimelockPeginByVersion(version: number): Promise<number> {\n const params = await this.getOffchainParamsByVersion(version);\n return deriveTimelockPegin(params.timelockAssert);\n }\n\n /**\n * Returned as `bigint` with no `Number` narrowing: the registry compares it\n * against `block.number`, so callers must do the same arithmetic the\n * contract does. `0` is the documented \"disabled\" case and is returned as\n * `0n`. A missing getter or a non-bigint payload throws — never coerced to\n * `0`, which would fail open and skip the observation window.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n async getPeginActivationDelay(): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"peginActivationDelay\",\n });\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid peginActivationDelay from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n }\n\n /**\n * Read TBV protocol params, latest offchain params, and the latest version\n * label atomically via multicall. The version is paired with the params so\n * that a governance update between separate reads cannot let JS build BTC\n * scripts with version N params while the contract registers the vault\n * under version N+1.\n *\n * That guarantee holds only within this multicall. A caller that also reads\n * participant keys — every fresh peg-in build does — must pass the same\n * `blockNumber` here and to those reads, or the two describe different\n * blocks and the pairing above buys nothing across the seam.\n */\n async getPegInConfiguration(\n blockNumber?: bigint,\n ): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\n blockNumber,\n contracts: [\n ...this.tbvParamsCalls(),\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"activeVaultCoreVersion\",\n },\n ],\n allowFailure: true,\n });\n\n const tbvParams = resolveTBVParams(results[0], results[1]);\n const offchainParams = mapOffchainParams(\n requireSuccess(results[2]) as RawOffchainParams,\n );\n const offchainParamsVersion = Number(requireSuccess(results[3]));\n const activeVaultCoreVersion = Number(requireSuccess(results[4]));\n\n const config: PegInConfiguration = {\n minimumPegInAmount: tbvParams.minimumPegInAmount,\n maxPegInAmount: tbvParams.maxPegInAmount,\n pegInAckTimeout: tbvParams.pegInAckTimeout,\n pegInActivationTimeout: tbvParams.pegInActivationTimeout,\n maxHtlcOutputCount: tbvParams.maxHtlcOutputCount,\n expiredPegInGraceBlocks: tbvParams.expiredPegInGraceBlocks,\n maxFundingInputCount: tbvParams.maxFundingInputCount,\n timelockPegin: deriveTimelockPegin(offchainParams.timelockAssert),\n timelockRefund: offchainParams.tRefund,\n minVpCommissionBps: offchainParams.minVpCommissionBps,\n offchainParams,\n offchainParamsVersion,\n activeVaultCoreVersion,\n };\n\n validatePegInConfiguration(config);\n return config;\n }\n\n /**\n * Fetch every historical offchain params version in a single multicall.\n * Iterates 1..latestVersion and calls `getOffchainParamsByVersion` for each.\n * Versions whose payload fails validation are skipped (not included in the\n * returned map) so a single bad historical version doesn't block the\n * lookup of the rest.\n *\n * @param onSkippedVersion - optional observer invoked once per skipped\n * version. Use to log/telemeter without coupling the SDK to a logger.\n */\n async fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData> {\n const latestVersion = await this.getLatestOffchainParamsVersion();\n if (latestVersion === 0) {\n return { byVersion: new Map(), latestVersion: 0 };\n }\n\n const versions = Array.from({ length: latestVersion }, (_, i) => i + 1);\n const contracts = versions.map((v) => ({\n address: this.contractAddress,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOffchainParamsByVersion\" as const,\n args: [v] as const,\n }));\n\n const results = await this.publicClient.multicall({\n contracts,\n allowFailure: false,\n });\n\n const byVersion = new Map<number, VersionedOffchainParams>();\n for (let i = 0; i < versions.length; i++) {\n const params = mapOffchainParams(results[i] as RawOffchainParams);\n try {\n validateOffchainParams(params);\n byVersion.set(versions[i], params);\n } catch (error) {\n // A malformed historical version mustn't block lookup of the rest.\n // Surface the skip to the caller's observer if one was supplied.\n onSkippedVersion?.(\n versions[i],\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n\n return { byVersion, latestVersion };\n }\n}\n","/**\n * Types and interfaces for ETH contract readers.\n *\n * These are optional utilities — callers can use them or build their own.\n * Core service functions never import from this module.\n */\n\nimport type { Address, Hex } from \"viem\";\n\n// ============================================================================\n// Vault Registry Types\n// ============================================================================\n\ndeclare const onChainBtcPubkeyBrand: unique symbol;\n\n/**\n * 64-char lowercase hex (no `0x`) x-only BTC pubkey sourced from an on-chain\n * registry. Minted only by `assertOnChainBtcPubkey`, which is the shared\n * validator behind both producers:\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey} (the fixed\n * registration key) and {@link OperationKeyReader} (RFC-006 operation keys,\n * resolved current or at a vault's frozen epoch).\n *\n * @stability frozen\n */\nexport type OnChainBtcPubkey = string & {\n readonly [onChainBtcPubkeyBrand]: true;\n};\n\n/**\n * Mirrors `IBTCVaultRegistry.BTCVaultStatus` in BTCVaultRegistry.sol exactly.\n * Use this when consuming `status` from `getVaultBasicInfo` /\n * `getBtcVaultBasicInfo`.\n *\n * Do NOT confuse with the app-side `ContractStatus` enum\n * (`services/deposit/peginState.ts`) — that one is for the indexer and\n * extends this with values 5-7, reassigning 4 to LIQUIDATED. Reading an\n * on-chain status through `ContractStatus[n]` for labels will mislabel\n * Expired(4) as LIQUIDATED.\n */\nexport enum OnChainBtcVaultStatus {\n PENDING = 0,\n VERIFIED = 1,\n ACTIVE = 2,\n REDEEMED = 3,\n EXPIRED = 4,\n}\n\n/** Basic vault info from BTCVaultRegistry.getBtcVaultBasicInfo */\nexport interface VaultBasicInfo {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n}\n\n/** Protocol info from BTCVaultRegistry.getBtcVaultProtocolInfo */\nexport interface VaultProtocolInfo {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n /**\n * ETH block number stamped at the Pending→Verified transition.\n * Compared against `block.number` (inclusive:\n * `block.number >= verifiedAt + peginActivationDelay`), never a unix timestamp.\n */\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n /**\n * Last ETH block (inclusive) at which `claimExpiredVault` is accepted for\n * this vault. Frozen when the vault is reported expired, as that block plus\n * `expiredPegInGraceBlocks`; zero until then. Only meaningful for a vault\n * that expired after reaching Verified (`verifiedAt > 0`) — the contract\n * rejects the claim for any other.\n */\n claimExpiredUntil: bigint;\n /** Vault core version (uint16) stamped at registration. VP-side gating only — see #1690. */\n vaultCoreVersion: number;\n}\n\n/** Combined vault data (basic + protocol) */\nexport interface VaultData {\n basic: VaultBasicInfo;\n protocol: VaultProtocolInfo;\n}\n\n/**\n * One vault's `PegInSubmittedV2` registration log, decoded.\n *\n * The registry discards several of these values after using them\n * (`maxAcceptableCommissionBps` is bound-checked and dropped), so the log is\n * their only on-chain source. Decoded leniently — no transaction is parsed and\n * no script is bound-checked here, so one malformed registration elsewhere in\n * the block cannot fail an unrelated caller's read; the strict per-record\n * checks live in `registration-records.ts` and run on selected records only.\n * That leniency stops at duplicates: a vault registers once, so two logs for\n * any vault id are an inconsistent node and fail the whole block's read\n * closed.\n *\n * @experimental\n */\nexport interface PeginRegistrationRecord {\n /** Lowercase, `0x`-prefixed. */\n vaultId: Hex;\n depositor: Address;\n vaultProvider: Address;\n /** btc-vault `pegin_amount`, satoshis. */\n amount: bigint;\n vaultCoreVersion: number;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n proverCircuitVersion: number;\n offchainParamsVersion: number;\n /**\n * The event's own `peginTxHash`: the txid of this vault's depositor-signed\n * PegIn, which with `depositor` re-derives the vault id. Per-vault, unlike\n * {@link PeginRegistrationRecord.unsignedPrePeginTx}, which siblings share.\n */\n peginTxHash: Hex;\n /**\n * The event's `depositorPayoutBtcAddress` bytes: the depositor's payout\n * scriptPubKey as `submitPeginRequest` received it (BTCVaultRegistry.sol\n * documents the parameter as \"BTC payout address (scriptPubKey)\"; the SDK\n * registers the validated scriptPubKey there). Lowercase, `0x`-prefixed.\n */\n depositorPayoutScriptPubKey: Hex;\n /**\n * The log's `unsignedPrePeginTx`, verbatim. Its txid\n * (`registrationPrePeginTxHash`) equals\n * {@link VaultProtocolInfo.prePeginTxHash}; siblings of one batch share it,\n * while the event's own `peginTxHash` is the per-vault PegIn id.\n */\n unsignedPrePeginTx: Hex;\n maxAcceptableCommissionBps: number;\n blockNumber: bigint;\n}\n\n/**\n * A vault's finalized `VaultClaimableBy` log for one claimer key.\n *\n * `blockNumber` is what the artifacts file records as\n * `claimable_event_block_number`, the block the prover proves against.\n *\n * @experimental\n */\nexport interface VaultClaimableByEvent {\n blockNumber: bigint;\n /** The `claimerPK` topic, validated as an x-only key. */\n claimerPk: OnChainBtcPubkey;\n peginTxHash: Hex;\n vaultCoreVersion: number;\n proverCircuitVersion: number;\n offchainParamsVersion: number;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n}\n\n/**\n * RFC-006 operation-key epochs a vault froze at `submitPeginRequest`.\n *\n * Each registry keeps a monotonic epoch counter that every key/payout setter\n * pre-increments. A vault stamps the counters live at its creation, and every\n * participant resolves \"which key did this vault bond?\" by asking the registry\n * for the key whose appended version is the latest stamped `<=` this epoch. A\n * rotation after the vault was created therefore never moves its keys.\n *\n * `uint64` — kept as `bigint` end-to-end and passed straight back to the\n * `...AtEpoch` getters, never narrowed through `Number`.\n *\n * Only ever read through {@link VaultRegistryReader.getVaultKeyEpochs}, which\n * uses the extended ABI. See `BTCVaultRegistryKeyEpochs.abi.ts` for why that\n * read is quarantined to its own ABI.\n */\nexport interface KeyEpochs {\n vpKeyEpoch: bigint;\n appKeeperKeyEpoch: bigint;\n ucKeyEpoch: bigint;\n}\n\n/** Interface for reading vault data from the BTCVaultRegistry contract. */\nexport interface VaultRegistryReader {\n getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo>;\n getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo>;\n getProtocolInfoBatch(vaultIds: readonly Hex[]): Promise<VaultProtocolInfo[]>;\n getVaultData(vaultId: Hex): Promise<VaultData>;\n /**\n * Read a vault provider's *genesis* (registration) BTC key — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Used only as the genesis fallback for epoch-based resolution and as a\n * candidate when cross-checking an indexer hint. Never the key to build a\n * Bitcoin lock with; that comes from `OperationKeyReader`.\n *\n * Resolves via `getOperationBtcKeyAtEpoch` at epoch 0, so it requires an\n * RFC-006 registry — as does every caller.\n */\n getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the vault provider operation key selected by an RFC-006 epoch.\n * Existing-vault consumers pass the vault's frozen `vpKeyEpoch` here so a\n * later rotation cannot move the result.\n */\n getVaultProviderOperationBtcKeyAtEpoch(\n vpAddress: Address,\n epoch: bigint,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /** Read the protocol pegin fee (in wei) for a given vault provider. */\n getPegInFee(vaultProvider: Address): Promise<bigint>;\n /**\n * Read a vault provider's current commission in basis points.\n *\n * Validates the contract-enforced `[0, 9999]` range — an out-of-range\n * value signals a wrong contract address or ABI drift, not a real rate.\n */\n getVaultProviderCommission(vaultProvider: Address): Promise<number>;\n /**\n * Read a vault's frozen RFC-006 key epochs.\n *\n * Uses the extended `getBtcVaultProtocolInfo` ABI. Against a registry whose\n * `BTCVaultProtocolInfo` struct is not extended this returns silent garbage\n * for a populated vault rather than throwing, so it must only be called\n * against an RFC-006 registry — a deployment invariant, not something this\n * call can detect. A registry missing the operation-key getters altogether is\n * the safer case: key resolution reverts downstream and these epochs are never\n * used. See `BTCVaultRegistryKeyEpochs.abi.ts`.\n */\n getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs>;\n /** {@link getVaultKeyEpochs} for many vaults in one multicall. */\n getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]>;\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key — the key its\n * server uses for the JSON-RPC token subject. Falls back to the registration\n * key when the provider has never rotated.\n */\n getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the depositor's commission ceiling (`maxAcceptableCommissionBps`)\n * for vaults registered in the same block `createdAt`, from their\n * `PegInSubmittedV2` logs, in `vaultIds` order. The contract discards the\n * ceiling after bound-checking it, so the log is its only on-chain source.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all, with none\n * for a vault asked for, or with V1 logs only — the registry emits both\n * shapes together, so every one of those can be a partial answer.\n * @throws when a vault has more than one V2 log.\n */\n getMaxAcceptableCommissionBpsBatch(\n vaultIds: readonly Hex[],\n createdAt: bigint,\n ): Promise<number[]>;\n /**\n * Decode every `PegInSubmittedV2` registration in block `createdAt`, the\n * `block.number` stamped on the vault at registration. One query at exactly\n * that block, so no range scan is needed and public-RPC range caps do not\n * apply. Records are keyed by lowercase vault id; use\n * `findRegistrationRecord` to pick one.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all, or with V1\n * registrations only — the registry emits both shapes together, so either\n * can be a partial answer.\n * @throws when a vault has more than one V2 log. Records are decoded\n * leniently: no transaction is parsed and no script is bound-checked here\n * (see `registration-records.ts`).\n */\n getRegistrationRecordsAtBlock(\n createdAt: bigint,\n ): Promise<PeginRegistrationRecord[]>;\n /**\n * The vault's finalized `VaultClaimableBy` log for `claimerPk` — the\n * redemption that authorized that key to claim, and the block the prover\n * proves against.\n *\n * The event's block is not stored in contract state, so it is found by\n * scanning `eth_getLogs` newest-first from the finalized block\n * (`eth_getBlockByNumber(\"finalized\")`) down to the vault's `createdAt`, in\n * chunks of `VAULT_CLAIMABLE_BY_QUERY_CHUNK_BLOCKS`, filtered on the indexed\n * `vaultId` and `claimerPK` topics. A redeem in the last chunk costs one\n * request; an older one costs one request per chunk. The bound is\n * finalized, not latest, because the block returned is what the prover\n * proves against (`claimable_event_block_number`) and an unfinalized redeem\n * can reorg away — the same bound btc-vault's reader uses\n * (`eth-client/src/client.rs:5989-6040`, `FinalityLevel::Finalized` default\n * `config.rs:11-21`).\n *\n * A REDEEMED vault can legitimately have no log for the depositor:\n * `redeemForAVK` (RedeemLogic.sol) authorizes the vault keeper alone.\n *\n * @throws {VaultClaimableByNotFoundError} (typed) when no log exists in\n * `createdAt..finalized` — the vault is not redeemed for that key, the\n * redeem is not finalized yet, or the node did not serve the block. The\n * last case is indistinguishable here, so a caller that knows the vault is\n * redeemed for this key owns the retry (as\n * `getMaxAcceptableCommissionBpsFromChainWithGrace` does in the vault app);\n * point the read at a node that serves whole blocks, not a load balancer.\n * @throws when matching logs span more than one transaction (a vault is\n * redeemed once), or `claimerPk` is not an x-only key on the curve.\n */\n getVaultClaimableBy(\n vaultId: Hex,\n claimerPk: Hex,\n createdAt: bigint,\n ): Promise<VaultClaimableByEvent>;\n /**\n * Read the application entry point a vault provider is registered for.\n *\n * The peg-in submit path resolves this internally and uses it to pick the\n * keeper roster, the roster version and the keeper key epoch a deposit is\n * bonded to. Pass `blockNumber` when the result will shape a Bitcoin lock,\n * so it describes the same block as the roster reads that follow it.\n */\n getVaultProviderApplication(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<Address>;\n}\n\n// ============================================================================\n// Protocol Params Types (from IProtocolParams.sol)\n// ============================================================================\n\n/**\n * TBV protocol parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.TBVProtocolParams`, except\n * `peginActivationDelay`, which is surfaced via `getPeginActivationDelay()`\n * rather than on this type.\n *\n * All uint64 amounts use bigint (satoshi values can exceed 2^53).\n * uint8 uses number (bounded, max 255).\n */\nexport interface TBVProtocolParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n /**\n * Number of blocks added to the activation deadline as a grace window\n * during which a depositor may still reclaim an expired pegin via the\n * HTLC preimage. Source: `IProtocolParams.TBVProtocolParams.expiredPegInGraceBlocks`.\n */\n expiredPegInGraceBlocks: bigint;\n /**\n * Maximum number of funding inputs one Pre-PegIn may spend; the contract\n * rejects a Pre-PegIn with more. Source:\n * `IProtocolParams.TBVProtocolParams.maxFundingInputCount`. `null` means the\n * deployed ProtocolParams predates `maxFundingInputCount` and enforces no\n * funding-input bound.\n */\n maxFundingInputCount: number | null;\n}\n\n/**\n * Versioned offchain parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.VersionedOffchainParams` exactly.\n *\n * bigint for: uint256 timelocks, uint64 fee rates/amounts.\n * number for: uint8/uint16/uint32 fields (bounded, safe for JS arithmetic).\n */\nexport interface VersionedOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/**\n * Combined peg-in configuration read atomically via multicall.\n * Prevents TOCTOU inconsistency if governance updates params between reads.\n */\nexport interface PegInConfiguration {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n maxFundingInputCount: number | null;\n timelockPegin: number;\n timelockRefund: number;\n minVpCommissionBps: number;\n offchainParams: VersionedOffchainParams;\n /**\n * Version label paired atomically with `offchainParams`.\n * Read in the same multicall as the params struct so that, if a parameter\n * update lands between separate reads, the script-construction code and\n * the version label stay consistent.\n */\n offchainParamsVersion: number;\n /**\n * Currently-active vault core (tx-graph) version\n * (`ProtocolParams.activeVaultCoreVersion()`, uint16 ≥ 1). Stamped onto\n * every new vault at peg-in submission; fresh deposits must build this\n * graph version. Read in the same multicall so a governance version bump\n * can't land between reading the params and reading the version.\n */\n activeVaultCoreVersion: number;\n}\n\n/**\n * All offchain params snapshots indexed by version, plus the latest version\n * number known when the snapshot was taken. Used by consumers that need to\n * resolve any historical version (e.g. signing for an existing vault locked\n * to an older version).\n */\nexport interface AllOffchainParamsData {\n byVersion: Map<number, VersionedOffchainParams>;\n latestVersion: number;\n}\n\n/**\n * Optional observer invoked by `fetchAllOffchainParams` when a historical\n * version fails validation. Called once per skipped version so callers can\n * log/telemeter without coupling the SDK to a specific logger.\n */\nexport type OnSkippedOffchainParamsVersion = (\n version: number,\n error: Error,\n) => void;\n\n/** Interface for reading protocol parameters from the ProtocolParams contract. */\nexport interface ProtocolParamsReader {\n getTBVProtocolParams(): Promise<TBVProtocolParams>;\n getOffchainParamsByVersion(version: number): Promise<VersionedOffchainParams>;\n getLatestOffchainParams(): Promise<VersionedOffchainParams>;\n getLatestOffchainParamsVersion(): Promise<number>;\n getTimelockPeginByVersion(version: number): Promise<number>;\n /**\n * Pass `blockNumber` when the result will shape a Bitcoin lock, so this\n * multicall and the participant-key reads describe the same block. Omit it\n * for display-only reads, where a slightly stale value is harmless.\n */\n getPegInConfiguration(blockNumber?: bigint): Promise<PegInConfiguration>;\n /**\n * Observation window enforced between a vault's final ACK and its\n * activation, in ETH blocks measured from `verifiedAt`. `0` disables it.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n getPeginActivationDelay(): Promise<bigint>;\n fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData>;\n}\n\n// ============================================================================\n// Signer-Set Types (from BTCVaultTypes.sol)\n// ============================================================================\n\n/**\n * Matches Solidity struct `BTCVaultTypes.AddressBTCKeyPair` exactly.\n * Used for vault keepers and universal challengers.\n */\nexport interface AddressBTCKeyPair {\n ethAddress: Address;\n btcPubKey: Hex;\n}\n\n/**\n * Interface for reading vault keepers from the ApplicationRegistry contract.\n *\n * The reads used to build a peg-in — here and on the sibling reader interfaces\n * — take an optional `blockNumber` that pins them to one block instead of\n * `latest`. Omitting it, the historical behaviour, is correct for every read\n * that resolves against a vault's already-frozen epochs, because those are\n * immutable once stamped. It is NOT correct for a fresh peg-in build: the\n * participant keys, roster versions and protocol params that shape the Bitcoin\n * lock must all describe the same block, or the lock commits to a mixture of\n * chain states that never existed at once. See\n * `services/deposit/validateOnChainParticipantKeys`.\n *\n * The `getCurrent*` roster reads are the exception and take no block. Nothing\n * on the build path uses them — it resolves rosters by version instead — so\n * they were left alone rather than given a pin no caller would pass.\n */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number>;\n /**\n * Read the application's current vault-keeper operation-key epoch.\n *\n * One counter for the whole application, bumped by any keeper's\n * operation-key or payout-script append. The peg-in config fingerprint\n * commits to it in place of the N resolved keeper keys, so it must be read\n * at the same block as the roster it labels. Returned as `bigint`; the\n * contract encodes it as `uint64` and a `Number` would truncate.\n */\n getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(blockNumber?: bigint): Promise<number>;\n /**\n * Read the protocol's current universal-challenger operation-key epoch.\n *\n * The challenger-axis counterpart to\n * {@link VaultKeeperReader.getCurrentAppKeeperKeyEpoch}: one protocol-wide\n * counter the fingerprint commits to in place of the M resolved challenger\n * keys. Returned as `bigint` for the same `uint64` reason.\n */\n getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint>;\n}\n\n// ============================================================================\n// RFC-006 Operation-Key Types\n// ============================================================================\n\n/**\n * The participants whose operation keys are being resolved, and the roster\n * they are resolved against.\n *\n * A roster entry's `ethAddress` is the operator's **admin** address — the\n * lookup key for its key history — and its `btcPubKey` is the operator's\n * **genesis** key. Both are needed: the `...AtEpochOrGenesis` getters take the\n * roster key explicitly because the correct genesis for a keeper/challenger is\n * its key in the vault's *frozen membership version*, which an operator that\n * was later dropped from the roster no longer has a current entry for.\n */\nexport interface OperationKeyQuery {\n vaultProviderEthAddress: Address;\n /**\n * The VP's genesis (registration) key, from\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey}.\n *\n * The VP has no roster entry to carry a genesis key the way keepers and\n * challengers do, so it is supplied here. Every call site already reads it:\n * it is what the indexer hint is compared against, and what makes the VP's\n * `rotated` flag mean the same thing as everyone else's.\n */\n vaultProviderGenesisBtcPubkey: Hex;\n applicationEntryPoint: Address;\n /** Keeper roster at the membership version being resolved against. */\n vaultKeepers: readonly AddressBTCKeyPair[];\n /** Challenger roster at the membership version being resolved against. */\n universalChallengers: readonly AddressBTCKeyPair[];\n}\n\n/** Raw registry-returned operation keys, index-aligned with the query rosters. */\nexport interface RawOperationKeys {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n universalChallengers: Hex[];\n}\n\n/**\n * Registry-returned payout scriptPubKeys, index-aligned with the query\n * rosters. `universalChallengers` has no counterpart: a UC is never a claimer,\n * so it has no payout script.\n */\nexport interface RawPayoutScripts {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts across all three registries\n * (BTCVaultRegistry, ApplicationRegistry, ProtocolParams).\n *\n * Every method resolves the whole participant set in a **single** multicall so\n * the keys are pinned to one block. That atomicity is load-bearing: a rotation\n * landing between two `eth_call`s would yield a self-inconsistent key set that\n * builds a lock no counterparty agrees with.\n */\nexport interface OperationKeyReader {\n /**\n * Resolve every participant's *current* operation key.\n *\n * Used for new peg-ins. The VP-only current getter separately supplies the\n * JSON-RPC auth pin. Needs no epoch read at all — each registry's\n * `getCurrentOperationBtcKey` resolves its own genesis fallback, so an\n * operator that never rotated yields its registration key.\n */\n getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve every participant's operation key bonded at a vault's frozen\n * epochs. Used for every existing-vault path (resume, payout, refund).\n */\n getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve the VP's commission payout script and each keeper's payout script\n * at a vault's frozen epochs.\n *\n * The registry backfills BIP-86 P2TR of the epoch's operation key for any\n * operator that never called `setPayoutScript`, so this returns byte-identical\n * results to local BIP-86 derivation until an operator registers a custom\n * script.\n */\n getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts>;\n}\n"],"names":["UINT16_MAX","PRE_FUNDING_INPUT_CAP_TBV_PARAMS_ABI","requireSuccess","entry","mapOffchainParams","result","mapTBVParams","maxFundingInputCount","resolveTBVParams","withFundingInputCap","preFundingInputCap","raw","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","params","validateTBVProtocolParams","ProtocolParamsABI","validateOffchainParams","version","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":"mHA8BMA,EAAa,MAG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 +1,6 @@
1
1
  {
2
2
  "name": "@babylonlabs-io/ts-sdk",
3
- "version": "3.2.1",
3
+ "version": "3.3.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -143,7 +143,6 @@
143
143
  }
144
144
  },
145
145
  "devDependencies": {
146
- "@babylonlabs-io/babylon-tbv-rust-wasm": "1.2.1",
147
146
  "@vitest/browser-playwright": "4.0.9",
148
147
  "@vitest/coverage-v8": "^4.0.8",
149
148
  "@vitest/ui": "^4.0.8",
@@ -159,6 +158,7 @@
159
158
  "vite": "^6.4.1",
160
159
  "vite-plugin-dts": "^4.3.0",
161
160
  "vitest": "4.0.9",
161
+ "@babylonlabs-io/babylon-tbv-rust-wasm": "1.2.1",
162
162
  "@internal/eslint-config": "0.0.0"
163
163
  },
164
164
  "publishConfig": {
@@ -1,2 +0,0 @@
1
- "use strict";var ve=Object.defineProperty;var Ee=(o,e,t)=>e in o?ve(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var w=(o,e,t)=>Ee(o,typeof e!="symbol"?e+"":e,t);const P=require("./sha2-Ce6KewYx.cjs"),O=require("bitcoinjs-lib"),I=require("buffer"),ee=require("viem"),te=require("./pegin-registration-client-Bmkh1OZ9.cjs"),le=require("./tbv/core/clients/mempool/index.cjs"),Y=require("./tbv/core/wasm/index.cjs"),A=require("./verifyScriptPathSchnorrSignature-CahYx5Td.cjs"),$=require("./verifyKeyPathSchnorrSignature-BRTpEH9X.cjs"),h=require("./bitcoin-D-O2GjbC.cjs"),Se=require("./signing-DvISftFk.cjs"),L=require("./validation-C6XTfZak.cjs"),ue=require("./deriveVaultRoot-C3uqnJto.cjs"),E=require("./PayoutManager-B1Ev0r7o.cjs"),_e=require("./registration-records-DaBufozs.cjs"),oe=require("./psbtInputFields-BrV_ZfL_.cjs"),ne=require("./fundPeginTransaction-54-Rwb2k.cjs"),U=require("./constants-CAm10Qwp.cjs"),Be=require("./btcTxHash-CGb5BqFL.cjs"),Ae=require("./parseFundingOutpoints-C_-PT9BT.cjs"),Ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),V=require("./bip322Verify-DLxJR9CQ.cjs");function he(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const pe=he(O),Ie=he(Ce),M=BigInt(2**32-1),se=BigInt(32);function He(o,e=!1){return e?{h:Number(o&M),l:Number(o>>se&M)}:{h:Number(o>>se&M)|0,l:Number(o&M)|0}}function $e(o,e=!1){const t=o.length;let n=new Uint32Array(t),r=new Uint32Array(t);for(let s=0;s<t;s++){const{h:i,l:a}=He(o[s],e);[n[s],r[s]]=[i,a]}return[n,r]}const Oe=(o,e,t)=>o<<t|e>>>32-t,Re=(o,e,t)=>e<<t|o>>>32-t,Fe=(o,e,t)=>e<<t-32|o>>>64-t,We=(o,e,t)=>o<<t-32|e>>>64-t,Ve=64;function de(o){const e=o.prepeginTxid.toLowerCase();if(!/^[0-9a-f]+$/.test(e)||e.length!==Ve)throw new Error(`buildDepositTerms: prepeginTxid must be 64 hex chars, got "${o.prepeginTxid}"`);if(o.peginAmounts.length===0)throw new Error("buildDepositTerms: at least one pegin amount is required");if(o.timelockPegin<=0||o.timelockAssert<=0||o.timelockRefund<=0)throw new Error("buildDepositTerms: timelocks must be positive");if(!Number.isInteger(o.maxAcceptableCommissionBps)||o.maxAcceptableCommissionBps<0||o.maxAcceptableCommissionBps>=U.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${U.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${o.maxAcceptableCommissionBps}`);const t=BigInt(U.BPS_DENOMINATOR),n=o.peginAmounts.map((r,s)=>({htlcVout:s,vaultProviderBtcPubkey:o.vaultProviderBtcPubkey,peginAmount:r,commissionFee:r*BigInt(o.maxAcceptableCommissionBps)/t,depositorClaimValue:o.depositorClaimValue,peginMaxFee:o.peginMaxFee}));return{vaultCoreVersion:o.vaultCoreVersion,protocolFeeRate:o.protocolFeeRate,timelockPegin:o.timelockPegin,timelockAssert:o.timelockAssert,timelockRefund:o.timelockRefund,prepeginTxid:e,prepeginMaxFee:o.prepeginMaxFee,vaultKeeperBtcPubkeys:[...o.vaultKeeperBtcPubkeys],universalChallengerBtcPubkeys:[...o.universalChallengerBtcPubkeys],vaults:n}}const Me=/^0x[0-9a-f]+$/i,De=/^[0-9a-f]+$/i,Ke=/^[A-Za-z0-9+/]+={0,2}$/;function C(o){if(typeof o!="string"||o.length===0)throw new Error("BTC wallet returned empty public key");return h.processPublicKeyToXOnly(o).toLowerCase()}function Ne(o){if(typeof o!="string"||o.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(o.startsWith("0x")||o.startsWith("0X")){if(!Me.test(o)||o.length<4||o.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return o.toLowerCase()}if(De.test(o)){if(o.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${o.toLowerCase()}`}if(!Ke.test(o)||o.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const e=I.Buffer.from(o,"base64");if(e.length===0||e.toString("base64")!==o)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${e.toString("hex")}`}async function ge(o){const{wallet:e,depositTerms:t,fundedPrePeginTxHex:n,depositorBtcPubkey:r}=o,s=typeof e.approveDepositTerms=="function"?e.approveDepositTerms:void 0;if(!s&&!t)return;const i=n.startsWith("0x")?n.slice(2):n,c=O.Transaction.fromHex(i).getId();if(t&&t.prepeginTxid.replace(/^0x/,"").toLowerCase()!==c)throw new Error(`Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${t.prepeginTxid}, but this transaction is ${c}.`);if(!s)return;if(!t)throw new Error("This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild.");if(typeof e.deriveContextHash!="function")throw new Error("A deposit-approval wallet must also implement deriveContextHash, but this one does not.");if(typeof e.holdsApprovedDepositTerms=="function"){let m=!1;try{m=await e.holdsApprovedDepositTerms(t)}catch{}if(m)return}typeof e.validateDepositTerms=="function"&&await e.validateDepositTerms(t);const p=Ae.parseFundingOutpointsFromTx(n);(await ue.deriveVaultRoot({deriveContextHash:e.deriveContextHash.bind(e)},{depositorBtcPubkey:h.hexToUint8Array(C(r)),fundingOutpoints:p})).fill(0),await s.call(e,t)}const Le=BigInt(0),H=BigInt(1),Ue=BigInt(2),Xe=BigInt(7),qe=BigInt(256),ze=BigInt(113),fe=[],me=[],Pe=[];for(let o=0,e=H,t=1,n=0;o<24;o++){[t,n]=[n,(2*t+3*n)%5],fe.push(2*(5*n+t)),me.push((o+1)*(o+2)/2%64);let r=Le;for(let s=0;s<7;s++)e=(e<<H^(e>>Xe)*ze)%qe,e&Ue&&(r^=H<<(H<<BigInt(s))-H);Pe.push(r)}const be=$e(Pe,!0),Ge=be[0],je=be[1],ie=(o,e,t)=>t>32?Fe(o,e,t):Oe(o,e,t),re=(o,e,t)=>t>32?We(o,e,t):Re(o,e,t);function Ye(o,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)t[i]=o[i]^o[i+10]^o[i+20]^o[i+30]^o[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,p=t[c],d=t[c+1],m=ie(p,d,1)^t[a],k=re(p,d,1)^t[a+1];for(let x=0;x<50;x+=10)o[i+x]^=m,o[i+x+1]^=k}let r=o[2],s=o[3];for(let i=0;i<24;i++){const a=me[i],c=ie(r,s,a),p=re(r,s,a),d=fe[i];r=o[d],s=o[d+1],o[d]=c,o[d+1]=p}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)t[a]=o[i+a];for(let a=0;a<10;a++)o[i+a]^=~t[(a+2)%10]&t[(a+4)%10]}o[0]^=Ge[n],o[1]^=je[n]}P.clean(t)}class Z{constructor(e,t,n,r=!1,s=24){w(this,"state");w(this,"pos",0);w(this,"posOut",0);w(this,"finished",!1);w(this,"state32");w(this,"destroyed",!1);w(this,"blockLen");w(this,"suffix");w(this,"outputLen");w(this,"enableXOF",!1);w(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,P.anumber(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=P.u32(this.state)}clone(){return this._cloneInto()}keccak(){P.swap32IfBE(this.state32),Ye(this.state32,this.rounds),P.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(e){P.aexists(this),P.abytes(e);const{blockLen:t,state:n}=this,r=e.length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let a=0;a<i;a++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,(t&128)!==0&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){P.aexists(this,!1),P.abytes(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return P.anumber(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(P.aoutput(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,P.clean(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new Z(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Qe=(o,e,t,n={})=>P.createHasher(()=>new Z(e,o,t),n),Ze=Qe(1,136,32),ae=64,y=20,Q=4,we=2,Je=0,et=1,D=[64,64],tt=o=>Array.from(o).map(e=>e.toString(16).padStart(2,"0")).join("");function J(o){return _e.ripemd160(P.sha256(o))}function xe(o){return(1<<o)-1}function ot(o){let e=1;for(;e*e<o+1;)e++;return Math.max(e,2)}function nt(o){const e=Q,t=o*xe(e);return{d:e,n:o,checksum_radix:ot(t)}}function X(o,e){const t=[];let n=e;for(;n>0;)t.push(n&255),n>>>=8;const r=new Uint8Array(o.length+t.length);r.set(o);for(let s=0;s<t.length;s++)r[o.length+s]=t[s];return J(r)}function q(o,e){let t=o;for(let n=0;n<e;n++)t=J(t);return t}function st(o,e){const t=xe(e.d),n=e.checksum_radix-1,r=Math.floor(e.n*t/e.checksum_radix),s=[];for(let d=0;d<e.n;d++){const m=X(o,d+we),k=q(m,t);s.push(Array.from(k))}const i=X(o,Je),a=q(i,n),c=X(o,et),p=q(c,r);return{config:e,message_terminals:s,checksum_major_terminal:Array.from(p),checksum_minor_terminal:Array.from(a)}}async function ye(o){try{if(o.length!==ae)throw new Error(`WOTS seed must be exactly ${ae} bytes, got ${o.length}`);const e=[];for(let t=0;t<D.length;t++){const n=D[t],r=nt(n),s=new Uint8Array(o.length+1);s.set(o),s[o.length]=t;const i=J(s);try{const a=st(i,r);if(a.config.d!==Q)throw new Error(`Block ${t}: expected d=${Q}, got d=${a.config.d}`);if(a.config.n!==n)throw new Error(`Block ${t}: expected n=${n}, got n=${a.config.n}`);if(a.message_terminals.length!==n)throw new Error(`Block ${t}: expected ${n} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==y)throw new Error(`Block ${t} terminal ${c}: expected ${y} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==y)throw new Error(`Block ${t} checksum_minor: expected ${y} bytes`);if(a.checksum_major_terminal.length!==y)throw new Error(`Block ${t} checksum_major: expected ${y} bytes`);e.push(a)}finally{s.fill(0),i.fill(0)}}if(e.length!==D.length)throw new Error(`Expected ${D.length} blocks, got ${e.length}`);return e}finally{o.fill(0)}}function z(o,e,t){if(o.length!==y)throw new Error(`Block ${e} ${t}: expected ${y} bytes, got ${o.length}`);for(let n=0;n<o.length;n++){const r=o[n];if(!Number.isInteger(r)||r<0||r>255)throw new Error(`Block ${e} ${t}[${n}]: invalid byte value ${r}`)}}function ke(o){if(o.length===0)throw new Error("Public keys array must not be empty");for(let s=0;s<o.length;s++){const i=o[s];z(i.checksum_minor_terminal,s,"checksum_minor_terminal"),z(i.checksum_major_terminal,s,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)z(i.message_terminals[a],s,`message_terminal[${a}]`)}let e=0;for(const s of o)e+=we+s.message_terminals.length;const t=new Uint8Array(e*y);let n=0;for(const s of o){t.set(s.checksum_minor_terminal,n),n+=y,t.set(s.checksum_major_terminal,n),n+=y;for(const i of s.message_terminals)t.set(i,n),n+=y}const r=Ze(t);return`0x${tt(r)}`}async function Te(o,e){const t=[],n=[],r=[],s=[];try{for(let i=0;i<e;i++){const a=await Y.expandWotsSeed(o,i);try{const p=await ye(a);t.push(p),n.push(ke(p))}finally{a.fill(0)}const c=await Y.expandHashlockSecret(o,i);try{const p=h.uint8ArrayToHex(c);r.push(p),s.push(E.computeHashlock(h.ensureHexPrefix(p)).slice(2))}finally{c.fill(0)}}}finally{o.fill(0)}return{perVaultWotsKeys:t,wotsPkHashes:n,htlcSecretHexes:r,hashlocks:s}}const it=1,rt=2,at=33,ct=2,lt=3,ut=1,K=64,ht=0,G=1,ce=/^[0-9a-f]{64}$/i,pt=/^(?:[0-9a-f]{2})+$/;function dt(o){const e=o.slice(2);if(!pt.test(e))throw new Error("proof of possession witness is not even-length lowercase hex");return $.decodeWitnessStack(Uint8Array.from(I.Buffer.from(e,"hex")),"proof of possession witness")}function gt(o,e,t){var r;const n=dt(t);if(n.length===it){const[s]=n;let i,a;if(s.length===K)i=s,a=ht;else if(s.length===K+1&&s[K]===G)i=s.subarray(0,K),a=G;else throw new Error("proof of possession witness item must be a 64-byte Schnorr signature (or 65 bytes ending in 0x01)");if(!ce.test(e))throw new Error(`depositor public key must be bare 64-char x-only hex, got "${e}"`);const c=Uint8Array.from(I.Buffer.from(e,"hex"));if(!V.verifyBip322Simple(o,c,i,a))throw new Error("proof of possession signature does not verify against the depositor key");return{kind:"p2tr-verified"}}if(n.length===rt){if(!ce.test(e))throw new Error(`depositor public key must be bare 64-char x-only hex, got "${e}"`);const[s,i]=n;if(i.length!==at||i[0]!==ct&&i[0]!==lt)throw new Error(`proof of possession P2WPKH witness item 1 is not a compressed public key (${i.length} bytes, prefix 0x${((r=i[0])==null?void 0:r.toString(16))??"none"})`);if(!Ie.isPointCompressed(i))throw new Error("proof of possession P2WPKH witness pubkey is not a valid secp256k1 point");const a=I.Buffer.from(i.subarray(ut)).toString("hex");if(a!==e.toLowerCase())throw new Error(`proof of possession witness pubkey does not match the depositor key: witness carries ${a}, expected ${e}`);if(s.length<V.P2WPKH_ENCODED_SIG_MIN||s.length>V.P2WPKH_ENCODED_SIG_MAX)throw new Error(`proof of possession signature is ${s.length} bytes; vault ingestion accepts only 71/72-byte DER signatures with a sighash byte — try a different account or a Taproot address`);if(s[s.length-1]!==G)throw new Error(`proof of possession P2WPKH signature must end in a SIGHASH_ALL (0x01) byte, got 0x${s[s.length-1].toString(16)}`);if(!V.verifyBip322P2wpkhSimple(o,i,s))throw new Error("proof of possession signature does not verify against the depositor key");return{kind:"p2wpkh-verified"}}throw new Error(`proof of possession witness has ${n.length} items; expected 1 (P2TR) or 2 (P2WPKH)`)}const j="00".repeat(32),ft="00".repeat(32);function mt(o,e){const t={bitcoin:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"};try{const n=pe.address.fromBech32(o);return n.prefix===t[e]&&n.version===0&&n.data.length===20}catch{return!1}}function Pt(o,e,t,n){const r=t==null?void 0:t[`${o}:${e}`];return r?Promise.resolve({txid:o,vout:e,value:r.value,scriptPubKey:r.scriptPubKey}):le.getUtxoInfo(o,e,n)}class bt{constructor(e){w(this,"config");this.config=e}async preparePegin(e){if(e.amounts.length===0)throw new Error("amounts must contain at least one entry");const t=await this.config.btcWallet.getPublicKeyHex(),n=C(t);if(E.supportsDepositApproval(this.config.btcWallet)){const l=(await E.requireChangeAddress(this.config.btcWallet)).trim();if(e.changeAddress.trim()!==l)throw new Error(`Pre-PegIn changeAddress "${e.changeAddress}" is not the approval wallet's change address ("${l}"). Refusing to build a tx the signing device would reject.`)}else if(!h.isAddressFromPublicKey(e.changeAddress,t,this.config.btcNetwork))throw new Error(`Pre-PegIn changeAddress "${e.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`);const r=await this.prepareSizing(n,e);if(E.supportsDepositApproval(this.config.btcWallet)){const{validateDepositTerms:l}=this.config.btcWallet;typeof l=="function"&&await l.call(this.config.btcWallet,this.buildPeginDepositTerms({params:e,prepeginTxid:ft,prepeginMaxFee:r.fee,depositorClaimValue:r.depositorClaimValue,peginMaxFee:r.minPeginFee}))}const s=r.selectedUTXOs.map(l=>({txid:h.hexToUint8Array(l.txid),vout:l.vout})),i=await ue.deriveVaultRoot(this.config.btcWallet,{depositorBtcPubkey:h.hexToUint8Array(n),fundingOutpoints:s});let a,c;try{const l=await Y.expandAuthAnchor(i);try{a=h.uint8ArrayToHex(l),c=h.uint8ArrayToHex(P.sha256(l))}finally{l.fill(0)}}catch(l){throw i.fill(0),l}const p=await Te(i,e.amounts.length),{perVaultWotsKeys:d,wotsPkHashes:m,htlcSecretHexes:k,hashlocks:x}=p,f=await this.preparePeginCommit({depositorBtcPubkeyRaw:t,depositorBtcPubkey:n,hashlocks:x,authAnchorHash:c,sizing:r,params:e});for(let l=0;l<f.perVault.length;l++)if(f.perVault[l].htlcVout!==l)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${l} (expected ${l}, got ${f.perVault[l].htlcVout})`);E.assertAuthAnchorOpReturn(f.fundedPrePeginTxHex,e.amounts.length,c);const{depositTerms:S,...T}=f;return{transaction:{...T,selectedUTXOs:r.selectedUTXOs,fee:r.fee,changeAmount:r.changeAmount},depositorBtcPubkey:n,derivedSecrets:{perVaultWotsKeys:d,wotsPkHashes:m,htlcSecretHexes:k,authAnchorHex:a},depositTerms:S}}async prepareSizing(e,t){const n=t.amounts.map(()=>j),r=t.vaultKeeperBtcPubkeys.length,s=await A.buildPrePeginPsbt({vaultCoreVersion:t.vaultCoreVersion,depositorPubkey:e,vaultProviderPubkey:h.stripHexPrefix(t.vaultProviderBtcPubkey),vaultKeeperPubkeys:t.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerPubkeys:t.universalChallengerBtcPubkeys.map(h.stripHexPrefix),hashlocks:n,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,minPeginFeeRate:t.minPeginFeeRate,numLocalChallengers:r,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork,authAnchorHash:j}),i=oe.selectUtxosForPegin([...t.availableUTXOs],s.totalOutputValue,t.mempoolFeeRate,ne.peginOutputCount(s.htlcValues.length,!0));return{selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount,depositorClaimValue:s.depositorClaimValue,minPeginFee:s.minPeginFee}}buildPeginDepositTerms(e){const{params:t}=e;return de({vaultCoreVersion:t.vaultCoreVersion,protocolFeeRate:t.protocolFeeRate,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,timelockRefund:t.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:h.stripHexPrefix(t.vaultProviderBtcPubkey),vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys.map(h.stripHexPrefix),maxAcceptableCommissionBps:te.capMaxAcceptableCommissionBps(t.commissionBps),peginAmounts:t.amounts,depositorClaimValue:e.depositorClaimValue,peginMaxFee:e.peginMaxFee})}async preparePeginCommit(e){const{depositorBtcPubkeyRaw:t,depositorBtcPubkey:n,hashlocks:r,authAnchorHash:s,sizing:i,params:a}=e,c=j.toLowerCase();for(let u=0;u<r.length;u++)if(r[u].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${u} — internal substitution bug`);if(s.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const p=h.stripHexPrefix(a.vaultProviderBtcPubkey),d=a.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),m=a.universalChallengerBtcPubkeys.map(h.stripHexPrefix),k=d.length,x={vaultCoreVersion:a.vaultCoreVersion,depositorPubkey:n,vaultProviderPubkey:p,vaultKeeperPubkeys:d,universalChallengerPubkeys:m,hashlocks:r,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,minPeginFeeRate:a.minPeginFeeRate,numLocalChallengers:k,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:s},f=await A.buildPrePeginPsbt(x);if(f.depositorClaimValue!==i.depositorClaimValue||f.minPeginFee!==i.minPeginFee)throw new Error(`Pre-PegIn sizing/commit divergence: depositorClaimValue ${i.depositorClaimValue} -> ${f.depositorClaimValue}, minPeginFee ${i.minPeginFee} -> ${f.minPeginFee}. The provisional deposit terms validated before derivation would not match the terms sent for approval; refusing to continue.`);const S=h.getNetwork(this.config.btcNetwork),T=ne.fundPeginTransaction({unfundedTxHex:f.psbtHex,selectedUTXOs:i.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:i.changeAmount,network:S}),l=i.selectedUTXOs.reduce((u,B)=>u+BigInt(B.value),0n)-f.totalOutputValue-i.changeAmount;if(l!==i.fee)throw new Error(`Pre-PegIn funded fee ${l} does not match the sizing-pass fee ${i.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`);const R=h.stripHexPrefix(Be.calculateBtcTxHash(T)),F=[],g=[],b=[];for(let u=0;u<r.length;u++){const B=await A.buildPeginTxFromFundedPrePegin({prePeginParams:x,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:T,htlcVout:u}),N=await $.buildPeginInputPsbt({vaultCoreVersion:a.vaultCoreVersion,peginTxHex:B.txHex,fundedPrePeginTxHex:T,depositorPubkey:n,vaultProviderPubkey:p,vaultKeeperPubkeys:d,universalChallengerPubkeys:m,hashlock:r[u],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});F.push(B),g.push(N.psbtHex),b.push(Se.createTaprootScriptPathSignOptions(t,1))}const v=this.buildPeginDepositTerms({params:a,prepeginTxid:R,prepeginMaxFee:i.fee,depositorClaimValue:f.depositorClaimValue,peginMaxFee:f.minPeginFee});E.supportsDepositApproval(this.config.btcWallet)&&await this.config.btcWallet.approveDepositTerms(v);const _=await E.signPsbtsWithFallback(this.config.btcWallet,g,b),W=[];for(let u=0;u<_.length;u++){A.assertPsbtUnsignedTxMatches({requestedPsbtHex:g[u],returnedPsbtHex:_[u]});const B=$.extractPeginInputSignature(_[u],n);A.assertScriptPathSchnorrSignature({requestedPsbtHex:g[u],signatureHex:B,signerXOnlyPubkeyHex:n,inputIndex:0});const N=$.finalizePeginInputPsbt(_[u]);W.push({htlcVout:u,htlcValue:f.htlcValues[u],peginTxHex:N,peginTxid:F[u].txid,peginInputSignature:B,vaultScriptPubKey:F[u].vaultScriptPubKey})}return{fundedPrePeginTxHex:T,prePeginTxid:R,perVault:W,depositTerms:v}}async signAndBroadcast(e){const{fundedPrePeginTxHex:t,depositorBtcPubkey:n}=e,r=t.startsWith("0x")?t.slice(2):t,s=O.Transaction.fromHex(r);if(s.ins.length===0)throw new Error("Transaction has no inputs");const i=new O.Psbt;i.setVersion(s.version),i.setLocktime(s.locktime);const a=I.Buffer.from(C(n),"hex"),c=this.config.mempoolApiUrl,p=s.ins.map(g=>{const b=I.Buffer.from(g.hash).reverse().toString("hex"),v=g.index;return Pt(b,v,e.localPrevouts,c).then(_=>({input:g,utxoData:_,txid:b,vout:v}))}),d=await Promise.all(p),m=d.reduce((g,b)=>g+BigInt(b.utxoData.value),0n),k=s.outs.reduce((g,b)=>g+BigInt(b.value),0n);if(m<k)throw new Error(`UTXO value mismatch: total input value (${m} sat) is less than total output value (${k} sat). This may indicate the mempool API returned manipulated UTXO data.`);const x=m-k;if(x>L.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${x} sat) exceeds maximum reasonable fee (${L.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:g,utxoData:b,txid:v,vout:_}of d){const W=oe.getPsbtInputFields({value:b.value,scriptPubKey:b.scriptPubKey},a);i.addInput({hash:g.hash,index:g.index,sequence:g.sequence,...W})}for(const g of s.outs)i.addOutput({script:g.script,value:g.value});await ge({wallet:this.config.btcWallet,depositTerms:e.depositTerms,fundedPrePeginTxHex:t,depositorBtcPubkey:n});const f=i.toHex(),S=await this.config.btcWallet.signPsbt(f);A.assertPsbtUnsignedTxMatches({requestedPsbtHex:f,returnedPsbtHex:S});const T=$.assertReturnedKeyPathSignatures({requestedPsbtHex:f,returnedPsbtHex:S});if(E.supportsDepositApproval(this.config.btcWallet)&&T!==i.data.inputs.length)throw new Error(`Key-path verification covered ${T} of ${i.data.inputs.length} Pre-PegIn inputs; an approval wallet signs every input key-path, so the unverified ones must not be broadcast.`);const l=O.Psbt.fromHex(S);try{l.finalizeAllInputs()}catch(g){if(!l.data.inputs.every(v=>v.finalScriptWitness||v.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${g}`)}const R=l.extractTransaction().toHex();return await le.pushTx(R,c)}async registerPeginOnChain(e){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address;if(!ee.isAddressEqual(e.popSignature.depositorEthAddress,t))throw new Error(`Proof of possession was signed for ${e.popSignature.depositorEthAddress} but the Ethereum wallet is currently connected to ${t}. Reconnect the original account or call signProofOfPossession() again.`);const n=await this.assertPopMatchesBtcWallet(e.popSignature),r=e.depositorPayoutBtcAddress??await this.config.btcWallet.getAddress(),s=this.resolvePayoutScriptPubKey(n,r);return this.createRegistrationClient().registerPeginOnChain({unsignedPrePeginTx:e.unsignedPrePeginTx,depositorSignedPeginTx:e.depositorSignedPeginTx,vaultProvider:e.vaultProvider,hashlock:e.hashlock,htlcVout:e.htlcVout,depositorPayoutScriptPubKey:s,depositorBtcPubkeyRaw:n,depositorWotsPkHash:e.depositorWotsPkHash,popSignature:e.popSignature,quotedCommissionBps:e.quotedCommissionBps,expectedFingerprint:e.expectedFingerprint})}async registerPeginBatchOnChain(e){if(e.requests.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address;if(!ee.isAddressEqual(e.popSignature.depositorEthAddress,t))throw new Error(`Proof of possession was signed for ${e.popSignature.depositorEthAddress} but the Ethereum wallet is currently connected to ${t}. Reconnect the original account or call signProofOfPossession() again.`);const n=await this.assertPopMatchesBtcWallet(e.popSignature),r=e.requests.map(s=>this.resolvePayoutScriptPubKey(n,s.depositorPayoutBtcAddress));return this.createRegistrationClient().registerPeginBatchOnChain({vaultProvider:e.vaultProvider,unsignedPrePeginTx:e.unsignedPrePeginTx,popSignature:e.popSignature,depositorBtcPubkeyRaw:n,quotedCommissionBps:e.quotedCommissionBps,expectedFingerprint:e.expectedFingerprint,requests:e.requests.map((s,i)=>({depositorSignedPeginTx:s.depositorSignedPeginTx,hashlock:s.hashlock,htlcVout:s.htlcVout,depositorPayoutScriptPubKey:r[i],depositorWotsPkHash:s.depositorWotsPkHash}))})}createRegistrationClient(){return new te.ViemPeginRegistrationClient({ethWallet:this.config.ethWallet,ethChain:this.config.ethChain,publicClient:this.config.publicClient,btcVaultRegistry:this.config.vaultContracts.btcVaultRegistry,requireQuotedCommissionBps:E.supportsDepositApproval(this.config.btcWallet)})}resolvePayoutScriptPubKey(e,t){if(!h.isAddressFromPublicKey(t,e,this.config.btcNetwork))throw h.stripHexPrefix(e).length===L.X_ONLY_PUBKEY_HEX_LEN&&mt(t,this.config.btcNetwork)?new Error(`BTC payout address "${t}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`):new Error(`BTC payout address "${t}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`);const n=h.getNetwork(this.config.btcNetwork);let r;try{r=pe.address.toOutputScript(t,n).toString("hex")}catch{throw new Error(`Invalid BTC payout address: "${t}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}return r}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const e=this.config.ethWallet.account.address,t=C(await this.config.btcWallet.getPublicKeyHex()),n=this.config.vaultContracts.btcVaultRegistry,r=`${e.toLowerCase()}:${this.config.ethChain.id}:pegin:${n.toLowerCase()}`,s=await this.config.btcWallet.signMessage(r,"bip322-simple"),i=Ne(s);return gt(new TextEncoder().encode(r),t,i),{btcPopSignature:i,depositorEthAddress:e,depositorBtcPubkey:t}}async assertPopMatchesBtcWallet(e){const t=await this.config.btcWallet.getPublicKeyHex(),n=C(t),r=C(e.depositorBtcPubkey);if(n!==r)throw new Error(`Proof of possession was signed with BTC pubkey ${r} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`);return t}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}exports.PeginManager=bt;exports.buildDepositTerms=de;exports.computeWotsBlockPublicKeysHash=ke;exports.deriveWotsBlocksFromSeed=ye;exports.ensurePrePeginTermsApproval=ge;exports.expandPerVaultSecrets=Te;
2
- //# sourceMappingURL=PeginManager-BCRtUqyX.cjs.map