@babylonlabs-io/ts-sdk 3.2.0 → 3.2.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 (114) hide show
  1. package/dist/{PayoutManager-DOdsgcUR.cjs → PayoutManager-B1Ev0r7o.cjs} +2 -2
  2. package/dist/{PayoutManager-DOdsgcUR.cjs.map → PayoutManager-B1Ev0r7o.cjs.map} +1 -1
  3. package/dist/{PayoutManager-BZ212yml.js → PayoutManager-xEGvTbhL.js} +3 -3
  4. package/dist/{PayoutManager-BZ212yml.js.map → PayoutManager-xEGvTbhL.js.map} +1 -1
  5. package/dist/{PeginManager-BHplS4dM.cjs → PeginManager-BCRtUqyX.cjs} +2 -2
  6. package/dist/{PeginManager-BHplS4dM.cjs.map → PeginManager-BCRtUqyX.cjs.map} +1 -1
  7. package/dist/{PeginManager-DcwGom01.js → PeginManager-sizm3dlw.js} +7 -7
  8. package/dist/{PeginManager-DcwGom01.js.map → PeginManager-sizm3dlw.js.map} +1 -1
  9. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs +2 -0
  10. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs.map +1 -0
  11. package/dist/{buildAndBroadcastReclaim-CcQ0b1be.js → buildAndBroadcastReclaim-rQyAiAUS.js} +846 -822
  12. package/dist/buildAndBroadcastReclaim-rQyAiAUS.js.map +1 -0
  13. package/dist/challengeAssert-B2otuf7y.js +509 -0
  14. package/dist/challengeAssert-B2otuf7y.js.map +1 -0
  15. package/dist/challengeAssert-C3eMcM5Y.cjs +2 -0
  16. package/dist/challengeAssert-C3eMcM5Y.cjs.map +1 -0
  17. package/dist/constants-CAm10Qwp.cjs +2 -0
  18. package/dist/constants-CAm10Qwp.cjs.map +1 -0
  19. package/dist/constants-CvQZuxKv.js +48 -0
  20. package/dist/constants-CvQZuxKv.js.map +1 -0
  21. package/dist/{index-CVBtBjQ5.js → index-BRsWXDlv.js} +6 -6
  22. package/dist/{index-CVBtBjQ5.js.map → index-BRsWXDlv.js.map} +1 -1
  23. package/dist/{index-DpjYs5yr.cjs → index-C6avwx1s.cjs} +2 -2
  24. package/dist/{index-DpjYs5yr.cjs.map → index-C6avwx1s.cjs.map} +1 -1
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +302 -303
  27. package/dist/index.js.map +1 -1
  28. package/dist/{pegin-registration-client-DvyrUNku.js → pegin-registration-client-8tzSRDaq.js} +3 -3
  29. package/dist/{pegin-registration-client-DvyrUNku.js.map → pegin-registration-client-8tzSRDaq.js.map} +1 -1
  30. package/dist/{pegin-registration-client-BogzOk8B.cjs → pegin-registration-client-Bmkh1OZ9.cjs} +2 -2
  31. package/dist/{pegin-registration-client-BogzOk8B.cjs.map → pegin-registration-client-Bmkh1OZ9.cjs.map} +1 -1
  32. package/dist/{primeVpAuth-BPj2TPdD.cjs → primeVpAuth-CXNXYKrh.cjs} +2 -2
  33. package/dist/{primeVpAuth-BPj2TPdD.cjs.map → primeVpAuth-CXNXYKrh.cjs.map} +1 -1
  34. package/dist/{primeVpAuth-CiCdRNGf.js → primeVpAuth-D4UWXQ76.js} +2 -2
  35. package/dist/{primeVpAuth-CiCdRNGf.js.map → primeVpAuth-D4UWXQ76.js.map} +1 -1
  36. package/dist/{registration-records-CKLAv3gw.js → registration-records-BBOz21Dm.js} +15 -15
  37. package/dist/{registration-records-CKLAv3gw.js.map → registration-records-BBOz21Dm.js.map} +1 -1
  38. package/dist/{registration-records-DFQgBaYi.cjs → registration-records-DaBufozs.cjs} +2 -2
  39. package/dist/{registration-records-DFQgBaYi.cjs.map → registration-records-DaBufozs.cjs.map} +1 -1
  40. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  41. package/dist/tbv/core/clients/eth/index.js +3 -3
  42. package/dist/tbv/core/clients/index.cjs +1 -1
  43. package/dist/tbv/core/clients/index.js +5 -5
  44. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  45. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  46. package/dist/tbv/core/index.cjs +1 -1
  47. package/dist/tbv/core/index.js +300 -301
  48. package/dist/tbv/core/index.js.map +1 -1
  49. package/dist/tbv/core/managers/index.cjs +1 -1
  50. package/dist/tbv/core/managers/index.js +2 -2
  51. package/dist/tbv/core/primitives/index.cjs +1 -1
  52. package/dist/tbv/core/primitives/index.js +29 -30
  53. package/dist/tbv/core/primitives/index.js.map +1 -1
  54. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts +2 -0
  55. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts.map +1 -0
  56. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts +2 -0
  57. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts.map +1 -0
  58. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +43 -0
  59. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
  60. package/dist/tbv/core/primitives/psbt/constants.d.ts +50 -2
  61. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  62. package/dist/tbv/core/primitives/psbt/noPayout.d.ts +42 -0
  63. package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
  64. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts +12 -0
  65. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts.map +1 -0
  66. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +7 -0
  67. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  68. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +46 -1
  69. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  70. package/dist/tbv/core/services/index.cjs +1 -1
  71. package/dist/tbv/core/services/index.js +2 -2
  72. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts +2 -0
  73. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts.map +1 -0
  74. package/dist/tbv/core/wasm/index.cjs +1 -1
  75. package/dist/tbv/core/wasm/index.cjs.map +1 -1
  76. package/dist/tbv/core/wasm/index.d.ts +14 -2
  77. package/dist/tbv/core/wasm/index.d.ts.map +1 -1
  78. package/dist/tbv/core/wasm/index.js +81 -77
  79. package/dist/tbv/core/wasm/index.js.map +1 -1
  80. package/dist/tbv/index.cjs +1 -1
  81. package/dist/tbv/index.js +300 -301
  82. package/dist/tbv/index.js.map +1 -1
  83. package/dist/{toRefundInputs-8DgBT_Bg.cjs → toRefundInputs-DOCLxqC1.cjs} +2 -2
  84. package/dist/{toRefundInputs-8DgBT_Bg.cjs.map → toRefundInputs-DOCLxqC1.cjs.map} +1 -1
  85. package/dist/{toRefundInputs-CCMNAoRx.js → toRefundInputs-Dso_QEr-.js} +5 -5
  86. package/dist/{toRefundInputs-CCMNAoRx.js.map → toRefundInputs-Dso_QEr-.js.map} +1 -1
  87. package/dist/{types-Bda75Od0.cjs → types-DGr5HWwD.cjs} +2 -2
  88. package/dist/{types-Bda75Od0.cjs.map → types-DGr5HWwD.cjs.map} +1 -1
  89. package/dist/{types-C5jj3Cc-.js → types-Dbs--c2M.js} +2 -2
  90. package/dist/{types-C5jj3Cc-.js.map → types-Dbs--c2M.js.map} +1 -1
  91. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs} +2 -2
  92. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map} +1 -1
  93. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js → verifyKeyPathSchnorrSignature-IIj3Z2se.js} +2 -2
  94. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map → verifyKeyPathSchnorrSignature-IIj3Z2se.js.map} +1 -1
  95. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs → verifyScriptPathSchnorrSignature-CahYx5Td.cjs} +2 -2
  96. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map → verifyScriptPathSchnorrSignature-CahYx5Td.cjs.map} +1 -1
  97. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js → verifyScriptPathSchnorrSignature-owu3BfyT.js} +2 -2
  98. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js.map → verifyScriptPathSchnorrSignature-owu3BfyT.js.map} +1 -1
  99. package/package.json +3 -3
  100. package/dist/buildAndBroadcastReclaim-C7bq5wNM.cjs +0 -2
  101. package/dist/buildAndBroadcastReclaim-C7bq5wNM.cjs.map +0 -1
  102. package/dist/buildAndBroadcastReclaim-CcQ0b1be.js.map +0 -1
  103. package/dist/challengeAssert-Cp_GeRg8.js +0 -64
  104. package/dist/challengeAssert-Cp_GeRg8.js.map +0 -1
  105. package/dist/challengeAssert-Z7_YULBb.cjs +0 -2
  106. package/dist/challengeAssert-Z7_YULBb.cjs.map +0 -1
  107. package/dist/constants-BeYquVd-.js +0 -36
  108. package/dist/constants-BeYquVd-.js.map +0 -1
  109. package/dist/constants-BwCg5K6R.cjs +0 -2
  110. package/dist/constants-BwCg5K6R.cjs.map +0 -1
  111. package/dist/noPayout-B-vGXJ-V.js +0 -361
  112. package/dist/noPayout-B-vGXJ-V.js.map +0 -1
  113. package/dist/noPayout-DOHak0ui.cjs +0 -2
  114. package/dist/noPayout-DOHak0ui.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types-Bda75Od0.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/**\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}\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(result: RawTBVParams): 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 };\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 result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\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 {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\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: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\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 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` exactly.\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\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 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 * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\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","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","ProtocolParamsABI","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":"mHA8BMA,EAAa,MAiCnB,SAASC,EAAkBC,EAAoD,CAC7E,MAAO,CACL,eAAgBA,EAAO,eACvB,wBAAyBA,EAAO,wBAChC,oBAAqB,CAAC,GAAGA,EAAO,mBAAmB,EACnD,cAAeA,EAAO,cACtB,QAASA,EAAO,QAChB,mBAAoBA,EAAO,mBAC3B,wBAAyBA,EAAO,wBAChC,mBAAoBA,EAAO,mBAC3B,QAASA,EAAO,QAChB,OAAQA,EAAO,OACf,gBAAiBA,EAAO,gBACxB,qBAAsBA,EAAO,qBAC7B,iBAAkBA,EAAO,gBAAA,CAE7B,CAGA,SAASC,EAAaD,EAAyC,CAC7D,MAAO,CACL,mBAAoBA,EAAO,mBAC3B,eAAgBA,EAAO,eACvB,gBAAiBA,EAAO,gBACxB,uBAAwBA,EAAO,uBAC/B,mBAAoBA,EAAO,mBAC3B,wBAAyBA,EAAO,uBAAA,CAEpC,CAcO,SAASE,EAAoBC,EAAgC,CAClE,GAAIA,EAAiB,OAAOL,CAAU,EACpC,MAAM,IAAI,MACR,wBAAwBK,CAAc,wBAAwBL,CAAU,GAAA,EAG5E,OAAO,OAAOK,CAAc,CAC9B,CAeO,MAAMC,CAAyD,CACpE,YACUC,EACAC,EACR,CAFQ,KAAA,aAAAD,EACA,KAAA,gBAAAC,CACP,CAEH,MAAM,sBAAmD,CACvD,MAAMN,EAAU,MAAM,KAAK,aAAa,aAAa,CACnD,QAAS,KAAK,gBACd,IAAKO,EAAAA,kBACL,aAAc,sBAAA,CACf,EAEKC,EAASP,EAAaD,CAAM,EAClCS,OAAAA,EAAAA,0BAA0BD,CAAM,EACzBA,CACT,CAEA,MAAM,yBAA4D,CAChE,MAAMR,EAAU,MAAM,KAAK,aAAa,aAAa,CACnD,QAAS,KAAK,gBACd,IAAKO,EA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,IAAI,MAAM,OAAOA,CAAK,CAAC,EAE5D,CACF,CAEA,MAAO,CAAE,UAAAD,EAAW,cAAAN,CAAA,CACtB,CACF,CC/RO,IAAKQ,GAAAA,IACVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UALUA,IAAAA,GAAA,CAAA,CAAA"}
1
+ {"version":3,"file":"types-DGr5HWwD.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/**\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}\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(result: RawTBVParams): 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 };\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 result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\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 {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\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: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\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 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` exactly.\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\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 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 * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\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","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","ProtocolParamsABI","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":"mHA8BMA,EAAa,MAiCnB,SAASC,EAAkBC,EAAoD,CAC7E,MAAO,CACL,eAAgBA,EAAO,eACvB,wBAAyBA,EAAO,wBAChC,oBAAqB,CAAC,GAAGA,EAAO,mBAAmB,EACnD,cAAeA,EAAO,cACtB,QAASA,EAAO,QAChB,mBAAoBA,EAAO,mBAC3B,wBAAyBA,EAAO,wBAChC,mBAAoBA,EAAO,mBAC3B,QAASA,EAAO,QAChB,OAAQA,EAAO,OACf,gBAAiBA,EAAO,gBACxB,qBAAsBA,EAAO,qBAC7B,iBAAkBA,EAAO,gBAAA,CAE7B,CAGA,SAASC,EAAaD,EAAyC,CAC7D,MAAO,CACL,mBAAoBA,EAAO,mBAC3B,eAAgBA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,KAAK,+BAAA,EACjC,GAAIA,IAAkB,EACpB,MAAO,CAAE,UAAW,IAAI,IAAO,cAAe,CAAA,EAGhD,MAAMC,EAAW,MAAM,KAAK,CAAE,OAAQD,CAAA,EAAiB,CAACE,EAAGC,IAAMA,EAAI,CAAC,EAChEC,EAAYH,EAAS,IAAKI,IAAO,CACrC,QAAS,KAAK,gBACd,IAAKrB,EAAAA,kBACL,aAAc,6BACd,KAAM,CAACqB,CAAC,CAAA,EACR,EAEIb,EAAU,MAAM,KAAK,aAAa,UAAU,CAChD,UAAAY,EACA,aAAc,EAAA,CACf,EAEKE,MAAgB,IACtB,QAAS,EAAI,EAAG,EAAIL,EAAS,OAAQ,IAAK,CACxC,MAAMhB,EAAST,EAAkBgB,EAAQ,CAAC,CAAsB,EAChE,GAAI,CACFL,EAAAA,uBAAuBF,CAAM,EAC7BqB,EAAU,IAAIL,EAAS,CAAC,EAAGhB,CAAM,CACnC,OAASsB,EAAO,CAGdR,GAAA,MAAAA,EACEE,EAAS,CAAC,EACVM,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,EAE5D,CACF,CAEA,MAAO,CAAE,UAAAD,EAAW,cAAAN,CAAA,CACtB,CACF,CC/RO,IAAKQ,GAAAA,IACVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UALUA,IAAAA,GAAA,CAAA,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import { P as s } from "./ProtocolParams.abi-CKOVqFJP.js";
2
- import { c as p, v as l, j as A, b as I } from "./registration-records-CKLAv3gw.js";
2
+ import { c as p, v as l, j as A, b as I } from "./registration-records-BBOz21Dm.js";
3
3
  const g = 65535;
4
4
  function m(e) {
5
5
  return {
@@ -195,4 +195,4 @@ export {
195
195
  C as V,
196
196
  P as d
197
197
  };
198
- //# sourceMappingURL=types-C5jj3Cc-.js.map
198
+ //# sourceMappingURL=types-Dbs--c2M.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types-C5jj3Cc-.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/**\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}\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(result: RawTBVParams): 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 };\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 result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\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 {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\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: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\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 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` exactly.\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\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 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 * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\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","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","ProtocolParamsABI","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":";;AA8BA,MAAMA,IAAa;AAiCnB,SAASC,EAAkBC,GAAoD;AAC7E,SAAO;AAAA,IACL,gBAAgBA,EAAO;AAAA,IACvB,yBAAyBA,EAAO;AAAA,IAChC,qBAAqB,CAAC,GAAGA,EAAO,mBAAmB;AAAA,IACnD,eAAeA,EAAO;AAAA,IACtB,SAASA,EAAO;AAAA,IAChB,oBAAoBA,EAAO;AAAA,IAC3B,yBAAyBA,EAAO;AAAA,IAChC,oBAAoBA,EAAO;AAAA,IAC3B,SAASA,EAAO;AAAA,IAChB,QAAQA,EAAO;AAAA,IACf,iBAAiBA,EAAO;AAAA,IACxB,sBAAsBA,EAAO;AAAA,IAC7B,kBAAkBA,EAAO;AAAA,EAAA;AAE7B;AAGA,SAASC,EAAaD,GAAyC;AAC7D,SAAO;AAAA,IACL,oBAAoBA,EAAO;AAAA,IAC3B,gBAAgBA,EAAO;AAAA,IACvB,iBAAiBA,EAAO;AAAA,IACxB,wBAAwBA,EAAO;AAAA,IAC/B,oBAAoBA,EAAO;AAAA,IAC3B,yBAAyBA,EAAO;AAAA,EAAA;AAEpC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AD,GAAW,eAAAN,EAAA;AAAA,EACtB;AACF;AC/RO,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;"}
1
+ {"version":3,"file":"types-Dbs--c2M.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/**\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}\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(result: RawTBVParams): 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 };\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 result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\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 {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\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: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\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 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` exactly.\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\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 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 * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\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","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","publicClient","contractAddress","ProtocolParamsABI","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","blockNumber","results","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","contracts","v","byVersion","error","OnChainBtcVaultStatus"],"mappings":";;AA8BA,MAAMA,IAAa;AAiCnB,SAASC,EAAkBC,GAAoD;AAC7E,SAAO;AAAA,IACL,gBAAgBA,EAAO;AAAA,IACvB,yBAAyBA,EAAO;AAAA,IAChC,qBAAqB,CAAC,GAAGA,EAAO,mBAAmB;AAAA,IACnD,eAAeA,EAAO;AAAA,IACtB,SAASA,EAAO;AAAA,IAChB,oBAAoBA,EAAO;AAAA,IAC3B,yBAAyBA,EAAO;AAAA,IAChC,oBAAoBA,EAAO;AAAA,IAC3B,SAASA,EAAO;AAAA,IAChB,QAAQA,EAAO;AAAA,IACf,iBAAiBA,EAAO;AAAA,IACxB,sBAAsBA,EAAO;AAAA,IAC7B,kBAAkBA,EAAO;AAAA,EAAA;AAE7B;AAGA,SAASC,EAAaD,GAAyC;AAC7D,SAAO;AAAA,IACL,oBA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AAO;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;AC/RO,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;"}
@@ -1,2 +1,2 @@
1
- "use strict";const u=require("bitcoinjs-lib"),g=require("buffer"),E=require("./tbv/core/wasm/index.cjs"),P=require("./bitcoin-D-O2GjbC.cjs"),k=require("./verifyScriptPathSchnorrSignature-D2t1yACC.cjs"),B=require("@bitcoin-js/tiny-secp256k1-asmjs");function R(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const e=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,e.get?e:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const w=R(B);async function A(t){const r=P.stripHexPrefix(t.peginTxHex),n=P.stripHexPrefix(t.fundedPrePeginTxHex);await E.getPrePeginHtlcConnectorInfo({txGraphVersion:t.vaultCoreVersion,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network});const e=k.deriveExpectedPrePeginHtlc(t,t.hashlock),i=u.Transaction.fromHex(r),a=u.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const s=i.ins[0],o=a.getId(),h=P.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(h!==o)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${o}, got ${h}`);const l=a.outs[s.index];if(!l)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${a.outs.length} outputs)`);if(!e.scriptPubKey.equals(l.script))throw new Error("PegIn HTLC taptree mismatch: the independent 2-leaf tree does not reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.");const c=new u.Psbt;c.setVersion(i.version),c.setLocktime(i.locktime),c.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:l.script,value:l.value},tapLeafScript:[{leafVersion:P.TAPSCRIPT_LEAF_VERSION,script:e.hashlockScript,controlBlock:e.hashlockControlBlock}],tapInternalKey:g.Buffer.from(E.tapInternalPubkey),tapMerkleRoot:e.tapMerkleRoot});for(const f of i.outs)c.addOutput({script:f.script,value:f.value});return{psbtHex:c.toHex()}}function K(t,r){const e=u.Psbt.fromHex(t).data.inputs[0];if(!e)throw new Error("PegIn PSBT has no inputs");if(e.tapScriptSig&&e.tapScriptSig.length>0){const i=g.Buffer.from(P.hexToUint8Array(r));for(const a of e.tapScriptSig)if(a.pubkey.equals(i))return C(a.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw e.finalScriptWitness&&e.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function W(t){const r=u.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(n){if(!r.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return r.extractTransaction().toHex()}function C(t){if(t.length===64)return P.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}const H=253,U=254,b=3,x=5,q=253,L=65536;function y(t,r){let n=0;const e=()=>{if(n>=t.length)throw new Error(`${r} is truncated`);const s=t[n];if(s<H)return n+=1,s;if(s===H){if(n+b>t.length)throw new Error(`${r} is truncated`);const o=t[n+1]|t[n+2]<<8;if(o<q)throw new Error(`${r} has a non-minimal length encoding`);return n+=b,o}if(s===U){if(n+x>t.length)throw new Error(`${r} is truncated`);const o=(t[n+1]|t[n+2]<<8|t[n+3]<<16|t[n+4]<<24)>>>0;if(o<L)throw new Error(`${r} has a non-minimal length encoding`);return n+=x,o}throw new Error(`${r} carries an out-of-range item length`)},i=e(),a=[];for(let s=0;s<i;s++){const o=e();if(n+o>t.length)throw new Error(`${r} is truncated`);a.push(t.subarray(n,n+o)),n+=o}if(n!==t.length)throw new Error(`${r} has trailing bytes`);return a}const v=22,O=0,z=20,M=2,N=33,F=2;function $(t){return t!==void 0&&t.length===v&&t[0]===O&&t[1]===z}function T(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function G(t,r){const n=y(t,"finalScriptWitness");if(n.length!==F)throw new Error(`Returned PSBT input ${r}: a finalized P2WPKH witness must have exactly 2 items [signature, pubkey], got ${n.length}.`);return{signature:n[0],pubkey:n[1]}}function D(t){const{requestedPsbtHex:r,returnedInput:n,inputIndex:e}=t,i=n.partialSig;if(i!==void 0&&i.length>1)throw new Error(`Returned PSBT input ${e}: a P2WPKH input must carry at most one partial signature, got ${i.length}.`);const a=i==null?void 0:i[0],s=n.finalScriptWitness?G(n.finalScriptWitness,e):void 0;if(a&&s&&(!T(a.signature,s.signature)||!T(a.pubkey,s.pubkey)))throw new Error(`Returned PSBT input ${e} finalized witness does not match its partialSig.`);const o=a??s;if(!o)throw new Error(`Returned PSBT input ${e} carries no P2WPKH signature (no partialSig, not finalized).`);V(r,o.signature,o.pubkey,e)}function V(t,r,n,e){const i=u.Psbt.fromHex(t);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);const a=i.data.inputs[e].witnessUtxo;if(!a||!$(a.script))throw new Error(`Input ${e} of the requested PSBT is not a P2WPKH input.`);if(n.length!==N)throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey must be 33 bytes, got ${n.length}.`);if(!w.isPointCompressed(n))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey is not a valid secp256k1 point.`);const s=a.script.subarray(M,v);if(!T(u.crypto.hash160(g.Buffer.from(n)),s))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey does not hash to the prevout's witness program.`);let o;try{o=u.script.signature.decode(g.Buffer.from(r))}catch(p){throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not DER with a defined sighash byte: ${p instanceof Error?p.message:String(p)}`)}if(!u.script.signature.encode(o.signature,o.hashType).equals(g.Buffer.from(r)))throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not canonical DER.`);if(o.hashType!==u.Transaction.SIGHASH_ALL)throw new Error(`Returned PSBT input ${e}: P2WPKH signature has sighash type 0x${o.hashType.toString(16)} (expected SIGHASH_ALL).`);const h=u.payments.p2pkh({hash:g.Buffer.from(s)}).output;if(!h)throw new Error(`Returned PSBT input ${e}: could not build the P2WPKH scriptCode.`);const c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV0(e,h,a.value,o.hashType);let f=!1;try{f=w.verify(c,n,o.signature,!0)}catch{f=!1}if(!f)throw new Error(`P2WPKH signature for input ${e} does not verify against the requested PSBT's prevout. The wallet may have signed a different transaction or key.`)}const d=64,Y=u.Transaction.SIGHASH_DEFAULT,_=u.Transaction.SIGHASH_ALL,Z=34,X=81,J=32,Q=2;function j(t){return t!==void 0&&t.length===Z&&t[0]===X&&t[1]===J}function tt(t,r){if(t.length===d)return{signature:t,hashType:Y};if(t.length===d+1&&t[d]===_)return{signature:t.subarray(0,d),hashType:_};throw new Error(`Key-path signature for input ${r} must be 64 bytes (SIGHASH_DEFAULT) or 65 bytes ending in 0x01 (SIGHASH_ALL), got ${t.length}.`)}function m(t){const{requestedPsbtHex:r,signatureHex:n,inputIndex:e}=t,i=u.Psbt.fromHex(r);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);if(!I(i.data.inputs[e]))throw new Error(`Input ${e} of the requested PSBT is not a key-path P2TR input.`);const a=[],s=[];for(let p=0;p<i.data.inputs.length;p++){const S=i.data.inputs[p].witnessUtxo;if(!S)throw new Error(`Cannot verify signature: input ${p} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);a.push(S.script),s.push(S.value)}const{signature:o,hashType:h}=tt(P.hexToUint8Array(P.stripHexPrefix(n)),e),c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV1(e,a,s,h),f=a[e].subarray(Q);if(!w.verifySchnorr(c,f,o))throw new Error(`Key-path Schnorr signature for input ${e} does not verify against the requested PSBT's prevout (output key ${g.Buffer.from(f).toString("hex")}). The wallet may have signed a different transaction or key.`)}function I(t){var r;return t.tapInternalKey!==void 0&&t.tapLeafScript===void 0&&t.tapMerkleRoot===void 0&&j((r=t.witnessUtxo)==null?void 0:r.script)}function et(t,r){const n=y(t,"finalScriptWitness");if(n.length!==1)throw new Error(`Returned PSBT input ${r}: a finalized key-path witness must have exactly one item, got ${n.length}.`);return n[0]}function nt(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function rt(t){const{requestedPsbtHex:r,returnedPsbtHex:n}=t,e=u.Psbt.fromHex(r),i=u.Psbt.fromHex(n);if(i.data.inputs.length!==e.data.inputs.length)throw new Error(`Returned PSBT input count ${i.data.inputs.length} differs from the requested ${e.data.inputs.length}.`);let a=0;return e.data.inputs.forEach((s,o)=>{var p;const h=i.data.inputs[o];if(!I(s)){if($((p=s.witnessUtxo)==null?void 0:p.script)){D({requestedPsbtHex:r,returnedInput:h,inputIndex:o});return}throw new Error(`Input ${o} of the requested PSBT is neither key-path P2TR nor P2WPKH; refusing to treat it as verified.`)}a++;const l=h.tapKeySig,c=h.finalScriptWitness?et(h.finalScriptWitness,o):void 0;if(l&&c&&!nt(l,c))throw new Error(`Returned PSBT input ${o} finalized witness does not match its tapKeySig.`);const f=l??c;if(!f)throw new Error(`Returned PSBT input ${o} carries no key-path signature (no tapKeySig, not finalized).`);m({requestedPsbtHex:r,signatureHex:g.Buffer.from(f).toString("hex"),inputIndex:o})}),a}exports.assertKeyPathSchnorrSignature=m;exports.assertReturnedKeyPathSignatures=rt;exports.buildPeginInputPsbt=A;exports.decodeWitnessStack=y;exports.extractPeginInputSignature=K;exports.finalizePeginInputPsbt=W;
2
- //# sourceMappingURL=verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map
1
+ "use strict";const u=require("bitcoinjs-lib"),g=require("buffer"),E=require("./tbv/core/wasm/index.cjs"),P=require("./bitcoin-D-O2GjbC.cjs"),k=require("./verifyScriptPathSchnorrSignature-CahYx5Td.cjs"),B=require("@bitcoin-js/tiny-secp256k1-asmjs");function R(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const e=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,e.get?e:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const w=R(B);async function A(t){const r=P.stripHexPrefix(t.peginTxHex),n=P.stripHexPrefix(t.fundedPrePeginTxHex);await E.getPrePeginHtlcConnectorInfo({txGraphVersion:t.vaultCoreVersion,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network});const e=k.deriveExpectedPrePeginHtlc(t,t.hashlock),i=u.Transaction.fromHex(r),a=u.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const s=i.ins[0],o=a.getId(),h=P.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(h!==o)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${o}, got ${h}`);const l=a.outs[s.index];if(!l)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${a.outs.length} outputs)`);if(!e.scriptPubKey.equals(l.script))throw new Error("PegIn HTLC taptree mismatch: the independent 2-leaf tree does not reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.");const c=new u.Psbt;c.setVersion(i.version),c.setLocktime(i.locktime),c.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:l.script,value:l.value},tapLeafScript:[{leafVersion:P.TAPSCRIPT_LEAF_VERSION,script:e.hashlockScript,controlBlock:e.hashlockControlBlock}],tapInternalKey:g.Buffer.from(E.tapInternalPubkey),tapMerkleRoot:e.tapMerkleRoot});for(const f of i.outs)c.addOutput({script:f.script,value:f.value});return{psbtHex:c.toHex()}}function K(t,r){const e=u.Psbt.fromHex(t).data.inputs[0];if(!e)throw new Error("PegIn PSBT has no inputs");if(e.tapScriptSig&&e.tapScriptSig.length>0){const i=g.Buffer.from(P.hexToUint8Array(r));for(const a of e.tapScriptSig)if(a.pubkey.equals(i))return C(a.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw e.finalScriptWitness&&e.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function W(t){const r=u.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(n){if(!r.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return r.extractTransaction().toHex()}function C(t){if(t.length===64)return P.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}const H=253,U=254,b=3,x=5,q=253,L=65536;function y(t,r){let n=0;const e=()=>{if(n>=t.length)throw new Error(`${r} is truncated`);const s=t[n];if(s<H)return n+=1,s;if(s===H){if(n+b>t.length)throw new Error(`${r} is truncated`);const o=t[n+1]|t[n+2]<<8;if(o<q)throw new Error(`${r} has a non-minimal length encoding`);return n+=b,o}if(s===U){if(n+x>t.length)throw new Error(`${r} is truncated`);const o=(t[n+1]|t[n+2]<<8|t[n+3]<<16|t[n+4]<<24)>>>0;if(o<L)throw new Error(`${r} has a non-minimal length encoding`);return n+=x,o}throw new Error(`${r} carries an out-of-range item length`)},i=e(),a=[];for(let s=0;s<i;s++){const o=e();if(n+o>t.length)throw new Error(`${r} is truncated`);a.push(t.subarray(n,n+o)),n+=o}if(n!==t.length)throw new Error(`${r} has trailing bytes`);return a}const v=22,O=0,z=20,M=2,N=33,F=2;function $(t){return t!==void 0&&t.length===v&&t[0]===O&&t[1]===z}function T(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function G(t,r){const n=y(t,"finalScriptWitness");if(n.length!==F)throw new Error(`Returned PSBT input ${r}: a finalized P2WPKH witness must have exactly 2 items [signature, pubkey], got ${n.length}.`);return{signature:n[0],pubkey:n[1]}}function D(t){const{requestedPsbtHex:r,returnedInput:n,inputIndex:e}=t,i=n.partialSig;if(i!==void 0&&i.length>1)throw new Error(`Returned PSBT input ${e}: a P2WPKH input must carry at most one partial signature, got ${i.length}.`);const a=i==null?void 0:i[0],s=n.finalScriptWitness?G(n.finalScriptWitness,e):void 0;if(a&&s&&(!T(a.signature,s.signature)||!T(a.pubkey,s.pubkey)))throw new Error(`Returned PSBT input ${e} finalized witness does not match its partialSig.`);const o=a??s;if(!o)throw new Error(`Returned PSBT input ${e} carries no P2WPKH signature (no partialSig, not finalized).`);V(r,o.signature,o.pubkey,e)}function V(t,r,n,e){const i=u.Psbt.fromHex(t);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);const a=i.data.inputs[e].witnessUtxo;if(!a||!$(a.script))throw new Error(`Input ${e} of the requested PSBT is not a P2WPKH input.`);if(n.length!==N)throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey must be 33 bytes, got ${n.length}.`);if(!w.isPointCompressed(n))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey is not a valid secp256k1 point.`);const s=a.script.subarray(M,v);if(!T(u.crypto.hash160(g.Buffer.from(n)),s))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey does not hash to the prevout's witness program.`);let o;try{o=u.script.signature.decode(g.Buffer.from(r))}catch(p){throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not DER with a defined sighash byte: ${p instanceof Error?p.message:String(p)}`)}if(!u.script.signature.encode(o.signature,o.hashType).equals(g.Buffer.from(r)))throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not canonical DER.`);if(o.hashType!==u.Transaction.SIGHASH_ALL)throw new Error(`Returned PSBT input ${e}: P2WPKH signature has sighash type 0x${o.hashType.toString(16)} (expected SIGHASH_ALL).`);const h=u.payments.p2pkh({hash:g.Buffer.from(s)}).output;if(!h)throw new Error(`Returned PSBT input ${e}: could not build the P2WPKH scriptCode.`);const c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV0(e,h,a.value,o.hashType);let f=!1;try{f=w.verify(c,n,o.signature,!0)}catch{f=!1}if(!f)throw new Error(`P2WPKH signature for input ${e} does not verify against the requested PSBT's prevout. The wallet may have signed a different transaction or key.`)}const d=64,Y=u.Transaction.SIGHASH_DEFAULT,_=u.Transaction.SIGHASH_ALL,Z=34,X=81,J=32,Q=2;function j(t){return t!==void 0&&t.length===Z&&t[0]===X&&t[1]===J}function tt(t,r){if(t.length===d)return{signature:t,hashType:Y};if(t.length===d+1&&t[d]===_)return{signature:t.subarray(0,d),hashType:_};throw new Error(`Key-path signature for input ${r} must be 64 bytes (SIGHASH_DEFAULT) or 65 bytes ending in 0x01 (SIGHASH_ALL), got ${t.length}.`)}function m(t){const{requestedPsbtHex:r,signatureHex:n,inputIndex:e}=t,i=u.Psbt.fromHex(r);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);if(!I(i.data.inputs[e]))throw new Error(`Input ${e} of the requested PSBT is not a key-path P2TR input.`);const a=[],s=[];for(let p=0;p<i.data.inputs.length;p++){const S=i.data.inputs[p].witnessUtxo;if(!S)throw new Error(`Cannot verify signature: input ${p} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);a.push(S.script),s.push(S.value)}const{signature:o,hashType:h}=tt(P.hexToUint8Array(P.stripHexPrefix(n)),e),c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV1(e,a,s,h),f=a[e].subarray(Q);if(!w.verifySchnorr(c,f,o))throw new Error(`Key-path Schnorr signature for input ${e} does not verify against the requested PSBT's prevout (output key ${g.Buffer.from(f).toString("hex")}). The wallet may have signed a different transaction or key.`)}function I(t){var r;return t.tapInternalKey!==void 0&&t.tapLeafScript===void 0&&t.tapMerkleRoot===void 0&&j((r=t.witnessUtxo)==null?void 0:r.script)}function et(t,r){const n=y(t,"finalScriptWitness");if(n.length!==1)throw new Error(`Returned PSBT input ${r}: a finalized key-path witness must have exactly one item, got ${n.length}.`);return n[0]}function nt(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function rt(t){const{requestedPsbtHex:r,returnedPsbtHex:n}=t,e=u.Psbt.fromHex(r),i=u.Psbt.fromHex(n);if(i.data.inputs.length!==e.data.inputs.length)throw new Error(`Returned PSBT input count ${i.data.inputs.length} differs from the requested ${e.data.inputs.length}.`);let a=0;return e.data.inputs.forEach((s,o)=>{var p;const h=i.data.inputs[o];if(!I(s)){if($((p=s.witnessUtxo)==null?void 0:p.script)){D({requestedPsbtHex:r,returnedInput:h,inputIndex:o});return}throw new Error(`Input ${o} of the requested PSBT is neither key-path P2TR nor P2WPKH; refusing to treat it as verified.`)}a++;const l=h.tapKeySig,c=h.finalScriptWitness?et(h.finalScriptWitness,o):void 0;if(l&&c&&!nt(l,c))throw new Error(`Returned PSBT input ${o} finalized witness does not match its tapKeySig.`);const f=l??c;if(!f)throw new Error(`Returned PSBT input ${o} carries no key-path signature (no tapKeySig, not finalized).`);m({requestedPsbtHex:r,signatureHex:g.Buffer.from(f).toString("hex"),inputIndex:o})}),a}exports.assertKeyPathSchnorrSignature=m;exports.assertReturnedKeyPathSignatures=rt;exports.buildPeginInputPsbt=A;exports.decodeWitnessStack=y;exports.extractPeginInputSignature=K;exports.finalizePeginInputPsbt=W;
2
+ //# sourceMappingURL=verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map