@babylonlabs-io/ts-sdk 0.71.0 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/PeginManager-Bn8FxM35.cjs +2 -0
  2. package/dist/{PeginManager-BIKAnZ-X.cjs.map → PeginManager-Bn8FxM35.cjs.map} +1 -1
  3. package/dist/{PeginManager-Byvmccdd.js → PeginManager-C3ojNTlv.js} +6 -6
  4. package/dist/{PeginManager-Byvmccdd.js.map → PeginManager-C3ojNTlv.js.map} +1 -1
  5. package/dist/{buildAndBroadcastReclaim-C0TdwO2M.js → buildAndBroadcastReclaim-YvWDRAN8.js} +492 -489
  6. package/dist/{buildAndBroadcastReclaim-C0TdwO2M.js.map → buildAndBroadcastReclaim-YvWDRAN8.js.map} +1 -1
  7. package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs +2 -0
  8. package/dist/{buildAndBroadcastReclaim-kRx7-o2y.cjs.map → buildAndBroadcastReclaim-zfjDI5__.cjs.map} +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +227 -226
  11. package/dist/{mempoolApi-CRNMOsbC.js → mempoolApi-CKD_IbrM.js} +32 -33
  12. package/dist/mempoolApi-CKD_IbrM.js.map +1 -0
  13. package/dist/mempoolApi-DronQ5xn.cjs +2 -0
  14. package/dist/mempoolApi-DronQ5xn.cjs.map +1 -0
  15. package/dist/noPayout-DpGRzidi.js +353 -0
  16. package/dist/noPayout-DpGRzidi.js.map +1 -0
  17. package/dist/noPayout-zEifyecV.cjs +2 -0
  18. package/dist/noPayout-zEifyecV.cjs.map +1 -0
  19. package/dist/{primeVpAuth-tEXx9TGx.cjs → primeVpAuth-Cjq6qFHq.cjs} +2 -2
  20. package/dist/primeVpAuth-Cjq6qFHq.cjs.map +1 -0
  21. package/dist/{primeVpAuth-D1qbOkhb.js → primeVpAuth-tLRjdHwZ.js} +2 -2
  22. package/dist/primeVpAuth-tLRjdHwZ.js.map +1 -0
  23. package/dist/{signPsbtsWithFallback-BjXdnI0X.js → signPsbtsWithFallback-CCFTzE0o.js} +3 -3
  24. package/dist/{signPsbtsWithFallback-BjXdnI0X.js.map → signPsbtsWithFallback-CCFTzE0o.js.map} +1 -1
  25. package/dist/{signPsbtsWithFallback-zOQWokmk.cjs → signPsbtsWithFallback-CrkvpSJz.cjs} +2 -2
  26. package/dist/{signPsbtsWithFallback-zOQWokmk.cjs.map → signPsbtsWithFallback-CrkvpSJz.cjs.map} +1 -1
  27. package/dist/signing-BJ3X66b-.cjs +2 -0
  28. package/dist/signing-BJ3X66b-.cjs.map +1 -0
  29. package/dist/signing-Cm-McVR2.js +22 -0
  30. package/dist/signing-Cm-McVR2.js.map +1 -0
  31. package/dist/tbv/core/clients/eth/types.d.ts +0 -2
  32. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  33. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  34. package/dist/tbv/core/clients/index.cjs +1 -1
  35. package/dist/tbv/core/clients/index.js +2 -2
  36. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +9 -1
  37. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  38. package/dist/tbv/core/index.cjs +1 -1
  39. package/dist/tbv/core/index.js +222 -221
  40. package/dist/tbv/core/managers/index.cjs +1 -1
  41. package/dist/tbv/core/managers/index.js +2 -2
  42. package/dist/tbv/core/primitives/index.cjs +1 -1
  43. package/dist/tbv/core/primitives/index.d.ts +2 -0
  44. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  45. package/dist/tbv/core/primitives/index.js +23 -22
  46. package/dist/tbv/core/primitives/psbt/__tests__/finalizeScriptPathWithSignatures.test.d.ts +11 -0
  47. package/dist/tbv/core/primitives/psbt/__tests__/finalizeScriptPathWithSignatures.test.d.ts.map +1 -0
  48. package/dist/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.d.ts +52 -0
  49. package/dist/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.d.ts.map +1 -0
  50. package/dist/tbv/core/primitives/psbt/reclaim.d.ts +23 -1
  51. package/dist/tbv/core/primitives/psbt/reclaim.d.ts.map +1 -1
  52. package/dist/tbv/core/services/index.cjs +1 -1
  53. package/dist/tbv/core/services/index.js +2 -2
  54. package/dist/tbv/core/services/reclaim/__tests__/buildAndBroadcastReclaim.walletPsbt.test.d.ts +14 -0
  55. package/dist/tbv/core/services/reclaim/__tests__/buildAndBroadcastReclaim.walletPsbt.test.d.ts.map +1 -0
  56. package/dist/tbv/core/services/reclaim/buildAndBroadcastReclaim.d.ts +14 -2
  57. package/dist/tbv/core/services/reclaim/buildAndBroadcastReclaim.d.ts.map +1 -1
  58. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
  59. package/dist/tbv/core/utils/index.cjs +1 -1
  60. package/dist/tbv/core/utils/index.js +13 -13
  61. package/dist/tbv/index.cjs +1 -1
  62. package/dist/tbv/index.js +222 -221
  63. package/dist/toRefundInputs-CY9u84U9.cjs +2 -0
  64. package/dist/{toRefundInputs-Bdtz8p27.cjs.map → toRefundInputs-CY9u84U9.cjs.map} +1 -1
  65. package/dist/{toRefundInputs-CgXMcHrk.js → toRefundInputs-Df1vi23S.js} +5 -5
  66. package/dist/{toRefundInputs-CgXMcHrk.js.map → toRefundInputs-Df1vi23S.js.map} +1 -1
  67. package/dist/{verifyScriptPathSchnorrSignature-mzYCzaSy.cjs → verifyScriptPathSchnorrSignature-BfNUSgA7.cjs} +2 -2
  68. package/dist/{verifyScriptPathSchnorrSignature-mzYCzaSy.cjs.map → verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map} +1 -1
  69. package/dist/{verifyScriptPathSchnorrSignature-ZAZfFJ6S.js → verifyScriptPathSchnorrSignature-Ciq_xZhw.js} +5 -4
  70. package/dist/{verifyScriptPathSchnorrSignature-ZAZfFJ6S.js.map → verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map} +1 -1
  71. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs +2 -0
  72. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs.map +1 -0
  73. package/dist/{waitForTransactionReceiptSmartAware-B6oYRdFO.js → waitForTransactionReceiptSmartAware-z3Xfmo44.js} +42 -47
  74. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js.map +1 -0
  75. package/package.json +1 -1
  76. package/dist/PeginManager-BIKAnZ-X.cjs +0 -2
  77. package/dist/buildAndBroadcastReclaim-kRx7-o2y.cjs +0 -2
  78. package/dist/mempoolApi-BQllf-ji.cjs +0 -2
  79. package/dist/mempoolApi-BQllf-ji.cjs.map +0 -1
  80. package/dist/mempoolApi-CRNMOsbC.js.map +0 -1
  81. package/dist/noPayout--lxo7qe4.js +0 -300
  82. package/dist/noPayout--lxo7qe4.js.map +0 -1
  83. package/dist/noPayout-CegnEwfp.cjs +0 -2
  84. package/dist/noPayout-CegnEwfp.cjs.map +0 -1
  85. package/dist/primeVpAuth-D1qbOkhb.js.map +0 -1
  86. package/dist/primeVpAuth-tEXx9TGx.cjs.map +0 -1
  87. package/dist/signing-Bnsro0hE.cjs +0 -2
  88. package/dist/signing-Bnsro0hE.cjs.map +0 -1
  89. package/dist/signing-DaLvGwQe.js +0 -16
  90. package/dist/signing-DaLvGwQe.js.map +0 -1
  91. package/dist/toRefundInputs-Bdtz8p27.cjs +0 -2
  92. package/dist/waitForTransactionReceiptSmartAware-B6oYRdFO.js.map +0 -1
  93. package/dist/waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs +0 -2
  94. package/dist/waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"primeVpAuth-tEXx9TGx.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","../src/tbv/core/clients/vault-provider/auth/cbor.ts","../src/tbv/core/clients/vault-provider/auth/serverIdentity.ts","../src/tbv/core/clients/vault-provider/auth/gatedMethods.ts","../src/tbv/core/clients/vault-provider/auth/innerTokenClient.ts","../src/tbv/core/clients/vault-provider/auth/cborDecode.ts","../src/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.ts","../src/tbv/core/clients/vault-provider/auth/tokenProvider.ts","../src/tbv/core/clients/vault-provider/auth/tokenRegistry.ts","../src/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.ts","../src/tbv/core/clients/vault-provider/auth/primeVpAuth.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 ) {\n const results = (await this.publicClient.multicall({\n contracts: calls,\n allowFailure: false,\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 ): 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 );\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 async getPegInConfiguration(): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\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 ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\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 ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\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 ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\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(): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\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 /** Block deadline (uint256) for depositor reclaim. TODO(#1690): wire to refund flow. */\n claimExpiredUntil: bigint;\n /** Vault core version (uint16) stamped at registration. VP-side gating only — see #1690. */\n vaultCoreVersion: number;\n}\n\n/** Combined vault data (basic + protocol) */\nexport interface VaultData {\n basic: VaultBasicInfo;\n protocol: VaultProtocolInfo;\n}\n\n/**\n * 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 ): 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 getPegInConfiguration(): 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/** Interface for reading vault keepers from the ApplicationRegistry contract. */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(appEntryPoint: Address): Promise<number>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(): 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(query: OperationKeyQuery): 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","/**\n * Minimal CBOR encoder for the server-identity payload shape.\n *\n * We only need to encode one specific CBOR structure — the 3-tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey_bytes, expires_at_u64)` —\n * byte-for-byte identical to what the Rust `ciborium` crate produces\n * for the corresponding tuple, because that's the exact message the\n * VP signs with BIP-322.\n *\n * IMPORTANT encoding quirk: the Rust side passes the domain and\n * pubkey as `&[u8]` / `Vec<u8>` without a `#[serde(with = \"serde_bytes\")]`\n * attribute, so serde/ciborium encodes them as **CBOR arrays of u8**\n * (major type 4, one item per byte) — NOT as CBOR byte strings (major\n * type 2). A naive byte-string encoding would produce the wrong bytes\n * and signature verification would fail.\n *\n * Rather than pull in a full CBOR dependency for this one shape, we\n * implement the exact subset inline (~40 LOC) and pin it with golden\n * vectors against the Rust reference output.\n *\n * @module tbv/core/clients/vault-provider/auth/cbor\n */\n\n/**\n * Encode a small CBOR unsigned-integer \"head\" byte for major type\n * `major` (0..7) with argument `arg` (0..2^64-1).\n *\n * Returns the header bytes; the caller concatenates any trailing data\n * (e.g. array elements). Encoding rules:\n * arg < 24 → single byte `(major << 5) | arg`\n * arg < 256 → `(major << 5) | 24` + 1-byte arg\n * arg < 65536 → `(major << 5) | 25` + 2-byte BE arg\n * arg < 2^32 → `(major << 5) | 26` + 4-byte BE arg\n * arg < 2^64 → `(major << 5) | 27` + 8-byte BE arg\n */\nfunction cborHead(major: number, arg: number | bigint): Uint8Array {\n const tag = (major & 0x07) << 5;\n const n = typeof arg === \"bigint\" ? arg : BigInt(arg);\n if (n < 0n) throw new Error(\"cborHead: negative argument\");\n\n if (n < 24n) return new Uint8Array([tag | Number(n)]);\n if (n < 0x100n) return new Uint8Array([tag | 24, Number(n)]);\n if (n < 0x10000n) {\n const v = Number(n);\n return new Uint8Array([tag | 25, (v >>> 8) & 0xff, v & 0xff]);\n }\n if (n < 0x1_0000_0000n) {\n const v = Number(n);\n return new Uint8Array([\n tag | 26,\n (v >>> 24) & 0xff,\n (v >>> 16) & 0xff,\n (v >>> 8) & 0xff,\n v & 0xff,\n ]);\n }\n // 8-byte BE for u64 range\n const out = new Uint8Array(9);\n out[0] = tag | 27;\n for (let i = 7; i >= 0; i--) {\n out[1 + i] = Number(n >> BigInt((7 - i) * 8)) & 0xff;\n }\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\n/**\n * Encode a `Vec<u8>` / `&[u8]` the way ciborium does by default — as a\n * CBOR array of u8 (major type 4), one element per byte.\n *\n * Each byte becomes a CBOR unsigned integer (major type 0): bytes\n * < 24 are encoded as single bytes, bytes 24..255 as `0x18 XX`.\n */\nfunction encodeBytesAsArrayOfU8(bytes: Uint8Array): Uint8Array {\n const header = cborHead(4, bytes.length);\n const items: Uint8Array[] = [header];\n for (const b of bytes) {\n items.push(cborHead(0, b));\n }\n return concat(...items);\n}\n\n/**\n * Encode the server-identity payload the Rust side signs:\n *\n * ciborium::into_writer(\n * &(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey.serialize().to_vec(), expires_at),\n * buf\n * )\n *\n * Output bytes are byte-for-byte identical to the Rust reference,\n * pinned by the golden vector in the corresponding test file.\n *\n * @internal Exposed only for the golden-vector test that pins this\n * encoding against ciborium's output. Production callers reach this\n * via `verifyServerIdentity` from `./serverIdentity`.\n *\n * @param domain - Must be `\"btc-auth.server-identity.v1\"` (27 bytes)\n * — the constant from btc-vault's `server_identity.rs`.\n * @param ephemeralPubkeyCompressed - 33-byte SEC1-compressed pubkey.\n * @param expiresAt - Unix timestamp (seconds). Must be a safe integer.\n */\nexport function encodeServerIdentityPayload(\n domain: Uint8Array,\n ephemeralPubkeyCompressed: Uint8Array,\n expiresAt: number,\n): Uint8Array {\n if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {\n throw new Error(\n `encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${expiresAt}`,\n );\n }\n const arrayHeader = cborHead(4, 3); // 3-tuple encoded as array of 3\n const domainBytes = encodeBytesAsArrayOfU8(domain);\n const pubkeyBytes = encodeBytesAsArrayOfU8(ephemeralPubkeyCompressed);\n const expiresAtBytes = cborHead(0, expiresAt);\n return concat(arrayHeader, domainBytes, pubkeyBytes, expiresAtBytes);\n}\n","/**\n * Server-identity verification for the vault provider's\n * `auth_createDepositorToken` response.\n *\n * The VP returns a `ServerIdentityResponse` bundled with every issued\n * token:\n *\n * - `server_pubkey`: VP's persistent x-only pubkey (HEX, 32B)\n * - `ephemeral_pubkey`: VP's ephemeral token-signing key (HEX, 33B compressed)\n * - `expires_at`: Unix timestamp when the ephemeral key expires\n * - `signature`: BIP-322 signature by the persistent key over\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`\n *\n * The FE pins `server_pubkey` against the on-chain `VaultProvider.btcPubKey`\n * it reads from the registry contract. A mismatch rejects the token.\n *\n * @module tbv/core/clients/vault-provider/auth/serverIdentity\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { verifyBip322Simple } from \"./bip322Verify\";\nimport { encodeServerIdentityPayload } from \"./cbor\";\n\n/**\n * Byte-string domain the btc-vault Rust reference passes as the first\n * element of the CBOR tuple signed over for server-identity proofs.\n * Must match `SERVER_IDENTITY_DOMAIN` in\n * `btc-vault/crates/btc-auth/src/server_identity.rs`.\n */\nconst SERVER_IDENTITY_DOMAIN = new TextEncoder().encode(\n \"btc-auth.server-identity.v1\",\n);\n\n/**\n * Cap on `proof.expires_at - now`. Bounds how long a leaked VP\n * ephemeral key stays usable; the bearer token's own TTL does not\n * (different trust boundary). 2h = Rust ref VP's 1h rotation × 2 for\n * clock skew. Override per call via `maxLifetimeSecs`.\n */\nconst DEFAULT_MAX_PROOF_LIFETIME_SECS = 2 * 3600;\n\n/**\n * Wire representation from btc-vault's `ServerIdentityResponse`.\n */\nexport interface ServerIdentityResponse {\n /** Hex-encoded x-only (32-byte) persistent server pubkey. */\n server_pubkey: string;\n /** Hex-encoded compressed (33-byte) ephemeral token-signing pubkey. */\n ephemeral_pubkey: string;\n /** Unix timestamp at which the ephemeral key expires. */\n expires_at: number;\n /** Hex-encoded 64-byte BIP-322 Schnorr signature. */\n signature: string;\n}\n\nexport interface VerifyServerIdentityInput {\n /** The proof returned by `auth_createDepositorToken`. */\n proof: ServerIdentityResponse;\n /**\n * The x-only persistent server pubkey the FE expects (sourced from\n * the on-chain `VaultProvider.btcPubKey` via the vault registry\n * reader). 64-char lowercase hex, no `0x` prefix.\n */\n pinnedServerPubkey: string;\n /** Current Unix timestamp in seconds. Injected for testability. */\n now: number;\n /** Cap on `proof.expires_at - now` (seconds). Defaults to {@link DEFAULT_MAX_PROOF_LIFETIME_SECS}. */\n maxLifetimeSecs?: number;\n}\n\nexport class ServerIdentityError extends Error {\n constructor(\n message: string,\n public readonly reason:\n | \"pinned_pubkey_mismatch\"\n | \"expired\"\n | \"expires_too_far\"\n | \"invalid_expires_at\"\n | \"invalid_max_lifetime\"\n | \"invalid_pubkey_encoding\"\n | \"invalid_ephemeral_pubkey\"\n | \"invalid_signature_encoding\"\n | \"signature_verification_failed\",\n ) {\n super(message);\n this.name = \"ServerIdentityError\";\n }\n}\n\n/** Parse a lowercase-hex string to bytes. Expects even length, already validated. */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * Verify a server identity proof against a pinned server pubkey.\n *\n * Checks:\n * 1. `server_pubkey` matches the pin.\n * 2. `now < expires_at <= now + maxLifetimeSecs` (with integer guards).\n * 3. `ephemeral_pubkey` is a well-formed 33-byte compressed pubkey.\n * 4. `signature` is a well-formed 64-byte Schnorr hex string.\n * 5. The BIP-322 Schnorr signature cryptographically verifies\n * against `server_pubkey` over the CBOR-encoded tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`.\n *\n * Step 5 is what actually binds the ephemeral key to the persistent\n * pubkey — without it, a TLS-MITM attacker who reads the pinned\n * pubkey from the on-chain registry could substitute an arbitrary\n * ephemeral pubkey paired with any lexically-valid signature.\n *\n * @throws ServerIdentityError on any validation failure.\n */\nexport function verifyServerIdentity(input: VerifyServerIdentityInput): void {\n const { proof, pinnedServerPubkey, now } = input;\n const maxLifetimeSecs =\n input.maxLifetimeSecs ?? DEFAULT_MAX_PROOF_LIFETIME_SECS;\n\n const pinned = stripHexPrefix(pinnedServerPubkey).toLowerCase();\n if (pinned.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(pinned)) {\n throw new ServerIdentityError(\n `pinnedServerPubkey must be 32-byte hex; got ${pinned.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n const actual = stripHexPrefix(proof.server_pubkey).toLowerCase();\n if (actual.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(actual)) {\n throw new ServerIdentityError(\n `server_pubkey must be 32-byte hex; got ${actual.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n if (actual !== pinned) {\n throw new ServerIdentityError(\n `server_pubkey does not match pinned value: expected ${pinned}, got ${actual}`,\n \"pinned_pubkey_mismatch\",\n );\n }\n\n // Validate both sides of the comparison are well-formed integers\n // BEFORE comparing — untrusted JSON-RPC input can supply\n // undefined/NaN/string values for `expires_at`, and relational\n // comparisons with those silently evaluate to `false` (accepting the\n // proof). Caller's `now` is injected but we still sanity-check it.\n // Garbage data and \"valid but past\" both render the proof unusable\n // but mean different things to a caller — keep the reasons distinct.\n if (!Number.isSafeInteger(proof.expires_at)) {\n throw new ServerIdentityError(\n `expires_at must be a finite integer; got ${JSON.stringify(proof.expires_at)}`,\n \"invalid_expires_at\",\n );\n }\n if (!Number.isSafeInteger(now)) {\n throw new ServerIdentityError(\n `now must be a finite integer; got ${JSON.stringify(now)}`,\n \"invalid_expires_at\",\n );\n }\n if (proof.expires_at <= now) {\n throw new ServerIdentityError(\n `server identity proof expired at ${proof.expires_at}, now ${now}`,\n \"expired\",\n );\n }\n if (!Number.isSafeInteger(maxLifetimeSecs) || maxLifetimeSecs <= 0) {\n throw new ServerIdentityError(\n `maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(maxLifetimeSecs)}`,\n \"invalid_max_lifetime\",\n );\n }\n if (proof.expires_at - now > maxLifetimeSecs) {\n throw new ServerIdentityError(\n `server identity proof expires too far in the future: ` +\n `expires_at=${proof.expires_at}, now=${now}, max lifetime=${maxLifetimeSecs}s`,\n \"expires_too_far\",\n );\n }\n\n const eph = stripHexPrefix(proof.ephemeral_pubkey).toLowerCase();\n if (eph.length !== COMPRESSED_PUBKEY_HEX_LEN || !HEX_RE.test(eph)) {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be 33-byte compressed hex; got ${eph.length} chars`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n const prefix = eph.slice(0, 2);\n if (prefix !== \"02\" && prefix !== \"03\") {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be compressed (prefix 02/03); got ${prefix}`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n // Curve validation. The BIP-322 signature attests to the byte string\n // of `ephemeral_pubkey` only, not to its curve validity. Without\n // this check, a server could sign a structurally-valid byte string\n // that doesn't decode to a secp256k1 point — passing verification\n // here and surfacing as an obscure crypto error later when the\n // depositor tries to use the key. Reject up front.\n const ephBytes = hexToBytes(eph);\n if (!ecc.isPoint(ephBytes)) {\n throw new ServerIdentityError(\n \"ephemeral_pubkey is not a valid secp256k1 point\",\n \"invalid_ephemeral_pubkey\",\n );\n }\n\n const sig = stripHexPrefix(proof.signature).toLowerCase();\n if (sig.length !== SCHNORR_SIG_HEX_LEN || !HEX_RE.test(sig)) {\n throw new ServerIdentityError(\n `signature must be 64-byte Schnorr hex; got ${sig.length} chars`,\n \"invalid_signature_encoding\",\n );\n }\n\n // Cryptographic verification of the BIP-322 signature over the\n // CBOR-encoded payload. Without this, the ephemeral-key binding is\n // unenforced and a TLS-MITM could substitute a fake ephemeral key\n // alongside the real (publicly-readable) pinned pubkey.\n const payload = encodeServerIdentityPayload(\n SERVER_IDENTITY_DOMAIN,\n hexToBytes(eph),\n proof.expires_at,\n );\n const verified = verifyBip322Simple(\n payload,\n hexToBytes(actual),\n hexToBytes(sig),\n );\n if (!verified) {\n throw new ServerIdentityError(\n \"BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey\",\n \"signature_verification_failed\",\n );\n }\n}\n","/**\n * VP RPC methods that require `Authorization: Bearer <token>`.\n * Protocol invariant — must be kept in sync with the VP server.\n *\n * Split into two sets by the CWT subject the VP demands:\n *\n * - {@link AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorToken` (Subject::VaultdJsonRpc). These run\n * through the proxy's plain JSON-RPC forward path.\n * - {@link GRPC_AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorTokenGrpc` (Subject::VaultdGrpc). The proxy\n * translates these into gRPC calls to vaultd's daemon gRPC server,\n * so a JSON-RPC-subject token would be rejected by\n * `GrpcAuthInterceptor`.\n *\n * @stability frozen\n *\n * @module tbv/core/clients/vault-provider/auth/gatedMethods\n */\n\nexport const AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_submitDepositorWotsKey\",\n \"vaultProvider_submitDepositorPresignatures\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nexport const GRPC_AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n","/**\n * Shared internals for the unauthenticated token-issuing JSON-RPC\n * client. The \"inner\" client is dedicated to `auth_createDepositorToken`\n * — it MUST NOT carry a `tokenProvider`, else the JSON-RPC header\n * builder would recurse into token acquisition.\n *\n * @module tbv/core/clients/vault-provider/auth/innerTokenClient\n */\n\nimport { JsonRpcClient } from \"../json-rpc-client\";\n\nconst TOKEN_RPC_TIMEOUT_MS = 60_000;\n\nexport const TOKEN_ISSUE_METHOD = \"auth_createDepositorToken\";\n/**\n * gRPC-subject sibling of {@link TOKEN_ISSUE_METHOD}. The proxy bridges\n * this call to vaultd's `VaultProviderDepositorAuthService.CreateDepositorToken`\n * so the resulting CWT is bound to `Subject::VaultdGrpc` — required to\n * pass vaultd's `GrpcAuthInterceptor` on methods the proxy translates to\n * gRPC (currently just the artifact stream).\n */\nexport const GRPC_TOKEN_ISSUE_METHOD = \"auth_createDepositorTokenGrpc\";\n\nexport function buildInnerTokenClient(\n baseUrl: string,\n headers?: Record<string, string>,\n): JsonRpcClient {\n return new JsonRpcClient({\n baseUrl,\n timeout: TOKEN_RPC_TIMEOUT_MS,\n headers,\n retryableFor: (method) =>\n method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD,\n });\n}\n","/**\n * Minimal CBOR decoder — the read-side counterpart to {@link ./cbor}.\n *\n * Decodes only the subset needed to verify a vault-provider CWT bearer\n * token (RFC 8392) wrapped in a COSE Sign1 envelope (RFC 8152): tagged\n * values, definite-length arrays and maps, byte/text strings, and\n * unsigned/negative integers. Indefinite-length items, floats, and\n * big-number tags are intentionally rejected — the issuer\n * (btc-vault's `coset`/`ciborium` stack) never emits them for this\n * shape, so accepting them would only widen the parser's attack\n * surface.\n *\n * The decoder is a cursor over a single buffer. {@link CborReader.pos}\n * is public so callers can slice the exact encoded byte range of an\n * item (head + content) — required to reconstruct the COSE\n * `Sig_structure` byte-for-byte from the token's own protected-header\n * and payload byte strings.\n *\n * @module tbv/core/clients/vault-provider/auth/cborDecode\n */\n\n/** CBOR major types (the high 3 bits of the initial byte). */\nconst MAJOR_UNSIGNED_INT = 0;\nconst MAJOR_NEGATIVE_INT = 1;\nconst MAJOR_BYTE_STRING = 2;\nconst MAJOR_TEXT_STRING = 3;\nconst MAJOR_ARRAY = 4;\nconst MAJOR_MAP = 5;\nconst MAJOR_TAG = 6;\nconst MAJOR_SIMPLE = 7;\n\n/**\n * Smallest additional-info value that introduces a multi-byte argument\n * (24 ⇒ 1 byte, 25 ⇒ 2, 26 ⇒ 4, 27 ⇒ 8 — i.e. `1 << (info - 24)`).\n */\nconst ARG_IN_NEXT_1_BYTE = 24;\n/** Additional-info ≥ this (28..31) is reserved/indefinite — unsupported. */\nconst ARG_RESERVED_MIN = 28;\n\n/** Major-7 simple values we accept. */\nconst SIMPLE_FALSE = 20;\nconst SIMPLE_TRUE = 21;\nconst SIMPLE_NULL = 22;\n\n/**\n * Maximum CBOR nesting depth. Mirrors the issuer's recursion cap (256 in\n * btc-vault's `ciborium` stack). The COSE protected header is decoded\n * *before* the signature is verified, so without this bound a\n * malicious/MITM'd VP could send a deeply-nested blob and crash token\n * acquisition with an uncatchable stack overflow. Far below the JS call\n * stack limit, so it converts that DoS into a catchable decode error.\n */\nconst MAX_NESTING_DEPTH = 256;\n\n/** A decoded CBOR data item. Maps preserve key insertion order. */\nexport type CborValue =\n | number\n | bigint\n | string\n | Uint8Array\n | boolean\n | null\n | CborValue[]\n | Map<CborValue, CborValue>\n | CborTagged;\n\n/** A CBOR tagged value (major type 6). */\nexport interface CborTagged {\n tag: number;\n value: CborValue;\n}\n\n/** Parsed initial-byte header: major type plus its decoded argument. */\nexport interface CborHead {\n major: number;\n /** The header argument (length, value, tag number, …) as a number. */\n arg: number;\n}\n\nexport class CborDecodeError extends Error {\n constructor(message: string) {\n super(`CBOR decode: ${message}`);\n this.name = \"CborDecodeError\";\n }\n}\n\n/**\n * Cursor-based reader over a CBOR buffer. Not reusable across buffers —\n * construct one per decode.\n */\nexport class CborReader {\n readonly buf: Uint8Array;\n /** Current read offset. Public so callers can slice encoded sub-ranges. */\n pos = 0;\n\n constructor(buf: Uint8Array) {\n this.buf = buf;\n }\n\n private nextByte(): number {\n if (this.pos >= this.buf.length) {\n throw new CborDecodeError(\"unexpected end of input\");\n }\n return this.buf[this.pos++];\n }\n\n /**\n * Read an initial byte and its argument. Rejects indefinite-length\n * and reserved additional-info encodings. Arguments wider than\n * {@link Number.MAX_SAFE_INTEGER} are rejected — none of the token's\n * lengths, tags, or timestamps approach that bound.\n */\n readHead(): CborHead {\n const initial = this.nextByte();\n const major = initial >> 5;\n const info = initial & 0x1f;\n\n if (info < ARG_IN_NEXT_1_BYTE) {\n return { major, arg: info };\n }\n if (info >= ARG_RESERVED_MIN) {\n throw new CborDecodeError(\n `unsupported additional info ${info} (indefinite-length or reserved)`,\n );\n }\n\n const byteCount = 1 << (info - ARG_IN_NEXT_1_BYTE);\n\n let value = 0n;\n for (let i = 0; i < byteCount; i++) {\n value = (value << 8n) | BigInt(this.nextByte());\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CborDecodeError(`argument ${value} exceeds safe integer range`);\n }\n return { major, arg: Number(value) };\n }\n\n /** Read `length` raw bytes as a sub-array view into the backing buffer. */\n private readBytes(length: number): Uint8Array {\n if (this.pos + length > this.buf.length) {\n throw new CborDecodeError(\"length overruns end of input\");\n }\n const slice = this.buf.subarray(this.pos, this.pos + length);\n this.pos += length;\n return slice;\n }\n\n /**\n * Read a byte string (major type 2), returning its content bytes.\n * Throws if the next item is not a byte string.\n */\n readByteString(): Uint8Array {\n const head = this.readHead();\n if (head.major !== MAJOR_BYTE_STRING) {\n throw new CborDecodeError(\n `expected byte string (major ${MAJOR_BYTE_STRING}), got major ${head.major}`,\n );\n }\n return this.readBytes(head.arg);\n }\n\n /**\n * Read the next complete data item as a decoded {@link CborValue}.\n *\n * `depth` tracks the current nesting level so a deeply-nested blob is\n * rejected with a {@link CborDecodeError} rather than overflowing the\n * native call stack (see {@link MAX_NESTING_DEPTH}).\n */\n readValue(depth = 0): CborValue {\n if (depth > MAX_NESTING_DEPTH) {\n throw new CborDecodeError(\n `nesting exceeds maximum depth ${MAX_NESTING_DEPTH}`,\n );\n }\n const head = this.readHead();\n switch (head.major) {\n case MAJOR_UNSIGNED_INT:\n return head.arg;\n case MAJOR_NEGATIVE_INT:\n // RFC 8949 §3.1: the encoded argument n represents -1 - n.\n return -1 - head.arg;\n case MAJOR_BYTE_STRING:\n return this.readBytes(head.arg);\n case MAJOR_TEXT_STRING:\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n this.readBytes(head.arg),\n );\n case MAJOR_ARRAY: {\n const items: CborValue[] = [];\n for (let i = 0; i < head.arg; i++) {\n items.push(this.readValue(depth + 1));\n }\n return items;\n }\n case MAJOR_MAP: {\n const map = new Map<CborValue, CborValue>();\n for (let i = 0; i < head.arg; i++) {\n const key = this.readValue(depth + 1);\n const value = this.readValue(depth + 1);\n map.set(key, value);\n }\n return map;\n }\n case MAJOR_TAG:\n return { tag: head.arg, value: this.readValue(depth + 1) };\n case MAJOR_SIMPLE:\n if (head.arg === SIMPLE_FALSE) return false;\n if (head.arg === SIMPLE_TRUE) return true;\n if (head.arg === SIMPLE_NULL) return null;\n throw new CborDecodeError(\n `unsupported simple/float value ${head.arg}`,\n );\n default:\n throw new CborDecodeError(`unsupported major type ${head.major}`);\n }\n }\n}\n\n/**\n * Decode a single CBOR item from `bytes`, rejecting any trailing bytes.\n *\n * Used to parse the COSE protected header and CWT claims set — both are\n * exactly one top-level item, so a valid prefix followed by extra bytes\n * is a malformed structure, not a benign tail. Strict consumption keeps\n * the parser from silently accepting a token a stricter CWT/COSE\n * consumer would interpret differently.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue {\n const reader = new CborReader(bytes);\n const value = reader.readValue();\n if (reader.pos !== bytes.length) {\n throw new CborDecodeError(\"trailing bytes after top-level item\");\n }\n return value;\n}\n","/**\n * Verify a vault-provider CWT bearer (RFC 8392 / COSE Sign1, ES256K): checks the\n * signature against the VP's attested ephemeral key (see {@link ./serverIdentity})\n * and binds `iss`/`sub`/`aud` to the pinned VP, subject, and depositor. TS port\n * of btc-vault `client.rs::validate_token_with_public_key_at_time`.\n *\n * Divergence from that reference: the FE does NOT clock-gate `nbf`/`iat`. The VP\n * server is the temporal authority and re-checks `nbf`/`exp` on every gated call;\n * re-checking `nbf` against the browser clock only bricked freshly minted tokens\n * on benign skew. `exp` (wide window) and the structural `iat <= exp` are kept.\n *\n * @module tbv/core/clients/vault-provider/auth/verifyDepositorCwt\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { CborReader, decodeCbor } from \"./cborDecode\";\n\n/** CWT `sub` value for JSON-RPC-subject tokens (`auth_createDepositorToken`). */\nexport const CWT_SUBJECT_JSONRPC = \"vaultd-jsonrpc\";\n/** CWT `sub` value for gRPC-subject tokens (`auth_createDepositorTokenGrpc`). */\nexport const CWT_SUBJECT_GRPC = \"vaultd-grpc\";\n\n/** CBOR tag wrapping a COSE_Sign1 structure (RFC 8152 §2). */\nconst COSE_SIGN1_TAG = 18;\n/** A COSE_Sign1 is a 4-element array: [protected, unprotected, payload, signature]. */\nconst COSE_SIGN1_ARRAY_LEN = 4;\n/** COSE algorithm id for ES256K (ECDSA w/ secp256k1 + SHA-256), RFC 8812. */\nconst COSE_ALG_ES256K = -47;\n/** COSE header label for the algorithm (RFC 8152 §3.1). */\nconst COSE_HEADER_LABEL_ALG = 1;\n/** ECDSA signature length in COSE compact (r‖s) form. */\nconst ECDSA_COMPACT_SIG_LEN = 64;\n\n/** CBOR major-type 4 (array) high bits, for the Sig_structure header. */\nconst CBOR_ARRAY_HEAD = 0x80;\n/** CBOR major-type 3 (text string) high bits, for the context string head. */\nconst CBOR_TEXT_STRING_HEAD = 0x60;\n/** CBOR encoding of an empty byte string (major type 2, length 0). */\nconst CBOR_EMPTY_BYTE_STRING = 0x40;\n\n/** CWT registered claim keys (RFC 8392 §4 / IANA CWT registry). */\nconst CWT_CLAIM_ISS = 1;\nconst CWT_CLAIM_SUB = 2;\nconst CWT_CLAIM_AUD = 3;\nconst CWT_CLAIM_EXP = 4;\nconst CWT_CLAIM_NBF = 5;\nconst CWT_CLAIM_IAT = 6;\nconst CWT_CLAIM_CTI = 7;\n\n/**\n * Context string for a COSE_Sign1 Sig_structure (RFC 8152 §4.4). 10\n * bytes, so it encodes with a single-byte CBOR text-string head.\n */\nconst SIG_STRUCTURE_CONTEXT = new TextEncoder().encode(\"Signature1\");\n\nexport type CwtVerificationReason =\n | \"invalid_input\"\n | \"invalid_token_structure\"\n | \"unexpected_algorithm\"\n | \"signature_verification_failed\"\n | \"invalid_claims\"\n | \"issuer_mismatch\"\n | \"subject_mismatch\"\n | \"audience_mismatch\"\n | \"token_expired\"\n | \"expiry_mismatch\"\n | \"server_identity_expires_before_token\";\n\nexport class CwtVerificationError extends Error {\n constructor(\n message: string,\n public readonly reason: CwtVerificationReason,\n ) {\n super(message);\n this.name = \"CwtVerificationError\";\n }\n}\n\nexport interface VerifyDepositorCwtInput {\n /** Base64url (no padding) COSE Sign1 token from `auth_createDepositorToken`. */\n token: string;\n /**\n * VP ephemeral token-signing pubkey (33-byte compressed hex) from the\n * bundled `server_identity` proof — MUST already be verified by\n * {@link verifyServerIdentity} before being passed here.\n */\n ephemeralPubkeyHex: string;\n /** Pinned VP persistent x-only pubkey (on-chain). Asserted against the token `iss`. */\n expectedIssuerXOnlyPubkey: string;\n /** Expected `sub` — {@link CWT_SUBJECT_JSONRPC} or {@link CWT_SUBJECT_GRPC}. */\n expectedSubject: string;\n /** Depositor x-only pubkey. Asserted against the token `aud`. */\n expectedAudienceXOnlyPubkey: string;\n /** Outer wire `expires_at`. Must equal the token's `exp` exactly. */\n responseExpiresAt: number;\n /** `server_identity.expires_at`. Must be ≥ the token's `exp`. */\n serverIdentityExpiresAt: number;\n /** Current Unix time (seconds). Injected for testability. */\n now: number;\n}\n\nexport interface VerifiedCwtClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/**\n * Verify a depositor CWT and return its claims, or throw\n * {@link CwtVerificationError}.\n *\n * Steps (mirroring the Rust reference; see the divergence note above):\n * 1. Decode the COSE Sign1 envelope and assert the protected header\n * pins ES256K.\n * 2. Verify the ECDSA signature over the reconstructed Sig_structure\n * against the (already server-identity-verified) ephemeral key.\n * 3. Decode the CWT claims and assert `iss`/`sub`/`aud` bindings, the\n * structural `iat <= exp`, `exp` validity, `cti` presence, and the\n * outer-vs-inner expiry cross-checks. `nbf`/`iat` are intentionally not\n * clock-gated here (see the module note above).\n */\nexport function verifyDepositorCwt(\n input: VerifyDepositorCwtInput,\n): VerifiedCwtClaims {\n const expectedIssuer = normalizeXOnly(\n input.expectedIssuerXOnlyPubkey,\n \"expectedIssuerXOnlyPubkey\",\n );\n const expectedAudience = normalizeXOnly(\n input.expectedAudienceXOnlyPubkey,\n \"expectedAudienceXOnlyPubkey\",\n );\n const ephemeral = decodeCompressedPubkey(input.ephemeralPubkeyHex);\n\n const tokenBytes = base64UrlToBytes(input.token);\n\n // --- 1. COSE Sign1 structural decode -------------------------------\n // Capture the exact encoded byte ranges of the protected header and\n // payload so the Sig_structure can be rebuilt byte-for-byte from the\n // token's own bytes (any re-encoding risks a non-canonical mismatch).\n const reader = new CborReader(tokenBytes);\n const tag = reader.readHead();\n if (tag.major !== 6 || tag.arg !== COSE_SIGN1_TAG) {\n throw new CwtVerificationError(\n `token is not a COSE Sign1 tagged value (tag ${COSE_SIGN1_TAG})`,\n \"invalid_token_structure\",\n );\n }\n const array = reader.readHead();\n if (array.major !== 4 || array.arg !== COSE_SIGN1_ARRAY_LEN) {\n throw new CwtVerificationError(\n `COSE Sign1 must be a ${COSE_SIGN1_ARRAY_LEN}-element array`,\n \"invalid_token_structure\",\n );\n }\n\n const protectedStart = reader.pos;\n const protectedContent = reader.readByteString();\n const protectedBstr = tokenBytes.subarray(protectedStart, reader.pos);\n\n // Unprotected header map: present in the envelope but unused here.\n reader.readValue();\n\n const payloadStart = reader.pos;\n const payloadContent = reader.readByteString();\n const payloadBstr = tokenBytes.subarray(payloadStart, reader.pos);\n\n const signature = reader.readByteString();\n if (signature.length !== ECDSA_COMPACT_SIG_LEN) {\n throw new CwtVerificationError(\n `COSE signature must be ${ECDSA_COMPACT_SIG_LEN} bytes, got ${signature.length}`,\n \"invalid_token_structure\",\n );\n }\n // Reject anything after the COSE_Sign1 structure. The bearer we verify\n // must be the exact bytes attached to authenticated calls; a stricter\n // CWT/COSE consumer could interpret trailing bytes differently.\n if (reader.pos !== tokenBytes.length) {\n throw new CwtVerificationError(\n \"COSE Sign1 token has trailing bytes after the signature\",\n \"invalid_token_structure\",\n );\n }\n\n // --- 2a. Algorithm pin --------------------------------------------\n const alg = readProtectedAlgorithm(protectedContent);\n if (alg !== COSE_ALG_ES256K) {\n throw new CwtVerificationError(\n `unexpected COSE algorithm ${alg} (expected ES256K ${COSE_ALG_ES256K})`,\n \"unexpected_algorithm\",\n );\n }\n\n // --- 2b. Signature verification -----------------------------------\n const sigStructure = buildSigStructure(protectedBstr, payloadBstr);\n const digest = sha256(sigStructure);\n // strict = true enforces low-S, matching libsecp256k1's `verify_ecdsa`.\n if (!ecc.verify(digest, ephemeral, signature, true)) {\n throw new CwtVerificationError(\n \"COSE signature does not verify against the server's ephemeral key\",\n \"signature_verification_failed\",\n );\n }\n\n // --- 3. Claims -----------------------------------------------------\n const claims = decodeClaims(payloadContent);\n\n const audience = claims.audience.toLowerCase();\n if (audience.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(audience)) {\n throw new CwtVerificationError(\n \"token `aud` is not a 32-byte x-only pubkey hex\",\n \"invalid_claims\",\n );\n }\n if (claims.issuedAt > claims.expiresAt) {\n throw new CwtVerificationError(\n `token iat (${claims.issuedAt}) is after exp (${claims.expiresAt})`,\n \"invalid_claims\",\n );\n }\n\n if (claims.issuer.toLowerCase() !== expectedIssuer) {\n throw new CwtVerificationError(\n `token issuer does not match pinned server pubkey: expected ${expectedIssuer}, got ${claims.issuer.toLowerCase()}`,\n \"issuer_mismatch\",\n );\n }\n if (claims.subject !== input.expectedSubject) {\n throw new CwtVerificationError(\n `token subject mismatch: expected ${input.expectedSubject}, got ${claims.subject}`,\n \"subject_mismatch\",\n );\n }\n if (audience !== expectedAudience) {\n throw new CwtVerificationError(\n `token audience does not match depositor pubkey: expected ${expectedAudience}, got ${audience}`,\n \"audience_mismatch\",\n );\n }\n // No nbf/iat clock-gate on purpose — the VP server is the temporal authority\n // (re-checks nbf/exp per call). See the module-level divergence note.\n if (claims.expiresAt <= input.now) {\n throw new CwtVerificationError(\n `token expired: exp ${claims.expiresAt} <= now ${input.now}`,\n \"token_expired\",\n );\n }\n if (input.responseExpiresAt !== claims.expiresAt) {\n throw new CwtVerificationError(\n `response expires_at (${input.responseExpiresAt}) does not equal token exp (${claims.expiresAt})`,\n \"expiry_mismatch\",\n );\n }\n if (input.serverIdentityExpiresAt < claims.expiresAt) {\n throw new CwtVerificationError(\n `server identity expires (${input.serverIdentityExpiresAt}) before token exp (${claims.expiresAt})`,\n \"server_identity_expires_before_token\",\n );\n }\n\n return {\n issuer: claims.issuer,\n subject: claims.subject,\n audience,\n expiresAt: claims.expiresAt,\n notBefore: claims.notBefore,\n issuedAt: claims.issuedAt,\n };\n}\n\n/** Read the algorithm label from the COSE protected-header byte string. */\nfunction readProtectedAlgorithm(protectedContent: Uint8Array): number {\n if (protectedContent.length === 0) {\n throw new CwtVerificationError(\n \"empty COSE protected header (no algorithm)\",\n \"unexpected_algorithm\",\n );\n }\n const header = decodeCbor(protectedContent);\n if (!(header instanceof Map)) {\n throw new CwtVerificationError(\n \"COSE protected header is not a map\",\n \"invalid_token_structure\",\n );\n }\n const alg = header.get(COSE_HEADER_LABEL_ALG);\n if (typeof alg !== \"number\") {\n throw new CwtVerificationError(\n \"COSE protected header missing integer algorithm label\",\n \"unexpected_algorithm\",\n );\n }\n return alg;\n}\n\n/**\n * Rebuild the COSE_Sign1 Sig_structure (RFC 8152 §4.4):\n *\n * [ \"Signature1\", body_protected (bstr), external_aad = h'' , payload (bstr) ]\n *\n * `body_protected` and `payload` are spliced verbatim from the token's\n * own encoded byte strings, so the result is byte-identical to what the\n * issuer signed regardless of CBOR canonicalization choices.\n */\nfunction buildSigStructure(\n protectedBstr: Uint8Array,\n payloadBstr: Uint8Array,\n): Uint8Array {\n return concatBytes(\n Uint8Array.of(CBOR_ARRAY_HEAD | COSE_SIGN1_ARRAY_LEN),\n Uint8Array.of(CBOR_TEXT_STRING_HEAD | SIG_STRUCTURE_CONTEXT.length),\n SIG_STRUCTURE_CONTEXT,\n protectedBstr,\n Uint8Array.of(CBOR_EMPTY_BYTE_STRING),\n payloadBstr,\n );\n}\n\ninterface DecodedClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/** Decode and type-check the CWT registered claims from the payload. */\nfunction decodeClaims(payloadContent: Uint8Array): DecodedClaims {\n const root = decodeCbor(payloadContent);\n if (!(root instanceof Map)) {\n throw new CwtVerificationError(\n \"CWT claims root is not a map\",\n \"invalid_claims\",\n );\n }\n const cti = requireBytes(root, CWT_CLAIM_CTI, \"cti\");\n if (cti.length === 0) {\n throw new CwtVerificationError(\"token cti is empty\", \"invalid_claims\");\n }\n return {\n issuer: requireString(root, CWT_CLAIM_ISS, \"iss\"),\n subject: requireString(root, CWT_CLAIM_SUB, \"sub\"),\n audience: requireString(root, CWT_CLAIM_AUD, \"aud\"),\n expiresAt: requireTimestamp(root, CWT_CLAIM_EXP, \"exp\"),\n notBefore: requireTimestamp(root, CWT_CLAIM_NBF, \"nbf\"),\n issuedAt: requireTimestamp(root, CWT_CLAIM_IAT, \"iat\"),\n };\n}\n\nfunction requireString(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): string {\n const value = claims.get(key);\n if (typeof value !== \"string\") {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a text string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireBytes(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): Uint8Array {\n const value = claims.get(key);\n if (!(value instanceof Uint8Array)) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a byte string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireTimestamp(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): number {\n const value = claims.get(key);\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a non-negative integer timestamp`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\n/** Validate and normalize a 32-byte x-only pubkey to lowercase hex. */\nfunction normalizeXOnly(pubkey: string, label: string): string {\n const normalized = stripHexPrefix(pubkey).toLowerCase();\n if (normalized.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(normalized)) {\n throw new CwtVerificationError(\n `${label} must be 32-byte x-only hex; got ${normalized.length} chars`,\n \"invalid_input\",\n );\n }\n return normalized;\n}\n\n/** Validate a 33-byte compressed pubkey hex and return its bytes. */\nfunction decodeCompressedPubkey(pubkeyHex: string): Uint8Array {\n const normalized = stripHexPrefix(pubkeyHex).toLowerCase();\n const prefix = normalized.slice(0, 2);\n if (\n normalized.length !== COMPRESSED_PUBKEY_HEX_LEN ||\n !HEX_RE.test(normalized) ||\n (prefix !== \"02\" && prefix !== \"03\")\n ) {\n throw new CwtVerificationError(\n \"ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)\",\n \"invalid_input\",\n );\n }\n return hexToUint8Array(normalized);\n}\n\nconst B64URL_LOOKUP = (() => {\n const table = new Int16Array(128).fill(-1);\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n for (let i = 0; i < alphabet.length; i++) {\n table[alphabet.charCodeAt(i)] = i;\n }\n return table;\n})();\n\n/** Decode a base64url (no-padding) string to bytes. */\nfunction base64UrlToBytes(input: string): Uint8Array {\n const len = input.length;\n const fullGroups = Math.floor(len / 4);\n const remainder = len % 4;\n if (remainder === 1) {\n throw new CwtVerificationError(\n \"invalid base64url length\",\n \"invalid_token_structure\",\n );\n }\n const outLen = fullGroups * 3 + (remainder === 0 ? 0 : remainder - 1);\n const out = new Uint8Array(outLen);\n\n const sextet = (charCode: number): number => {\n const value = charCode < 128 ? B64URL_LOOKUP[charCode] : -1;\n if (value < 0) {\n throw new CwtVerificationError(\n \"invalid base64url character\",\n \"invalid_token_structure\",\n );\n }\n return value;\n };\n\n let inPos = 0;\n let outPos = 0;\n for (let g = 0; g < fullGroups; g++) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n const d = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n out[outPos++] = ((c & 0x03) << 6) | d;\n }\n if (remainder === 2) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n } else if (remainder === 3) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n }\n return out;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n","/**\n * `VpTokenProvider` — caches CWT bearer tokens issued by the vault\n * provider's `auth_createDepositorToken` RPC, with lazy expiry check\n * and single-flight concurrent acquire.\n *\n * Usage:\n *\n * ```ts\n * const provider = new VpTokenProvider({\n * client,\n * peginTxid,\n * authAnchorHex,\n * pinnedServerPubkey,\n * authGatedMethods,\n * });\n * const bearer = await provider.getToken(method); // null if not gated\n * ```\n *\n * The provider implements the `BearerTokenProvider` interface expected\n * by `JsonRpcClient`. Plug directly:\n *\n * ```ts\n * const client = new JsonRpcClient({ ..., tokenProvider: provider });\n * ```\n *\n * @module tbv/core/clients/vault-provider/auth/tokenProvider\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { BearerTokenProvider, JsonRpcClient } from \"../json-rpc-client\";\nimport {\n GRPC_TOKEN_ISSUE_METHOD,\n TOKEN_ISSUE_METHOD,\n} from \"./innerTokenClient\";\nimport {\n type ServerIdentityResponse,\n verifyServerIdentity,\n} from \"./serverIdentity\";\nimport {\n CWT_SUBJECT_GRPC,\n CWT_SUBJECT_JSONRPC,\n verifyDepositorCwt,\n} from \"./verifyDepositorCwt\";\n\n/**\n * Maximum reasonable `expires_at` value (seconds since epoch). Guards\n * against a bogus far-future timestamp that would lock the cache on a\n * bad token forever. Jan 1, 2100 in Unix seconds.\n */\nconst MAX_EXPIRES_AT_SECS = 4_102_444_800;\n\n/**\n * Default safety margin before `expires_at` — we treat a token as\n * expired this many seconds before its stated expiry so that in-flight\n * requests don't race the expiry boundary.\n */\nconst DEFAULT_REFRESH_SKEW_SECS = 30;\n\n/**\n * Wire response shape of `auth_createDepositorToken`.\n */\nexport interface CreateDepositorTokenResponse {\n /** Base64url-encoded COSE Sign1 CWT bearer token. */\n token: string;\n /** Unix timestamp at which the token expires. */\n expires_at: number;\n /** Server identity proof bundled with every token response. */\n server_identity: ServerIdentityResponse;\n}\n\nexport interface VpTokenProviderConfig {\n client: JsonRpcClient;\n /** Per-vault depositor-signed PegIn tx id. NOT shared across sibling vaults in a batch. */\n peginTxid: string;\n /** 64-char hex of the 32-byte OP_RETURN auth-anchor preimage. */\n authAnchorHex: string;\n /** Pinned VP pubkey from the on-chain registry; branded so indexer mirrors can't substitute. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor x-only pubkey (32-byte hex). Asserted against every\n * issued token's CWT `aud` claim so a token minted for a different\n * depositor — or mis-issued by a buggy/compromised VP — is rejected\n * before it can authenticate a mutation.\n */\n expectedAudienceXOnlyPubkey: string;\n /**\n * Methods that need a JSON-RPC-subject bearer (minted via\n * `auth_createDepositorToken`). Forwarded over plain HTTP JSON-RPC by\n * the proxy. `getToken` returns `null` for any method outside this and\n * {@link grpcGatedMethods}.\n */\n authGatedMethods: ReadonlySet<string>;\n /**\n * Methods that need a gRPC-subject bearer (minted via\n * `auth_createDepositorTokenGrpc`). The proxy translates these into\n * gRPC calls to vaultd; the JSON-RPC bearer is rejected with a\n * `Subject` mismatch.\n */\n grpcGatedMethods: ReadonlySet<string>;\n /** Default {@link DEFAULT_REFRESH_SKEW_SECS}. */\n refreshSkewSecs?: number;\n /** Clock source for testability. */\n now?: () => number;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\n/**\n * Acquire, cache, and refresh VP bearer tokens.\n *\n * Implements {@link BearerTokenProvider}. Safe to pass directly into\n * `JsonRpcClient` as `tokenProvider`.\n */\nexport class VpTokenProvider implements BearerTokenProvider {\n // `client` is the only mutable field — see `setClient`. The\n // identity-bearing fields (peginTxid/authAnchorHex/pinnedServerPubkey)\n // remain readonly and are checked against re-registration in the\n // registry's `getOrCreate`.\n private client: JsonRpcClient;\n private readonly peginTxid: string;\n private readonly authAnchorHex: string;\n private readonly pinnedServerPubkey: OnChainBtcPubkey;\n private readonly expectedAudienceXOnlyPubkey: string;\n private readonly authGatedMethods: ReadonlySet<string>;\n private readonly grpcGatedMethods: ReadonlySet<string>;\n private readonly refreshSkewSecs: number;\n private readonly now: () => number;\n\n /** Cached JSON-RPC-subject bearer (auth_createDepositorToken). */\n private cachedJsonRpc: CachedToken | null = null;\n private inFlightJsonRpc: Promise<CachedToken> | null = null;\n /** Cached gRPC-subject bearer (auth_createDepositorTokenGrpc). */\n private cachedGrpc: CachedToken | null = null;\n private inFlightGrpc: Promise<CachedToken> | null = null;\n\n constructor(config: VpTokenProviderConfig) {\n this.client = config.client;\n this.peginTxid = config.peginTxid;\n this.authAnchorHex = config.authAnchorHex;\n this.pinnedServerPubkey = config.pinnedServerPubkey;\n this.expectedAudienceXOnlyPubkey = config.expectedAudienceXOnlyPubkey;\n this.authGatedMethods = config.authGatedMethods;\n this.grpcGatedMethods = config.grpcGatedMethods;\n this.refreshSkewSecs = config.refreshSkewSecs ?? DEFAULT_REFRESH_SKEW_SECS;\n this.now = config.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /**\n * Return a bearer token for `method`, or `null` if `method` is not\n * auth-gated.\n *\n * Routes by subject: `authGatedMethods` → JSON-RPC bearer (issued via\n * `auth_createDepositorToken`); `grpcGatedMethods` → gRPC bearer\n * (`auth_createDepositorTokenGrpc`). Either path acquires lazily and\n * single-flights concurrent callers; the two cache slots are\n * independent.\n *\n * Both token-issuing methods are hard-exempted from the gate — if\n * either were ever included in the gated sets (caller misconfiguration)\n * the provider would recurse into `acquireSingleFlight` from inside the\n * JSON-RPC header builder before `inFlight` is assigned, defeating the\n * single-flight guard. Returning `null` here breaks that recursion\n * deterministically.\n */\n async getToken(method: string): Promise<string | null> {\n if (method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD) {\n return null;\n }\n\n if (this.grpcGatedMethods.has(method)) {\n return this.getTokenForSubject(\"grpc\");\n }\n if (this.authGatedMethods.has(method)) {\n return this.getTokenForSubject(\"jsonrpc\");\n }\n return null;\n }\n\n /**\n * Drop both cached tokens. Next `getToken` call re-acquires the slot\n * that's actually needed. Called by `JsonRpcClient` on wire\n * `auth_expired` responses; the client doesn't tell us which subject\n * expired, so we evict both to stay correct under either.\n *\n * Worst case is one extra round-trip on the slot that was still fresh,\n * which is cheaper than carrying a `Subject` argument through\n * `BearerTokenProvider`.\n */\n invalidate(): void {\n this.cachedJsonRpc = null;\n this.cachedGrpc = null;\n // Do NOT clear `inFlight*` — a concurrent acquire is still valid;\n // the invalidator is saying \"the cached token is bad\", not \"any\n // in-flight acquire is bad\". The in-flight acquire will populate\n // a fresh `cached*` on completion.\n }\n\n private async getTokenForSubject(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<string> {\n const cached =\n subject === \"grpc\" ? this.cachedGrpc : this.cachedJsonRpc;\n if (cached && this.now() + this.refreshSkewSecs < cached.expiresAt) {\n return cached.token;\n }\n const fresh = await this.acquireSingleFlight(subject);\n return fresh.token;\n }\n\n /**\n * Swap in a different transport for subsequent token-issuing calls.\n * Used by the registry when a later caller registers the same\n * `peginTxid` against a different `baseUrl` — the cached token\n * (bound to identity, not transport) stays valid, but future\n * refreshes hit the new URL. An in-flight acquire keeps using the\n * old client (it captured the reference); next call uses the new.\n */\n setClient(client: JsonRpcClient): void {\n this.client = client;\n }\n\n private acquireSingleFlight(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<CachedToken> {\n const existing =\n subject === \"grpc\" ? this.inFlightGrpc : this.inFlightJsonRpc;\n if (existing) return existing;\n\n const issueMethod =\n subject === \"grpc\" ? GRPC_TOKEN_ISSUE_METHOD : TOKEN_ISSUE_METHOD;\n\n const p = (async () => {\n try {\n const response = await this.client.call<\n { pegin_txid: string; auth_anchor: string },\n CreateDepositorTokenResponse\n >(issueMethod, {\n pegin_txid: this.peginTxid,\n auth_anchor: this.authAnchorHex,\n });\n\n verifyServerIdentity({\n proof: response.server_identity,\n pinnedServerPubkey: this.pinnedServerPubkey,\n now: this.now(),\n });\n\n // Validate wire payload before caching so a malformed response\n // from a compromised VP or proxy can't poison the cache with\n // unusable values (non-string token, non-integer expiry, etc.).\n if (typeof response.token !== \"string\" || response.token.length === 0) {\n throw new Error(\n `VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof response.token})`,\n );\n }\n const now = this.now();\n if (\n !Number.isSafeInteger(response.expires_at) ||\n response.expires_at <= now ||\n response.expires_at > MAX_EXPIRES_AT_SECS\n ) {\n throw new Error(\n `VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(response.expires_at)}; must be a safe integer in (${now}, ${MAX_EXPIRES_AT_SECS}])`,\n );\n }\n\n // Cryptographically verify the token itself — not just the wire\n // envelope. The COSE Sign1 signature is checked against the\n // (server-identity-verified) ephemeral key, and the inner CWT\n // claims are bound to this depositor (`aud`), this VP (`iss`),\n // and this subject. Without this the bearer is an opaque blob the\n // FE would attach to mutations on the VP's word alone.\n verifyDepositorCwt({\n token: response.token,\n ephemeralPubkeyHex: response.server_identity.ephemeral_pubkey,\n expectedIssuerXOnlyPubkey: this.pinnedServerPubkey,\n expectedSubject:\n subject === \"grpc\" ? CWT_SUBJECT_GRPC : CWT_SUBJECT_JSONRPC,\n expectedAudienceXOnlyPubkey: this.expectedAudienceXOnlyPubkey,\n responseExpiresAt: response.expires_at,\n serverIdentityExpiresAt: response.server_identity.expires_at,\n now,\n });\n\n const fresh: CachedToken = {\n token: response.token,\n expiresAt: response.expires_at,\n };\n if (subject === \"grpc\") {\n this.cachedGrpc = fresh;\n } else {\n this.cachedJsonRpc = fresh;\n }\n return fresh;\n } finally {\n if (subject === \"grpc\") {\n this.inFlightGrpc = null;\n } else {\n this.inFlightJsonRpc = null;\n }\n }\n })();\n\n if (subject === \"grpc\") {\n this.inFlightGrpc = p;\n } else {\n this.inFlightJsonRpc = p;\n }\n return p;\n }\n}\n","/**\n * In-memory registry of {@link VpTokenProvider} instances keyed by\n * the per-vault depositor-signed PegIn tx hash. Module-level\n * singleton, per-tab, never persisted.\n *\n * @module tbv/core/clients/vault-provider/auth/tokenRegistry\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { JsonRpcClient } from \"../json-rpc-client\";\n\nimport { AUTH_GATED_METHODS, GRPC_AUTH_GATED_METHODS } from \"./gatedMethods\";\nimport { VpTokenProvider } from \"./tokenProvider\";\n\nexport interface VpTokenRegistryInput {\n client: JsonRpcClient;\n peginTxid: string;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Depositor x-only pubkey (32-byte hex), asserted against each token's CWT `aud`. */\n expectedAudienceXOnlyPubkey: string;\n}\n\ninterface RegistryEntry {\n provider: VpTokenProvider;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport class VpTokenRegistry {\n private readonly entries = new Map<string, RegistryEntry>();\n\n /**\n * Return the cached `VpTokenProvider` for `peginTxid` if one exists\n * with matching `authAnchorHex` and `pinnedServerPubkey`, otherwise\n * construct and cache a fresh provider. A mismatch on either throws —\n * silent overwrite would mask derivation drift or VP pubkey rotation.\n */\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider {\n const existing = this.entries.get(input.peginTxid);\n if (existing) {\n if (existing.authAnchorHex !== input.authAnchorHex) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to authAnchorHex ${existing.authAnchorHex.slice(0, 8)}…; got ${input.authAnchorHex.slice(0, 8)}…`,\n );\n }\n if (existing.pinnedServerPubkey !== input.pinnedServerPubkey) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to pinnedServerPubkey ${existing.pinnedServerPubkey.slice(0, 8)}…; got ${input.pinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey !==\n input.expectedAudienceXOnlyPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n // Refresh the inner transport on every reuse so a VP URL\n // change between calls doesn't leave the cached provider\n // pinned to a dead URL for token refresh.\n existing.provider.setClient(input.client);\n return existing.provider;\n }\n\n const provider = new VpTokenProvider({\n client: input.client,\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n authGatedMethods: AUTH_GATED_METHODS,\n grpcGatedMethods: GRPC_AUTH_GATED_METHODS,\n });\n this.entries.set(input.peginTxid, {\n provider,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n });\n return provider;\n }\n\n /** Return the cached provider, or `undefined` if none. */\n peek(peginTxid: string): VpTokenProvider | undefined {\n return this.entries.get(peginTxid)?.provider;\n }\n\n /**\n * Evict the entry for `peginTxid`. Idempotent. Called on terminal\n * paths — activation success, user-cancel, or component unmount —\n * so `authAnchorHex` doesn't outlive the deposit session.\n */\n release(peginTxid: string): void {\n this.entries.delete(peginTxid);\n }\n\n /**\n * Wipe every cached entry. Test-only escape hatch — not exposed on\n * the public {@link VpTokenRegistryPublic} singleton type.\n *\n * @internal\n */\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Public surface of the singleton — excludes the test-only `clear`\n * method.\n */\nexport interface VpTokenRegistryPublic {\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider;\n peek(peginTxid: string): VpTokenProvider | undefined;\n release(peginTxid: string): void;\n readonly size: number;\n}\n\nexport const vpTokenRegistry: VpTokenRegistryPublic = new VpTokenRegistry();\n","/**\n * Build a {@link VaultProviderRpcClient} that auto-attaches CWT\n * bearer tokens on auth-gated methods. Caller pre-derives both the\n * `authAnchorHex` (from the wallet) and the `pinnedServerPubkey`\n * (from the on-chain registry) and hands them in — the SDK has no\n * notion of wallets here.\n *\n * @module tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport {\n VaultProviderRpcClient,\n type VaultProviderRpcClientOptions,\n} from \"../api\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface AuthenticatedVpClientConfig {\n /** Base URL of the VP RPC endpoint (already proxied if applicable). */\n baseUrl: string;\n /** Per-vault depositor-signed PegIn tx id (registry cache key). */\n peginTxid: string;\n /** Already-derived 32-byte auth-anchor preimage (64-char hex, no `0x`). */\n authAnchorHex: string;\n /** On-chain VP pubkey, branded so it can only come from the registry reader. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional outer-client tunables (timeout, retries, headers, etc.). */\n options?: VaultProviderRpcClientOptions;\n}\n\nexport function createAuthenticatedVpClient(\n config: AuthenticatedVpClientConfig,\n): VaultProviderRpcClient {\n const innerTokenClient = buildInnerTokenClient(\n config.baseUrl,\n config.options?.headers,\n );\n\n const tokenProvider = vpTokenRegistry.getOrCreate({\n client: innerTokenClient,\n peginTxid: config.peginTxid,\n authAnchorHex: config.authAnchorHex,\n pinnedServerPubkey: config.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n config.depositorBtcPubkey,\n ),\n });\n\n return new VaultProviderRpcClient(config.baseUrl, {\n ...config.options,\n tokenProvider,\n });\n}\n","/**\n * Pre-populate {@link vpTokenRegistry} when the caller already has\n * both the auth-anchor preimage and the on-chain VP pubkey. Seeds\n * the cache for a `peginTxid` so a later `createAuthenticatedVpClient`\n * call reuses the cached `VpTokenProvider` instead of rebuilding it.\n *\n * @module tbv/core/clients/vault-provider/auth/primeVpAuth\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface PrimeVpAuthInput {\n baseUrl: string;\n peginTxid: string;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional headers forwarded to the inner token client (e.g. gateway auth). */\n headers?: Record<string, string>;\n}\n\nexport function primeVpTokenRegistry(input: PrimeVpAuthInput): void {\n vpTokenRegistry.getOrCreate({\n client: buildInnerTokenClient(input.baseUrl, input.headers),\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n input.depositorBtcPubkey,\n ),\n });\n}\n"],"names":["resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","BTCVaultRegistryABI","assertMulticallLength","actual","expected","label","partition","results","keeperCount","ViemOperationKeyReader","contracts","calls","challengerCount","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","cborHead","major","arg","tag","out","concat","parts","total","s","p","offset","encodeBytesAsArrayOfU8","bytes","items","b","encodeServerIdentityPayload","domain","ephemeralPubkeyCompressed","expiresAt","arrayHeader","domainBytes","pubkeyBytes","expiresAtBytes","SERVER_IDENTITY_DOMAIN","DEFAULT_MAX_PROOF_LIFETIME_SECS","ServerIdentityError","message","reason","hexToBytes","hex","verifyServerIdentity","input","proof","pinnedServerPubkey","now","maxLifetimeSecs","pinned","stripHexPrefix","X_ONLY_PUBKEY_HEX_LEN","HEX_RE","eph","COMPRESSED_PUBKEY_HEX_LEN","prefix","ephBytes","ecc","sig","SCHNORR_SIG_HEX_LEN","payload","verifyBip322Simple","AUTH_GATED_METHODS","GRPC_AUTH_GATED_METHODS","TOKEN_RPC_TIMEOUT_MS","TOKEN_ISSUE_METHOD","GRPC_TOKEN_ISSUE_METHOD","buildInnerTokenClient","baseUrl","headers","JsonRpcClient","method","MAJOR_UNSIGNED_INT","MAJOR_NEGATIVE_INT","MAJOR_BYTE_STRING","MAJOR_TEXT_STRING","MAJOR_ARRAY","MAJOR_MAP","MAJOR_TAG","MAJOR_SIMPLE","ARG_IN_NEXT_1_BYTE","ARG_RESERVED_MIN","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","MAX_NESTING_DEPTH","CborDecodeError","CborReader","buf","__publicField","initial","info","byteCount","value","length","slice","head","depth","map","key","decodeCbor","reader","CWT_SUBJECT_JSONRPC","CWT_SUBJECT_GRPC","COSE_SIGN1_TAG","COSE_SIGN1_ARRAY_LEN","COSE_ALG_ES256K","COSE_HEADER_LABEL_ALG","ECDSA_COMPACT_SIG_LEN","CBOR_ARRAY_HEAD","CBOR_TEXT_STRING_HEAD","CBOR_EMPTY_BYTE_STRING","CWT_CLAIM_ISS","CWT_CLAIM_SUB","CWT_CLAIM_AUD","CWT_CLAIM_EXP","CWT_CLAIM_NBF","CWT_CLAIM_IAT","CWT_CLAIM_CTI","SIG_STRUCTURE_CONTEXT","CwtVerificationError","verifyDepositorCwt","expectedIssuer","normalizeXOnly","expectedAudience","ephemeral","decodeCompressedPubkey","tokenBytes","base64UrlToBytes","array","protectedStart","protectedContent","protectedBstr","payloadStart","payloadContent","payloadBstr","signature","alg","readProtectedAlgorithm","sigStructure","buildSigStructure","digest","sha256","claims","decodeClaims","audience","header","concatBytes","root","requireBytes","requireString","requireTimestamp","name","pubkey","normalized","pubkeyHex","hexToUint8Array","B64URL_LOOKUP","table","alphabet","len","fullGroups","remainder","outLen","sextet","charCode","inPos","outPos","g","a","c","d","sum","part","MAX_EXPIRES_AT_SECS","DEFAULT_REFRESH_SKEW_SECS","VpTokenProvider","subject","cached","client","existing","issueMethod","response","fresh","VpTokenRegistry","provider","peginTxid","_a","vpTokenRegistry","createAuthenticatedVpClient","innerTokenClient","tokenProvider","processPublicKeyToXOnly","VaultProviderRpcClient","primeVpTokenRegistry"],"mappings":"20BA8BA,eAAsBA,GACpBC,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,CAAM,gBAAgBC,CAAQ,qEAAA,CAIpE,CAYA,SAASE,GACPC,EACAC,EACoE,CACpE,MAAO,CACL,cAAeD,EAAQ,CAAC,EACxB,aAAcA,EAAQ,MAAM,EAAG,EAAIC,CAAW,EAC9C,qBAAsBD,EAAQ,MAAM,EAAIC,CAAW,CAAA,CAEvD,CAWO,MAAMC,EAAqD,CAChE,YACUZ,EACAa,EACR,CAFQ,KAAA,aAAAb,EACA,KAAA,UAAAa,CACP,CAQH,MAAc,QACZC,EACAH,EACAI,EACAP,EACA,CACA,MAAME,EAAW,MAAM,KAAK,aAAa,UAAU,CACjD,UAAWI,EACX,aAAc,EAAA,CACf,EAED,OAAAT,EACEK,EAAQ,OACR,EAAIC,EAAcI,EAClBP,CAAA,EAGKC,GAAUC,EAASC,CAAW,CACvC,CAEA,MAAM,wBACJK,EAC2B,CAC3B,MAAMF,EAAgB,CACpB,CACE,QAAS,KAAK,UAAU,iBACxB,IAAKV,EAAAA,oBACL,aAAc,4BACd,KAAM,CAACY,EAAM,uBAAuB,CAAA,EAEtC,GAAGA,EAA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ACwB,OACxB,MAAMiM,EAAmB3H,GACvBtE,EAAO,SACP8L,EAAA9L,EAAO,UAAP,YAAA8L,EAAgB,OAAA,EAGZI,EAAgBH,EAAgB,YAAY,CAChD,OAAQE,EACR,UAAWjM,EAAO,UAClB,cAAeA,EAAO,cACtB,mBAAoBA,EAAO,mBAC3B,4BAA6BmM,EAAAA,wBAC3BnM,EAAO,kBAAA,CACT,CACD,EAED,OAAO,IAAIoM,GAAAA,uBAAuBpM,EAAO,QAAS,CAChD,GAAGA,EAAO,QACV,cAAAkM,CAAA,CACD,CACH,CC/BO,SAASG,GAAqBtJ,EAA+B,CAClEgJ,EAAgB,YAAY,CAC1B,OAAQzH,GAAsBvB,EAAM,QAASA,EAAM,OAAO,EAC1D,UAAWA,EAAM,UACjB,cAAeA,EAAM,cACrB,mBAAoBA,EAAM,mBAC1B,4BAA6BoJ,EAAAA,wBAC3BpJ,EAAM,kBAAA,CACR,CACD,CACH"}
