@babylonlabs-io/ts-sdk 0.55.2 → 0.56.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 (155) hide show
  1. package/README.md +1 -2
  2. package/dist/{PayoutManager-BJmPnyRP.js → PayoutManager-BVgmuKuK.js} +117 -105
  3. package/dist/PayoutManager-BVgmuKuK.js.map +1 -0
  4. package/dist/PayoutManager-Cu4_l-_Y.cjs +2 -0
  5. package/dist/PayoutManager-Cu4_l-_Y.cjs.map +1 -0
  6. package/dist/{PeginManager-CW03-M3T.js → PeginManager-Ba7Cr51Z.js} +520 -460
  7. package/dist/PeginManager-Ba7Cr51Z.js.map +1 -0
  8. package/dist/PeginManager-CcjGRo4O.cjs +2 -0
  9. package/dist/PeginManager-CcjGRo4O.cjs.map +1 -0
  10. package/dist/{buildAndBroadcastRefund-BiSO4zg2.js → buildAndBroadcastRefund-BtXUqBkb.js} +444 -430
  11. package/dist/buildAndBroadcastRefund-BtXUqBkb.js.map +1 -0
  12. package/dist/buildAndBroadcastRefund-Cq01wyZX.cjs +2 -0
  13. package/dist/buildAndBroadcastRefund-Cq01wyZX.cjs.map +1 -0
  14. package/dist/challengeAssert-BVQq50su.js +75 -0
  15. package/dist/challengeAssert-BVQq50su.js.map +1 -0
  16. package/dist/challengeAssert-Cu-PtJ1g.cjs +2 -0
  17. package/dist/challengeAssert-Cu-PtJ1g.cjs.map +1 -0
  18. package/dist/constants-BqU1Uz15.cjs +2 -0
  19. package/dist/{constants-CvbARMl-.cjs.map → constants-BqU1Uz15.cjs.map} +1 -1
  20. package/dist/{constants-BhclpREj.js → constants-CDQE812z.js} +8 -6
  21. package/dist/{constants-BhclpREj.js.map → constants-CDQE812z.js.map} +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.js +195 -192
  24. package/dist/{mempoolApi-DqJByvqR.cjs → mempoolApi-DkyKmmgI.cjs} +2 -2
  25. package/dist/mempoolApi-DkyKmmgI.cjs.map +1 -0
  26. package/dist/{mempoolApi-CB7bHuwi.js → mempoolApi-lpJdvPkK.js} +66 -66
  27. package/dist/mempoolApi-lpJdvPkK.js.map +1 -0
  28. package/dist/{noPayout-CNMqNNpc.cjs → noPayout-Cb8vFrkY.cjs} +2 -2
  29. package/dist/{noPayout-CNMqNNpc.cjs.map → noPayout-Cb8vFrkY.cjs.map} +1 -1
  30. package/dist/{noPayout-CfBg3HzC.js → noPayout-CihCk1HE.js} +2 -2
  31. package/dist/{noPayout-CfBg3HzC.js.map → noPayout-CihCk1HE.js.map} +1 -1
  32. package/dist/{primeVpAuth-l-5x_2UV.js → primeVpAuth-Caa5J_uv.js} +4 -4
  33. package/dist/{primeVpAuth-l-5x_2UV.js.map → primeVpAuth-Caa5J_uv.js.map} +1 -1
  34. package/dist/{primeVpAuth-CF4cH5_e.cjs → primeVpAuth-y-4A88ah.cjs} +2 -2
  35. package/dist/{primeVpAuth-CF4cH5_e.cjs.map → primeVpAuth-y-4A88ah.cjs.map} +1 -1
  36. package/dist/tbv/core/clients/index.cjs +1 -1
  37. package/dist/tbv/core/clients/index.js +2 -2
  38. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  39. package/dist/tbv/core/deposit-terms/__tests__/buildDepositTerms.test.d.ts +2 -0
  40. package/dist/tbv/core/deposit-terms/__tests__/buildDepositTerms.test.d.ts.map +1 -0
  41. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts +8 -0
  42. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts.map +1 -0
  43. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +92 -0
  44. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -0
  45. package/dist/tbv/core/deposit-terms/index.d.ts +12 -0
  46. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -0
  47. package/dist/tbv/core/index.cjs +1 -1
  48. package/dist/tbv/core/index.d.ts +1 -0
  49. package/dist/tbv/core/index.d.ts.map +1 -1
  50. package/dist/tbv/core/index.js +194 -191
  51. package/dist/tbv/core/managers/PayoutManager.d.ts +7 -0
  52. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  53. package/dist/tbv/core/managers/PeginManager.d.ts +13 -0
  54. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  55. package/dist/tbv/core/managers/index.cjs +1 -1
  56. package/dist/tbv/core/managers/index.js +2 -2
  57. package/dist/tbv/core/primitives/index.cjs +1 -1
  58. package/dist/tbv/core/primitives/index.d.ts +0 -3
  59. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  60. package/dist/tbv/core/primitives/index.js +37 -38
  61. package/dist/tbv/core/primitives/psbt/__tests__/assertPayoutFeeBand.test.d.ts +7 -0
  62. package/dist/tbv/core/primitives/psbt/__tests__/assertPayoutFeeBand.test.d.ts.map +1 -0
  63. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts +63 -0
  64. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts.map +1 -0
  65. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +4 -1
  66. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  67. package/dist/tbv/core/primitives/psbt/constants.d.ts +18 -4
  68. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  69. package/dist/tbv/core/primitives/psbt/payout.d.ts +21 -2
  70. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  71. package/dist/tbv/core/primitives/psbt/pegin.d.ts +6 -0
  72. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  73. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +12 -0
  74. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  75. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +5 -0
  76. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  77. package/dist/tbv/core/services/index.cjs +1 -1
  78. package/dist/tbv/core/services/index.js +2 -2
  79. package/dist/tbv/core/utils/__tests__/abortSignals.test.d.ts +11 -0
  80. package/dist/tbv/core/utils/__tests__/abortSignals.test.d.ts.map +1 -0
  81. package/dist/tbv/core/utils/abortSignals.d.ts +23 -0
  82. package/dist/tbv/core/utils/abortSignals.d.ts.map +1 -0
  83. package/dist/tbv/core/utils/index.cjs +1 -1
  84. package/dist/tbv/core/utils/index.d.ts +1 -0
  85. package/dist/tbv/core/utils/index.d.ts.map +1 -1
  86. package/dist/tbv/core/utils/index.js +44 -43
  87. package/dist/tbv/index.cjs +1 -1
  88. package/dist/tbv/index.js +194 -191
  89. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  90. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  91. package/dist/tbv/integrations/aave/clients/spoke.d.ts +0 -20
  92. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
  93. package/dist/tbv/integrations/aave/constants.d.ts +0 -22
  94. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  95. package/dist/tbv/integrations/aave/index.cjs +1 -1
  96. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  97. package/dist/tbv/integrations/aave/index.d.ts +5 -6
  98. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  99. package/dist/tbv/integrations/aave/index.js +236 -339
  100. package/dist/tbv/integrations/aave/index.js.map +1 -1
  101. package/dist/tbv/integrations/aave/types.d.ts +0 -7
  102. package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
  103. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -7
  104. package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
  105. package/dist/tbv/integrations/aave/utils/index.d.ts +3 -8
  106. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  107. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts +0 -65
  108. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
  109. package/dist/validation-CDbOaDj7.cjs +2 -0
  110. package/dist/validation-CDbOaDj7.cjs.map +1 -0
  111. package/dist/validation-Dj3dqYtl.js +30 -0
  112. package/dist/validation-Dj3dqYtl.js.map +1 -0
  113. package/dist/verifyScriptPathSchnorrSignature-BZhX-SOd.cjs +2 -0
  114. package/dist/verifyScriptPathSchnorrSignature-BZhX-SOd.cjs.map +1 -0
  115. package/dist/verifyScriptPathSchnorrSignature-CgrnAjMW.js +724 -0
  116. package/dist/verifyScriptPathSchnorrSignature-CgrnAjMW.js.map +1 -0
  117. package/package.json +2 -2
  118. package/dist/PayoutManager-BJmPnyRP.js.map +0 -1
  119. package/dist/PayoutManager-aqtsj60t.cjs +0 -2
  120. package/dist/PayoutManager-aqtsj60t.cjs.map +0 -1
  121. package/dist/PeginManager-CW03-M3T.js.map +0 -1
  122. package/dist/PeginManager-C_akOB1E.cjs +0 -2
  123. package/dist/PeginManager-C_akOB1E.cjs.map +0 -1
  124. package/dist/buildAndBroadcastRefund-BiSO4zg2.js.map +0 -1
  125. package/dist/buildAndBroadcastRefund-Bwi1I5we.cjs +0 -2
  126. package/dist/buildAndBroadcastRefund-Bwi1I5we.cjs.map +0 -1
  127. package/dist/challengeAssert-DLQfNcfU.cjs +0 -2
  128. package/dist/challengeAssert-DLQfNcfU.cjs.map +0 -1
  129. package/dist/challengeAssert-DvdbpEDY.js +0 -128
  130. package/dist/challengeAssert-DvdbpEDY.js.map +0 -1
  131. package/dist/constants-CvbARMl-.cjs +0 -2
  132. package/dist/mempoolApi-CB7bHuwi.js.map +0 -1
  133. package/dist/mempoolApi-DqJByvqR.cjs.map +0 -1
  134. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts +0 -34
  135. package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts.map +0 -1
  136. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts +0 -5
  137. package/dist/tbv/integrations/aave/utils/__tests__/borrowRatio.test.d.ts.map +0 -1
  138. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts +0 -5
  139. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts.map +0 -1
  140. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts +0 -2
  141. package/dist/tbv/integrations/aave/utils/__tests__/vaultSelection.test.d.ts.map +0 -1
  142. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts +0 -15
  143. package/dist/tbv/integrations/aave/utils/borrowRatio.d.ts.map +0 -1
  144. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts +0 -109
  145. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts.map +0 -1
  146. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts +0 -33
  147. package/dist/tbv/integrations/aave/utils/vaultSelection.d.ts.map +0 -1
  148. package/dist/validation-CxqROCno.js +0 -15
  149. package/dist/validation-CxqROCno.js.map +0 -1
  150. package/dist/validation-u8W7Lp2x.cjs +0 -2
  151. package/dist/validation-u8W7Lp2x.cjs.map +0 -1
  152. package/dist/verifyScriptPathSchnorrSignature-BDznSCOR.cjs +0 -2
  153. package/dist/verifyScriptPathSchnorrSignature-BDznSCOR.cjs.map +0 -1
  154. package/dist/verifyScriptPathSchnorrSignature-DA4Z4yZ3.js +0 -658
  155. package/dist/verifyScriptPathSchnorrSignature-DA4Z4yZ3.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mempoolApi-CB7bHuwi.js","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":";;;;;AAwBA,MAAMA,IAAa,OAGbC,IAAmB,KAGnBC,IAAa,YAGbC,IAAY;AAQX,SAASC,EAAiCC,GAAuB;AACtE,MACE,CAAC,OAAO,UAAUA,CAAO,KACzBA,IAAU,KACVA,IAAUH;AAEV,UAAM,IAAI;AAAA,MACR,sEAAsEG,CAAO;AAAA,IAAA;AAGnF;AAMO,SAASC,EAAuBC,GAAuC;AAC5E,QAAMC,IAAmB,CAAA;AA+FzB,MA7FID,EAAO,kBAAkB,MAC3BC,EAAO;AAAA,IACL,wCAAwCD,EAAO,cAAc;AAAA,EAAA,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AK,eACpBA,EAAK,cAAcA,EAAK;AAExB,UAAM,IAAI;AAAA,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"mempoolApi-DqJByvqR.cjs","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"6fAwBMA,EAAa,MAGbC,EAAmB,IAGnBC,EAAa,WAGbC,EAAY,IAQX,SAASC,EAAiCC,EAAuB,CACtE,GACE,CAAC,OAAO,UAAUA,CAAO,GACzBA,EAAU,GACVA,EAAUH,EAEV,MAAM,IAAI,MACR,sEAAsEG,CAAO,EAAA,CAGnF,CAMO,SAASC,EAAuBC,EAAuC,CAC5E,MAAMC,EAAmB,CAAA,EA+FzB,GA7FID,EAAO,gBAAkB,IAC3BC,EAAO,KACL,wCAAwCD,EAAO,cAAc,EAAA,EAG7DA,EAAO,eAAiB,OAAOP,CAAU,GAC3CQ,EAAO,KACL,kBAAkBD,EAAO,cAAc,wBAAwBP,CAAU,GAAA,EAIzEO,EAAO,yBAA2B,IACpCC,EAAO,KACL,iDAAiDD,EAAO,uBAAuB,EAAA,EAI/EA,EAAO,SAAW,GACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,EAG3DA,EAAO,QAAU,GACnBC,EAAO,KAAK,gCAAgCD,EAAO,MAAM,EAAE,EAGzDA,EAAO,oBAAoB,SAAW,GACxCC,EAAO,KAAK,uCAAuC,EAGjDD,EAAO,eAAiB,GAC1BC,EAAO,KAAK,uCAAuCD,EAAO,aAAa,EAAE,EAEvEA,EAAO,cAAgBA,EAAO,oBAAoB,QACpDC,EAAO,KACL,kBAAkBD,EAAO,aAAa,wCAAwCA,EAAO,oBAAoB,MAAM,GAAA,EAI/GA,EAAO,SAAW,IACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,EAG3DA,EAAO,iBAAmB,IAC5BC,EAAO,KACL,yCAAyCD,EAAO,eAAe,EAAA,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B,EAAY,CAChB,aACA,cACA,UACA,aACA,YAAA,EAGF,UAAWC,KAASD,EAClB,GAAI,CAAC9C,EAAe6C,EAAKE,CAAK,CAAC,EAC7B,MAAM,IAAI,MACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmDlD,CAAY,EAAA,EAK7G,GACEgD,EAAK,WAAaA,EAAK,YACvBA,EAAK,WAAaA,EAAK,SACvBA,EAAK,QAAUA,EAAK,aACpBA,EAAK,YAAcA,EAAK,WAExB,MAAM,IAAI,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU,IAAA,EAIpC,OAAOA,CACT"}
