@babylonlabs-io/ts-sdk 0.72.0 → 0.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -13
- package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs +2 -0
- package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs.map +1 -0
- package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js +229 -0
- package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js.map +1 -0
- package/dist/PeginManager-C9RPOd0L.js +1216 -0
- package/dist/PeginManager-C9RPOd0L.js.map +1 -0
- package/dist/PeginManager-E-UHA1un.cjs +2 -0
- package/dist/PeginManager-E-UHA1un.cjs.map +1 -0
- package/dist/bip322Verify-B7_gIhRk.cjs +2 -0
- package/dist/bip322Verify-B7_gIhRk.cjs.map +1 -0
- package/dist/bip322Verify-D6sBBUHE.js +79 -0
- package/dist/bip322Verify-D6sBBUHE.js.map +1 -0
- package/dist/{buildAndBroadcastReclaim-YvWDRAN8.js → buildAndBroadcastReclaim-BXclIcu_.js} +366 -357
- package/dist/buildAndBroadcastReclaim-BXclIcu_.js.map +1 -0
- package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +209 -205
- package/dist/index.js.map +1 -1
- package/dist/onChainBtcPubkey-BbxRrbvg.cjs +2 -0
- package/dist/onChainBtcPubkey-BbxRrbvg.cjs.map +1 -0
- package/dist/onChainBtcPubkey-C-6UWpD8.js +34 -0
- package/dist/onChainBtcPubkey-C-6UWpD8.js.map +1 -0
- package/dist/{parseFundingOutpoints-BkgGihaY.cjs → parseFundingOutpoints-B4iQeX6q.cjs} +2 -2
- package/dist/{parseFundingOutpoints-BkgGihaY.cjs.map → parseFundingOutpoints-B4iQeX6q.cjs.map} +1 -1
- package/dist/{parseFundingOutpoints-DlINgQ3X.js → parseFundingOutpoints-B67CoXpF.js} +2 -2
- package/dist/{parseFundingOutpoints-DlINgQ3X.js.map → parseFundingOutpoints-B67CoXpF.js.map} +1 -1
- package/dist/pegin-registration-client-6vLk2itL.cjs +2 -0
- package/dist/pegin-registration-client-6vLk2itL.cjs.map +1 -0
- package/dist/pegin-registration-client-BdRiR8br.js +2635 -0
- package/dist/pegin-registration-client-BdRiR8br.js.map +1 -0
- package/dist/primeVpAuth-DBHohVKM.cjs +2 -0
- package/dist/primeVpAuth-DBHohVKM.cjs.map +1 -0
- package/dist/primeVpAuth-DvaD45q_.js +745 -0
- package/dist/primeVpAuth-DvaD45q_.js.map +1 -0
- package/dist/psbtInputFields-B3e05Xe6.js +171 -0
- package/dist/psbtInputFields-B3e05Xe6.js.map +1 -0
- package/dist/psbtInputFields-BIxBpPj2.cjs +2 -0
- package/dist/psbtInputFields-BIxBpPj2.cjs.map +1 -0
- package/dist/sha2-CrlWM5S8.js +312 -0
- package/dist/{sha2-BYVxyZzX.js.map → sha2-CrlWM5S8.js.map} +1 -1
- package/dist/sha2-DI0-0SHr.cjs +2 -0
- package/dist/{sha2-DsrLC4NM.cjs.map → sha2-DI0-0SHr.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-CCFTzE0o.js → signPsbtsWithFallback-0VBALhjS.js} +2 -2
- package/dist/{signPsbtsWithFallback-CCFTzE0o.js.map → signPsbtsWithFallback-0VBALhjS.js.map} +1 -1
- package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs → signPsbtsWithFallback-DMSpIQWH.cjs} +2 -2
- package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs.map → signPsbtsWithFallback-DMSpIQWH.cjs.map} +1 -1
- package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/index.cjs +2 -0
- package/dist/tbv/core/clients/eth/index.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/index.d.ts +4 -0
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/index.js +22 -0
- package/dist/tbv/core/clients/eth/index.js.map +1 -0
- package/dist/tbv/core/clients/eth/onChainBtcPubkey.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/operation-key-reader.d.ts +1 -1
- package/dist/tbv/core/clients/eth/operation-key-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/payout-script.d.ts +4 -0
- package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts +99 -0
- package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/pegin-transaction.d.ts +14 -0
- package/dist/tbv/core/clients/eth/pegin-transaction.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +6 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +4 -4
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +29 -8
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +55 -48
- package/dist/tbv/core/clients/index.js.map +1 -1
- package/dist/tbv/core/clients/mempool/index.cjs +2 -0
- package/dist/tbv/core/clients/mempool/index.cjs.map +1 -0
- package/dist/tbv/core/clients/mempool/index.js +222 -0
- package/dist/tbv/core/clients/mempool/index.js.map +1 -0
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.cjs.map +1 -1
- package/dist/tbv/core/contracts/index.js +491 -12
- package/dist/tbv/core/contracts/index.js.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +1 -0
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +207 -203
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/PeginManager.d.ts +38 -30
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.d.ts +2 -1
- package/dist/tbv/core/managers/index.d.ts.map +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts +20 -0
- package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +8 -0
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
- package/dist/tbv/core/utils/eth/index.cjs +2 -0
- package/dist/tbv/core/utils/eth/index.cjs.map +1 -0
- package/dist/tbv/core/utils/eth/index.js +109 -0
- package/dist/tbv/core/utils/eth/index.js.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +41 -40
- package/dist/tbv/core/utils/index.js.map +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +207 -203
- package/dist/tbv/index.js.map +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{toRefundInputs-Df1vi23S.js → toRefundInputs-BkcFhvDp.js} +5 -5
- package/dist/{toRefundInputs-Df1vi23S.js.map → toRefundInputs-BkcFhvDp.js.map} +1 -1
- package/dist/{toRefundInputs-CY9u84U9.cjs → toRefundInputs-CatCKniS.cjs} +2 -2
- package/dist/{toRefundInputs-CY9u84U9.cjs.map → toRefundInputs-CatCKniS.cjs.map} +1 -1
- package/dist/types-CPDLZm3l.js +430 -0
- package/dist/types-CPDLZm3l.js.map +1 -0
- package/dist/types-DSlcXtog.cjs +2 -0
- package/dist/types-DSlcXtog.cjs.map +1 -0
- package/package.json +32 -3
- package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js +0 -111
- package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js.map +0 -1
- package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs +0 -2
- package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs.map +0 -1
- package/dist/PeginManager-Bn8FxM35.cjs +0 -2
- package/dist/PeginManager-Bn8FxM35.cjs.map +0 -1
- package/dist/PeginManager-C3ojNTlv.js +0 -1503
- package/dist/PeginManager-C3ojNTlv.js.map +0 -1
- package/dist/ProtocolParams.abi-C0TSRaHV.js +0 -486
- package/dist/ProtocolParams.abi-C0TSRaHV.js.map +0 -1
- package/dist/ProtocolParams.abi-CYZoV2EI.cjs +0 -2
- package/dist/ProtocolParams.abi-CYZoV2EI.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-YvWDRAN8.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs.map +0 -1
- package/dist/errors-Blc-JWnI.js +0 -121
- package/dist/errors-Blc-JWnI.js.map +0 -1
- package/dist/errors-CGcNP0rV.cjs +0 -2
- package/dist/errors-CGcNP0rV.cjs.map +0 -1
- package/dist/mempoolApi-CKD_IbrM.js +0 -611
- package/dist/mempoolApi-CKD_IbrM.js.map +0 -1
- package/dist/mempoolApi-DronQ5xn.cjs +0 -2
- package/dist/mempoolApi-DronQ5xn.cjs.map +0 -1
- package/dist/onChainBtcPubkey-B5ZvWCCF.cjs +0 -2
- package/dist/onChainBtcPubkey-B5ZvWCCF.cjs.map +0 -1
- package/dist/onChainBtcPubkey-DATNfAAl.js +0 -19
- package/dist/onChainBtcPubkey-DATNfAAl.js.map +0 -1
- package/dist/primeVpAuth-Cjq6qFHq.cjs +0 -2
- package/dist/primeVpAuth-Cjq6qFHq.cjs.map +0 -1
- package/dist/primeVpAuth-tLRjdHwZ.js +0 -1159
- package/dist/primeVpAuth-tLRjdHwZ.js.map +0 -1
- package/dist/sha2-BYVxyZzX.js +0 -274
- package/dist/sha2-DsrLC4NM.cjs +0 -2
- package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs +0 -2
- package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs.map +0 -1
- package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js +0 -277
- package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-DSlcXtog.cjs","sources":["../src/tbv/core/clients/eth/contract-address-resolver.ts","../src/tbv/core/clients/eth/operation-key-reader.ts","../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/signer-set-reader.ts","../src/tbv/core/clients/eth/types.ts"],"sourcesContent":["/**\n * Contract Address Resolver\n *\n * Resolves ProtocolParams and ApplicationRegistry contract addresses\n * from the BTCVaultRegistry contract. These addresses are needed to\n * construct the SDK's contract readers.\n *\n * @module clients/eth/contract-address-resolver\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\n\nexport interface ProtocolAddresses {\n /** Address of the ProtocolParams contract */\n protocolParams: Address;\n /** Address of the ApplicationRegistry contract */\n applicationRegistry: Address;\n}\n\n/**\n * Resolve ProtocolParams and ApplicationRegistry addresses from BTCVaultRegistry.\n *\n * Uses a single multicall for atomicity and efficiency.\n *\n * @param publicClient - viem PublicClient instance\n * @param btcVaultRegistryAddress - Address of the BTCVaultRegistry contract\n * @returns Resolved contract addresses\n */\nexport async function resolveProtocolAddresses(\n publicClient: PublicClient,\n btcVaultRegistryAddress: Address,\n): Promise<ProtocolAddresses> {\n const [protocolParams, applicationRegistry] = await publicClient.multicall({\n contracts: [\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"protocolParams\",\n },\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"applicationRegistry\",\n },\n ],\n allowFailure: false,\n });\n\n return {\n protocolParams: protocolParams as Address,\n applicationRegistry: applicationRegistry as Address,\n };\n}\n","/**\n * Concrete RFC-006 operation-key reader spanning all three registries.\n *\n * This is an optional utility — callers can use their own implementation of\n * the {@link OperationKeyReader} interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n KeyEpochs,\n OperationKeyQuery,\n OperationKeyReader,\n RawOperationKeys,\n RawPayoutScripts,\n} from \"./types\";\n\n/** Addresses of the three registries an operation-key resolution spans. */\nexport interface OperationKeyContracts {\n btcVaultRegistry: Address;\n applicationRegistry: Address;\n protocolParams: Address;\n}\n\n/** One `multicall` entry. Loosely typed because the three ABIs differ. */\ntype Call = {\n address: Address;\n abi: Abi;\n functionName: string;\n args: readonly unknown[];\n};\n\n/**\n * Reject a multicall result that is not one-per-call.\n *\n * Every method here relies on positional alignment between calls and results,\n * so a short array does not fail — it silently hands back `undefined` for the\n * tail entries. Downstream that surfaces as a complaint about whichever\n * operator happens to occupy the missing slot, blaming a participant that is\n * perfectly fine for a read that came back incomplete. Assert the length where\n * the array arrives so the error names the real fault.\n */\nfunction assertMulticallLength(\n actual: number,\n expected: number,\n label: string,\n): void {\n if (actual !== expected) {\n throw new Error(\n `${label}: multicall returned ${actual} results for ${expected} calls, ` +\n `so the results are not roster-aligned; refusing to use them`,\n );\n }\n}\n\n/**\n * Split a flat multicall result into VP / keepers / challengers.\n *\n * Every method below builds its calls in the same order — vault provider\n * first, then keepers in roster order, then challengers in roster order — so\n * the results stay index-aligned with `query.vaultKeepers` /\n * `query.universalChallengers`. That alignment is what lets the resolver pair\n * a resolved key back to its admin address; the sorted key arrays it exposes\n * are derived from those pairs, never the other way round.\n */\nfunction partition<T>(\n results: readonly T[],\n keeperCount: number,\n): { vaultProvider: T; vaultKeepers: T[]; universalChallengers: T[] } {\n return {\n vaultProvider: results[0],\n vaultKeepers: results.slice(1, 1 + keeperCount),\n universalChallengers: results.slice(1 + keeperCount),\n };\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts.\n *\n * Usage:\n * ```ts\n * const reader = new ViemOperationKeyReader(publicClient, contracts);\n * const keys = await reader.getCurrentOperationKeys(query);\n * ```\n */\nexport class ViemOperationKeyReader implements OperationKeyReader {\n constructor(\n private publicClient: PublicClient,\n private contracts: OperationKeyContracts,\n ) {}\n\n /**\n * One multicall, `allowFailure: false`, so every key in the set is read at\n * the same block. A rotation landing between two separate `eth_call`s would\n * otherwise produce a mixed-epoch key set and a lock no counterparty agrees\n * with.\n */\n private async readAll<T>(\n calls: Call[],\n keeperCount: number,\n challengerCount: number,\n label: string,\n blockNumber?: bigint,\n ) {\n const results = (await this.publicClient.multicall({\n contracts: calls,\n allowFailure: false,\n blockNumber,\n })) as readonly T[];\n\n assertMulticallLength(\n results.length,\n 1 + keeperCount + challengerCount,\n label,\n );\n\n return partition(results, keeperCount);\n }\n\n async getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.vaultProviderEthAddress],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.applicationEntryPoint, keeper.ethAddress],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [challenger.ethAddress],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getCurrentOperationKeys\",\n blockNumber,\n );\n }\n\n async getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n // The VP takes the plain `AtEpoch` variant: it has no membership\n // version, so its genesis (the registration key at version 0) is\n // unambiguous and the contract resolves it internally.\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n // Keepers and challengers take `...OrGenesis` with their roster key\n // passed explicitly, because the correct genesis for them is their key\n // in *this vault's frozen membership version*. An operator dropped from\n // the current roster, or listed under a different key in an older\n // version, would otherwise resolve against the wrong genesis.\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n keeper.btcPubKey,\n ],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [challenger.ethAddress, epochs.ucKeyEpoch, challenger.btcPubKey],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getOperationKeysAtEpochs\",\n );\n }\n\n async getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts> {\n // Universal challengers are never claimers, so they have no payout script\n // and no call here.\n const results = (await this.publicClient.multicall({\n contracts: [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n ],\n })),\n ],\n allowFailure: false,\n })) as readonly Hex[];\n\n // Expected length is `1 + keepers`, with no challenger term — see the\n // comment above on why universal challengers have no call here.\n assertMulticallLength(\n results.length,\n 1 + query.vaultKeepers.length,\n \"getPayoutScriptsAtEpochs\",\n );\n\n return {\n vaultProvider: results[0],\n vaultKeepers: [...results.slice(1)],\n };\n }\n}\n","/**\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.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\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 * Matches PeginLogic.sol: `uint16(timelockAssert)`.\n * The contract validates `timelockAssert <= type(uint16).max` on write,\n * but we enforce the same bound here to reject invalid values early\n * rather than silently truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nfunction 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 * Concrete signer-set readers for vault keepers and universal challengers.\n *\n * These are optional utilities — callers can use their own implementations\n * of the VaultKeeperReader and UniversalChallengerReader interfaces.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n AddressBTCKeyPair,\n UniversalChallengerReader,\n VaultKeeperReader,\n} from \"./types\";\n\n/** Map viem tuple array to AddressBTCKeyPair[]. */\nfunction mapKeyPairs(\n result: readonly { ethAddress: Address; btcPubKey: Hex }[],\n): AddressBTCKeyPair[] {\n return result.map((pair) => ({\n ethAddress: pair.ethAddress,\n btcPubKey: pair.btcPubKey,\n }));\n}\n\n/**\n * Reads vault keepers from the ApplicationRegistry contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultKeeperReader(publicClient, applicationRegistryAddress);\n * const keepers = await reader.getCurrentVaultKeepers(appEntryPoint);\n * ```\n */\nexport class ViemVaultKeeperReader implements VaultKeeperReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepers(\n appEntryPoint: Address,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepers\",\n args: [appEntryPoint],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\n blockNumber,\n })) as number;\n\n return result;\n }\n}\n\n/**\n * Reads universal challengers from the ProtocolParams contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemUniversalChallengerReader(publicClient, protocolParamsAddress);\n * const challengers = await reader.getCurrentUniversalChallengers();\n * ```\n */\nexport class ViemUniversalChallengerReader implements UniversalChallengerReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getCurrentUniversalChallengers\",\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getLatestUniversalChallengersVersion(\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\n blockNumber,\n })) as number;\n\n return result;\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 /** 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 * 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 /** 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 signs auth tokens with. Falls back to the registration key when the\n * provider has never rotated.\n */\n getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey>;\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\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\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 and for the VP auth pin. Needs no epoch read at all —\n * each registry's `getCurrentOperationBtcKey` resolves its own genesis\n * fallback, so an 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":["resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","BTCVaultRegistryABI","assertMulticallLength","actual","expected","label","partition","results","keeperCount","ViemOperationKeyReader","contracts","calls","challengerCount","blockNumber","query","keeper","ApplicationRegistryABI","challenger","ProtocolParamsABI","epochs","UINT16_MAX","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","contractAddress","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","v","byVersion","error","mapKeyPairs","pair","ViemVaultKeeperReader","appEntryPoint","ViemUniversalChallengerReader","OnChainBtcVaultStatus"],"mappings":"sKA8BA,eAAsBA,EACpBC,EACAC,EAC4B,CAC5B,KAAM,CAACC,EAAgBC,CAAmB,EAAI,MAAMH,EAAa,UAAU,CACzE,UAAW,CACT,CACE,QAASC,EACT,IAAKG,EAAAA,oBACL,aAAc,gBAAA,EAEhB,CACE,QAASH,EACT,IAAKG,EAAAA,oBACL,aAAc,qBAAA,CAChB,EAEF,aAAc,EAAA,CACf,EAED,MAAO,CACL,eAAAF,EACA,oBAAAC,CAAA,CAEJ,CCTA,SAASE,EACPC,EACAC,EACAC,EACM,CACN,GAAIF,IAAWC,EACb,MAAM,IAAI,MACR,GAAGC,CAAK,wBAAwBF,CAA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,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babylonlabs-io/ts-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.73.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -34,11 +34,26 @@
|
|
|
34
34
|
"require": "./dist/tbv/core/utils/index.cjs",
|
|
35
35
|
"import": "./dist/tbv/core/utils/index.js"
|
|
36
36
|
},
|
|
37
|
+
"./tbv/core/utils/eth": {
|
|
38
|
+
"types": "./dist/tbv/core/utils/eth/index.d.ts",
|
|
39
|
+
"require": "./dist/tbv/core/utils/eth/index.cjs",
|
|
40
|
+
"import": "./dist/tbv/core/utils/eth/index.js"
|
|
41
|
+
},
|
|
37
42
|
"./tbv/core/clients": {
|
|
38
43
|
"types": "./dist/tbv/core/clients/index.d.ts",
|
|
39
44
|
"require": "./dist/tbv/core/clients/index.cjs",
|
|
40
45
|
"import": "./dist/tbv/core/clients/index.js"
|
|
41
46
|
},
|
|
47
|
+
"./tbv/core/clients/eth": {
|
|
48
|
+
"types": "./dist/tbv/core/clients/eth/index.d.ts",
|
|
49
|
+
"require": "./dist/tbv/core/clients/eth/index.cjs",
|
|
50
|
+
"import": "./dist/tbv/core/clients/eth/index.js"
|
|
51
|
+
},
|
|
52
|
+
"./tbv/core/clients/mempool": {
|
|
53
|
+
"types": "./dist/tbv/core/clients/mempool/index.d.ts",
|
|
54
|
+
"require": "./dist/tbv/core/clients/mempool/index.cjs",
|
|
55
|
+
"import": "./dist/tbv/core/clients/mempool/index.js"
|
|
56
|
+
},
|
|
42
57
|
"./tbv/core/clients/vault-provider/status": {
|
|
43
58
|
"types": "./dist/tbv/core/clients/vault-provider/status/index.d.ts",
|
|
44
59
|
"require": "./dist/tbv/core/clients/vault-provider/status/index.cjs",
|
|
@@ -106,16 +121,29 @@
|
|
|
106
121
|
"license": "ISC",
|
|
107
122
|
"description": "TypeScript SDK for Babylon protocol integrations",
|
|
108
123
|
"dependencies": {
|
|
109
|
-
"@
|
|
124
|
+
"@noble/curves": "1.9.7",
|
|
110
125
|
"@noble/hashes": "2.0.1",
|
|
111
126
|
"buffer": "6.0.3"
|
|
112
127
|
},
|
|
113
128
|
"peerDependencies": {
|
|
129
|
+
"@babylonlabs-io/babylon-tbv-rust-wasm": "0.18.0",
|
|
114
130
|
"@bitcoin-js/tiny-secp256k1-asmjs": "2.2.3",
|
|
115
131
|
"bitcoinjs-lib": "6.1.7",
|
|
116
132
|
"viem": "^2.38.2"
|
|
117
133
|
},
|
|
134
|
+
"peerDependenciesMeta": {
|
|
135
|
+
"@babylonlabs-io/babylon-tbv-rust-wasm": {
|
|
136
|
+
"optional": true
|
|
137
|
+
},
|
|
138
|
+
"@bitcoin-js/tiny-secp256k1-asmjs": {
|
|
139
|
+
"optional": true
|
|
140
|
+
},
|
|
141
|
+
"bitcoinjs-lib": {
|
|
142
|
+
"optional": true
|
|
143
|
+
}
|
|
144
|
+
},
|
|
118
145
|
"devDependencies": {
|
|
146
|
+
"@babylonlabs-io/babylon-tbv-rust-wasm": "0.18.0",
|
|
119
147
|
"@vitest/coverage-v8": "^4.0.8",
|
|
120
148
|
"@vitest/ui": "^4.0.8",
|
|
121
149
|
"eslint-plugin-jsdoc": "^50.6.17",
|
|
@@ -136,7 +164,8 @@
|
|
|
136
164
|
"provenance": true
|
|
137
165
|
},
|
|
138
166
|
"scripts": {
|
|
139
|
-
"build": "tsc -b --noEmit tsconfig.lib.json && vite build",
|
|
167
|
+
"build": "tsc -b --noEmit tsconfig.lib.json && vite build && node scripts/check-eth-build.js",
|
|
168
|
+
"check:packed-consumer": "node scripts/check-packed-consumer.js",
|
|
140
169
|
"format": "prettier --check \"src/**/*.ts\"",
|
|
141
170
|
"format:fix": "prettier --write \"src/**/*.ts\"",
|
|
142
171
|
"lint": "eslint .",
|
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
const e = [
|
|
2
|
-
{
|
|
3
|
-
type: "function",
|
|
4
|
-
name: "getBtcVaultProtocolInfo",
|
|
5
|
-
inputs: [
|
|
6
|
-
{
|
|
7
|
-
name: "vaultId",
|
|
8
|
-
type: "bytes32",
|
|
9
|
-
internalType: "bytes32"
|
|
10
|
-
}
|
|
11
|
-
],
|
|
12
|
-
outputs: [
|
|
13
|
-
{
|
|
14
|
-
name: "vProtocol",
|
|
15
|
-
type: "tuple",
|
|
16
|
-
internalType: "struct BTCVaultRegistryTypes.BTCVaultProtocolInfo",
|
|
17
|
-
components: [
|
|
18
|
-
{
|
|
19
|
-
name: "depositorSignedPeginTx",
|
|
20
|
-
type: "bytes",
|
|
21
|
-
internalType: "bytes"
|
|
22
|
-
},
|
|
23
|
-
{
|
|
24
|
-
name: "universalChallengersVersion",
|
|
25
|
-
type: "uint16",
|
|
26
|
-
internalType: "uint16"
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
name: "appVaultKeepersVersion",
|
|
30
|
-
type: "uint16",
|
|
31
|
-
internalType: "uint16"
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
name: "offchainParamsVersion",
|
|
35
|
-
type: "uint16",
|
|
36
|
-
internalType: "uint16"
|
|
37
|
-
},
|
|
38
|
-
{
|
|
39
|
-
name: "verifiedAt",
|
|
40
|
-
type: "uint256",
|
|
41
|
-
internalType: "uint256"
|
|
42
|
-
},
|
|
43
|
-
{
|
|
44
|
-
name: "depositorWotsPkHash",
|
|
45
|
-
type: "bytes32",
|
|
46
|
-
internalType: "bytes32"
|
|
47
|
-
},
|
|
48
|
-
{
|
|
49
|
-
name: "hashlock",
|
|
50
|
-
type: "bytes32",
|
|
51
|
-
internalType: "bytes32"
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
name: "htlcVout",
|
|
55
|
-
type: "uint8",
|
|
56
|
-
internalType: "uint8"
|
|
57
|
-
},
|
|
58
|
-
{
|
|
59
|
-
name: "depositorPopSignature",
|
|
60
|
-
type: "bytes",
|
|
61
|
-
internalType: "bytes"
|
|
62
|
-
},
|
|
63
|
-
{
|
|
64
|
-
name: "prePeginTxHash",
|
|
65
|
-
type: "bytes32",
|
|
66
|
-
internalType: "bytes32"
|
|
67
|
-
},
|
|
68
|
-
{
|
|
69
|
-
name: "vaultProviderCommissionBps",
|
|
70
|
-
type: "uint16",
|
|
71
|
-
internalType: "uint16"
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
name: "claimExpiredUntil",
|
|
75
|
-
type: "uint256",
|
|
76
|
-
internalType: "uint256"
|
|
77
|
-
},
|
|
78
|
-
{
|
|
79
|
-
name: "vaultCoreVersion",
|
|
80
|
-
type: "uint16",
|
|
81
|
-
internalType: "uint16"
|
|
82
|
-
},
|
|
83
|
-
// RFC-006: per-pegin operation-key epochs, frozen at
|
|
84
|
-
// `submitPeginRequest`. All three pack into one storage slot and were
|
|
85
|
-
// appended after `vaultCoreVersion` so pre-existing rows decode
|
|
86
|
-
// unchanged.
|
|
87
|
-
{
|
|
88
|
-
name: "vpKeyEpoch",
|
|
89
|
-
type: "uint64",
|
|
90
|
-
internalType: "uint64"
|
|
91
|
-
},
|
|
92
|
-
{
|
|
93
|
-
name: "appKeeperKeyEpoch",
|
|
94
|
-
type: "uint64",
|
|
95
|
-
internalType: "uint64"
|
|
96
|
-
},
|
|
97
|
-
{
|
|
98
|
-
name: "ucKeyEpoch",
|
|
99
|
-
type: "uint64",
|
|
100
|
-
internalType: "uint64"
|
|
101
|
-
}
|
|
102
|
-
]
|
|
103
|
-
}
|
|
104
|
-
],
|
|
105
|
-
stateMutability: "view"
|
|
106
|
-
}
|
|
107
|
-
];
|
|
108
|
-
export {
|
|
109
|
-
e as B
|
|
110
|
-
};
|
|
111
|
-
//# sourceMappingURL=BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistryKeyEpochs.abi.ts"],"sourcesContent":["/**\n * BTCVaultRegistry ABI — RFC-006 key-epoch view of `getBtcVaultProtocolInfo`.\n *\n * This is a deliberate second copy of a single function entry, NOT a\n * convenience re-export, and it must never be merged into\n * `BTCVaultRegistryABI`.\n *\n * `getBtcVaultProtocolInfo` returns a *positional* tuple. RFC-006 appended\n * three `uint64` epoch fields (`vpKeyEpoch`, `appKeeperKeyEpoch`,\n * `ucKeyEpoch`) after `vaultCoreVersion`. Declaring those three components\n * against a registry that predates RFC-006 makes viem read past the end of\n * the returndata and throw — and because the shared reader batches this call\n * through `multicall({ allowFailure: false })`, one bad decode fails the\n * whole batch. That would break vault status, resume, payout and refund\n * app-wide, on every network whose registry has not been upgraded yet.\n *\n * So the shared `BTCVaultRegistryABI` keeps the 13-field shape that decodes\n * against every deployed registry, and the extended shape lives here, read\n * only by `ViemVaultRegistryReader.getVaultKeyEpochs*` on the epoch-aware\n * path. Reading the same call through two ABIs is the price of keeping the\n * shared decode path independent of the registry version.\n *\n * The 13 shared components must stay an exact prefix of the 16 below;\n * `__tests__/abi-key-epochs.test.ts` pins that.\n *\n * Generated from vault-contracts-aave-v4\n * `src/protocol/lib/types/BTCVaultRegistryTypes.sol`.\n *\n * @module contracts/abis/BTCVaultRegistryKeyEpochs\n */\n\nexport const BTCVaultRegistryKeyEpochsABI = [\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vProtocol\",\n type: \"tuple\",\n internalType: \"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo\",\n components: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"claimExpiredUntil\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"vaultCoreVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n // RFC-006: per-pegin operation-key epochs, frozen at\n // `submitPeginRequest`. All three pack into one storage slot and were\n // appended after `vaultCoreVersion` so pre-existing rows decode\n // unchanged.\n {\n name: \"vpKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"appKeeperKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"ucKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n"],"names":["BTCVaultRegistryKeyEpochsABI"],"mappings":"AA+BO,MAAMA,IAA+B;AAAA,EAC1C;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,Q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ACN,MAAM;AAAA,YACN,cAAc;AAAA,UAAA;AAAA,UAEhB;AAAA,YACE,MAAM;AAAA,YACN,MAAM;AAAA,YACN,cAAc;AAAA,UAAA;AAAA,UAEhB;AAAA,YACE,MAAM;AAAA,YACN,MAAM;AAAA,YACN,cAAc;AAAA,UAAA;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AAAA,IAEF,iBAAiB;AAAA,EAAA;AAErB;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const e=[{type:"function",name:"getBtcVaultProtocolInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"vProtocol",type:"tuple",internalType:"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo",components:[{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"universalChallengersVersion",type:"uint16",internalType:"uint16"},{name:"appVaultKeepersVersion",type:"uint16",internalType:"uint16"},{name:"offchainParamsVersion",type:"uint16",internalType:"uint16"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"},{name:"vaultProviderCommissionBps",type:"uint16",internalType:"uint16"},{name:"claimExpiredUntil",type:"uint256",internalType:"uint256"},{name:"vaultCoreVersion",type:"uint16",internalType:"uint16"},{name:"vpKeyEpoch",type:"uint64",internalType:"uint64"},{name:"appKeeperKeyEpoch",type:"uint64",internalType:"uint64"},{name:"ucKeyEpoch",type:"uint64",internalType:"uint64"}]}],stateMutability:"view"}];exports.BTCVaultRegistryKeyEpochsABI=e;
|
|
2
|
-
//# sourceMappingURL=BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistryKeyEpochs.abi.ts"],"sourcesContent":["/**\n * BTCVaultRegistry ABI — RFC-006 key-epoch view of `getBtcVaultProtocolInfo`.\n *\n * This is a deliberate second copy of a single function entry, NOT a\n * convenience re-export, and it must never be merged into\n * `BTCVaultRegistryABI`.\n *\n * `getBtcVaultProtocolInfo` returns a *positional* tuple. RFC-006 appended\n * three `uint64` epoch fields (`vpKeyEpoch`, `appKeeperKeyEpoch`,\n * `ucKeyEpoch`) after `vaultCoreVersion`. Declaring those three components\n * against a registry that predates RFC-006 makes viem read past the end of\n * the returndata and throw — and because the shared reader batches this call\n * through `multicall({ allowFailure: false })`, one bad decode fails the\n * whole batch. That would break vault status, resume, payout and refund\n * app-wide, on every network whose registry has not been upgraded yet.\n *\n * So the shared `BTCVaultRegistryABI` keeps the 13-field shape that decodes\n * against every deployed registry, and the extended shape lives here, read\n * only by `ViemVaultRegistryReader.getVaultKeyEpochs*` on the epoch-aware\n * path. Reading the same call through two ABIs is the price of keeping the\n * shared decode path independent of the registry version.\n *\n * The 13 shared components must stay an exact prefix of the 16 below;\n * `__tests__/abi-key-epochs.test.ts` pins that.\n *\n * Generated from vault-contracts-aave-v4\n * `src/protocol/lib/types/BTCVaultRegistryTypes.sol`.\n *\n * @module contracts/abis/BTCVaultRegistryKeyEpochs\n */\n\nexport const BTCVaultRegistryKeyEpochsABI = [\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vProtocol\",\n type: \"tuple\",\n internalType: \"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo\",\n components: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"claimExpiredUntil\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"vaultCoreVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n // RFC-006: per-pegin operation-key epochs, frozen at\n // `submitPeginRequest`. All three pack into one storage slot and were\n // appended after `vaultCoreVersion` so pre-existing rows decode\n // unchanged.\n {\n name: \"vpKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"appKeeperKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"ucKeyEpoch\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n"],"names":["BTCVaultRegistryKeyEpochsABI"],"mappings":"aA+BO,MAAMA,EAA+B,CAC1C,CACE,KAAM,WACN,KAAM,0BACN,OAAQ,CACN,CACE,KAAM,UACN,KAAM,UACN,aAAc,SAAA,CAChB,EAEF,QAAS,CACP,CACE,KAAM,YACN,KAAM,QACN,aAAc,oDACd,WAAY,CACV,CACE,KAAM,yBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,8BACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,yBACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,wBACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,aACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,sBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,wBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,iBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,6BACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,oBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,mBACN,KAAM,SACN,aAAc,QAAA,EAMhB,CACE,KAAM,aACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,oBACN,KAAM,SACN,aAAc,QAAA,EAEhB,CACE,KAAM,aACN,KAAM,SACN,aAAc,QAAA,CAChB,CACF,CACF,EAEF,gBAAiB,MAAA,CAErB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var We=Object.defineProperty;var Ne=(s,e,t)=>e in s?We(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var T=(s,e,t)=>Ne(s,typeof e!="symbol"?e+"":e,t);const b=require("./sha2-DsrLC4NM.cjs"),L=require("bitcoinjs-lib"),D=require("buffer"),M=require("viem"),R=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),$=require("./errors-CGcNP0rV.cjs"),K=require("./tbv/core/wasm/index.cjs"),V=require("./verifyScriptPathSchnorrSignature-BfNUSgA7.cjs"),U=require("./verifyKeyPathSchnorrSignature-BedSbH2D.cjs"),h=require("./bitcoin-D-O2GjbC.cjs"),te=require("./validation-C6XTfZak.cjs"),q=require("./signing-BJ3X66b-.cjs"),ae=require("./parseFundingOutpoints-BkgGihaY.cjs"),I=require("./signPsbtsWithFallback-CrkvpSJz.cjs"),G=require("./waitForTransactionReceiptSmartAware-DpQ69ySe.cjs"),de=require("./fundPeginTransaction-BLD8FRL9.cjs"),X=require("./constants-Bh38W9mq.cjs"),O=require("./mempoolApi-DronQ5xn.cjs"),Ue=require("@bitcoin-js/tiny-secp256k1-asmjs");function we(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const ye=we(L),Le=we(Ue),Y=BigInt(2**32-1),pe=BigInt(32);function Ke(s,e=!1){return e?{h:Number(s&Y),l:Number(s>>pe&Y)}:{h:Number(s>>pe&Y)|0,l:Number(s&Y)|0}}function Xe(s,e=!1){const t=s.length;let o=new Uint32Array(t),i=new Uint32Array(t);for(let r=0;r<t;r++){const{h:n,l:a}=Ke(s[r],e);[o[r],i[r]]=[n,a]}return[o,i]}const qe=(s,e,t)=>s<<t|e>>>32-t,Ge=(s,e,t)=>e<<t|s>>>32-t,Ye=(s,e,t)=>e<<t-32|s>>>64-t,ze=(s,e,t)=>s<<t-32|e>>>64-t,je=64;function ke(s){const e=s.prepeginTxid.toLowerCase();if(!/^[0-9a-f]+$/.test(e)||e.length!==je)throw new Error(`buildDepositTerms: prepeginTxid must be 64 hex chars, got "${s.prepeginTxid}"`);if(s.peginAmounts.length===0)throw new Error("buildDepositTerms: at least one pegin amount is required");if(s.timelockPegin<=0||s.timelockAssert<=0||s.timelockRefund<=0)throw new Error("buildDepositTerms: timelocks must be positive");if(!Number.isInteger(s.maxAcceptableCommissionBps)||s.maxAcceptableCommissionBps<0||s.maxAcceptableCommissionBps>=X.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${X.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s.maxAcceptableCommissionBps}`);const t=BigInt(X.BPS_DENOMINATOR),o=s.peginAmounts.map((i,r)=>({htlcVout:r,vaultProviderBtcPubkey:s.vaultProviderBtcPubkey,peginAmount:i,commissionFee:i*BigInt(s.maxAcceptableCommissionBps)/t,depositorClaimValue:s.depositorClaimValue,peginMaxFee:s.peginMaxFee}));return{vaultCoreVersion:s.vaultCoreVersion,protocolFeeRate:s.protocolFeeRate,timelockPegin:s.timelockPegin,timelockAssert:s.timelockAssert,timelockRefund:s.timelockRefund,prepeginTxid:e,prepeginMaxFee:s.prepeginMaxFee,vaultKeeperBtcPubkeys:[...s.vaultKeeperBtcPubkeys],universalChallengerBtcPubkeys:[...s.universalChallengerBtcPubkeys],vaults:o}}const J=25,le=9999;function Z(s){if(!Number.isInteger(s)||s<0||s>=X.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${X.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s}`);return Math.min(s+J,le)}const Qe=/^0x[0-9a-f]+$/i,Ze=/^[0-9a-f]+$/i,Je=/^[A-Za-z0-9+/]+={0,2}$/;function F(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty public key");return h.processPublicKeyToXOnly(s).toLowerCase()}function et(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(s.startsWith("0x")||s.startsWith("0X")){if(!Qe.test(s)||s.length<4||s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return s.toLowerCase()}if(Ze.test(s)){if(s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${s.toLowerCase()}`}if(!Je.test(s)||s.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const e=D.Buffer.from(s,"base64");if(e.length===0||e.toString("base64")!==s)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${e.toString("hex")}`}async function Te(s){const{wallet:e,depositTerms:t,fundedPrePeginTxHex:o,depositorBtcPubkey:i}=s,r=typeof e.approveDepositTerms=="function"?e.approveDepositTerms:void 0;if(!r&&!t)return;const n=o.startsWith("0x")?o.slice(2):o,c=L.Transaction.fromHex(n).getId();if(t&&t.prepeginTxid.replace(/^0x/,"").toLowerCase()!==c)throw new Error(`Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${t.prepeginTxid}, but this transaction is ${c}.`);if(!r)return;if(!t)throw new Error("This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild.");if(typeof e.deriveContextHash!="function")throw new Error("A deposit-approval wallet must also implement deriveContextHash, but this one does not.");if(typeof e.holdsApprovedDepositTerms=="function"){let m=!1;try{m=await e.holdsApprovedDepositTerms(t)}catch{}if(m)return}typeof e.validateDepositTerms=="function"&&await e.validateDepositTerms(t);const d=ae.parseFundingOutpointsFromTx(o);(await ae.deriveVaultRoot({deriveContextHash:e.deriveContextHash.bind(e)},{depositorBtcPubkey:h.hexToUint8Array(F(i)),fundingOutpoints:d})).fill(0),await r.call(e,t)}const tt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ee=Uint8Array.from(new Array(16).fill(0).map((s,e)=>e)),st=Ee.map(s=>(9*s+5)%16),ve=(()=>{const t=[[Ee],[st]];for(let o=0;o<4;o++)for(let i of t)i.push(i[o].map(r=>tt[r]));return t})(),Se=ve[0],Be=ve[1],_e=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(s=>Uint8Array.from(s)),ot=Se.map((s,e)=>s.map(t=>_e[e][t])),rt=Be.map((s,e)=>s.map(t=>_e[e][t])),nt=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),it=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function fe(s,e,t,o){return s===0?e^t^o:s===1?e&t|~e&o:s===2?(e|~t)^o:s===3?e&o|t&~o:e^(t|~o)}const z=new Uint32Array(16);class at extends b.HashMD{constructor(){super(64,20,8,!0);T(this,"h0",1732584193);T(this,"h1",-271733879);T(this,"h2",-1732584194);T(this,"h3",271733878);T(this,"h4",-1009589776)}get(){const{h0:t,h1:o,h2:i,h3:r,h4:n}=this;return[t,o,i,r,n]}set(t,o,i,r,n){this.h0=t|0,this.h1=o|0,this.h2=i|0,this.h3=r|0,this.h4=n|0}process(t,o){for(let l=0;l<16;l++,o+=4)z[l]=t.getUint32(o,!0);let i=this.h0|0,r=i,n=this.h1|0,a=n,c=this.h2|0,d=c,p=this.h3|0,m=p,x=this.h4|0,w=x;for(let l=0;l<5;l++){const v=4-l,E=nt[l],f=it[l],B=Se[l],A=Be[l],g=ot[l],y=rt[l];for(let u=0;u<16;u++){const k=b.rotl(i+fe(l,n,c,p)+z[B[u]]+E,g[u])+x|0;i=x,x=p,p=b.rotl(c,10)|0,c=n,n=k}for(let u=0;u<16;u++){const k=b.rotl(r+fe(v,a,d,m)+z[A[u]]+f,y[u])+w|0;r=w,w=m,m=b.rotl(d,10)|0,d=a,a=k}}this.set(this.h1+c+m|0,this.h2+p+w|0,this.h3+x+r|0,this.h4+i+a|0,this.h0+n+d|0)}roundClean(){b.clean(z)}destroy(){this.destroyed=!0,b.clean(this.buffer),this.set(0,0,0,0,0)}}const ct=b.createHasher(()=>new at),lt=BigInt(0),N=BigInt(1),ut=BigInt(2),ht=BigInt(7),dt=BigInt(256),pt=BigInt(113),Ae=[],Ce=[],Ie=[];for(let s=0,e=N,t=1,o=0;s<24;s++){[t,o]=[o,(2*t+3*o)%5],Ae.push(2*(5*o+t)),Ce.push((s+1)*(s+2)/2%64);let i=lt;for(let r=0;r<7;r++)e=(e<<N^(e>>ht)*pt)%dt,e&ut&&(i^=N<<(N<<BigInt(r))-N);Ie.push(i)}const He=Xe(Ie,!0),ft=He[0],gt=He[1],ge=(s,e,t)=>t>32?Ye(s,e,t):qe(s,e,t),me=(s,e,t)=>t>32?ze(s,e,t):Ge(s,e,t);function mt(s,e=24){const t=new Uint32Array(10);for(let o=24-e;o<24;o++){for(let n=0;n<10;n++)t[n]=s[n]^s[n+10]^s[n+20]^s[n+30]^s[n+40];for(let n=0;n<10;n+=2){const a=(n+8)%10,c=(n+2)%10,d=t[c],p=t[c+1],m=ge(d,p,1)^t[a],x=me(d,p,1)^t[a+1];for(let w=0;w<50;w+=10)s[n+w]^=m,s[n+w+1]^=x}let i=s[2],r=s[3];for(let n=0;n<24;n++){const a=Ce[n],c=ge(i,r,a),d=me(i,r,a),p=Ae[n];i=s[p],r=s[p+1],s[p]=c,s[p+1]=d}for(let n=0;n<50;n+=10){for(let a=0;a<10;a++)t[a]=s[n+a];for(let a=0;a<10;a++)s[n+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=ft[o],s[1]^=gt[o]}b.clean(t)}class ue{constructor(e,t,o,i=!1,r=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=o,this.enableXOF=i,this.rounds=r,b.anumber(o,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=b.u32(this.state)}clone(){return this._cloneInto()}keccak(){b.swap32IfBE(this.state32),mt(this.state32,this.rounds),b.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(e){b.aexists(this),b.abytes(e);const{blockLen:t,state:o}=this,i=e.length;for(let r=0;r<i;){const n=Math.min(t-this.pos,i-r);for(let a=0;a<n;a++)o[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:o,blockLen:i}=this;e[o]^=t,(t&128)!==0&&o===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){b.aexists(this,!1),b.abytes(e),this.finish();const t=this.state,{blockLen:o}=this;for(let i=0,r=e.length;i<r;){this.posOut>=o&&this.keccak();const n=Math.min(o-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+n),i),this.posOut+=n,i+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return b.anumber(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(b.aoutput(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,b.clean(this.state)}_cloneInto(e){const{blockLen:t,suffix:o,outputLen:i,rounds:r,enableXOF:n}=this;return e||(e=new ue(t,o,i,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=o,e.outputLen=i,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Pt=(s,e,t,o={})=>b.createHasher(()=>new ue(e,s,t),o),bt=Pt(1,136,32),Pe=64,_=20,ce=4,Re=2,xt=0,wt=1,j=[64,64],yt=s=>Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("");function he(s){return ct(b.sha256(s))}function Oe(s){return(1<<s)-1}function kt(s){let e=1;for(;e*e<s+1;)e++;return Math.max(e,2)}function Tt(s){const e=ce,t=s*Oe(e);return{d:e,n:s,checksum_radix:kt(t)}}function se(s,e){const t=[];let o=e;for(;o>0;)t.push(o&255),o>>>=8;const i=new Uint8Array(s.length+t.length);i.set(s);for(let r=0;r<t.length;r++)i[s.length+r]=t[r];return he(i)}function oe(s,e){let t=s;for(let o=0;o<e;o++)t=he(t);return t}function Et(s,e){const t=Oe(e.d),o=e.checksum_radix-1,i=Math.floor(e.n*t/e.checksum_radix),r=[];for(let p=0;p<e.n;p++){const m=se(s,p+Re),x=oe(m,t);r.push(Array.from(x))}const n=se(s,xt),a=oe(n,o),c=se(s,wt),d=oe(c,i);return{config:e,message_terminals:r,checksum_major_terminal:Array.from(d),checksum_minor_terminal:Array.from(a)}}async function $e(s){try{if(s.length!==Pe)throw new Error(`WOTS seed must be exactly ${Pe} bytes, got ${s.length}`);const e=[];for(let t=0;t<j.length;t++){const o=j[t],i=Tt(o),r=new Uint8Array(s.length+1);r.set(s),r[s.length]=t;const n=he(r);try{const a=Et(n,i);if(a.config.d!==ce)throw new Error(`Block ${t}: expected d=${ce}, got d=${a.config.d}`);if(a.config.n!==o)throw new Error(`Block ${t}: expected n=${o}, got n=${a.config.n}`);if(a.message_terminals.length!==o)throw new Error(`Block ${t}: expected ${o} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==_)throw new Error(`Block ${t} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==_)throw new Error(`Block ${t} checksum_minor: expected ${_} bytes`);if(a.checksum_major_terminal.length!==_)throw new Error(`Block ${t} checksum_major: expected ${_} bytes`);e.push(a)}finally{r.fill(0),n.fill(0)}}if(e.length!==j.length)throw new Error(`Expected ${j.length} blocks, got ${e.length}`);return e}finally{s.fill(0)}}function re(s,e,t){if(s.length!==_)throw new Error(`Block ${e} ${t}: expected ${_} bytes, got ${s.length}`);for(let o=0;o<s.length;o++){const i=s[o];if(!Number.isInteger(i)||i<0||i>255)throw new Error(`Block ${e} ${t}[${o}]: invalid byte value ${i}`)}}function Ve(s){if(s.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<s.length;r++){const n=s[r];re(n.checksum_minor_terminal,r,"checksum_minor_terminal"),re(n.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<n.message_terminals.length;a++)re(n.message_terminals[a],r,`message_terminal[${a}]`)}let e=0;for(const r of s)e+=Re+r.message_terminals.length;const t=new Uint8Array(e*_);let o=0;for(const r of s){t.set(r.checksum_minor_terminal,o),o+=_,t.set(r.checksum_major_terminal,o),o+=_;for(const n of r.message_terminals)t.set(n,o),o+=_}const i=bt(t);return`0x${yt(i)}`}async function Me(s,e){const t=[],o=[],i=[],r=[];try{for(let n=0;n<e;n++){const a=await K.expandWotsSeed(s,n);try{const d=await $e(a);t.push(d),o.push(Ve(d))}finally{a.fill(0)}const c=await K.expandHashlockSecret(s,n);try{const d=h.uint8ArrayToHex(c);i.push(d),r.push(I.computeHashlock(h.ensureHexPrefix(d)).slice(2))}finally{c.fill(0)}}}finally{s.fill(0)}return{perVaultWotsKeys:t,wotsPkHashes:o,htlcSecretHexes:i,hashlocks:r}}const vt=1,St=2,Bt=33,_t=2,At=3,Ct=1,Q=64,It=0,ne=1,be=/^[0-9a-f]{64}$/i,Ht=/^(?:[0-9a-f]{2})+$/;function Rt(s){const e=s.slice(2);if(!Ht.test(e))throw new Error("proof of possession witness is not even-length lowercase hex");return U.decodeWitnessStack(Uint8Array.from(D.Buffer.from(e,"hex")),"proof of possession witness")}function Ot(s,e,t){var i;const o=Rt(t);if(o.length===vt){const[r]=o;let n,a;if(r.length===Q)n=r,a=It;else if(r.length===Q+1&&r[Q]===ne)n=r.subarray(0,Q),a=ne;else throw new Error("proof of possession witness item must be a 64-byte Schnorr signature (or 65 bytes ending in 0x01)");if(!be.test(e))throw new Error(`depositor public key must be bare 64-char x-only hex, got "${e}"`);const c=Uint8Array.from(D.Buffer.from(e,"hex"));if(!O.verifyBip322Simple(s,c,n,a))throw new Error("proof of possession signature does not verify against the depositor key");return{kind:"p2tr-verified"}}if(o.length===St){if(!be.test(e))throw new Error(`depositor public key must be bare 64-char x-only hex, got "${e}"`);const[r,n]=o;if(n.length!==Bt||n[0]!==_t&&n[0]!==At)throw new Error(`proof of possession P2WPKH witness item 1 is not a compressed public key (${n.length} bytes, prefix 0x${((i=n[0])==null?void 0:i.toString(16))??"none"})`);if(!Le.isPointCompressed(n))throw new Error("proof of possession P2WPKH witness pubkey is not a valid secp256k1 point");const a=D.Buffer.from(n.subarray(Ct)).toString("hex");if(a!==e.toLowerCase())throw new Error(`proof of possession witness pubkey does not match the depositor key: witness carries ${a}, expected ${e}`);if(r.length<O.P2WPKH_ENCODED_SIG_MIN||r.length>O.P2WPKH_ENCODED_SIG_MAX)throw new Error(`proof of possession signature is ${r.length} bytes; vault ingestion accepts only 71/72-byte DER signatures with a sighash byte — try a different account or a Taproot address`);if(r[r.length-1]!==ne)throw new Error(`proof of possession P2WPKH signature must end in a SIGHASH_ALL (0x01) byte, got 0x${r[r.length-1].toString(16)}`);if(!O.verifyBip322P2wpkhSimple(s,n,r))throw new Error("proof of possession signature does not verify against the depositor key");return{kind:"p2wpkh-verified"}}throw new Error(`proof of possession witness has ${o.length} items; expected 1 (P2TR) or 2 (P2WPKH)`)}const Fe=0,ie="00".repeat(32),$t="00".repeat(32);function Vt(s,e){const t={bitcoin:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"};try{const o=ye.address.fromBech32(s);return o.prefix===t[e]&&o.version===0&&o.data.length===20}catch{return!1}}function Mt(s,e,t,o){const i=t==null?void 0:t[`${s}:${e}`];return i?Promise.resolve({txid:s,vout:e,value:i.value,scriptPubKey:i.scriptPubKey}):O.getUtxoInfo(s,e,o)}const xe=12e4;class Ft{constructor(e){T(this,"config");this.config=e}async preparePegin(e){if(e.amounts.length===0)throw new Error("amounts must contain at least one entry");const t=await this.config.btcWallet.getPublicKeyHex(),o=F(t);if(I.supportsDepositApproval(this.config.btcWallet)){const f=(await I.requireChangeAddress(this.config.btcWallet)).trim();if(e.changeAddress.trim()!==f)throw new Error(`Pre-PegIn changeAddress "${e.changeAddress}" is not the approval wallet's change address ("${f}"). Refusing to build a tx the signing device would reject.`)}else if(!h.isAddressFromPublicKey(e.changeAddress,t,this.config.btcNetwork))throw new Error(`Pre-PegIn changeAddress "${e.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`);const i=await this.prepareSizing(o,e);if(I.supportsDepositApproval(this.config.btcWallet)){const{validateDepositTerms:f}=this.config.btcWallet;typeof f=="function"&&await f.call(this.config.btcWallet,this.buildPeginDepositTerms({params:e,prepeginTxid:$t,prepeginMaxFee:i.fee,depositorClaimValue:i.depositorClaimValue,peginMaxFee:i.minPeginFee}))}const r=i.selectedUTXOs.map(f=>({txid:h.hexToUint8Array(f.txid),vout:f.vout})),n=await ae.deriveVaultRoot(this.config.btcWallet,{depositorBtcPubkey:h.hexToUint8Array(o),fundingOutpoints:r});let a,c;try{const f=await K.expandAuthAnchor(n);try{a=h.uint8ArrayToHex(f),c=h.uint8ArrayToHex(b.sha256(f))}finally{f.fill(0)}}catch(f){throw n.fill(0),f}const d=await Me(n,e.amounts.length),{perVaultWotsKeys:p,wotsPkHashes:m,htlcSecretHexes:x,hashlocks:w}=d,l=await this.preparePeginCommit({depositorBtcPubkeyRaw:t,depositorBtcPubkey:o,hashlocks:w,authAnchorHash:c,sizing:i,params:e});for(let f=0;f<l.perVault.length;f++)if(l.perVault[f].htlcVout!==f)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${f} (expected ${f}, got ${l.perVault[f].htlcVout})`);I.assertAuthAnchorOpReturn(l.fundedPrePeginTxHex,e.amounts.length,c);const{depositTerms:v,...E}=l;return{transaction:{...E,selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount},depositorBtcPubkey:o,derivedSecrets:{perVaultWotsKeys:p,wotsPkHashes:m,htlcSecretHexes:x,authAnchorHex:a},depositTerms:v}}async prepareSizing(e,t){const o=t.amounts.map(()=>ie),i=t.vaultKeeperBtcPubkeys.length,r=await V.buildPrePeginPsbt({vaultCoreVersion:t.vaultCoreVersion,depositorPubkey:e,vaultProviderPubkey:h.stripHexPrefix(t.vaultProviderBtcPubkey),vaultKeeperPubkeys:t.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerPubkeys:t.universalChallengerBtcPubkeys.map(h.stripHexPrefix),hashlocks:o,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,minPeginFeeRate:t.minPeginFeeRate,numLocalChallengers:i,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork,authAnchorHash:ie}),n=G.selectUtxosForPegin([...t.availableUTXOs],r.totalOutputValue,t.mempoolFeeRate,de.peginOutputCount(r.htlcValues.length,!0));return{selectedUTXOs:n.selectedUTXOs,fee:n.fee,changeAmount:n.changeAmount,depositorClaimValue:r.depositorClaimValue,minPeginFee:r.minPeginFee}}buildPeginDepositTerms(e){const{params:t}=e;return ke({vaultCoreVersion:t.vaultCoreVersion,protocolFeeRate:t.protocolFeeRate,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,timelockRefund:t.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:h.stripHexPrefix(t.vaultProviderBtcPubkey),vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys.map(h.stripHexPrefix),maxAcceptableCommissionBps:Z(t.commissionBps),peginAmounts:t.amounts,depositorClaimValue:e.depositorClaimValue,peginMaxFee:e.peginMaxFee})}async preparePeginCommit(e){const{depositorBtcPubkeyRaw:t,depositorBtcPubkey:o,hashlocks:i,authAnchorHash:r,sizing:n,params:a}=e,c=ie.toLowerCase();for(let P=0;P<i.length;P++)if(i[P].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${P} — internal substitution bug`);if(r.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const d=h.stripHexPrefix(a.vaultProviderBtcPubkey),p=a.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),m=a.universalChallengerBtcPubkeys.map(h.stripHexPrefix),x=p.length,w={vaultCoreVersion:a.vaultCoreVersion,depositorPubkey:o,vaultProviderPubkey:d,vaultKeeperPubkeys:p,universalChallengerPubkeys:m,hashlocks:i,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,minPeginFeeRate:a.minPeginFeeRate,numLocalChallengers:x,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:r},l=await V.buildPrePeginPsbt(w);if(l.depositorClaimValue!==n.depositorClaimValue||l.minPeginFee!==n.minPeginFee)throw new Error(`Pre-PegIn sizing/commit divergence: depositorClaimValue ${n.depositorClaimValue} -> ${l.depositorClaimValue}, minPeginFee ${n.minPeginFee} -> ${l.minPeginFee}. The provisional deposit terms validated before derivation would not match the terms sent for approval; refusing to continue.`);const v=h.getNetwork(this.config.btcNetwork),E=de.fundPeginTransaction({unfundedTxHex:l.psbtHex,selectedUTXOs:n.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:n.changeAmount,network:v}),f=n.selectedUTXOs.reduce((P,S)=>P+BigInt(S.value),0n)-l.totalOutputValue-n.changeAmount;if(f!==n.fee)throw new Error(`Pre-PegIn funded fee ${f} does not match the sizing-pass fee ${n.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`);const B=h.stripHexPrefix(q.calculateBtcTxHash(E)),A=[],g=[],y=[];for(let P=0;P<i.length;P++){const S=await V.buildPeginTxFromFundedPrePegin({prePeginParams:w,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:E,htlcVout:P}),H=await U.buildPeginInputPsbt({vaultCoreVersion:a.vaultCoreVersion,peginTxHex:S.txHex,fundedPrePeginTxHex:E,depositorPubkey:o,vaultProviderPubkey:d,vaultKeeperPubkeys:p,universalChallengerPubkeys:m,hashlock:i[P],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});A.push(S),g.push(H.psbtHex),y.push(q.createTaprootScriptPathSignOptions(t,1))}const u=this.buildPeginDepositTerms({params:a,prepeginTxid:B,prepeginMaxFee:n.fee,depositorClaimValue:l.depositorClaimValue,peginMaxFee:l.minPeginFee});I.supportsDepositApproval(this.config.btcWallet)&&await this.config.btcWallet.approveDepositTerms(u);const k=await I.signPsbtsWithFallback(this.config.btcWallet,g,y),C=[];for(let P=0;P<k.length;P++){V.assertPsbtUnsignedTxMatches({requestedPsbtHex:g[P],returnedPsbtHex:k[P]});const S=U.extractPeginInputSignature(k[P],o);V.assertScriptPathSchnorrSignature({requestedPsbtHex:g[P],signatureHex:S,signerXOnlyPubkeyHex:o,inputIndex:0});const H=U.finalizePeginInputPsbt(k[P]);C.push({htlcVout:P,htlcValue:l.htlcValues[P],peginTxHex:H,peginTxid:A[P].txid,peginInputSignature:S,vaultScriptPubKey:A[P].vaultScriptPubKey})}return{fundedPrePeginTxHex:E,prePeginTxid:B,perVault:C,depositTerms:u}}async signAndBroadcast(e){const{fundedPrePeginTxHex:t,depositorBtcPubkey:o}=e,i=t.startsWith("0x")?t.slice(2):t,r=L.Transaction.fromHex(i);if(r.ins.length===0)throw new Error("Transaction has no inputs");const n=new L.Psbt;n.setVersion(r.version),n.setLocktime(r.locktime);const a=D.Buffer.from(F(o),"hex"),c=this.config.mempoolApiUrl,d=r.ins.map(g=>{const y=D.Buffer.from(g.hash).reverse().toString("hex"),u=g.index;return Mt(y,u,e.localPrevouts,c).then(k=>({input:g,utxoData:k,txid:y,vout:u}))}),p=await Promise.all(d),m=p.reduce((g,y)=>g+BigInt(y.utxoData.value),0n),x=r.outs.reduce((g,y)=>g+BigInt(y.value),0n);if(m<x)throw new Error(`UTXO value mismatch: total input value (${m} sat) is less than total output value (${x} sat). This may indicate the mempool API returned manipulated UTXO data.`);const w=m-x;if(w>te.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${w} sat) exceeds maximum reasonable fee (${te.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:g,utxoData:y,txid:u,vout:k}of p){const C=G.getPsbtInputFields({value:y.value,scriptPubKey:y.scriptPubKey},a);n.addInput({hash:g.hash,index:g.index,sequence:g.sequence,...C})}for(const g of r.outs)n.addOutput({script:g.script,value:g.value});await Te({wallet:this.config.btcWallet,depositTerms:e.depositTerms,fundedPrePeginTxHex:t,depositorBtcPubkey:o});const l=n.toHex(),v=await this.config.btcWallet.signPsbt(l);V.assertPsbtUnsignedTxMatches({requestedPsbtHex:l,returnedPsbtHex:v});const E=U.assertReturnedKeyPathSignatures({requestedPsbtHex:l,returnedPsbtHex:v});if(I.supportsDepositApproval(this.config.btcWallet)&&E!==n.data.inputs.length)throw new Error(`Key-path verification covered ${E} of ${n.data.inputs.length} Pre-PegIn inputs; an approval wallet signs every input key-path, so the unverified ones must not be broadcast.`);const f=L.Psbt.fromHex(v);try{f.finalizeAllInputs()}catch(g){if(!f.data.inputs.every(u=>u.finalScriptWitness||u.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${g}`)}const B=f.extractTransaction().toHex();return await O.pushTx(B,c)}async registerPeginOnChain(e){const{unsignedPrePeginTx:t,depositorSignedPeginTx:o,vaultProvider:i,hashlock:r,htlcVout:n,depositorPayoutBtcAddress:a,depositorWotsPkHash:c,popSignature:d}=e;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const p=this.config.ethWallet.account.address;if(!M.isAddressEqual(d.depositorEthAddress,p))throw new Error(`Proof of possession was signed for ${d.depositorEthAddress} but the Ethereum wallet is currently connected to ${p}. Reconnect the original account or call signProofOfPossession() again.`);const m=await this.assertPopMatchesBtcWallet(d),x=d.btcPopSignature,w=h.ensureHexPrefix(d.depositorBtcPubkey),l=h.ensureHexPrefix(t),v=h.ensureHexPrefix(o),E=a??await this.config.btcWallet.getAddress(),f=this.resolvePayoutScriptPubKey(m,E),B=q.calculateBtcTxHash(v),A=await K.deriveVaultId(h.stripHexPrefix(B),h.stripHexPrefix(p)),g=h.ensureHexPrefix(A);if(await this.checkVaultExists(g))throw new Error(`Vault already exists (ID: ${g}, peginTxHash: ${B}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const u=this.config.publicClient;let k;try{k=await u.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[i]})}catch(W){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:W})}const C=await this.resolveMaxAcceptableCommissionBps(i,e.quotedCommissionBps),P=M.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[p,w,x,l,v,i,C,r,n,f,c]});let S;try{S=await u.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:P,value:k,account:this.config.ethWallet.account.address})}catch(W){$.handleContractError(W)}let H;try{H=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:P,value:k,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:S})}catch(W){$.handleContractError(W)}const ee=await G.waitForTransactionReceiptSmartAware({publicClient:u,walletAddress:this.config.ethWallet.account.address,hash:H,timeout:xe});return ee.status==="reverted"&&$.handleContractError(new Error(`Transaction reverted. Hash: ${ee.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:ee.transactionHash,vaultId:g,peginTxHash:B}}async registerPeginBatchOnChain(e){const{vaultProvider:t,unsignedPrePeginTx:o,requests:i,popSignature:r}=e;if(i.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const n=this.config.ethWallet.account.address;if(!M.isAddressEqual(r.depositorEthAddress,n))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${n}. Reconnect the original account or call signProofOfPossession() again.`);const a=await this.assertPopMatchesBtcWallet(r),c=r.btcPopSignature,d=i.map(u=>this.resolvePayoutScriptPubKey(a,u.depositorPayoutBtcAddress)),p=[];for(const u of i){const k=h.ensureHexPrefix(u.depositorSignedPeginTx),C=q.calculateBtcTxHash(k),P=await K.deriveVaultId(h.stripHexPrefix(C),h.stripHexPrefix(n)),S=h.ensureHexPrefix(P);if(await this.checkVaultExists(S))throw new Error(`Vault already exists (ID: ${S}, peginTxHash: ${C}). To create a new vault, use different UTXOs or a different amount.`);p.push({vaultId:S,peginTxHash:C})}const m=this.config.publicClient;let x;try{x=await m.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}catch(u){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:u})}const w=x*BigInt(i.length),l=await this.resolveMaxAcceptableCommissionBps(t,e.quotedCommissionBps),v=h.ensureHexPrefix(r.depositorBtcPubkey),E=h.ensureHexPrefix(o),f=i.map((u,k)=>({depositorBtcPubKey:v,btcPopSignature:c,unsignedPrePeginTx:E,depositorSignedPeginTx:h.ensureHexPrefix(u.depositorSignedPeginTx),hashlock:u.hashlock,htlcVout:u.htlcVout,referralCode:Fe,depositorPayoutBtcAddress:d[k],depositorWotsPkHash:u.depositorWotsPkHash})),B=M.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,t,l,f]});let A;try{A=await m.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:B,value:w,account:this.config.ethWallet.account.address})}catch(u){$.handleContractError(u)}let g;try{g=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:B,value:w,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:A})}catch(u){$.handleContractError(u)}const y=await G.waitForTransactionReceiptSmartAware({publicClient:m,walletAddress:this.config.ethWallet.account.address,hash:g,timeout:xe});return y.status==="reverted"&&$.handleContractError(new Error(`Batch transaction reverted. Hash: ${y.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:y.transactionHash,vaults:p}}async resolveMaxAcceptableCommissionBps(e,t){if(t===void 0&&I.supportsDepositApproval(this.config.btcWallet))throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.");let o;try{o=await new O.ViemVaultRegistryReader(this.config.publicClient,this.config.vaultContracts.btcVaultRegistry).getVaultProviderCommission(e)}catch(i){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and that the contract address is correct.",{cause:i})}if(t!==void 0){if(o>t+J)throw new Error(`Vault provider commission changed since quote: quoted ${t} bps, chain currently reports ${o} bps (allowed drift ${J} bps). Please refresh to see the new commission and try again.`);return Z(t)}return Z(o)}async checkVaultExists(e){return(await this.config.publicClient.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]})).depositor!==M.zeroAddress}resolvePayoutScriptPubKey(e,t){if(!h.isAddressFromPublicKey(t,e,this.config.btcNetwork))throw h.stripHexPrefix(e).length===te.X_ONLY_PUBKEY_HEX_LEN&&Vt(t,this.config.btcNetwork)?new Error(`BTC payout address "${t}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`):new Error(`BTC payout address "${t}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`);const o=h.getNetwork(this.config.btcNetwork);try{return`0x${ye.address.toOutputScript(t,o).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${t}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const e=this.config.ethWallet.account.address,t=F(await this.config.btcWallet.getPublicKeyHex()),o=this.config.vaultContracts.btcVaultRegistry,i=`${e.toLowerCase()}:${this.config.ethChain.id}:pegin:${o.toLowerCase()}`,r=await this.config.btcWallet.signMessage(i,"bip322-simple"),n=et(r);return Ot(new TextEncoder().encode(i),t,n),{btcPopSignature:n,depositorEthAddress:e,depositorBtcPubkey:t}}async assertPopMatchesBtcWallet(e){const t=await this.config.btcWallet.getPublicKeyHex(),o=F(t),i=F(e.depositorBtcPubkey);if(o!==i)throw new Error(`Proof of possession was signed with BTC pubkey ${i} but the BTC wallet is currently connected to ${o}. Reconnect the original wallet or call signProofOfPossession() again.`);return t}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}const Dt=80,Wt=250,Nt=300,Ut=22,De="ab";function Lt(s,e){const t=De.repeat(Nt),o=h.stripHexPrefix(s).toLowerCase(),i=e.toString(16).padStart(8,"0"),r=`${o}${i}`,n=t.slice(r.length);return`0x${r}${n}`}function Kt(s,e){const t=o=>`0x${De.repeat(o)}`;return{depositorBtcPubKey:t(32),btcPopSignature:t(Dt),unsignedPrePeginTx:t(Wt),depositorSignedPeginTx:Lt(s,e),hashlock:t(32),htlcVout:e,referralCode:Fe,depositorPayoutBtcAddress:t(Ut),depositorWotsPkHash:t(32)}}async function Xt(s){const{publicClient:e,btcVaultRegistry:t,depositorEthAddress:o,vaultProvider:i,batchSize:r}=s;if(r<=0)throw new Error(`estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${r})`);const a=await e.readContract({address:t,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[i]})*BigInt(r),c=Array.from({length:r},(p,m)=>Kt(o,m)),d=M.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[o,i,le,c]});return e.estimateGas({to:t,data:d,value:a,account:o})}exports.COMMISSION_BPS_HEADROOM=J;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=le;exports.PeginManager=Ft;exports.buildDepositTerms=ke;exports.capMaxAcceptableCommissionBps=Z;exports.computeWotsBlockPublicKeysHash=Ve;exports.deriveWotsBlocksFromSeed=$e;exports.ensurePrePeginTermsApproval=Te;exports.estimateSubmitPeginRequestBatchGas=Xt;exports.expandPerVaultSecrets=Me;
|
|
2
|
-
//# sourceMappingURL=PeginManager-Bn8FxM35.cjs.map
|