@@ -1,2 +0,0 @@
1
- "use strict";function i(r,e){if(!Number.isInteger(e)||e<1)throw new Error(`inputCount must be a positive integer, got ${e}`);return{autoFinalized:!1,signInputs:Array.from({length:e},(a,t)=>({index:t,publicKey:r,useTweakedSigner:!1}))}}exports.createTaprootScriptPathSignOptions=i;
2
- //# sourceMappingURL=signing-Bnsro0hE.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-Bnsro0hE.cjs","sources":["../src/tbv/core/utils/signing.ts"],"sourcesContent":["import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["createTaprootScriptPathSignOptions","publicKey","inputCount","_","i"],"mappings":"aAcO,SAASA,EACdC,EACAC,EACiB,CACjB,GAAI,CAAC,OAAO,UAAUA,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MAAM,8CAA8CA,CAAU,EAAE,EAG5E,MAAO,CACL,cAAe,GACf,WAAY,MAAM,KAAK,CAAE,OAAQA,GAAc,CAACC,EAAGC,KAAO,CACxD,MAAOA,EACP,UAAAH,EACA,iBAAkB,EAAA,EAClB,CAAA,CAEN"}
@@ -1,16 +0,0 @@
1
- function a(r, e) {
2
- if (!Number.isInteger(e) || e < 1)
3
- throw new Error(`inputCount must be a positive integer, got ${e}`);
4
- return {
5
- autoFinalized: !1,
6
- signInputs: Array.from({ length: e }, (i, t) => ({
7
- index: t,
8
- publicKey: r,
9
- useTweakedSigner: !1
10
- }))
11
- };
12
- }
13
- export {
14
- a as c
15
- };
16
- //# sourceMappingURL=signing-DaLvGwQe.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signing-DaLvGwQe.js","sources":["../src/tbv/core/utils/signing.ts"],"sourcesContent":["import type { SignPsbtOptions } from \"../../../shared/wallets/interfaces\";\n\n/**\n * Create SignPsbtOptions for Taproot script-path PSBT signing.\n *\n * All vault protocol signing operations are Taproot script-path spends that\n * require `useTweakedSigner: false` (untweaked key) and `autoFinalized: false`\n * (to preserve tapScriptSig for Schnorr signature extraction).\n *\n * @param publicKey - Signer's BTC public key (hex). Accepts both compressed\n * (66-char) and x-only (64-char) formats — the wallet connector handles both.\n * @param inputCount - Number of inputs to sign. Generates entries\n * for indices 0 through inputCount-1.\n */\nexport function createTaprootScriptPathSignOptions(\n publicKey: string,\n inputCount: number,\n): SignPsbtOptions {\n if (!Number.isInteger(inputCount) || inputCount < 1) {\n throw new Error(`inputCount must be a positive integer, got ${inputCount}`);\n }\n\n return {\n autoFinalized: false,\n signInputs: Array.from({ length: inputCount }, (_, i) => ({\n index: i,\n publicKey,\n useTweakedSigner: false,\n })),\n };\n}\n"],"names":["createTaprootScriptPathSignOptions","publicKey","inputCount","_","i"],"mappings":"AAcO,SAASA,EACdC,GACAC,GACiB;AACjB,MAAI,CAAC,OAAO,UAAUA,CAAU,KAAKA,IAAa;AAChD,UAAM,IAAI,MAAM,8CAA8CA,CAAU,EAAE;AAG5E,SAAO;AAAA,IACL,eAAe;AAAA,IACf,YAAY,MAAM,KAAK,EAAE,QAAQA,KAAc,CAACC,GAAGC,OAAO;AAAA,MACxD,OAAOA;AAAA,MACP,WAAAH;AAAA,MACA,kBAAkB;AAAA,IAAA,EAClB;AAAA,EAAA;AAEN;"}
@@ -1,2 +0,0 @@
1
- "use strict";var te=Object.defineProperty;var re=(e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var K=(e,t,r)=>re(e,typeof t!="symbol"?t+"":t,r);const ne=require("./sha2-DsrLC4NM.cjs"),S=require("./signPsbtsWithFallback-zOQWokmk.cjs"),q=require("./PeginManager-BIKAnZ-X.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),f=require("./tbv/core/wasm/index.cjs"),N=require("./parseFundingOutpoints-BkgGihaY.cjs"),U=require("bitcoinjs-lib"),H=require("./verifyScriptPathSchnorrSignature-mzYCzaSy.cjs"),z=require("./fundPeginTransaction-BLD8FRL9.cjs"),j=require("./waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs"),M="DepositTermsRejectedError";class L extends Error{constructor(r,n="device-envelope"){super(r);K(this,"reason");this.name=M,this.reason=n}}function oe(e){if(e instanceof L)return!0;if(typeof e!="object"||e===null)return!1;const t=e;return t.name===M&&t.reason==="device-envelope"}async function W(e){const t=e.siblings.length;if(t===0)throw new Error("rebuildDepositTermsCore: at least one sibling is required");for(const[o,b]of e.siblings.entries())if(b.amount<=0n)throw new Error(`rebuildDepositTermsCore: sibling[${o}] has non-positive on-chain pegin amount ${b.amount}; the chain-read vault record is invalid. Resume refused.`);if(e.prepeginMaxFee<=0n)throw new Error(`rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${e.prepeginMaxFee}`);const r=p.stripHexPrefix(e.prepeginTxid).toLowerCase(),n=p.stripHexPrefix(j.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(n!==r)throw new Error(`Funded Pre-PegIn tx hashes to ${n}, expected ${r} (on-chain prepeginTxid). Resume refused.`);const h=S.findAuthAnchorOpReturn(p.stripHexPrefix(e.fundedPrePeginTxHex));if(h===void 0)throw new Error("Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN commitment — it either predates auth anchoring or is malformed. The intent resume path requires the anchor to prove sibling completeness. Resume refused.");if(h.vout!==t)throw new Error(`Auth-anchor OP_RETURN at vout ${h.vout} does not match the discovered sibling count ${t}; the discovered sibling set does not cover this transaction's HTLC outputs (a lagging index can cause this — retry later). Resume refused.`);const c=e.vaultKeeperBtcPubkeys.length,u=e.universalChallengerBtcPubkeys.length,l=await f.computeMinClaimValue(e.vaultCoreVersion,c,u,e.councilQuorum,e.councilSize,e.protocolFeeRate),a=await f.computeMinPeginFee(e.vaultCoreVersion,c,u,e.minPeginFeeRate),d=await f.peginP2aAnchorOutput(e.vaultCoreVersion),s=(d==null?void 0:d.value)??0n;if(l<=0n)throw new Error(`WASM returned non-positive depositorClaimValue ${l}; expected > 0. Resume refused.`);if(a<=0n)throw new Error(`WASM returned non-positive peginMaxFee ${a}; expected > 0. Resume refused.`);if(s<0n)throw new Error(`WASM returned negative P2A anchor value ${s}. Resume refused.`);const i=a+s,v=e.minPeginFeeRate*z.MAX_REASONABLE_PEGIN_VBYTES;if(i<=0n||i>v)throw new Error(`WASM implied PegIn reserve ${i} sat is outside (0, ${v}] (minPeginFeeRate=${e.minPeginFeeRate} × ${z.MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`);const x=e.siblings.map(o=>o.amount+l+a+s),R=await Promise.all(e.siblings.map(async o=>(await f.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorBtcPubkey,vaultProviderPubkey:e.vaultProviderBtcPubkey,vaultKeeperPubkeys:[...e.vaultKeeperBtcPubkeys],universalChallengerPubkeys:[...e.universalChallengerBtcPubkeys],hashlock:p.stripHexPrefix(o.hashlock),timelockRefund:e.timelockRefund,network:e.network})).scriptPubKey)),E=U.Transaction.fromHex(p.stripHexPrefix(e.fundedPrePeginTxHex)).outs.map(o=>({value:o.value,script:o.script}));return H.assertEncodedHtlcOutputsMatch(E,x,R),q.buildDepositTerms({vaultCoreVersion:e.vaultCoreVersion,protocolFeeRate:e.protocolFeeRate,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,timelockRefund:e.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,maxAcceptableCommissionBps:e.maxAcceptableCommissionBps,peginAmounts:e.siblings.map(o=>o.amount),depositorClaimValue:l,peginMaxFee:a})}function se(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}class Q extends Error{constructor(t,r){super(`Re-derived vault root does not match this Pre-PegIn: derived auth-anchor hash ${t}, transaction commits to ${r}. Connect the same wallet, on the same account and the same network, that created the deposit.`),this.derivedAuthAnchorHash=t,this.onChainAuthAnchorHash=r,this.name="VaultRootMismatchError"}}class A extends Error{constructor(t){super(t),this.name="UnanchoredPrePeginError"}}class X extends Error{constructor(t,r,n=[]){super(`No candidate parameter set reproduces this Pre-PegIn's HTLC outputs (${t} candidate(s) tried). `+(n.length>0?`${n.length} version(s) could not be resolved and may hold the answer: ${n.join(" | ")}. `:"")+`Sample rejections: ${r.join(" | ")}`),this.candidatesTried=t,this.sampleRejections=r,this.unresolvedLabels=n,this.name="PeginParamsNotFoundError"}}class J extends Error{constructor(t){super(`${t.length} candidate parameter sets reproduce this Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be determined: ${t.join(" | ")}. Reconstruction refused.`),this.survivorLabels=t,this.name="PeginParamsAmbiguousError"}}class G extends Error{constructor(t,r){super(`A candidate matched this Pre-PegIn (${t}), but ${r.length} version(s) could not be resolved, so the search space did not provably contain the true parameters: ${r.join(" | ")}. A version sharing the matched timelockRefund and participants is indistinguishable from the true one, so the match cannot be trusted. Reconstruction refused.`),this.matchedLabel=t,this.unresolvedLabels=r,this.name="PeginParamsIncompleteSpaceError"}}class T extends Error{constructor(t){super(`${t}. Reconstruction refused.`),this.name="PeginSizingIntegrityError"}}async function ie(e){const{wallet:t,depositorBtcPubkey:r,fundedPrePeginTxHex:n}=e,h=p.stripHexPrefix(n),c=S.findAuthAnchorOpReturn(h);if(c===void 0)throw new A("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the number of HTLC outputs it funds cannot be determined. Legacy pre-anchor deposits are not recoverable by this path.");const u=c.vout;if(u===0)throw new A("Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC outputs; there is nothing to recover.");const l=N.parseFundingOutpointsFromTx(h),a=await N.deriveVaultRoot(t,{depositorBtcPubkey:p.hexToUint8Array(p.processPublicKeyToXOnly(r)),fundingOutpoints:l});try{const s=await f.expandAuthAnchor(a);let i;try{i=p.uint8ArrayToHex(ne.sha256(s))}finally{s.fill(0)}if(i!==c.hash)throw new Q(i,c.hash)}catch(s){throw a.fill(0),s}const{hashlocks:d}=await q.expandPerVaultSecrets(a,u);return{vaultCount:u,hashlocks:d,authAnchorHash:c.hash}}function ae(e){const{vaultCoreVersion:t,offchainParams:r,participantKeySets:n}=e;if(!Number.isInteger(t)||t<1)throw new Error(`buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${t}`);if(r.length===0)throw new Error("buildPeginParamsCandidates: at least one offchain-params version is required");if(n.length===0)throw new Error("buildPeginParamsCandidates: at least one participant key set is required");const h=[];for(const c of r)for(const u of n)h.push({vaultCoreVersion:t,offchainParams:c,participants:u});return h}function Y(e){return`${e.axis} v${e.version} (${e.reason})`}function $(e){const{participants:t}=e;return`core=${e.vaultCoreVersion} offchain=${e.offchainParams.version} keepers=${t.appVaultKeepersVersion} challengers=${t.universalChallengersVersion} vp=${t.vaultProvider}`}const D=5;function ce(e,t){return JSON.stringify({terms:e,peginAmounts:t},(r,n)=>typeof n=="bigint"?`${n}`:n)}function ue(e){const{offchainParams:t,participants:r}=e;return[e.vaultCoreVersion,r.vaultKeeperBtcPubkeys.length,r.universalChallengerBtcPubkeys.length,t.councilQuorum,t.councilSize,t.protocolFeeRate,t.minPeginFeeRate].join("|")}async function le(e){const{offchainParams:t,participants:r}=e,n=r.vaultKeeperBtcPubkeys.length,h=r.universalChallengerBtcPubkeys.length,[c,u,l]=await Promise.all([f.computeMinClaimValue(e.vaultCoreVersion,n,h,t.councilQuorum,t.councilSize,t.protocolFeeRate),f.computeMinPeginFee(e.vaultCoreVersion,n,h,t.minPeginFeeRate),f.peginP2aAnchorOutput(e.vaultCoreVersion)]),a=(l==null?void 0:l.value)??0n;if(c<=0n)throw new T(`WASM returned non-positive depositorClaimValue ${c} for graph version ${e.vaultCoreVersion}`);if(u<=0n)throw new T(`WASM returned non-positive peginMaxFee ${u} for graph version ${e.vaultCoreVersion}`);if(a<0n)throw new T(`WASM returned negative P2A anchor value ${a} for graph version ${e.vaultCoreVersion}`);return{depositorClaimValue:c,peginMaxFee:u,p2aAnchorValue:a}}async function he(e){const{hashlocks:t,fundedPrePeginTxHex:r,depositorBtcPubkey:n,prepeginMaxFee:h,maxAcceptableCommissionBps:c,network:u,candidates:l,unresolvedVersions:a}=e;if(t.length===0)throw new Error("reconstructPeginParams: at least one hashlock is required");if(l.length===0)throw new Error("reconstructPeginParams: candidate space is empty");const d=p.processPublicKeyToXOnly(n),s=p.stripHexPrefix(r),i=S.findAuthAnchorOpReturn(s);if(i===void 0)throw new A("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the sibling set cannot be proven complete. Reconstruction refused.");if(i.vout!==t.length)throw new Error(`reconstructPeginParams: ${t.length} hashlock(s) supplied but the auth-anchor OP_RETURN sits at vout ${i.vout}, so the transaction funds ${i.vout} HTLC output(s). Reconstruction refused.`);const v=U.Transaction.fromHex(s).outs,x=t.map((m,g)=>BigInt(v[g].value)),R=p.stripHexPrefix(j.calculateBtcTxHash(s)).toLowerCase(),E=new Map,o=[],b=[],F=[];let I=0;for(const m of l)try{const g=ue(m);let P=E.get(g);P===void 0&&(P=await le(m),E.set(g,P));const k=P.depositorClaimValue+P.peginMaxFee+P.p2aAnchorValue,C=x.map(y=>y-k),V=C.findIndex(y=>y<=0n);if(V!==-1)throw new H.HtlcOutputMismatchError(`HTLC output[${V}] value ${x[V]} is not above this candidate's reserve ${k}, so it implies a non-positive pegin amount ${C[V]}.`);const{offchainParams:w,participants:B}=m,_=await W({vaultCoreVersion:m.vaultCoreVersion,siblings:t.map((y,ee)=>({hashlock:y,amount:C[ee]})),fundedPrePeginTxHex:s,depositorBtcPubkey:d,vaultProviderBtcPubkey:B.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:B.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:B.universalChallengerBtcPubkeys,protocolFeeRate:w.protocolFeeRate,minPeginFeeRate:w.minPeginFeeRate,councilQuorum:w.councilQuorum,councilSize:w.councilSize,timelockPegin:w.timelockPegin,timelockAssert:w.timelockAssert,timelockRefund:w.timelockRefund,prepeginTxid:R,prepeginMaxFee:h,maxAcceptableCommissionBps:c,network:u});o.push({candidate:m,terms:_,peginAmounts:C,fingerprint:ce(_,C)})}catch(g){if(g instanceof T)throw g;const P=$(m),k=g instanceof Error?g.message:String(g);g instanceof H.HtlcOutputMismatchError?b.length<D&&b.push(`[${P}] ${k}`):(I++,F.length<D&&F.push(`${P} (${k})`))}const Z=a.length+I,O=[...a.map(Y),...F];if(o.length===0)throw new X(l.length,b,O);if(new Set(o.map(m=>m.fingerprint)).size>1)throw new J(o.map(m=>$(m.candidate)));if(Z>0)throw new G($(o[0].candidate),O);return{candidate:o[0].candidate,terms:o[0].terms,peginAmounts:o[0].peginAmounts,authAnchorHash:i.hash,candidatesTried:l.length,matchedCandidates:o.map(m=>m.candidate)}}function de(e,t){const{htlcVout:r,depositorBtcPubkey:n,applicationEntryPoint:h,fundedPrePeginTxHex:c,hashlocks:u,network:l}=t,{candidate:a,peginAmounts:d}=e,{offchainParams:s,participants:i}=a;if(u.length!==d.length)throw new Error(`toRefundInputs: ${u.length} hashlock(s) but ${d.length} reconstructed amount(s); the reconstruction and the hashlock vector describe different transactions.`);if(!Number.isInteger(r)||r<0||r>=d.length)throw new Error(`toRefundInputs: htlcVout ${r} is outside the reconstructed batch of ${d.length} vault(s).`);const v=d.map((E,o)=>({hashlock:p.ensureHexPrefix(u[o]),amount:E,htlcVout:o})),x={vaultCoreVersion:a.vaultCoreVersion,hashlock:v[r].hashlock,htlcVout:r,offchainParamsVersion:s.version,appVaultKeepersVersion:i.appVaultKeepersVersion,universalChallengersVersion:i.universalChallengersVersion,vaultProvider:i.vaultProvider,applicationEntryPoint:h,amount:d[r],unsignedPrePeginTxHex:c,depositorBtcPubkey:n,batch:v},R={vaultProviderPubkey:i.vaultProviderBtcPubkey,vaultKeeperPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerPubkeys:i.universalChallengerBtcPubkeys,timelockRefund:s.timelockRefund,feeRate:s.protocolFeeRate,minPeginFeeRate:s.minPeginFeeRate,numLocalChallengers:i.vaultKeeperBtcPubkeys.length,councilQuorum:s.councilQuorum,councilSize:s.councilSize,network:l};return{vault:x,context:R}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=M;exports.DepositTermsRejectedError=L;exports.PeginParamsAmbiguousError=J;exports.PeginParamsIncompleteSpaceError=G;exports.PeginParamsNotFoundError=X;exports.PeginSizingIntegrityError=T;exports.UnanchoredPrePeginError=A;exports.VaultRootMismatchError=Q;exports.buildPeginParamsCandidates=ae;exports.deriveHashlocksFromPrePegin=ie;exports.describePeginParamsCandidate=$;exports.describeUnresolvedVersion=Y;exports.isDepositTermsRejectedError=oe;exports.isWotsMismatchError=se;exports.rebuildDepositTermsCore=W;exports.reconstructPeginParams=he;exports.toRefundInputs=de;
2
- //# sourceMappingURL=toRefundInputs-Bdtz8p27.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"waitForTransactionReceiptSmartAware-B6oYRdFO.js","sources":["../src/tbv/core/utils/fee/peginFeeMath.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts","../src/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.ts"],"sourcesContent":["/**\n * Pre-PegIn fee math primitives used by both UTXO selection and\n * transaction funding so they make bit-identical decisions about base\n * fee, change-output fee, and whether to emit change at all.\n *\n * Dust handling matches the wallet-side check in\n * `babylon-vault crates/btc-wallet-remote/src/client.rs` (dust-change\n * rejection): a change output is emitted only when the post-fee residual\n * exceeds DUST_THRESHOLD (546 sats). Broader fee-estimation behaviors\n * (output sizing, safety margins) are NOT cross-stack guarantees — see\n * JS-vs-Rust parity fixtures in `__tests__/peginFeeMath.test.ts` for the\n * invariants we pin.\n */\n\nimport {\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"./constants\";\n\nexport interface ComputeBaseFeeParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction (HTLC vault outputs +\n * CPFP anchor + optional auth-anchor OP_RETURN). Excludes the change\n * output — `applyChangeOutputPolicy` adds the change-output fee\n * separately.\n */\n numOutputs: number;\n feeRate: number;\n}\n\n/**\n * Compute the base fee (sats) for a Pre-PegIn transaction with no change\n * output, including the low-fee-rate buffer.\n *\n * Used as the starting point by `applyChangeOutputPolicy`, which then\n * decides whether to add the incremental change-output fee.\n */\nexport function computePeginBaseFeeSats(\n params: ComputeBaseFeeParams,\n): bigint {\n const { numInputs, numOutputs, feeRate } = params;\n if (!Number.isInteger(numInputs) || numInputs < 0) {\n throw new Error(\n `computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${numInputs}`,\n );\n }\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `computePeginBaseFeeSats: numOutputs must be a positive integer, got ${numOutputs}`,\n );\n }\n const txVsize =\n numInputs * P2TR_INPUT_SIZE +\n numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE +\n TX_BUFFER_SIZE_OVERHEAD;\n return (\n BigInt(Math.ceil(txVsize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate))\n );\n}\n\n/**\n * Incremental fee (sats) for adding one P2TR-sized change output at the\n * given fee rate. Does NOT include the low-fee-rate buffer — that is part\n * of the base fee, paid once per transaction.\n */\nexport function computeChangeOutputFeeSats(feeRate: number): bigint {\n return BigInt(Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate));\n}\n\nexport interface ApplyChangeOutputPolicyParams {\n totalInputValue: bigint;\n peginAmount: bigint;\n baseFee: bigint;\n changeOutputFee: bigint;\n}\n\nexport interface ChangeOutputPolicyResult {\n /** Final transaction fee (sats). */\n fee: bigint;\n /**\n * Final change amount (sats). 0n when no change output is emitted.\n * When `emitChangeOutput` is false, the would-be change is paid to\n * miners as part of `fee` — i.e. it is dust by policy.\n */\n changeAmount: bigint;\n /** Whether the funded transaction must include a change output. */\n emitChangeOutput: boolean;\n}\n\n/**\n * Apply the change-output dust policy: emit a change output iff the\n * post-change-output-fee residual strictly exceeds DUST_THRESHOLD.\n *\n * Returns `{ fee, changeAmount, emitChangeOutput }` so the selector and\n * funder both end up with the same fee and same change decision for the\n * same inputs.\n *\n * Inputs:\n * - `totalInputValue`: sum of selected UTXO values\n * - `peginAmount`: amount being pegged in\n * - `baseFee`: fee assuming no change output (from `computePeginBaseFeeSats`)\n * - `changeOutputFee`: incremental fee for adding one change output\n * (from `computeChangeOutputFeeSats`)\n *\n * @throws If `totalInputValue < peginAmount + baseFee` (insufficient funds\n * even before considering change). Callers that need to surface\n * \"insufficient funds\" with their own error wording should check the\n * precondition themselves before invoking this.\n */\nexport function applyChangeOutputPolicy(\n params: ApplyChangeOutputPolicyParams,\n): ChangeOutputPolicyResult {\n const { totalInputValue, peginAmount, baseFee, changeOutputFee } = params;\n\n const residualBeforeChange = totalInputValue - peginAmount - baseFee;\n if (residualBeforeChange < 0n) {\n throw new Error(\n `applyChangeOutputPolicy: insufficient funds (need ${peginAmount + baseFee} sats, have ${totalInputValue})`,\n );\n }\n\n const residualWithChangeOutput = residualBeforeChange - changeOutputFee;\n if (residualWithChangeOutput > DUST_THRESHOLD) {\n return {\n fee: baseFee + changeOutputFee,\n changeAmount: residualWithChangeOutput,\n emitChangeOutput: true,\n };\n }\n\n // Dust-revert: the would-be change is below (or equal to) the dust\n // threshold once the change-output fee is paid, so we omit the change\n // output and let the residual go to miners. The reported `fee` is the\n // ACTUAL on-wire fee — `baseFee + residualBeforeChange` — not just\n // `baseFee`, otherwise fee displays would under-report by up to\n // (changeOutputFee + DUST_THRESHOLD) sats whenever dust gets absorbed.\n return {\n fee: baseFee + residualBeforeChange,\n changeAmount: 0n,\n emitChangeOutput: false,\n };\n}\n\nexport interface ComputeMaxDepositParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction. Use the worst-case\n * count for the use case being budgeted (e.g. max-batch with\n * auth-anchor) — `computeMaxDeposit` is intentionally an UPPER BOUND\n * and assumes no change output.\n */\n numOutputs: number;\n totalBalance: bigint;\n feeRate: number;\n}\n\n/**\n * Compute the maximum depositable amount (sats) given a fixed-cost\n * sweep: every UTXO is spent, no change output is emitted, fee is the\n * base fee for the requested input/output count.\n *\n * Returns null when `totalBalance <= 0n`. Returns 0n if the base fee\n * alone exceeds the balance.\n */\nexport function computeMaxDeposit(\n params: ComputeMaxDepositParams,\n): bigint | null {\n const { numInputs, numOutputs, totalBalance, feeRate } = params;\n if (totalBalance <= 0n) return null;\n const fee = computePeginBaseFeeSats({ numInputs, numOutputs, feeRate });\n const max = totalBalance - fee;\n return max > 0n ? max : 0n;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { BTC_DUST_SAT, DUST_THRESHOLD } from \"../fee/constants\";\nimport {\n applyChangeOutputPolicy,\n computeChangeOutputFeeSats,\n computePeginBaseFeeSats,\n} from \"../fee/peginFeeMath\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs, recalculating the fee through the shared\n // `applyChangeOutputPolicy` helper so the selector and the funder\n // agree on (fee, change output emission, change amount) for the same\n // inputs. Without that, the funder can omit a change output the\n // selector charged for — silent depositor overpayment at the dust\n // boundary.\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n const baseFee = computePeginBaseFeeSats({\n numInputs: selectedUTXOs.length,\n numOutputs,\n feeRate,\n });\n const changeOutputFee = computeChangeOutputFeeSats(feeRate);\n\n if (accumulatedValue < peginAmount + baseFee) {\n estimatedFee = baseFee;\n continue;\n }\n\n const policy = applyChangeOutputPolicy({\n totalInputValue: accumulatedValue,\n peginAmount,\n baseFee,\n changeOutputFee,\n });\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: policy.fee,\n changeAmount: policy.changeAmount,\n };\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n","/**\n * Smart-account-aware wrapper around viem's `waitForTransactionReceipt`.\n *\n * Externally Owned Accounts (EOAs) — wallets controlled by a single private\n * key, e.g. MetaMask or a hardware wallet. `eth_sendTransaction` returns a real\n * Ethereum tx hash, which viem can poll directly. This wrapper delegates\n * unchanged for them.\n *\n * Smart-contract accounts (e.g. Safe multisigs) — the wallet address is a\n * deployed contract that decides whether to accept a transaction. WalletConnect's\n * `eth_sendTransaction` returns a `safeTxHash` (an EIP-712 hash of the\n * *proposal*) rather than a real tx hash, and the proposal is held in Safe's\n * off-chain Transaction Service until quorum signs and executes it. We poll\n * that service for the proposal until execution, then wait for receipt on the\n * real Ethereum tx hash exposed in the service's response.\n *\n * The two are told apart by `eth_getCode`, but NOT by \"empty vs non-empty\":\n * an EIP-7702 delegated EOA reports `0xef0100 ‖ <delegate address>` and is\n * still an EOA — it signs and submits its own transactions, so\n * `eth_sendTransaction` returns a real tx hash. MetaMask upgrades accounts to\n * smart accounts this way by default, and treating one as a Safe means polling\n * the Transaction Service for a hash that is not a `safeTxHash`: a permanent\n * 404 that reads as \"proposal not yet indexed\" and hangs for the full poll\n * budget on a transaction that already succeeded. Delegation designators are\n * therefore classified as EOAs. As a backstop for any wallet that behaves this\n * way in future, a 404 from the Transaction Service is also checked against the\n * node: if it knows the hash as a real transaction, we were never waiting on a\n * proposal and switch to waiting for that transaction's receipt.\n *\n * @module utils/eth\n */\n\nimport type { Address, Hash, PublicClient, TransactionReceipt } from \"viem\";\n\n/**\n * Chains where the Safe Transaction Service is supported by this utility.\n * Extend the map as more Safe-enabled chains are needed.\n */\nconst SAFE_TX_SERVICE_BASE_URLS: Record<number, string> = {\n 1: \"https://safe-transaction-mainnet.safe.global\",\n 11155111: \"https://safe-transaction-sepolia.safe.global\",\n};\n\nconst DEFAULT_SAFE_POLL_INTERVAL_MS = 5_000;\nconst DEFAULT_SAFE_POLL_TIMEOUT_MS = 4 * 60 * 60 * 1_000;\nconst SAFE_TX_SERVICE_FETCH_TIMEOUT_MS = 10_000;\n\n/** Safe Transaction Service route for one multisig-transaction proposal. */\nconst SAFE_MULTISIG_TX_PATH = \"/api/v1/multisig-transactions\";\n/** The service answers 404 both for an unindexed proposal and an unknown Safe. */\nconst SAFE_TX_SERVICE_NOT_FOUND = 404;\n/** Statuses at or above this are server-side, so worth retrying. */\nconst SAFE_TX_SERVICE_SERVER_ERROR = 500;\n\n/** Two hex characters encode one byte in an `eth_getCode` result. */\nconst HEX_CHARS_PER_BYTE = 2;\n\n/**\n * EIP-7702 delegation designator: an EOA that has delegated its code to a\n * contract reports exactly `0xef0100 ‖ <20-byte delegate address>` from\n * `eth_getCode` (EIP-7702 §\"Delegation Designation\"). Both the prefix and the\n * exact length are checked so ordinary contract bytecode that merely happens to\n * start with these bytes is not mistaken for a delegation.\n */\nconst EIP_7702_DELEGATION_PREFIX = \"0xef0100\";\nconst EIP_7702_DELEGATION_ADDRESS_BYTES = 20;\nconst EIP_7702_DELEGATION_CODE_LENGTH =\n EIP_7702_DELEGATION_PREFIX.length +\n HEX_CHARS_PER_BYTE * EIP_7702_DELEGATION_ADDRESS_BYTES;\n\n/**\n * True when `eth_getCode` reports an EIP-7702 delegation designator rather than\n * a deployed contract. Such an account is still an EOA for our purposes: it\n * signs and submits its own transactions, so the hash we hold is a real tx hash.\n */\nfunction isEip7702DelegatedEoa(code: string): boolean {\n return (\n code.length === EIP_7702_DELEGATION_CODE_LENGTH &&\n code.toLowerCase().startsWith(EIP_7702_DELEGATION_PREFIX)\n );\n}\n\nexport interface WaitForTransactionReceiptSmartAwareParams {\n publicClient: PublicClient;\n walletAddress: Address;\n hash: Hash;\n /**\n * Forwarded to viem verbatim.\n *\n * MUST NOT be used as a finality/reorg gate. viem fetches the receipt once\n * and then only compares block numbers against that cached copy — it never\n * re-checks that the receipt's block is still canonical, so it resolves\n * happily for a transaction that has been reorged out. Setting this buys a\n * delay, not a guarantee. For peg-in registration finality use\n * `waitForPeginRegistrationDepth`, which re-reads live contract state on\n * every poll.\n */\n confirmations?: number;\n /**\n * Forwarded to viem on the EOA (externally owned account) path, and on the\n * fallback where a supposed smart account turns out to submit its own\n * transactions — that is the EOA case too, however we arrived at it.\n *\n * Ignored only while waiting on a genuine Safe proposal, whose budget is\n * safePollTimeoutMs. It is not forwarded to the receipt wait that follows a\n * proposal's execution either: viem's own default applies there (180s as of\n * viem 2.38.2), so that wait is bounded too — a sufficiently slow node still\n * raises WaitForTransactionReceiptTimeoutError, just on viem's uniform bound\n * rather than on a caller's shorter one.\n */\n timeout?: number;\n /** Total budget for waiting on Safe quorum + execution. Default 4h. */\n safePollTimeoutMs?: number;\n /** Poll cadence against the Safe Transaction Service. Default 5s. */\n safePollIntervalMs?: number;\n}\n\nexport async function waitForTransactionReceiptSmartAware(\n params: WaitForTransactionReceiptSmartAwareParams,\n): Promise<TransactionReceipt> {\n const {\n publicClient,\n walletAddress,\n hash,\n confirmations,\n timeout,\n safePollTimeoutMs = DEFAULT_SAFE_POLL_TIMEOUT_MS,\n safePollIntervalMs = DEFAULT_SAFE_POLL_INTERVAL_MS,\n } = params;\n\n const code = await publicClient.getCode({ address: walletAddress });\n // An EIP-7702 delegated EOA has non-empty code but still submits its own\n // transactions, so it belongs on the EOA path — see the module docblock.\n const isSmartAccount =\n code !== undefined && code !== \"0x\" && !isEip7702DelegatedEoa(code);\n\n if (!isSmartAccount) {\n return publicClient.waitForTransactionReceipt({\n hash,\n confirmations,\n timeout,\n });\n }\n\n const chainId = await publicClient.getChainId();\n const outcome = await pollSafeTransactionServiceUntilExecuted({\n chainId,\n publicClient,\n safeTxHash: hash,\n pollIntervalMs: safePollIntervalMs,\n timeoutMs: safePollTimeoutMs,\n });\n\n // The wallet turned out to submit its own transactions, so this is the EOA\n // case after all — including the caller's `timeout`, which only ever meant to\n // be ignored while waiting on a genuine Safe proposal.\n if (outcome.kind === \"not-a-proposal\") {\n return publicClient.waitForTransactionReceipt({\n hash,\n confirmations,\n timeout,\n });\n }\n\n return publicClient.waitForTransactionReceipt({\n hash: outcome.transactionHash,\n confirmations,\n });\n}\n\n/**\n * How the Safe path ended. The two outcomes are not interchangeable, so they are\n * distinguished rather than both collapsing to a bare hash: `executed` is a real\n * Safe proposal that reached quorum, while `not-a-proposal` means the wallet was\n * never a Safe and we are really on the EOA path — which decides whether the\n * caller's `timeout` applies to the receipt wait that follows.\n */\ntype SafePollOutcome =\n | { kind: \"executed\"; transactionHash: Hash }\n | { kind: \"not-a-proposal\" };\n\ninterface SafeMultisigTransaction {\n isExecuted: boolean;\n isSuccessful: boolean | null;\n transactionHash: Hash | null;\n}\n\n/**\n * Decide whether a 404 from the Transaction Service means \"proposal not indexed\n * yet\" or \"this hash was never a proposal at all\".\n *\n * The Safe indexer cannot answer that: a genuine Safe and its freshly-submitted\n * proposal are both absent from it for a while, so its 404 proves nothing. The\n * NODE can. A `safeTxHash` is an EIP-712 digest of a proposal and is never a\n * transaction on chain, so if the node knows the hash as a real transaction then\n * this was never a proposal and we are on the wrong path entirely.\n *\n * Returns true only on that positive identification. Anything else — the node\n * has not seen it yet, or the lookup fails — is inconclusive and leaves the\n * caller polling, which is the correct behaviour for a Safe that is simply\n * still being indexed.\n */\nasync function hashIsRealTransaction(\n publicClient: PublicClient,\n hash: Hash,\n): Promise<boolean> {\n const transaction = await publicClient\n .getTransaction({ hash })\n .catch(() => null);\n return transaction !== null;\n}\n\nasync function pollSafeTransactionServiceUntilExecuted({\n chainId,\n publicClient,\n safeTxHash,\n pollIntervalMs,\n timeoutMs,\n}: {\n chainId: number;\n publicClient: PublicClient;\n safeTxHash: Hash;\n pollIntervalMs: number;\n timeoutMs: number;\n}): Promise<SafePollOutcome> {\n const baseUrl = SAFE_TX_SERVICE_BASE_URLS[chainId];\n if (!baseUrl) {\n throw new Error(\n `Safe Transaction Service not configured for chainId ${chainId}. ` +\n `Connected wallet appears to be a smart-contract account, but this ` +\n `chain is not in the supported list. Either connect an EOA or extend ` +\n `SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`,\n );\n }\n\n const url = `${baseUrl}${SAFE_MULTISIG_TX_PATH}/${safeTxHash}/`;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const controller = new AbortController();\n const fetchTimeoutId = setTimeout(\n () => controller.abort(),\n SAFE_TX_SERVICE_FETCH_TIMEOUT_MS,\n );\n\n let response: Response;\n try {\n response = await fetch(url, { signal: controller.signal });\n } catch (err) {\n // Transient failure (AbortError on per-request timeout, DNS hiccup,\n // connection reset, etc.). Log and continue to the next poll iteration\n // instead of consuming the entire safePollTimeoutMs budget on one blip.\n // The outer `while (Date.now() < deadline)` is what enforces the overall\n // budget; this catch deliberately preserves it.\n console.warn(\n `Safe Transaction Service request failed (will retry in ${pollIntervalMs}ms): ` +\n (err instanceof Error ? err.message : String(err)),\n );\n await sleep(pollIntervalMs);\n continue;\n } finally {\n clearTimeout(fetchTimeoutId);\n }\n\n if (response.ok) {\n const data = (await response.json()) as SafeMultisigTransaction;\n if (data.isExecuted) {\n if (data.isSuccessful === false) {\n throw new Error(\n `Safe transaction ${safeTxHash} was executed on chain but reverted. ` +\n `Check the Safe queue UI for details.`,\n );\n }\n if (data.transactionHash) {\n return { kind: \"executed\", transactionHash: data.transactionHash };\n }\n }\n } else if (response.status === SAFE_TX_SERVICE_NOT_FOUND) {\n // Usually \"proposal not indexed yet\", so keep polling. But the very same\n // 404 appears when the hash is not a safeTxHash at all — the case that\n // used to burn the whole budget on an already-mined transaction. Ask the\n // node: if it knows this hash, it is a real transaction, so stop treating\n // it as a proposal and let the caller wait on it directly.\n if (await hashIsRealTransaction(publicClient, safeTxHash)) {\n console.warn(\n `${safeTxHash} is a real transaction, not a Safe proposal — the ` +\n `connected wallet submits its own transactions despite reporting ` +\n `contract bytecode. Waiting for its receipt directly.`,\n );\n return { kind: \"not-a-proposal\" };\n }\n } else if (response.status >= SAFE_TX_SERVICE_SERVER_ERROR) {\n // Transient server error — same treatment as a hung connection: log and retry.\n console.warn(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}; retrying in ${pollIntervalMs}ms.`,\n );\n } else {\n // Other 4xx (403, 410, etc.) is likely permanent — surface immediately.\n throw new Error(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}.`,\n );\n }\n\n await sleep(pollIntervalMs);\n }\n\n throw new Error(\n `Timed out after ${timeoutMs}ms waiting for Safe transaction ${safeTxHash} ` +\n `to reach quorum and execute. The proposal is still pending in the Safe ` +\n `queue — co-signers must sign and execute it before the dApp can proceed.`,\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n"],"names":["computePeginBaseFeeSats","params","numInputs","numOutputs","feeRate","txVsize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","computeChangeOutputFeeSats","applyChangeOutputPolicy","totalInputValue","peginAmount","baseFee","changeOutputFee","residualBeforeChange","residualWithChangeOutput","DUST_THRESHOLD","computeMaxDeposit","totalBalance","fee","max","assertNoDuplicateUtxos","utxos","seen","utxo","key","selectUtxosForPegin","availableUTXOs","validUTXOs","script","Buffer","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","estimatedFee","policy","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type","SAFE_TX_SERVICE_BASE_URLS","DEFAULT_SAFE_POLL_INTERVAL_MS","DEFAULT_SAFE_POLL_TIMEOUT_MS","SAFE_TX_SERVICE_FETCH_TIMEOUT_MS","SAFE_MULTISIG_TX_PATH","SAFE_TX_SERVICE_NOT_FOUND","SAFE_TX_SERVICE_SERVER_ERROR","HEX_CHARS_PER_BYTE","EIP_7702_DELEGATION_PREFIX","EIP_7702_DELEGATION_ADDRESS_BYTES","EIP_7702_DELEGATION_CODE_LENGTH","isEip7702DelegatedEoa","code","waitForTransactionReceiptSmartAware","publicClient","walletAddress","hash","confirmations","timeout","safePollTimeoutMs","safePollIntervalMs","chainId","outcome","pollSafeTransactionServiceUntilExecuted","hashIsRealTransaction","safeTxHash","pollIntervalMs","timeoutMs","baseUrl","url","deadline","controller","fetchTimeoutId","response","err","sleep","data","ms","resolve"],"mappings":";;;AAyCO,SAASA,EACdC,GACQ;AACR,QAAM,EAAE,WAAAC,GAAW,YAAAC,GAAY,SAAAC,EAAA,IAAYH;AAC3C,MAAI,CAAC,OAAO,UAAUC,CAAS,KAAKA,IAAY;AAC9C,UAAM,IAAI;AAAA,MACR,0EAA0EA,CAAS;AAAA,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AAO,IAAI,QAAQ,CAACC,MAAY;AAC9B,eAAWA,GAASD,CAAE;AAAA,EACxB,CAAC;AACH;"}
@@ -1,2 +0,0 @@
1
- "use strict";const w=require("bitcoinjs-lib"),p=require("buffer"),h=require("./fundPeginTransaction-BLD8FRL9.cjs");function E(t){const{numInputs:e,numOutputs:n,feeRate:a}=t;if(!Number.isInteger(e)||e<0)throw new Error(`computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${e}`);if(!Number.isInteger(n)||n<1)throw new Error(`computePeginBaseFeeSats: numOutputs must be a positive integer, got ${n}`);const s=e*h.P2TR_INPUT_SIZE+n*h.MAX_NON_LEGACY_OUTPUT_SIZE+h.TX_BUFFER_SIZE_OVERHEAD;return BigInt(Math.ceil(s*a))+BigInt(h.rateBasedTxBufferFee(a))}function T(t){return BigInt(Math.ceil(h.MAX_NON_LEGACY_OUTPUT_SIZE*t))}function _(t){const{totalInputValue:e,peginAmount:n,baseFee:a,changeOutputFee:s}=t,i=e-n-a;if(i<0n)throw new Error(`applyChangeOutputPolicy: insufficient funds (need ${n+a} sats, have ${e})`);const c=i-s;return c>h.DUST_THRESHOLD?{fee:a+s,changeAmount:c,emitChangeOutput:!0}:{fee:a+i,changeAmount:0n,emitChangeOutput:!1}}function P(t){const{numInputs:e,numOutputs:n,totalBalance:a,feeRate:s}=t;if(a<=0n)return null;const i=E({numInputs:e,numOutputs:n,feeRate:s}),c=a-i;return c>0n?c:0n}function O(t){const e=new Set;for(const n of t){const a=`${n.txid.toLowerCase()}:${n.vout}`;if(e.has(a))throw new Error(`Duplicate UTXO detected: ${n.txid}:${n.vout}. This indicates a data integrity issue with the UTXO source.`);e.add(a)}}function A(t,e,n,a){if(!Number.isInteger(a)||a<1)throw new Error(`Invalid numOutputs: expected a positive integer, got ${a}`);if(t.length===0)throw new Error("Insufficient funds: no UTXOs available");O(t);const s=t.filter(f=>{const r=p.Buffer.from(f.scriptPubKey,"hex");return!!w.script.decompile(r)});if(s.length===0)throw new Error("Insufficient funds: no valid UTXOs available (all have invalid scripts)");const i=[...s].sort((f,r)=>r.value-f.value),c=[];let l=0n,u=0n;for(const f of i){c.push(f),l+=BigInt(f.value);const r=E({numInputs:c.length,numOutputs:a,feeRate:n}),o=T(n);if(l<e+r){u=r;continue}const S=_({totalInputValue:l,peginAmount:e,baseFee:r,changeOutputFee:o});return{selectedUTXOs:c,totalValue:l,fee:S.fee,changeAmount:S.changeAmount}}throw new Error(`Insufficient funds: need ${e+u} sats (${e} pegin + ${u} fee), have ${l} sats`)}function F(t){return t>h.DUST_THRESHOLD}function U(){return h.BTC_DUST_SAT}function R(t){const e=t.startsWith("0x")?t.slice(2):t;return`0x${w.Transaction.fromHex(e).getId()}`}var d=(t=>(t.P2PKH="P2PKH",t.P2SH="P2SH",t.P2WPKH="P2WPKH",t.P2WSH="P2WSH",t.P2TR="P2TR",t.UNKNOWN="UNKNOWN",t))(d||{});function m(t){const e=t.length;return e===25&&t[0]===118&&t[1]===169&&t[2]===20&&t[23]===136&&t[24]===172?"P2PKH":e===23&&t[0]===169&&t[1]===20&&t[22]===135?"P2SH":e===22&&t[0]===0&&t[1]===20?"P2WPKH":e===34&&t[0]===0&&t[1]===32?"P2WSH":e===34&&t[0]===81&&t[1]===32?"P2TR":"UNKNOWN"}function v(t,e){const n=p.Buffer.from(t.scriptPubKey,"hex"),a=m(n);switch(a){case d.P2WPKH:return{witnessUtxo:{script:n,value:t.value}};case d.P2WSH:{if(!t.witnessScript)throw new Error("Missing witnessScript for P2WSH input");return{witnessUtxo:{script:n,value:t.value},witnessScript:p.Buffer.from(t.witnessScript,"hex")}}case d.P2TR:{if(e&&e.length!==32)throw new Error(`Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`);return{witnessUtxo:{script:n,value:t.value},...e&&{tapInternalKey:e}}}default:throw new Error(`Unsupported script type: ${a}`)}}const $={1:"https://safe-transaction-mainnet.safe.global",11155111:"https://safe-transaction-sepolia.safe.global"},C=5e3,H=14400*1e3,x=1e4,D="/api/v1/multisig-transactions",N=404,L=500,B=2,I="0xef0100",W=20,X=I.length+B*W;function M(t){return t.length===X&&t.toLowerCase().startsWith(I)}async function V(t){const{publicClient:e,walletAddress:n,hash:a,confirmations:s,timeout:i,safePollTimeoutMs:c=H,safePollIntervalMs:l=C}=t,u=await e.getCode({address:n});if(!(u!==void 0&&u!=="0x"&&!M(u)))return e.waitForTransactionReceipt({hash:a,confirmations:s,timeout:i});const r=await e.getChainId(),o=await q({chainId:r,publicClient:e,safeTxHash:a,pollIntervalMs:l,timeoutMs:c});return o.kind==="not-a-proposal"?e.waitForTransactionReceipt({hash:a,confirmations:s,timeout:i}):e.waitForTransactionReceipt({hash:o.transactionHash,confirmations:s})}async function b(t,e){return await t.getTransaction({hash:e}).catch(()=>null)!==null}async function q({chainId:t,publicClient:e,safeTxHash:n,pollIntervalMs:a,timeoutMs:s}){const i=$[t];if(!i)throw new Error(`Safe Transaction Service not configured for chainId ${t}. Connected wallet appears to be a smart-contract account, but this chain is not in the supported list. Either connect an EOA or extend SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`);const c=`${i}${D}/${n}/`,l=Date.now()+s;for(;Date.now()<l;){const u=new AbortController,f=setTimeout(()=>u.abort(),x);let r;try{r=await fetch(c,{signal:u.signal})}catch(o){console.warn(`Safe Transaction Service request failed (will retry in ${a}ms): `+(o instanceof Error?o.message:String(o))),await g(a);continue}finally{clearTimeout(f)}if(r.ok){const o=await r.json();if(o.isExecuted){if(o.isSuccessful===!1)throw new Error(`Safe transaction ${n} was executed on chain but reverted. Check the Safe queue UI for details.`);if(o.transactionHash)return{kind:"executed",transactionHash:o.transactionHash}}}else if(r.status===N){if(await b(e,n))return console.warn(`${n} is a real transaction, not a Safe proposal — the connected wallet submits its own transactions despite reporting contract bytecode. Waiting for its receipt directly.`),{kind:"not-a-proposal"}}else if(r.status>=L)console.warn(`Safe Transaction Service returned ${r.status} for ${n}; retrying in ${a}ms.`);else throw new Error(`Safe Transaction Service returned ${r.status} for ${n}.`);await g(a)}throw new Error(`Timed out after ${s}ms waiting for Safe transaction ${n} to reach quorum and execute. The proposal is still pending in the Safe queue — co-signers must sign and execute it before the dApp can proceed.`)}function g(t){return new Promise(e=>{setTimeout(e,t)})}exports.BitcoinScriptType=d;exports.applyChangeOutputPolicy=_;exports.calculateBtcTxHash=R;exports.computeChangeOutputFeeSats=T;exports.computeMaxDeposit=P;exports.computePeginBaseFeeSats=E;exports.getDustThreshold=U;exports.getPsbtInputFields=v;exports.getScriptType=m;exports.selectUtxosForPegin=A;exports.shouldAddChangeOutput=F;exports.waitForTransactionReceiptSmartAware=V;
2
- //# sourceMappingURL=waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs.map