@@ -1,34 +0,0 @@
1
- import { PayoutConnectorParams } from '@babylonlabs-io/babylon-tbv-rust-wasm';
2
- /**
3
- * Parameters for building a depositor Payout PSBT
4
- */
5
- export interface DepositorPayoutParams {
6
- /** Payout transaction hex (unsigned) */
7
- payoutTxHex: string;
8
- /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */
9
- peginTxHex: string;
10
- /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */
11
- assertTxHex: string;
12
- /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */
13
- connectorParams: PayoutConnectorParams;
14
- }
15
- /**
16
- * Build unsigned depositor Payout PSBT.
17
- *
18
- * The depositor's payout transaction has 2 inputs:
19
- * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script
20
- * - Input 1: Assert:0 — NOT signed by depositor
21
- *
22
- * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT
23
- * commits to all input prevouts. Prevout script_pubkey/value are derived
24
- * from the authoritative parent transactions, not trusted from external input.
25
- *
26
- * @param params - Depositor payout parameters
27
- * @returns Unsigned PSBT hex ready for signing
28
- *
29
- * @throws If the payout transaction does not have exactly 2 inputs
30
- * @throws If input 0 does not reference peginTxHex at output index 0
31
- * @throws If input 1 does not reference assertTxHex at output index 0
32
- */
33
- export declare function buildDepositorPayoutPsbt(params: DepositorPayoutParams): Promise<string>;
34
- //# sourceMappingURL=depositorPayout.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"depositorPayout.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/psbt/depositorPayout.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EACL,KAAK,qBAAqB,EAG3B,MAAM,uCAAuC,CAAC;AAgB/C;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,uEAAuE;IACvE,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,WAAW,EAAE,MAAM,CAAC;IACpB,mFAAmF;IACnF,eAAe,EAAE,qBAAqB,CAAC;CACxC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,MAAM,CAAC,CAiFjB"}
@@ -1,5 +0,0 @@
1
- /**
2
- * Tests for borrow ratio utilities
3
- */
4
- export {};
5
- //# sourceMappingURL=borrowRatio.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"borrowRatio.test.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/integrations/aave/utils/__tests__/borrowRatio.test.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -1,5 +0,0 @@
1
- /**
2
- * Tests for seizure simulation utilities
3
- */
4
- export {};
5
- //# sourceMappingURL=seizureSimulation.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"seizureSimulation.test.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=vaultSelection.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vaultSelection.test.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/integrations/aave/utils/__tests__/vaultSelection.test.ts"],"names":[],"mappings":""}
@@ -1,15 +0,0 @@
1
- /**
2
- * Borrow Ratio Utilities
3
- *
4
- * Borrow ratio = debt / collateral as a percentage.
5
- * Shows how much of the collateral is being used for borrowing.
6
- */
7
- /**
8
- * Calculate borrow ratio (debt / collateral) as percentage string
9
- *
10
- * @param debtUsd - Total debt in USD
11
- * @param collateralValueUsd - Total collateral value in USD
12
- * @returns Formatted percentage string (e.g., "15.7%")
13
- */
14
- export declare function calculateBorrowRatio(debtUsd: number, collateralValueUsd: number): string;
15
- //# sourceMappingURL=borrowRatio.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"borrowRatio.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/borrowRatio.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,MAAM,EACf,kBAAkB,EAAE,MAAM,GACzB,MAAM,CAIR"}
@@ -1,109 +0,0 @@
1
- /**
2
- * Seizure Simulation Utilities
3
- *
4
- * Simulates which vaults would be seized during Aave liquidation.
5
- * Vaults are seized in prefix order (index 0, 1, 2, ...) until the
6
- * target seizure amount is covered.
7
- *
8
- * Reference: Aave v4 Section 4.2 — liquidation seizes a prefix of the
9
- * borrower's ordered vault list.
10
- */
11
- /**
12
- * A vault with its on-chain ID and BTC amount, in liquidation-priority order.
13
- */
14
- export interface OrderedVault {
15
- /** On-chain vault ID (bytes32 hex string) */
16
- id: string;
17
- /** Vault amount in satoshis */
18
- amountSats: bigint;
19
- }
20
- /**
21
- * Parameters for simulating prefix seizure.
22
- */
23
- export interface PrefixSeizureParams {
24
- /** Vaults in their current on-chain order (index 0 is seized first) */
25
- orderedVaults: OrderedVault[];
26
- /** Target seizure amount in satoshis */
27
- targetSeizureSats: bigint;
28
- }
29
- /**
30
- * Result of a prefix seizure simulation.
31
- */
32
- export interface PrefixSeizureResult {
33
- /** Vaults that would be seized (the prefix) */
34
- seizedVaults: OrderedVault[];
35
- /** Vaults that survive liquidation */
36
- protectedVaults: OrderedVault[];
37
- /** Over-seizure amount in satoshis (total seized - target) */
38
- overSeizureSats: bigint;
39
- /** Index where seizure stops (exclusive: vaults[0..cutoffIndex] are seized) */
40
- cutoffIndex: number;
41
- /** Total amount seized in satoshis */
42
- totalSeizedSats: bigint;
43
- }
44
- /**
45
- * Parameters for computing target seizure in satoshis.
46
- */
47
- export interface TargetSeizureParams {
48
- /** Total collateral in satoshis */
49
- totalCollateralSats: bigint;
50
- /** Collateral factor (e.g. 0.75) */
51
- CF: number;
52
- /** Liquidation bonus (e.g. 1.05) */
53
- LB: number;
54
- /** Target health factor (e.g. 1.10) */
55
- THF: number;
56
- /** Expected health factor at liquidation (e.g. 0.95) */
57
- expectedHF: number;
58
- }
59
- /**
60
- * Compute the target seizure amount in satoshis.
61
- *
62
- * Uses `computeSeizedFraction` to determine what fraction of total collateral
63
- * would be seized, then converts to an absolute satoshi amount.
64
- *
65
- * @param params - Total collateral and risk parameters
66
- * @returns Target seizure amount in satoshis (rounded up)
67
- *
68
- * @example
69
- * ```typescript
70
- * const targetSats = computeTargetSeizureSats({
71
- * totalCollateralSats: 1_000_000_000n, // 10 BTC
72
- * CF: 0.75,
73
- * LB: 1.05,
74
- * THF: 1.10,
75
- * expectedHF: 0.95,
76
- * });
77
- * // targetSats ≈ 398_000_000n (3.98 BTC)
78
- * ```
79
- */
80
- export declare function computeTargetSeizureSats(params: TargetSeizureParams): bigint;
81
- /**
82
- * Simulate prefix seizure for a given set of ordered vaults.
83
- *
84
- * Walks the ordered vault list, accumulating amounts until the target
85
- * seizure is covered. Returns which vaults are seized vs protected,
86
- * the over-seizure amount, and the cutoff index.
87
- *
88
- * @param params - Ordered vaults and target seizure amount
89
- * @returns Seizure simulation result
90
- * @throws Error if orderedVaults is empty
91
- * @throws Error if targetSeizureSats is <= 0
92
- *
93
- * @example
94
- * ```typescript
95
- * const result = simulatePrefixSeizure({
96
- * orderedVaults: [
97
- * { id: "0xabc...", amountSats: 200_000_000n },
98
- * { id: "0xdef...", amountSats: 300_000_000n },
99
- * { id: "0x123...", amountSats: 500_000_000n },
100
- * ],
101
- * targetSeizureSats: 400_000_000n,
102
- * });
103
- * // result.seizedVaults = first 2 vaults (200M + 300M = 500M >= 400M)
104
- * // result.overSeizureSats = 100_000_000n
105
- * // result.cutoffIndex = 2
106
- * ```
107
- */
108
- export declare function simulatePrefixSeizure(params: PrefixSeizureParams): PrefixSeizureResult;
109
- //# sourceMappingURL=seizureSimulation.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"seizureSimulation.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/seizureSimulation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,6CAA6C;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,+BAA+B;IAC/B,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,uEAAuE;IACvE,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,wCAAwC;IACxC,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,+CAA+C;IAC/C,YAAY,EAAE,YAAY,EAAE,CAAC;IAC7B,sCAAsC;IACtC,eAAe,EAAE,YAAY,EAAE,CAAC;IAChC,8DAA8D;IAC9D,eAAe,EAAE,MAAM,CAAC;IACxB,+EAA+E;IAC/E,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,mCAAmC;IACnC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,mBAAmB,GAC1B,MAAM,CAYR;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,mBAAmB,GAC1B,mBAAmB,CAwCrB"}
@@ -1,33 +0,0 @@
1
- /**
2
- * Vault Selection Utilities for Aave
3
- *
4
- * Provides functions for selecting vaults to match a target collateral amount.
5
- * Uses a greedy algorithm that prioritizes larger vaults first.
6
- */
7
- export interface SelectableVault {
8
- id: string;
9
- amount: number;
10
- }
11
- export interface VaultSelectionResult {
12
- /** IDs of selected vaults */
13
- vaultIds: string[];
14
- /** Actual total amount from selected vaults */
15
- actualAmount: number;
16
- }
17
- /**
18
- * Select vaults to match the target amount using a greedy algorithm.
19
- * Sorts vaults by amount descending and picks until target is met.
20
- *
21
- * @param vaults - Available vaults to select from
22
- * @param targetAmount - Target amount to reach
23
- * @returns Selected vault IDs and actual amount
24
- */
25
- export declare function selectVaultsForAmount(vaults: SelectableVault[], targetAmount: number): VaultSelectionResult;
26
- /**
27
- * Calculate total amount from a list of vaults
28
- *
29
- * @param vaults - Vaults to sum
30
- * @returns Total amount in BTC
31
- */
32
- export declare function calculateTotalVaultAmount(vaults: SelectableVault[]): number;
33
- //# sourceMappingURL=vaultSelection.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vaultSelection.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/vaultSelection.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,oBAAoB;IACnC,6BAA6B;IAC7B,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,+CAA+C;IAC/C,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,eAAe,EAAE,EACzB,YAAY,EAAE,MAAM,GACnB,oBAAoB,CAiBtB;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,CAE3E"}
@@ -1,15 +0,0 @@
1
- const E = /^[0-9a-fA-F]+$/, a = /^[0-9a-fA-F]{64}$/, s = /^[a-zA-Z0-9]{25,90}$/, _ = [
2
- "76a914",
3
- "a914",
4
- "0014",
5
- "0020",
6
- "5120"
7
- ], A = 1000000n;
8
- export {
9
- s as B,
10
- E as H,
11
- _ as K,
12
- A as M,
13
- a as T
14
- };
15
- //# sourceMappingURL=validation-CxqROCno.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validation-CxqROCno.js","sources":["../src/tbv/core/utils/validation.ts"],"sourcesContent":["/**\n * Shared validation constants for Bitcoin-related input sanitization.\n *\n * These are used across mempool API clients, broadcast services, and\n * transaction construction to enforce consistent format checks.\n */\n\n/** Non-empty string of hexadecimal characters (case-insensitive). */\nexport const HEX_RE = /^[0-9a-fA-F]+$/;\n\n/** Bitcoin txid: exactly 64 hex characters (32 bytes). */\nexport const TXID_RE = /^[0-9a-fA-F]{64}$/;\n\n/**\n * Bitcoin address format gate: 25–90 alphanumeric characters.\n * Covers legacy (P2PKH/P2SH), bech32 (P2WPKH/P2WSH), bech32m (P2TR),\n * and regtest addresses (bcrt1... which are 62–64 chars for 32-byte witness programs).\n * Upper bound of 90 provides headroom for future address formats.\n * This is a format gate to prevent path-traversal — not full address validation.\n */\nexport const BITCOIN_ADDRESS_RE = /^[a-zA-Z0-9]{25,90}$/;\n\n/**\n * Known Bitcoin scriptPubKey prefixes:\n * - P2PKH: 76a914...88ac (25 bytes)\n * - P2SH: a914...87 (23 bytes)\n * - P2WPKH: 0014... (22 bytes)\n * - P2WSH: 0020... (34 bytes)\n * - P2TR: 5120... (34 bytes)\n */\nexport const KNOWN_SCRIPT_PREFIXES = [\n \"76a914\",\n \"a914\",\n \"0014\",\n \"0020\",\n \"5120\",\n] as const;\n\n/**\n * Upper bound on the implied miner fee (0.01 BTC = 1,000,000 sats).\n * Catches inflated input values from a compromised mempool API — if inputs are\n * grossly overstated the implied fee becomes unreasonably large. The April 2024\n * Runes spike saw ~450 sat/vB; at 500 vB that's ~225k sats, well under this cap.\n */\nexport const MAX_REASONABLE_FEE_SATS = 1_000_000n;\n"],"names":["HEX_RE","TXID_RE","BITCOIN_ADDRESS_RE","KNOWN_SCRIPT_PREFIXES","MAX_REASONABLE_FEE_SATS"],"mappings":"AAQO,MAAMA,IAAS,kBAGTC,IAAU,qBASVC,IAAqB,wBAUrBC,IAAwB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAQaC,IAA0B;"}
@@ -1,2 +0,0 @@
1
- "use strict";const E=/^[0-9a-fA-F]+$/,_=/^[0-9a-fA-F]{64}$/,R=/^[a-zA-Z0-9]{25,90}$/,S=["76a914","a914","0014","0020","5120"],A=1000000n;exports.BITCOIN_ADDRESS_RE=R;exports.HEX_RE=E;exports.KNOWN_SCRIPT_PREFIXES=S;exports.MAX_REASONABLE_FEE_SATS=A;exports.TXID_RE=_;
2
- //# sourceMappingURL=validation-u8W7Lp2x.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validation-u8W7Lp2x.cjs","sources":["../src/tbv/core/utils/validation.ts"],"sourcesContent":["/**\n * Shared validation constants for Bitcoin-related input sanitization.\n *\n * These are used across mempool API clients, broadcast services, and\n * transaction construction to enforce consistent format checks.\n */\n\n/** Non-empty string of hexadecimal characters (case-insensitive). */\nexport const HEX_RE = /^[0-9a-fA-F]+$/;\n\n/** Bitcoin txid: exactly 64 hex characters (32 bytes). */\nexport const TXID_RE = /^[0-9a-fA-F]{64}$/;\n\n/**\n * Bitcoin address format gate: 25–90 alphanumeric characters.\n * Covers legacy (P2PKH/P2SH), bech32 (P2WPKH/P2WSH), bech32m (P2TR),\n * and regtest addresses (bcrt1... which are 62–64 chars for 32-byte witness programs).\n * Upper bound of 90 provides headroom for future address formats.\n * This is a format gate to prevent path-traversal — not full address validation.\n */\nexport const BITCOIN_ADDRESS_RE = /^[a-zA-Z0-9]{25,90}$/;\n\n/**\n * Known Bitcoin scriptPubKey prefixes:\n * - P2PKH: 76a914...88ac (25 bytes)\n * - P2SH: a914...87 (23 bytes)\n * - P2WPKH: 0014... (22 bytes)\n * - P2WSH: 0020... (34 bytes)\n * - P2TR: 5120... (34 bytes)\n */\nexport const KNOWN_SCRIPT_PREFIXES = [\n \"76a914\",\n \"a914\",\n \"0014\",\n \"0020\",\n \"5120\",\n] as const;\n\n/**\n * Upper bound on the implied miner fee (0.01 BTC = 1,000,000 sats).\n * Catches inflated input values from a compromised mempool API — if inputs are\n * grossly overstated the implied fee becomes unreasonably large. The April 2024\n * Runes spike saw ~450 sat/vB; at 500 vB that's ~225k sats, well under this cap.\n */\nexport const MAX_REASONABLE_FEE_SATS = 1_000_000n;\n"],"names":["HEX_RE","TXID_RE","BITCOIN_ADDRESS_RE","KNOWN_SCRIPT_PREFIXES","MAX_REASONABLE_FEE_SATS"],"mappings":"aAQO,MAAMA,EAAS,iBAGTC,EAAU,oBASVC,EAAqB,uBAUrBC,EAAwB,CACnC,SACA,OACA,OACA,OACA,MACF,EAQaC,EAA0B"}
@@ -1,2 +0,0 @@
1
- "use strict";const S=require("@babylonlabs-io/babylon-tbv-rust-wasm"),P=require("buffer"),v=require("bitcoinjs-lib"),C=require("./fundPeginTransaction-BLD8FRL9.cjs"),u=require("./bitcoin-CHfKAhcI.cjs"),w=require("./constants-CvbARMl-.cjs"),K=require("@bitcoin-js/tiny-secp256k1-asmjs");function F(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const X=F(K);async function W(e,t){const n=t.pegInAmounts.length;if(e.htlcValues.length!==n)throw new Error(`WASM Pre-PegIn returned ${e.htlcValues.length} HTLC value(s), expected ${n} (one per requested deposit).`);if(e.peginAmounts.length!==n||e.htlcScriptPubKeys.length!==n||e.htlcAddresses.length!==n)throw new Error(`WASM Pre-PegIn returned mismatched array lengths (htlcValues=${e.htlcValues.length}, peginAmounts=${e.peginAmounts.length}, htlcScriptPubKeys=${e.htlcScriptPubKeys.length}, htlcAddresses=${e.htlcAddresses.length}); expected ${n} each.`);if(e.depositorClaimValue<=0n)throw new Error(`WASM Pre-PegIn returned non-positive depositorClaimValue ${e.depositorClaimValue}; expected > 0.`);const r=await S.computeMinClaimValue(t.vaultCoreVersion,t.numLocalChallengers,t.universalChallengerPubkeys.length,t.councilQuorum,t.councilSize,t.feeRate);if(e.depositorClaimValue!==r)throw new Error(`WASM Pre-PegIn depositorClaimValue ${e.depositorClaimValue} does not match the independently computed minimum claim value ${r} (vaultCoreVersion=${t.vaultCoreVersion}, numLocalChallengers=${t.numLocalChallengers}, numUniversalChallengers=${t.universalChallengerPubkeys.length}, councilQuorum=${t.councilQuorum}, councilSize=${t.councilSize}, feeRate=${t.feeRate}).`);const o=await S.peginP2aAnchorOutput(t.vaultCoreVersion),i=(o==null?void 0:o.value)??0n,c=await S.computeMinPeginFee(t.vaultCoreVersion,t.vaultKeeperPubkeys.length,t.universalChallengerPubkeys.length,t.minPeginFeeRate),s=c+i,f=t.minPeginFeeRate*C.MAX_REASONABLE_PEGIN_VBYTES;for(let a=0;a<n;a++){const p=t.pegInAmounts[a],d=e.peginAmounts[a],h=e.htlcValues[a];if(d!==p)throw new Error(`WASM Pre-PegIn peginAmount[${a}] ${d} does not match the requested amount ${p}; refusing to build a tx whose recorded amount differs from the depositor's request.`);if(d<=0n)throw new Error(`WASM Pre-PegIn peginAmount[${a}] is non-positive (${d}); expected > 0.`);if(h<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] is non-positive (${h}); expected > 0.`);const l=h-d-e.depositorClaimValue;if(l<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${h} does not strictly cover peginAmount ${d} + depositorClaimValue ${e.depositorClaimValue} + a PegIn reserve (implied reserve ${l}).`);if(l>f)throw new Error(`WASM Pre-PegIn implied reserve for HTLC[${a}] (${l} sat) exceeds the plausibility cap ${f} sat (minPeginFeeRate=${t.minPeginFeeRate} × ${C.MAX_REASONABLE_PEGIN_VBYTES} vbytes); htlcValue ${h} appears grossly inflated.`);if(l!==s)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${h} implies a PegIn fee+anchor reserve of ${l} sat, expected exactly ${s} sat (minPeginFee ${c} + p2aAnchor ${i} for vaultCoreVersion ${t.vaultCoreVersion}, vaultKeepers=${t.vaultKeeperPubkeys.length}, universalChallengers=${t.universalChallengerPubkeys.length}, minPeginFeeRate=${t.minPeginFeeRate}).`)}}function G(e,t,n){if(e.length<t.length)throw new Error(`Encoded Pre-PegIn tx has ${e.length} output(s), fewer than the ${t.length} HTLC output(s) the cross-check validated.`);for(let r=0;r<t.length;r++){const o=BigInt(e[r].value);if(o!==t[r])throw new Error(`Encoded Pre-PegIn HTLC output[${r}] value ${o} does not match the cross-checked htlcValue ${t[r]}; the funded/signed tx would not pay the validated amount.`);const i=e[r].script.toString("hex").toLowerCase(),c=n[r].toLowerCase();if(i!==c)throw new Error(`Encoded Pre-PegIn HTLC output[${r}] scriptPubKey ${i} does not match the cross-checked htlcScriptPubKey ${c}.`)}}const H=64,D=/^[0-9a-fA-F]+$/;async function z(e){const t=I(e.authAnchorHash),n=await S.createPrePeginTransaction({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,minPeginFeeRate:e.minPeginFeeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network,authAnchorHash:t});await W(n,e);const r=C.parseUnfundedWasmTransaction(n.txHex);G(r.outputs,n.htlcValues,n.htlcScriptPubKeys);const o=r.outputs.reduce((c,s)=>c+BigInt(s.value),0n),i=t!==void 0?n.htlcValues.length:null;return{psbtHex:n.txHex,totalOutputValue:o,htlcValues:n.htlcValues,htlcScriptPubKeys:n.htlcScriptPubKeys,htlcAddresses:n.htlcAddresses,peginAmounts:n.peginAmounts,depositorClaimValue:n.depositorClaimValue,authAnchorVout:i}}function I(e){if(e===void 0)return;const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length!==H||!D.test(t))throw new Error(`authAnchorHash must be 32-byte hex (${H} chars, no 0x prefix); got length ${t.length}`);return t.toLowerCase()}async function Y(e){const t=await S.buildPeginTxFromPrePegin({txGraphVersion:e.prePeginParams.vaultCoreVersion,depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,minPeginFeeRate:e.prePeginParams.minPeginFeeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network,authAnchorHash:I(e.prePeginParams.authAnchorHash)},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return await j(t,e),{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}const Q=2,Z=1;async function j(e,t){const n=t.prePeginParams.vaultCoreVersion;await S.validatePeginP2aAnchor(n,e.txHex);const r=await S.peginP2aAnchorOutput(n),o=Q+(r?1:0),i=v.Transaction.fromHex(u.stripHexPrefix(e.txHex));if(i.ins.length!==1)throw new Error(`PegIn tx has ${i.ins.length} input(s), expected exactly 1 (the Pre-PegIn HTLC outpoint).`);const c=v.Transaction.fromHex(u.stripHexPrefix(t.fundedPrePeginTxHex)).getId(),s=u.uint8ArrayToHex(new Uint8Array(i.ins[0].hash).slice().reverse());if(s!==c)throw new Error(`PegIn input spends txid ${s}, expected the funded Pre-PegIn ${c}.`);if(i.ins[0].index!==t.htlcVout)throw new Error(`PegIn input spends Pre-PegIn output ${i.ins[0].index}, expected the requested HTLC vout ${t.htlcVout}.`);if(i.outs.length!==o)throw new Error(`PegIn tx has ${i.outs.length} output(s), expected exactly ${o} for vaultCoreVersion ${n} (vault + depositor claim${r?" + P2A anchor":""}).`);const f=t.prePeginParams.pegInAmounts[t.htlcVout];if(e.vaultValue!==f)throw new Error(`PegIn vault output value ${e.vaultValue} does not match the requested peg-in amount ${f} for HTLC ${t.htlcVout}; refusing to sign a vault that locks a different amount than requested.`);const a=i.outs[0];if(BigInt(a.value)!==e.vaultValue)throw new Error(`Encoded PegIn vault output value ${a.value} does not match the WASM-reported vaultValue ${e.vaultValue}.`);const p=a.script.toString("hex"),d=u.stripHexPrefix(e.vaultScriptPubKey).toLowerCase();if(p.toLowerCase()!==d)throw new Error(`Encoded PegIn vault output scriptPubKey ${p} does not match the WASM-reported vaultScriptPubKey ${e.vaultScriptPubKey}.`);const h=i.getId();if(h!==u.stripHexPrefix(e.txid).toLowerCase())throw new Error(`Encoded PegIn txid ${h} does not match the WASM-reported txid ${e.txid}.`);const l=await S.computeMinClaimValue(n,t.prePeginParams.numLocalChallengers,t.prePeginParams.universalChallengerPubkeys.length,t.prePeginParams.councilQuorum,t.prePeginParams.councilSize,t.prePeginParams.feeRate),g=i.outs[Z];if(BigInt(g.value)!==l)throw new Error(`Encoded PegIn depositor-claim output value ${g.value} does not match the independently computed claim value ${l} for vaultCoreVersion ${n}.`);const $=J(t.prePeginParams.depositorPubkey);if(!g.script.equals($))throw new Error(`Encoded PegIn depositor-claim output scriptPubKey ${g.script.toString("hex")} does not pay to the depositor's claim script (expected ${$.toString("hex")}).`)}function J(e){const t=v.script.compile([P.Buffer.from(u.hexToUint8Array(e)),v.opcodes.OP_CHECKSIG]),{output:n}=v.payments.p2tr({internalPubkey:P.Buffer.from(S.tapInternalPubkey),scriptTree:{output:t}});if(!n)throw new Error("Failed to derive the depositor-claim P2TR scriptPubKey for PegIn output validation");return n}async function q(e){const t=await S.createPayoutConnector({txGraphVersion:e.vaultCoreVersion,depositor:e.depositor,vaultProvider:e.vaultProvider,vaultKeepers:e.vaultKeepers,universalChallengers:e.universalChallengers,timelockPegin:e.timelockPegin},e.network);return{payoutScript:t.payoutScript,taprootScriptHash:t.taprootScriptHash,scriptPubKey:t.scriptPubKey,address:t.address,payoutControlBlock:t.payoutControlBlock}}const O=3,U=10,B=100;async function ee(e){const t=u.stripHexPrefix(e.payoutTxHex),n=u.stripHexPrefix(e.peginTxHex),r=u.stripHexPrefix(e.assertTxHex),o=await q({vaultCoreVersion:e.vaultCoreVersion,depositor:e.depositorBtcPubkey,vaultProvider:e.vaultProviderBtcPubkey,vaultKeepers:e.vaultKeeperBtcPubkeys,universalChallengers:e.universalChallengerBtcPubkeys,timelockPegin:e.timelockPegin,network:e.network}),i=u.hexToUint8Array(o.payoutScript),c=u.hexToUint8Array(o.payoutControlBlock),s=v.Transaction.fromHex(t),f=v.Transaction.fromHex(n),a=v.Transaction.fromHex(r),p=new v.Psbt;if(p.setVersion(s.version),p.setLocktime(s.locktime),s.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${s.ins.length}`);const d=s.ins[0],h=s.ins[1],l=u.uint8ArrayToHex(new Uint8Array(d.hash).slice().reverse()),g=f.getId();if(l!==g||d.index!==w.PEGIN_VAULT_OUTPUT_INDEX)throw new Error(`Input 0 must spend PegIn:${w.PEGIN_VAULT_OUTPUT_INDEX}. Expected ${g}:${w.PEGIN_VAULT_OUTPUT_INDEX}, got ${l}:${d.index}`);const $=u.uint8ArrayToHex(new Uint8Array(h.hash).slice().reverse()),x=a.getId();if($!==x||h.index!==w.ASSERT_PAYOUT_OUTPUT_INDEX)throw new Error(`Input 1 must spend Assert:${w.ASSERT_PAYOUT_OUTPUT_INDEX}. Expected ${x}:${w.ASSERT_PAYOUT_OUTPUT_INDEX}, got ${$}:${h.index}`);const y=f.outs[d.index];if(!y)throw new Error(`Previous output not found for input 0 (txid: ${l}, index: ${d.index})`);const T=a.outs[h.index];if(!T)throw new Error(`Previous output not found for input 1 (txid: ${$}, index: ${h.index})`);te({payoutTx:s,peginValueSats:y.value,claimerBtcPubkey:e.claimerBtcPubkey,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,depositorBtcPubkey:e.depositorBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,registeredPayoutScriptPubKey:e.registeredPayoutScriptPubKey,commissionBps:e.commissionBps});const m=y.value+T.value;let b=0;for(const A of s.outs)b+=A.value;if(b>m)throw new Error(`Payout outputs (${b} sats) exceed inputs (${m} sats); invalid transaction.`);const V=m-b,k=Math.floor(m*U/B);if(V>k)throw new Error(`Payout implicit fee ${V} sats exceeds the safety cap of ${k} sats (${U}/${B} of inputs=${m}); refusing to sign payout.`);p.addInput({hash:d.hash,index:d.index,sequence:d.sequence,witnessUtxo:{script:y.script,value:y.value},tapLeafScript:[{leafVersion:u.TAPSCRIPT_LEAF_VERSION,script:P.Buffer.from(i),controlBlock:P.Buffer.from(c)}],tapInternalKey:P.Buffer.from(S.tapInternalPubkey)}),p.addInput({hash:h.hash,index:h.index,sequence:h.sequence,witnessUtxo:{script:T.script,value:T.value}});for(const A of s.outs)p.addOutput({script:A.script,value:A.value});return{psbtHex:p.toHex()}}function te(e){const{payoutTx:t,peginValueSats:n,claimerBtcPubkey:r,vaultProviderBtcPubkey:o,depositorBtcPubkey:i,vaultKeeperBtcPubkeys:c,registeredPayoutScriptPubKey:s,commissionBps:f}=e;if(!u.isValidHex(s))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const a=u.stripHexPrefix(r).toLowerCase(),p=u.stripHexPrefix(o).toLowerCase(),d=u.stripHexPrefix(i).toLowerCase(),h=c.map(T=>u.stripHexPrefix(T).toLowerCase());let l,g,$;if(a===p)l="vp-claimer",g=w.VP_CLAIMER_PAYOUT_OUTPUT_COUNT,$=u.stripHexPrefix(s);else if(a===d)l="depositor-as-claimer",g=w.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,$=u.stripHexPrefix(s);else if(h.includes(a))l="vk-claimer",g=w.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,$=u.stripHexPrefix(u.deriveBip86ScriptPubKeyHex(a));else throw new Error(`Unknown claimer pubkey ${a}: not VP, depositor, or a registered vault keeper`);if(t.outs.length!==g)throw new Error(`Payout transaction has ${t.outs.length} output(s), expected exactly ${g} for role ${l}.`);const x=P.Buffer.from($,"hex");if(!t.outs[0].script.equals(x))throw new Error(`Payout transaction output 0 does not pay the expected scriptPubKey for role ${l}`);const y=g-1;if(t.outs[y].value!==w.PAYOUT_ANCHOR_DUST_SATS)throw new Error(`Payout CPFP anchor (out ${y}) value ${t.outs[y].value} sats must equal ${w.PAYOUT_ANCHOR_DUST_SATS} sats`);if(l==="vp-claimer"){if(!Number.isInteger(f)||f<0||f>=w.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`commissionBps must be an integer in [0, ${w.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${f}`);const T=Math.floor(n*f/w.MAX_VP_COMMISSION_BPS_EXCLUSIVE);if(t.outs[1].value>T)throw new Error(`Payout VP commission (out 1) value ${t.outs[1].value} sats exceeds cap ${T} sats (${f} bps of peginValue=${n})`)}}function ne(e,t,n=0){const r=v.Psbt.fromHex(e);if(n>=r.data.inputs.length)throw new Error(`Input index ${n} out of range (${r.data.inputs.length} inputs)`);const o=r.data.inputs[n];if(o.tapScriptSig&&o.tapScriptSig.length>0){const i=u.hexToUint8Array(t);for(const c of o.tapScriptSig)if(c.pubkey.equals(P.Buffer.from(i)))return L(c.signature,n);throw new Error(`No signature found for depositor pubkey: ${t} at input ${n}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const i=re(o.finalScriptWitness);if(i.length!==O)throw new Error(`Unexpected finalized witness stack size at input ${n}: expected ${O} items (signature, script, controlBlock), got ${i.length}`);return L(i[0],n)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${n}`)}function L(e,t){if(e.length===64)return u.uint8ArrayToHex(new Uint8Array(e));throw e.length===65?new Error(`Unexpected sighash byte 0x${e[64].toString(16).padStart(2,"0")} at input ${t}. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected signature length at input ${t}: ${e.length}`)}function re(e){const t=[];let n=0;const r=c=>{if(n+c>e.length)throw new Error(`Malformed witness data: need ${c} byte(s) at offset ${n}, only ${e.length-n} remaining`)},o=()=>{r(1);const c=e[n++];if(c<253)return c;if(c===253){r(2);const s=(e[n]|e[n+1]<<8)>>>0;return n+=2,s}if(c===254){r(4);const s=(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24)>>>0;return n+=4,s}throw new Error(`Malformed witness data: 8-byte varint (0xff) not supported at offset ${n-1}`)},i=o();for(let c=0;c<i;c++){const s=o();r(s),t.push(P.Buffer.from(e.subarray(n,n+s))),n+=s}if(n!==e.length)throw new Error(`Malformed witness data: ${e.length-n} trailing byte(s) after parsing ${i} item(s)`);return t}class E extends Error{constructor(t){super(`Wallet returned a PSBT for a different transaction: ${t}`),this.name="PsbtSubstitutionError"}}function R(e,t){try{return v.Psbt.fromHex(t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new Error(`Failed to parse ${e} PSBT: ${r}`)}}const oe=8;function _(e){return`${e.toString("hex").slice(0,oe)}…`}function N(e){const t=P.Buffer.from(e).reverse();return _(t)}function ie(e){const t=R("requested",e.requestedPsbtHex),n=R("returned",e.returnedPsbtHex);if(t.version!==n.version)throw new E(`tx version differs (requested=${t.version}, returned=${n.version})`);if(t.locktime!==n.locktime)throw new E(`tx locktime differs (requested=${t.locktime}, returned=${n.locktime})`);if(t.txInputs.length!==n.txInputs.length)throw new E(`input count differs (requested=${t.txInputs.length}, returned=${n.txInputs.length})`);if(t.txOutputs.length!==n.txOutputs.length)throw new E(`output count differs (requested=${t.txOutputs.length}, returned=${n.txOutputs.length})`);for(let r=0;r<t.txInputs.length;r++){const o=t.txInputs[r],i=n.txInputs[r];if(!o.hash.equals(i.hash))throw new E(`input ${r} prevout txid differs (requested=${N(o.hash)}, returned=${N(i.hash)})`);if(o.index!==i.index)throw new E(`input ${r} prevout vout differs (requested=${o.index}, returned=${i.index})`);if(o.sequence!==i.sequence)throw new E(`input ${r} sequence differs (requested=${o.sequence}, returned=${i.sequence})`)}for(let r=0;r<t.txOutputs.length;r++){const o=t.txOutputs[r],i=n.txOutputs[r];if(!o.script.equals(i.script))throw new E(`output ${r} scriptPubKey differs (requested=${_(o.script)}, returned=${_(i.script)})`);if(o.value!==i.value)throw new E(`output ${r} value differs (requested=${o.value}, returned=${i.value})`)}}const M=253,se=254,ue=65535,ce=4294967295;function ae(e){if(e<M)return P.Buffer.from([e]);if(e<=ue){const t=P.Buffer.alloc(2);return t.writeUInt16LE(e),P.Buffer.concat([P.Buffer.from([M]),t])}if(e<=ce){const t=P.Buffer.alloc(4);return t.writeUInt32LE(e),P.Buffer.concat([P.Buffer.from([se]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const le="TapLeaf";function de(e,t){const n=P.Buffer.concat([P.Buffer.from([e]),ae(t.length),P.Buffer.from(t)]);return v.crypto.taggedHash(le,n)}function he(e){const{requestedPsbtHex:t,signatureHex:n,signerXOnlyPubkeyHex:r,inputIndex:o}=e,i=u.stripHexPrefix(n);if(i.length!==u.SCHNORR_SIG_HEX_LEN)throw new Error(`Schnorr signature for input ${o} must be ${u.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);const c=u.stripHexPrefix(r);if(c.length!==u.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey for input ${o} must be ${u.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${c.length}.`);const s=v.Psbt.fromHex(t);if(o<0||o>=s.data.inputs.length)throw new Error(`Input index ${o} out of range (${s.data.inputs.length} inputs).`);const f=[],a=[];for(let x=0;x<s.data.inputs.length;x++){const y=s.data.inputs[x].witnessUtxo;if(!y)throw new Error(`Cannot verify signature: input ${x} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);f.push(y.script),a.push(y.value)}const p=s.data.inputs[o].tapLeafScript;if(!p||p.length!==1)throw new Error(`Cannot verify signature: input ${o} of the requested PSBT must have exactly one tapLeafScript, got ${(p==null?void 0:p.length)??0}.`);const d=p[0];if(d.leafVersion!==u.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot verify signature: input ${o} tapLeafScript has leaf version 0x${d.leafVersion.toString(16)}, expected 0x${u.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const h=de(d.leafVersion,d.script),l=new v.Transaction;l.version=s.version,l.locktime=s.locktime;for(const x of s.txInputs)l.addInput(x.hash,x.index,x.sequence);for(const x of s.txOutputs)l.addOutput(x.script,x.value);const g=l.hashForWitnessV1(o,f,a,v.Transaction.SIGHASH_DEFAULT,h);if(!X.verifySchnorr(g,u.hexToUint8Array(c),u.hexToUint8Array(i)))throw new Error(`Schnorr signature for input ${o} (signer ${c}) does not verify against the expected Taproot script-path sighash. The wallet may have signed with the tweaked key, signed a different transaction, or returned an invalid signature.`)}exports.PsbtSubstitutionError=E;exports.assertPsbtUnsignedTxMatches=ie;exports.assertScriptPathSchnorrSignature=he;exports.buildPayoutPsbt=ee;exports.buildPeginTxFromFundedPrePegin=Y;exports.buildPrePeginPsbt=z;exports.createPayoutScript=q;exports.extractPayoutSignature=ne;exports.normalizeAuthAnchorHash=I;
2
- //# sourceMappingURL=verifyScriptPathSchnorrSignature-BDznSCOR.cjs.map