@babylonlabs-io/ts-sdk 0.72.0 → 0.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +56 -13
  2. package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs +2 -0
  3. package/dist/BTCVaultRegistryKeyEpochs.abi-CrQiTLfA.cjs.map +1 -0
  4. package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js +229 -0
  5. package/dist/BTCVaultRegistryKeyEpochs.abi-D8cIbMtH.js.map +1 -0
  6. package/dist/PeginManager-C9RPOd0L.js +1216 -0
  7. package/dist/PeginManager-C9RPOd0L.js.map +1 -0
  8. package/dist/PeginManager-E-UHA1un.cjs +2 -0
  9. package/dist/PeginManager-E-UHA1un.cjs.map +1 -0
  10. package/dist/bip322Verify-B7_gIhRk.cjs +2 -0
  11. package/dist/bip322Verify-B7_gIhRk.cjs.map +1 -0
  12. package/dist/bip322Verify-D6sBBUHE.js +79 -0
  13. package/dist/bip322Verify-D6sBBUHE.js.map +1 -0
  14. package/dist/{buildAndBroadcastReclaim-YvWDRAN8.js → buildAndBroadcastReclaim-BXclIcu_.js} +366 -357
  15. package/dist/buildAndBroadcastReclaim-BXclIcu_.js.map +1 -0
  16. package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +2 -0
  17. package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs.map +1 -0
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.js +209 -205
  20. package/dist/index.js.map +1 -1
  21. package/dist/onChainBtcPubkey-BbxRrbvg.cjs +2 -0
  22. package/dist/onChainBtcPubkey-BbxRrbvg.cjs.map +1 -0
  23. package/dist/onChainBtcPubkey-C-6UWpD8.js +34 -0
  24. package/dist/onChainBtcPubkey-C-6UWpD8.js.map +1 -0
  25. package/dist/{parseFundingOutpoints-BkgGihaY.cjs → parseFundingOutpoints-B4iQeX6q.cjs} +2 -2
  26. package/dist/{parseFundingOutpoints-BkgGihaY.cjs.map → parseFundingOutpoints-B4iQeX6q.cjs.map} +1 -1
  27. package/dist/{parseFundingOutpoints-DlINgQ3X.js → parseFundingOutpoints-B67CoXpF.js} +2 -2
  28. package/dist/{parseFundingOutpoints-DlINgQ3X.js.map → parseFundingOutpoints-B67CoXpF.js.map} +1 -1
  29. package/dist/pegin-registration-client-6vLk2itL.cjs +2 -0
  30. package/dist/pegin-registration-client-6vLk2itL.cjs.map +1 -0
  31. package/dist/pegin-registration-client-BdRiR8br.js +2635 -0
  32. package/dist/pegin-registration-client-BdRiR8br.js.map +1 -0
  33. package/dist/primeVpAuth-DBHohVKM.cjs +2 -0
  34. package/dist/primeVpAuth-DBHohVKM.cjs.map +1 -0
  35. package/dist/primeVpAuth-DvaD45q_.js +745 -0
  36. package/dist/primeVpAuth-DvaD45q_.js.map +1 -0
  37. package/dist/psbtInputFields-B3e05Xe6.js +171 -0
  38. package/dist/psbtInputFields-B3e05Xe6.js.map +1 -0
  39. package/dist/psbtInputFields-BIxBpPj2.cjs +2 -0
  40. package/dist/psbtInputFields-BIxBpPj2.cjs.map +1 -0
  41. package/dist/sha2-CrlWM5S8.js +312 -0
  42. package/dist/{sha2-BYVxyZzX.js.map → sha2-CrlWM5S8.js.map} +1 -1
  43. package/dist/sha2-DI0-0SHr.cjs +2 -0
  44. package/dist/{sha2-DsrLC4NM.cjs.map → sha2-DI0-0SHr.cjs.map} +1 -1
  45. package/dist/{signPsbtsWithFallback-CCFTzE0o.js → signPsbtsWithFallback-0VBALhjS.js} +2 -2
  46. package/dist/{signPsbtsWithFallback-CCFTzE0o.js.map → signPsbtsWithFallback-0VBALhjS.js.map} +1 -1
  47. package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs → signPsbtsWithFallback-DMSpIQWH.cjs} +2 -2
  48. package/dist/{signPsbtsWithFallback-CrkvpSJz.cjs.map → signPsbtsWithFallback-DMSpIQWH.cjs.map} +1 -1
  49. package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts +2 -0
  50. package/dist/tbv/core/clients/eth/__tests__/eth-import-boundary.test.d.ts.map +1 -0
  51. package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts +2 -0
  52. package/dist/tbv/core/clients/eth/__tests__/onChainBtcPubkey.test.d.ts.map +1 -0
  53. package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts +2 -0
  54. package/dist/tbv/core/clients/eth/__tests__/payout-script.test.d.ts.map +1 -0
  55. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts +2 -0
  56. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-calldata.test.d.ts.map +1 -0
  57. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts +2 -0
  58. package/dist/tbv/core/clients/eth/__tests__/pegin-registration-client.test.d.ts.map +1 -0
  59. package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts +2 -0
  60. package/dist/tbv/core/clients/eth/__tests__/pegin-transaction.test.d.ts.map +1 -0
  61. package/dist/tbv/core/clients/eth/index.cjs +2 -0
  62. package/dist/tbv/core/clients/eth/index.cjs.map +1 -0
  63. package/dist/tbv/core/clients/eth/index.d.ts +4 -0
  64. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  65. package/dist/tbv/core/clients/eth/index.js +22 -0
  66. package/dist/tbv/core/clients/eth/index.js.map +1 -0
  67. package/dist/tbv/core/clients/eth/onChainBtcPubkey.d.ts.map +1 -1
  68. package/dist/tbv/core/clients/eth/operation-key-reader.d.ts +1 -1
  69. package/dist/tbv/core/clients/eth/operation-key-reader.d.ts.map +1 -1
  70. package/dist/tbv/core/clients/eth/payout-script.d.ts +4 -0
  71. package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -0
  72. package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts +99 -0
  73. package/dist/tbv/core/clients/eth/pegin-registration-client.d.ts.map +1 -0
  74. package/dist/tbv/core/clients/eth/pegin-transaction.d.ts +14 -0
  75. package/dist/tbv/core/clients/eth/pegin-transaction.d.ts.map +1 -0
  76. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +6 -1
  77. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  78. package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +4 -4
  79. package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -1
  80. package/dist/tbv/core/clients/eth/types.d.ts +29 -8
  81. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  82. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +1 -1
  83. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  84. package/dist/tbv/core/clients/index.cjs +1 -1
  85. package/dist/tbv/core/clients/index.js +55 -48
  86. package/dist/tbv/core/clients/index.js.map +1 -1
  87. package/dist/tbv/core/clients/mempool/index.cjs +2 -0
  88. package/dist/tbv/core/clients/mempool/index.cjs.map +1 -0
  89. package/dist/tbv/core/clients/mempool/index.js +222 -0
  90. package/dist/tbv/core/clients/mempool/index.js.map +1 -0
  91. package/dist/tbv/core/contracts/index.cjs +1 -1
  92. package/dist/tbv/core/contracts/index.cjs.map +1 -1
  93. package/dist/tbv/core/contracts/index.js +491 -12
  94. package/dist/tbv/core/contracts/index.js.map +1 -1
  95. package/dist/tbv/core/index.cjs +1 -1
  96. package/dist/tbv/core/index.d.ts +1 -0
  97. package/dist/tbv/core/index.d.ts.map +1 -1
  98. package/dist/tbv/core/index.js +207 -203
  99. package/dist/tbv/core/index.js.map +1 -1
  100. package/dist/tbv/core/managers/PeginManager.d.ts +38 -30
  101. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  102. package/dist/tbv/core/managers/index.cjs +1 -1
  103. package/dist/tbv/core/managers/index.d.ts +2 -1
  104. package/dist/tbv/core/managers/index.d.ts.map +1 -1
  105. package/dist/tbv/core/managers/index.js +2 -2
  106. package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts +20 -0
  107. package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts.map +1 -1
  108. package/dist/tbv/core/services/index.cjs +1 -1
  109. package/dist/tbv/core/services/index.js +2 -2
  110. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +8 -0
  111. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
  112. package/dist/tbv/core/utils/eth/index.cjs +2 -0
  113. package/dist/tbv/core/utils/eth/index.cjs.map +1 -0
  114. package/dist/tbv/core/utils/eth/index.js +109 -0
  115. package/dist/tbv/core/utils/eth/index.js.map +1 -0
  116. package/dist/tbv/core/utils/index.cjs +1 -1
  117. package/dist/tbv/core/utils/index.js +41 -40
  118. package/dist/tbv/core/utils/index.js.map +1 -1
  119. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  120. package/dist/tbv/core/vault-secrets/index.js +1 -1
  121. package/dist/tbv/index.cjs +1 -1
  122. package/dist/tbv/index.js +207 -203
  123. package/dist/tbv/index.js.map +1 -1
  124. package/dist/testing/index.cjs +1 -1
  125. package/dist/testing/index.js +1 -1
  126. package/dist/{toRefundInputs-Df1vi23S.js → toRefundInputs-BkcFhvDp.js} +5 -5
  127. package/dist/{toRefundInputs-Df1vi23S.js.map → toRefundInputs-BkcFhvDp.js.map} +1 -1
  128. package/dist/{toRefundInputs-CY9u84U9.cjs → toRefundInputs-CatCKniS.cjs} +2 -2
  129. package/dist/{toRefundInputs-CY9u84U9.cjs.map → toRefundInputs-CatCKniS.cjs.map} +1 -1
  130. package/dist/types-CPDLZm3l.js +430 -0
  131. package/dist/types-CPDLZm3l.js.map +1 -0
  132. package/dist/types-DSlcXtog.cjs +2 -0
  133. package/dist/types-DSlcXtog.cjs.map +1 -0
  134. package/package.json +32 -3
  135. package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js +0 -111
  136. package/dist/BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js.map +0 -1
  137. package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs +0 -2
  138. package/dist/BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs.map +0 -1
  139. package/dist/PeginManager-Bn8FxM35.cjs +0 -2
  140. package/dist/PeginManager-Bn8FxM35.cjs.map +0 -1
  141. package/dist/PeginManager-C3ojNTlv.js +0 -1503
  142. package/dist/PeginManager-C3ojNTlv.js.map +0 -1
  143. package/dist/ProtocolParams.abi-C0TSRaHV.js +0 -486
  144. package/dist/ProtocolParams.abi-C0TSRaHV.js.map +0 -1
  145. package/dist/ProtocolParams.abi-CYZoV2EI.cjs +0 -2
  146. package/dist/ProtocolParams.abi-CYZoV2EI.cjs.map +0 -1
  147. package/dist/buildAndBroadcastReclaim-YvWDRAN8.js.map +0 -1
  148. package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs +0 -2
  149. package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs.map +0 -1
  150. package/dist/errors-Blc-JWnI.js +0 -121
  151. package/dist/errors-Blc-JWnI.js.map +0 -1
  152. package/dist/errors-CGcNP0rV.cjs +0 -2
  153. package/dist/errors-CGcNP0rV.cjs.map +0 -1
  154. package/dist/mempoolApi-CKD_IbrM.js +0 -611
  155. package/dist/mempoolApi-CKD_IbrM.js.map +0 -1
  156. package/dist/mempoolApi-DronQ5xn.cjs +0 -2
  157. package/dist/mempoolApi-DronQ5xn.cjs.map +0 -1
  158. package/dist/onChainBtcPubkey-B5ZvWCCF.cjs +0 -2
  159. package/dist/onChainBtcPubkey-B5ZvWCCF.cjs.map +0 -1
  160. package/dist/onChainBtcPubkey-DATNfAAl.js +0 -19
  161. package/dist/onChainBtcPubkey-DATNfAAl.js.map +0 -1
  162. package/dist/primeVpAuth-Cjq6qFHq.cjs +0 -2
  163. package/dist/primeVpAuth-Cjq6qFHq.cjs.map +0 -1
  164. package/dist/primeVpAuth-tLRjdHwZ.js +0 -1159
  165. package/dist/primeVpAuth-tLRjdHwZ.js.map +0 -1
  166. package/dist/sha2-BYVxyZzX.js +0 -274
  167. package/dist/sha2-DsrLC4NM.cjs +0 -2
  168. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs +0 -2
  169. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs.map +0 -1
  170. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js +0 -277
  171. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-Blc-JWnI.js","sources":["../src/tbv/core/contracts/errors.ts"],"sourcesContent":["/**\n * Contract Error Handling Utilities\n *\n * Provides utilities for extracting and handling contract revert errors.\n * Maps known error selectors to user-friendly messages.\n *\n * @module contracts/errors\n */\n\n/**\n * Known contract error signatures mapped to user-friendly messages.\n *\n * Error selectors are the first 4 bytes of keccak256(error signature).\n * Example: keccak256(\"VaultAlreadyExists()\") = 0x04aabf33...\n */\nexport const CONTRACT_ERRORS: Record<string, string> = {\n // VaultAlreadyExists()\n \"0x04aabf33\":\n \"Vault already exists: This Bitcoin transaction has already been registered. \" +\n \"Please select different UTXOs or use a different amount to create a unique transaction.\",\n // ScriptPubKeyMismatch() - taproot output doesn't match expected script\n \"0x4fec082d\":\n \"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. \" +\n \"This may be caused by incorrect vault participants or key configuration.\",\n // InvalidBTCProofOfPossession()\n \"0x6cc363a5\":\n \"Invalid BTC proof of possession: The signature could not be verified. \" +\n \"Please ensure you're signing with the correct Bitcoin wallet.\",\n // InvalidBTCPublicKey()\n \"0x6c3f2bf6\":\n \"Invalid BTC public key: The Bitcoin public key format is invalid.\",\n // InvalidAmount()\n \"0x2c5211c6\":\n \"Invalid amount: The deposit amount is invalid or below the minimum required.\",\n // ApplicationNotRegistered()\n \"0x0405f772\":\n \"Application not registered: The application controller is not registered in the system.\",\n // InvalidProviderStatus()\n \"0x24e165cc\":\n \"Invalid provider status: The vault provider is not in a valid state to accept deposits.\",\n // ZeroAddress()\n \"0xd92e233d\":\n \"Zero address: One of the required addresses is the zero address.\",\n // BtcKeyMismatch()\n \"0x65aa7007\":\n \"BTC key mismatch: The Bitcoin public key does not match the expected key.\",\n // Unauthorized()\n \"0x82b42900\":\n \"Unauthorized: You must be the depositor or vault provider to submit this transaction.\",\n // InvalidSignature() - common signature verification error\n \"0x8baa579f\":\n \"Invalid signature: The BTC proof of possession signature could not be verified.\",\n // InvalidBtcTransaction()\n \"0x2f9d01e9\":\n \"Invalid BTC transaction: The Bitcoin transaction format is invalid.\",\n // VaultProviderNotRegistered()\n \"0x5a3c6b3e\":\n \"Vault provider not registered: The selected vault provider is not registered.\",\n // InvalidPeginFee(uint256,uint256)\n \"0x979f4518\":\n \"Invalid pegin fee: The ETH fee sent does not match the required amount. \" +\n \"This may indicate a fee rate change during the transaction.\",\n // PrePeginOutputAlreadyUsed()\n \"0x5fad9694\":\n \"This pre-pegin output has already been used to activate another vault.\",\n // PeginTransactionAlreadyUsed()\n \"0x7ed061c9\":\n \"This pegin transaction has already been used to activate another vault.\",\n // DuplicateHashlock() — keccak256(abi.encodePacked(hashlock, msg.sender))\n // collision in BTCVaultRegistry.hashlockToVaultId. Hashlocks are derived\n // deterministically from the depositor's BTC wallet + selected UTXOs, so\n // reusing the same UTXOs from the same wallet (even after a previous\n // vault expires) produces the same hashlock and reverts here.\n \"0x70f7d5e2\":\n \"Duplicate deposit: a BTC Vault with this hashlock is already registered to your wallet. Hashlocks are derived from your BTC wallet and selected UTXOs — use different UTXOs to create a unique deposit.\",\n};\n\n/**\n * Extract error data from various error formats.\n *\n * Viem and wallet providers wrap errors in multiple levels. This function\n * searches through the error chain to find the revert data.\n *\n * @param error - The error object to extract data from\n * @returns The error data (e.g., \"0x04aabf33\") or undefined\n */\nexport function extractErrorData(error: unknown): string | undefined {\n return walkForErrorData(error, 0);\n}\n\n/**\n * Walk an error chain looking for revert data in any of viem 2.x's known\n * shapes. Covers:\n * - `.data: \"0x...\"` — raw revert hex (most common with `estimateGas`)\n * - `.revertData: \"0x...\"` — alternate viem shape\n * - `.signature: \"0x...\"` — 4-byte selector from a *decoded*\n * ContractFunctionRevertedError (set when the ABI included the error def)\n * - `.error.data: \"0x...\"` — RPC-level error shape from some providers\n * - `.walk(fn)` — viem's chainable error walker (BaseError.walk)\n * - `.cause` chain — viem wraps errors many layers deep\n *\n * Depth-limited (10) and walk-result-deduplicated so a cycle can't loop.\n */\nfunction walkForErrorData(\n error: unknown,\n depth: number,\n): string | undefined {\n if (depth > 10 || !error || typeof error !== \"object\") return undefined;\n\n const err = error as Record<string, unknown>;\n\n if (typeof err.data === \"string\" && err.data.startsWith(\"0x\")) {\n return err.data;\n }\n if (typeof err.revertData === \"string\" && err.revertData.startsWith(\"0x\")) {\n return err.revertData;\n }\n if (typeof err.signature === \"string\" && err.signature.startsWith(\"0x\")) {\n return err.signature;\n }\n if (typeof err.details === \"string\" && err.details.startsWith(\"0x\")) {\n return err.details;\n }\n\n // RPC-level error shape (`{ error: { data: \"0x...\" } }`)\n if (err.error && typeof err.error === \"object\") {\n const inner = (err.error as Record<string, unknown>).data;\n if (typeof inner === \"string\" && inner.startsWith(\"0x\")) {\n return inner;\n }\n }\n\n // Recurse through `.cause`\n if (err.cause) {\n const fromCause = walkForErrorData(err.cause, depth + 1);\n if (fromCause) return fromCause;\n }\n\n // Use viem's `.walk()` if available\n if (typeof err.walk === \"function\") {\n try {\n let found: string | undefined;\n (err.walk as (fn: (e: unknown) => boolean) => unknown)((e) => {\n if (e === error) return false; // avoid self-cycle\n const data = walkForErrorData(e, depth + 1);\n if (data) {\n found = data;\n return true;\n }\n return false;\n });\n if (found) return found;\n } catch {\n // walk failed; ignore\n }\n }\n\n // Last resort: regex an embedded hex selector out of the message\n if (depth === 0) {\n const message = typeof err.message === \"string\" ? err.message : \"\";\n const hexMatch = message.match(/\\b(0x[a-fA-F0-9]{8})\\b/);\n if (hexMatch) return hexMatch[1];\n }\n\n return undefined;\n}\n\n/**\n * Get a user-friendly error message for a contract error.\n *\n * @param error - The error object from a contract call\n * @returns A user-friendly error message, or undefined if error is not recognized\n */\nexport function getContractErrorMessage(error: unknown): string | undefined {\n const errorData = extractErrorData(error);\n if (errorData) {\n // Check exact match first, then match by 4-byte selector prefix.\n // Parametric errors (e.g. InvalidPeginFee(uint256,uint256)) return\n // the selector + ABI-encoded args, so the full string won't match.\n const selector = errorData.substring(0, 10); // \"0x\" + 4 bytes\n return CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n }\n return undefined;\n}\n\n/**\n * Check if an error is a known contract error.\n *\n * @param error - The error object to check\n * @returns True if the error is a known contract error\n */\nexport function isKnownContractError(error: unknown): boolean {\n const errorData = extractErrorData(error);\n if (errorData === undefined) return false;\n const selector = errorData.substring(0, 10);\n return errorData in CONTRACT_ERRORS || selector in CONTRACT_ERRORS;\n}\n\n/**\n * Handle a contract error by throwing a user-friendly error.\n *\n * This function extracts error data, maps it to a user-friendly message,\n * and throws an appropriate error. Use this in catch blocks after contract calls.\n *\n * @param error - The error from a contract call\n * @throws Always throws an error with a descriptive message\n */\nexport function handleContractError(error: unknown): never {\n // Log full error for debugging\n console.error(\"[Contract Error] Raw error:\", error);\n\n // Extract error data from the error chain\n const errorData = extractErrorData(error);\n console.error(\"[Contract Error] Extracted error data:\", errorData);\n\n // Check for known contract error signatures (exact match or 4-byte selector prefix)\n if (errorData) {\n const selector = errorData.substring(0, 10);\n const knownError = CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n if (knownError) {\n console.error(\"[Contract Error] Known error:\", knownError);\n throw new Error(knownError);\n }\n }\n\n // Check for gas estimation errors or internal JSON-RPC errors\n const errorMsg = (error as Error)?.message || \"\";\n if (\n errorMsg.includes(\"gas limit too high\") ||\n errorMsg.includes(\"21000000\") ||\n errorMsg.includes(\"Internal JSON-RPC error\")\n ) {\n // If we found error data but it's not in our known list, include it\n const errorHint = errorData ? ` (error code: ${errorData})` : \"\";\n console.error(\n \"[Contract Error] Transaction rejected. Error code:\",\n errorData,\n \"Message:\",\n errorMsg,\n );\n throw new Error(\n `Transaction failed: The contract rejected this transaction${errorHint}. ` +\n \"Possible causes: (1) Vault already exists for this transaction, \" +\n \"(2) Invalid signature, (3) Unauthorized caller. \" +\n \"Please check your transaction parameters and try again.\",\n );\n }\n\n // Default: re-throw original error with better context\n if (error instanceof Error) {\n console.error(\"[Contract Error] Unhandled error:\", error.message);\n throw error;\n }\n throw new Error(`Contract call failed: ${String(error)}`);\n}\n"],"names":["CONTRACT_ERRORS","extractErrorData","error","walkForErrorData","depth","err","inner","fromCause","found","e","data","hexMatch","getContractErrorMessage","errorData","selector","isKnownContractError","handleContractError","knownError","errorMsg","errorHint"],"mappings":"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"}
@@ -1,2 +0,0 @@
1
- "use strict";const n={"0x04aabf33":"Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.","0x4fec082d":"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.","0x6cc363a5":"Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.","0x6c3f2bf6":"Invalid BTC public key: The Bitcoin public key format is invalid.","0x2c5211c6":"Invalid amount: The deposit amount is invalid or below the minimum required.","0x0405f772":"Application not registered: The application controller is not registered in the system.","0x24e165cc":"Invalid provider status: The vault provider is not in a valid state to accept deposits.","0xd92e233d":"Zero address: One of the required addresses is the zero address.","0x65aa7007":"BTC key mismatch: The Bitcoin public key does not match the expected key.","0x82b42900":"Unauthorized: You must be the depositor or vault provider to submit this transaction.","0x8baa579f":"Invalid signature: The BTC proof of possession signature could not be verified.","0x2f9d01e9":"Invalid BTC transaction: The Bitcoin transaction format is invalid.","0x5a3c6b3e":"Vault provider not registered: The selected vault provider is not registered.","0x979f4518":"Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction.","0x5fad9694":"This pre-pegin output has already been used to activate another vault.","0x7ed061c9":"This pegin transaction has already been used to activate another vault.","0x70f7d5e2":"Duplicate deposit: a BTC Vault with this hashlock is already registered to your wallet. Hashlocks are derived from your BTC wallet and selected UTXOs — use different UTXOs to create a unique deposit."};function i(e){return s(e,0)}function s(e,r){if(r>10||!e||typeof e!="object")return;const t=e;if(typeof t.data=="string"&&t.data.startsWith("0x"))return t.data;if(typeof t.revertData=="string"&&t.revertData.startsWith("0x"))return t.revertData;if(typeof t.signature=="string"&&t.signature.startsWith("0x"))return t.signature;if(typeof t.details=="string"&&t.details.startsWith("0x"))return t.details;if(t.error&&typeof t.error=="object"){const a=t.error.data;if(typeof a=="string"&&a.startsWith("0x"))return a}if(t.cause){const a=s(t.cause,r+1);if(a)return a}if(typeof t.walk=="function")try{let a;if(t.walk(o=>{if(o===e)return!1;const c=s(o,r+1);return c?(a=c,!0):!1}),a)return a}catch{}if(r===0){const o=(typeof t.message=="string"?t.message:"").match(/\b(0x[a-fA-F0-9]{8})\b/);if(o)return o[1]}}function d(e){const r=i(e);if(r){const t=r.substring(0,10);return n[r]??n[t]}}function u(e){const r=i(e);if(r===void 0)return!1;const t=r.substring(0,10);return r in n||t in n}function l(e){console.error("[Contract Error] Raw error:",e);const r=i(e);if(console.error("[Contract Error] Extracted error data:",r),r){const a=r.substring(0,10),o=n[r]??n[a];if(o)throw console.error("[Contract Error] Known error:",o),new Error(o)}const t=(e==null?void 0:e.message)||"";if(t.includes("gas limit too high")||t.includes("21000000")||t.includes("Internal JSON-RPC error")){const a=r?` (error code: ${r})`:"";throw console.error("[Contract Error] Transaction rejected. Error code:",r,"Message:",t),new Error(`Transaction failed: The contract rejected this transaction${a}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`)}throw e instanceof Error?(console.error("[Contract Error] Unhandled error:",e.message),e):new Error(`Contract call failed: ${String(e)}`)}exports.CONTRACT_ERRORS=n;exports.extractErrorData=i;exports.getContractErrorMessage=d;exports.handleContractError=l;exports.isKnownContractError=u;
2
- //# sourceMappingURL=errors-CGcNP0rV.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-CGcNP0rV.cjs","sources":["../src/tbv/core/contracts/errors.ts"],"sourcesContent":["/**\n * Contract Error Handling Utilities\n *\n * Provides utilities for extracting and handling contract revert errors.\n * Maps known error selectors to user-friendly messages.\n *\n * @module contracts/errors\n */\n\n/**\n * Known contract error signatures mapped to user-friendly messages.\n *\n * Error selectors are the first 4 bytes of keccak256(error signature).\n * Example: keccak256(\"VaultAlreadyExists()\") = 0x04aabf33...\n */\nexport const CONTRACT_ERRORS: Record<string, string> = {\n // VaultAlreadyExists()\n \"0x04aabf33\":\n \"Vault already exists: This Bitcoin transaction has already been registered. \" +\n \"Please select different UTXOs or use a different amount to create a unique transaction.\",\n // ScriptPubKeyMismatch() - taproot output doesn't match expected script\n \"0x4fec082d\":\n \"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. \" +\n \"This may be caused by incorrect vault participants or key configuration.\",\n // InvalidBTCProofOfPossession()\n \"0x6cc363a5\":\n \"Invalid BTC proof of possession: The signature could not be verified. \" +\n \"Please ensure you're signing with the correct Bitcoin wallet.\",\n // InvalidBTCPublicKey()\n \"0x6c3f2bf6\":\n \"Invalid BTC public key: The Bitcoin public key format is invalid.\",\n // InvalidAmount()\n \"0x2c5211c6\":\n \"Invalid amount: The deposit amount is invalid or below the minimum required.\",\n // ApplicationNotRegistered()\n \"0x0405f772\":\n \"Application not registered: The application controller is not registered in the system.\",\n // InvalidProviderStatus()\n \"0x24e165cc\":\n \"Invalid provider status: The vault provider is not in a valid state to accept deposits.\",\n // ZeroAddress()\n \"0xd92e233d\":\n \"Zero address: One of the required addresses is the zero address.\",\n // BtcKeyMismatch()\n \"0x65aa7007\":\n \"BTC key mismatch: The Bitcoin public key does not match the expected key.\",\n // Unauthorized()\n \"0x82b42900\":\n \"Unauthorized: You must be the depositor or vault provider to submit this transaction.\",\n // InvalidSignature() - common signature verification error\n \"0x8baa579f\":\n \"Invalid signature: The BTC proof of possession signature could not be verified.\",\n // InvalidBtcTransaction()\n \"0x2f9d01e9\":\n \"Invalid BTC transaction: The Bitcoin transaction format is invalid.\",\n // VaultProviderNotRegistered()\n \"0x5a3c6b3e\":\n \"Vault provider not registered: The selected vault provider is not registered.\",\n // InvalidPeginFee(uint256,uint256)\n \"0x979f4518\":\n \"Invalid pegin fee: The ETH fee sent does not match the required amount. \" +\n \"This may indicate a fee rate change during the transaction.\",\n // PrePeginOutputAlreadyUsed()\n \"0x5fad9694\":\n \"This pre-pegin output has already been used to activate another vault.\",\n // PeginTransactionAlreadyUsed()\n \"0x7ed061c9\":\n \"This pegin transaction has already been used to activate another vault.\",\n // DuplicateHashlock() — keccak256(abi.encodePacked(hashlock, msg.sender))\n // collision in BTCVaultRegistry.hashlockToVaultId. Hashlocks are derived\n // deterministically from the depositor's BTC wallet + selected UTXOs, so\n // reusing the same UTXOs from the same wallet (even after a previous\n // vault expires) produces the same hashlock and reverts here.\n \"0x70f7d5e2\":\n \"Duplicate deposit: a BTC Vault with this hashlock is already registered to your wallet. Hashlocks are derived from your BTC wallet and selected UTXOs — use different UTXOs to create a unique deposit.\",\n};\n\n/**\n * Extract error data from various error formats.\n *\n * Viem and wallet providers wrap errors in multiple levels. This function\n * searches through the error chain to find the revert data.\n *\n * @param error - The error object to extract data from\n * @returns The error data (e.g., \"0x04aabf33\") or undefined\n */\nexport function extractErrorData(error: unknown): string | undefined {\n return walkForErrorData(error, 0);\n}\n\n/**\n * Walk an error chain looking for revert data in any of viem 2.x's known\n * shapes. Covers:\n * - `.data: \"0x...\"` — raw revert hex (most common with `estimateGas`)\n * - `.revertData: \"0x...\"` — alternate viem shape\n * - `.signature: \"0x...\"` — 4-byte selector from a *decoded*\n * ContractFunctionRevertedError (set when the ABI included the error def)\n * - `.error.data: \"0x...\"` — RPC-level error shape from some providers\n * - `.walk(fn)` — viem's chainable error walker (BaseError.walk)\n * - `.cause` chain — viem wraps errors many layers deep\n *\n * Depth-limited (10) and walk-result-deduplicated so a cycle can't loop.\n */\nfunction walkForErrorData(\n error: unknown,\n depth: number,\n): string | undefined {\n if (depth > 10 || !error || typeof error !== \"object\") return undefined;\n\n const err = error as Record<string, unknown>;\n\n if (typeof err.data === \"string\" && err.data.startsWith(\"0x\")) {\n return err.data;\n }\n if (typeof err.revertData === \"string\" && err.revertData.startsWith(\"0x\")) {\n return err.revertData;\n }\n if (typeof err.signature === \"string\" && err.signature.startsWith(\"0x\")) {\n return err.signature;\n }\n if (typeof err.details === \"string\" && err.details.startsWith(\"0x\")) {\n return err.details;\n }\n\n // RPC-level error shape (`{ error: { data: \"0x...\" } }`)\n if (err.error && typeof err.error === \"object\") {\n const inner = (err.error as Record<string, unknown>).data;\n if (typeof inner === \"string\" && inner.startsWith(\"0x\")) {\n return inner;\n }\n }\n\n // Recurse through `.cause`\n if (err.cause) {\n const fromCause = walkForErrorData(err.cause, depth + 1);\n if (fromCause) return fromCause;\n }\n\n // Use viem's `.walk()` if available\n if (typeof err.walk === \"function\") {\n try {\n let found: string | undefined;\n (err.walk as (fn: (e: unknown) => boolean) => unknown)((e) => {\n if (e === error) return false; // avoid self-cycle\n const data = walkForErrorData(e, depth + 1);\n if (data) {\n found = data;\n return true;\n }\n return false;\n });\n if (found) return found;\n } catch {\n // walk failed; ignore\n }\n }\n\n // Last resort: regex an embedded hex selector out of the message\n if (depth === 0) {\n const message = typeof err.message === \"string\" ? err.message : \"\";\n const hexMatch = message.match(/\\b(0x[a-fA-F0-9]{8})\\b/);\n if (hexMatch) return hexMatch[1];\n }\n\n return undefined;\n}\n\n/**\n * Get a user-friendly error message for a contract error.\n *\n * @param error - The error object from a contract call\n * @returns A user-friendly error message, or undefined if error is not recognized\n */\nexport function getContractErrorMessage(error: unknown): string | undefined {\n const errorData = extractErrorData(error);\n if (errorData) {\n // Check exact match first, then match by 4-byte selector prefix.\n // Parametric errors (e.g. InvalidPeginFee(uint256,uint256)) return\n // the selector + ABI-encoded args, so the full string won't match.\n const selector = errorData.substring(0, 10); // \"0x\" + 4 bytes\n return CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n }\n return undefined;\n}\n\n/**\n * Check if an error is a known contract error.\n *\n * @param error - The error object to check\n * @returns True if the error is a known contract error\n */\nexport function isKnownContractError(error: unknown): boolean {\n const errorData = extractErrorData(error);\n if (errorData === undefined) return false;\n const selector = errorData.substring(0, 10);\n return errorData in CONTRACT_ERRORS || selector in CONTRACT_ERRORS;\n}\n\n/**\n * Handle a contract error by throwing a user-friendly error.\n *\n * This function extracts error data, maps it to a user-friendly message,\n * and throws an appropriate error. Use this in catch blocks after contract calls.\n *\n * @param error - The error from a contract call\n * @throws Always throws an error with a descriptive message\n */\nexport function handleContractError(error: unknown): never {\n // Log full error for debugging\n console.error(\"[Contract Error] Raw error:\", error);\n\n // Extract error data from the error chain\n const errorData = extractErrorData(error);\n console.error(\"[Contract Error] Extracted error data:\", errorData);\n\n // Check for known contract error signatures (exact match or 4-byte selector prefix)\n if (errorData) {\n const selector = errorData.substring(0, 10);\n const knownError = CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n if (knownError) {\n console.error(\"[Contract Error] Known error:\", knownError);\n throw new Error(knownError);\n }\n }\n\n // Check for gas estimation errors or internal JSON-RPC errors\n const errorMsg = (error as Error)?.message || \"\";\n if (\n errorMsg.includes(\"gas limit too high\") ||\n errorMsg.includes(\"21000000\") ||\n errorMsg.includes(\"Internal JSON-RPC error\")\n ) {\n // If we found error data but it's not in our known list, include it\n const errorHint = errorData ? ` (error code: ${errorData})` : \"\";\n console.error(\n \"[Contract Error] Transaction rejected. Error code:\",\n errorData,\n \"Message:\",\n errorMsg,\n );\n throw new Error(\n `Transaction failed: The contract rejected this transaction${errorHint}. ` +\n \"Possible causes: (1) Vault already exists for this transaction, \" +\n \"(2) Invalid signature, (3) Unauthorized caller. \" +\n \"Please check your transaction parameters and try again.\",\n );\n }\n\n // Default: re-throw original error with better context\n if (error instanceof Error) {\n console.error(\"[Contract Error] Unhandled error:\", error.message);\n throw error;\n }\n throw new Error(`Contract call failed: ${String(error)}`);\n}\n"],"names":["CONTRACT_ERRORS","extractErrorData","error","walkForErrorData","depth","err","inner","fromCause","found","e","data","hexMatch","getContractErrorMessage","errorData","selector","isKnownContractError","handleContractError","knownError","errorMsg","errorHint"],"mappings":"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"}
@@ -1,611 +0,0 @@
1
- import * as p from "@bitcoin-js/tiny-secp256k1-asmjs";
2
- import { Transaction as u, payments as E, script as T } from "bitcoinjs-lib";
3
- import { s as y } from "./sha2-BYVxyZzX.js";
4
- import { Buffer as c } from "buffer";
5
- import { B as a } from "./BTCVaultRegistry.abi-CJwWI2EO.js";
6
- import { B as A } from "./BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js";
7
- import { a as V } from "./onChainBtcPubkey-DATNfAAl.js";
8
- import { a as G } from "./vaultCoreVersion-D_fP9P3C.js";
9
- import { c as L } from "./abortSignals-BPpAUL1Z.js";
10
- import { B as W, H as Q, K as j, T as z } from "./validation-OSC0xTHB.js";
11
- const Y = "BIP0322-signed-message", Z = "TapTweak", k = 32, q = 64, J = 33, tt = 71, et = 72, g = 0, C = 0, v = 0, S = 0, ot = 32, nt = 4294967295, rt = 0, it = 0, st = 32, at = 106;
12
- function R(t, e) {
13
- const o = new TextEncoder().encode(t), n = y(o), i = new Uint8Array(n.length * 2 + e.length);
14
- return i.set(n, 0), i.set(n, n.length), i.set(e, n.length * 2), y(i);
15
- }
16
- function ct(t) {
17
- if (t.length !== k) return null;
18
- const e = R(Z, t), o = p.xOnlyPointAddTweak(t, e);
19
- return o ? o.xOnlyPubkey : null;
20
- }
21
- function H(t, e) {
22
- const o = R(Y, t), n = new u();
23
- n.version = C, n.locktime = v;
24
- const i = c.concat([
25
- c.from([it, st]),
26
- c.from(o)
27
- ]);
28
- n.addInput(
29
- c.alloc(ot, 0),
30
- nt,
31
- S,
32
- i
33
- ), n.addOutput(e, g);
34
- const r = new u();
35
- return r.version = C, r.locktime = v, r.addInput(
36
- n.getHash(),
37
- rt,
38
- S
39
- ), r.addOutput(c.from([at]), g), r;
40
- }
41
- function Vt(t, e, o, n = u.SIGHASH_DEFAULT) {
42
- if (e.length !== k || o.length !== q || n !== u.SIGHASH_DEFAULT && n !== u.SIGHASH_ALL)
43
- return !1;
44
- try {
45
- const i = E.p2tr({
46
- internalPubkey: c.from(e)
47
- });
48
- if (!i.output) return !1;
49
- const r = i.output, h = H(t, r).hashForWitnessV1(
50
- 0,
51
- [r],
52
- [g],
53
- n
54
- ), m = ct(e);
55
- return m ? p.verifySchnorr(h, m, o) : !1;
56
- } catch {
57
- return !1;
58
- }
59
- }
60
- function Ct(t, e, o) {
61
- if (e.length !== J || o.length < tt || o.length > et)
62
- return !1;
63
- try {
64
- if (!p.isPointCompressed(e)) return !1;
65
- const { signature: n, hashType: i } = T.signature.decode(
66
- c.from(o)
67
- );
68
- if (!T.signature.encode(n, i).equals(c.from(o)) || i !== u.SIGHASH_ALL) return !1;
69
- const r = E.p2wpkh({ pubkey: c.from(e) });
70
- if (!r.output || !r.hash) return !1;
71
- const s = H(t, r.output), h = E.p2pkh({ hash: r.hash }).output;
72
- if (!h) return !1;
73
- const m = s.hashForWitnessV0(0, h, g, i);
74
- return p.verify(m, e, n, !0);
75
- } catch {
76
- return !1;
77
- }
78
- }
79
- const w = 65535, _ = 1e4, d = 4294967295, B = 255;
80
- function ut(t) {
81
- if (!Number.isInteger(t) || t < 0 || t > d)
82
- throw new Error(
83
- `Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`
84
- );
85
- }
86
- function lt(t) {
87
- const e = [];
88
- if (t.timelockAssert <= 0n && e.push(
89
- `timelockAssert must be positive, got ${t.timelockAssert}`
90
- ), t.timelockAssert > BigInt(w) && e.push(
91
- `timelockAssert ${t.timelockAssert} exceeds uint16 max (${w})`
92
- ), t.timelockChallengeAssert <= 0n && e.push(
93
- `timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`
94
- ), t.tRefund <= 0 && e.push(`tRefund must be positive, got ${t.tRefund}`), t.tStale <= 0 && e.push(`tStale must be positive, got ${t.tStale}`), t.securityCouncilKeys.length === 0 && e.push("securityCouncilKeys must not be empty"), t.councilQuorum <= 0 && e.push(`councilQuorum must be positive, got ${t.councilQuorum}`), t.councilQuorum > t.securityCouncilKeys.length && e.push(
95
- `councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`
96
- ), t.feeRate <= 0n && e.push(`feeRate must be positive, got ${t.feeRate}`), t.minPeginFeeRate <= 0n && e.push(
97
- `minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`
98
- ), (!Number.isInteger(t.proverCircuitVersion) || t.proverCircuitVersion < 0 || t.proverCircuitVersion > w) && e.push(
99
- `proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`
100
- ), (!Number.isInteger(t.minPrepeginDepth) || t.minPrepeginDepth <= 0 || t.minPrepeginDepth > d) && e.push(
101
- `minPrepeginDepth must be a uint32 in [1, ${d}], got ${t.minPrepeginDepth}`
102
- ), t.babeTotalInstances <= 0 && e.push(
103
- `babeTotalInstances must be positive, got ${t.babeTotalInstances}`
104
- ), t.babeInstancesToFinalize <= 0 && e.push(
105
- `babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`
106
- ), t.babeInstancesToFinalize > t.babeTotalInstances && e.push(
107
- `babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`
108
- ), (t.minVpCommissionBps < 0 || t.minVpCommissionBps > _) && e.push(
109
- `minVpCommissionBps must be in [0, ${_}], got ${t.minVpCommissionBps}`
110
- ), e.length > 0)
111
- throw new Error(
112
- `Invalid offchain protocol parameters: ${e.join("; ")}`
113
- );
114
- }
115
- function ft(t) {
116
- const e = [];
117
- if (t.minimumPegInAmount <= 0n && e.push(
118
- `minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`
119
- ), t.maxPegInAmount < t.minimumPegInAmount && e.push(
120
- `maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`
121
- ), t.pegInAckTimeout <= 0n && e.push(
122
- `pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`
123
- ), t.pegInActivationTimeout <= 0n && e.push(
124
- `pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`
125
- ), (!Number.isInteger(t.maxHtlcOutputCount) || t.maxHtlcOutputCount <= 0 || t.maxHtlcOutputCount > B) && e.push(
126
- `maxHtlcOutputCount must be an integer in [1, ${B}], got ${t.maxHtlcOutputCount}`
127
- ), (typeof t.expiredPegInGraceBlocks != "bigint" || t.expiredPegInGraceBlocks <= 0n) && e.push(
128
- `expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`
129
- ), e.length > 0)
130
- throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`);
131
- }
132
- function vt(t) {
133
- if (ft(t), lt(t.offchainParams), !Number.isInteger(t.offchainParamsVersion) || t.offchainParamsVersion < 0 || t.offchainParamsVersion > d)
134
- throw new Error(
135
- `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`
136
- );
137
- G(
138
- t.activeVaultCoreVersion,
139
- "ProtocolParams.activeVaultCoreVersion()"
140
- );
141
- }
142
- const F = 9999;
143
- function x(t) {
144
- return {
145
- depositor: t.depositor,
146
- depositorBtcPubKey: t.depositorBtcPubKey,
147
- amount: t.amount,
148
- vaultProvider: t.vaultProvider,
149
- status: t.status,
150
- applicationEntryPoint: t.applicationEntryPoint,
151
- createdAt: t.createdAt
152
- };
153
- }
154
- function I(t) {
155
- const e = Number(t.offchainParamsVersion);
156
- return ut(e), {
157
- depositorSignedPeginTx: t.depositorSignedPeginTx,
158
- universalChallengersVersion: t.universalChallengersVersion,
159
- appVaultKeepersVersion: t.appVaultKeepersVersion,
160
- offchainParamsVersion: e,
161
- verifiedAt: t.verifiedAt,
162
- depositorWotsPkHash: t.depositorWotsPkHash,
163
- hashlock: t.hashlock,
164
- htlcVout: t.htlcVout,
165
- depositorPopSignature: t.depositorPopSignature,
166
- prePeginTxHash: t.prePeginTxHash,
167
- vaultProviderCommissionBps: t.vaultProviderCommissionBps,
168
- vaultCoreVersion: t.vaultCoreVersion
169
- };
170
- }
171
- const ht = 1n << 64n, O = 0n;
172
- function b(t, e, o) {
173
- if (t < 0n || t >= ht)
174
- throw new Error(
175
- `getBtcVaultProtocolInfo returned ${e}=${t} for vault ${o}, outside the uint64 range — the registry may predate RFC-006`
176
- );
177
- return t;
178
- }
179
- function N(t, e) {
180
- return {
181
- vpKeyEpoch: b(t.vpKeyEpoch, "vpKeyEpoch", e),
182
- appKeeperKeyEpoch: b(
183
- t.appKeeperKeyEpoch,
184
- "appKeeperKeyEpoch",
185
- e
186
- ),
187
- ucKeyEpoch: b(t.ucKeyEpoch, "ucKeyEpoch", e)
188
- };
189
- }
190
- class St {
191
- constructor(e, o) {
192
- this.publicClient = e, this.contractAddress = o;
193
- }
194
- /**
195
- * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded
196
- * at version 0, which never moves when the operator rotates.
197
- *
198
- * Resolved as "the operation key at epoch 0" rather than through the
199
- * dedicated `getVaultProviderBTCKey` getter, which
200
- * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.
201
- * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or
202
- * later — so it resolves to the registration key, and the contracts team has
203
- * confirmed that is a property we can rely on rather than an implementation
204
- * detail. The devnet comparison behind that claim — both getters returning the
205
- * identical key for a provider that *has* rotated, while
206
- * `getCurrentOperationBtcKey` differed — is recorded in
207
- * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.
208
- *
209
- * This makes the read RFC-006-only, where the removed getter also existed on a
210
- * legacy registry. That costs nothing: every caller of this method already
211
- * resolves participant keys through `OperationKeyReader`, so all of them
212
- * require an RFC-006 registry regardless.
213
- *
214
- * Validates length, hex form, and secp256k1 curve membership before minting
215
- * the brand. Returns 64-char lowercase hex without the `0x` prefix.
216
- */
217
- async getVaultProviderGenesisBtcPubKey(e) {
218
- const o = await this.publicClient.readContract({
219
- address: this.contractAddress,
220
- abi: a,
221
- functionName: "getOperationBtcKeyAtEpoch",
222
- args: [e, O]
223
- });
224
- return V(
225
- o,
226
- `getOperationBtcKeyAtEpoch (vp=${e}, epoch=${O})`
227
- );
228
- }
229
- /**
230
- * Read a vault provider's *current* RFC-006 operation BTC key.
231
- *
232
- * Falls back on-chain to the registration key when the provider has never
233
- * rotated, so this returns the same value as
234
- * `getVaultProviderGenesisBtcPubKey` until the first rotation.
235
- *
236
- * This is the key the VP's server signs its BIP-322 auth tokens with — a
237
- * live per-operator identity, not a per-vault binding, so the auth pin uses
238
- * the current key rather than any vault's frozen epoch.
239
- */
240
- async getCurrentVaultProviderOperationBtcKey(e) {
241
- const o = await this.publicClient.readContract({
242
- address: this.contractAddress,
243
- abi: a,
244
- functionName: "getCurrentOperationBtcKey",
245
- args: [e]
246
- });
247
- return V(
248
- o,
249
- `getCurrentOperationBtcKey (vp=${e})`
250
- );
251
- }
252
- /**
253
- * Read a vault's frozen RFC-006 operation-key epochs.
254
- *
255
- * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only
256
- * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`
257
- * struct is not extended this call does not fail for a populated vault, it
258
- * silently returns three words of tail data as epochs. Nothing here can detect
259
- * that, so the guarantee is a deployment one — every network this ships to has
260
- * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.
261
- *
262
- * A registry missing the operation-key getters entirely is the *safer* of the
263
- * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these
264
- * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}
265
- * for which state the range check actually guards, and
266
- * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.
267
- */
268
- async getVaultKeyEpochs(e) {
269
- const o = await this.publicClient.readContract({
270
- address: this.contractAddress,
271
- abi: A,
272
- functionName: "getBtcVaultProtocolInfo",
273
- args: [e]
274
- });
275
- return N(o, e);
276
- }
277
- async getVaultKeyEpochsBatch(e) {
278
- return e.length === 0 ? [] : (await this.publicClient.multicall({
279
- contracts: e.map((n) => ({
280
- address: this.contractAddress,
281
- abi: A,
282
- functionName: "getBtcVaultProtocolInfo",
283
- args: [n]
284
- })),
285
- allowFailure: !1
286
- })).map(
287
- (n, i) => N(n, e[i])
288
- );
289
- }
290
- async getVaultBasicInfo(e) {
291
- const o = await this.publicClient.readContract({
292
- address: this.contractAddress,
293
- abi: a,
294
- functionName: "getBtcVaultBasicInfo",
295
- args: [e]
296
- });
297
- return x(o);
298
- }
299
- async getVaultProtocolInfo(e) {
300
- const o = await this.publicClient.readContract({
301
- address: this.contractAddress,
302
- abi: a,
303
- functionName: "getBtcVaultProtocolInfo",
304
- args: [e]
305
- });
306
- return I(o);
307
- }
308
- async getProtocolInfoBatch(e) {
309
- return e.length === 0 ? [] : (await this.publicClient.multicall({
310
- contracts: e.map((n) => ({
311
- address: this.contractAddress,
312
- abi: a,
313
- functionName: "getBtcVaultProtocolInfo",
314
- args: [n]
315
- })),
316
- allowFailure: !1
317
- })).map((n, i) => {
318
- const r = n;
319
- if (!r.depositorSignedPeginTx || r.depositorSignedPeginTx === "0x")
320
- throw new Error(
321
- `Vault ${e[i]} not found on-chain or has no pegin transaction`
322
- );
323
- return I(r);
324
- });
325
- }
326
- /**
327
- * Read the protocol pegin fee (in wei) for a given vault provider.
328
- * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.
329
- */
330
- async getPegInFee(e) {
331
- return await this.publicClient.readContract({
332
- address: this.contractAddress,
333
- abi: a,
334
- functionName: "getPegInFee",
335
- args: [e]
336
- });
337
- }
338
- /**
339
- * Read a vault provider's current commission in basis points from
340
- * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the
341
- * legitimate range is `[0, 9999]`; anything outside indicates a wrong
342
- * contract address or ABI drift and is surfaced as an error rather than
343
- * trusted.
344
- */
345
- async getVaultProviderCommission(e) {
346
- const o = await this.publicClient.readContract({
347
- address: this.contractAddress,
348
- abi: a,
349
- functionName: "getVaultProviderCommission",
350
- args: [e]
351
- });
352
- if (!Number.isInteger(o) || o < 0 || o > F)
353
- throw new Error(
354
- `getVaultProviderCommission returned ${o} bps for ${e}, outside the protocol range [0, ${F}]`
355
- );
356
- return o;
357
- }
358
- async getVaultData(e) {
359
- const [o, n] = await this.publicClient.multicall({
360
- contracts: [
361
- {
362
- address: this.contractAddress,
363
- abi: a,
364
- functionName: "getBtcVaultBasicInfo",
365
- args: [e]
366
- },
367
- {
368
- address: this.contractAddress,
369
- abi: a,
370
- functionName: "getBtcVaultProtocolInfo",
371
- args: [e]
372
- }
373
- ],
374
- allowFailure: !1
375
- }), i = x(o), r = I(n);
376
- if (!r.depositorSignedPeginTx || r.depositorSignedPeginTx === "0x")
377
- throw new Error(
378
- `Vault ${e} not found on-chain or has no pegin transaction`
379
- );
380
- return { basic: i, protocol: r };
381
- }
382
- }
383
- const mt = 21e6 * 1e8, K = 3e4;
384
- async function P(t, e) {
385
- const o = new AbortController(), n = setTimeout(
386
- () => o.abort(),
387
- K
388
- ), i = [o.signal, e == null ? void 0 : e.signal].filter(
389
- Boolean
390
- ), r = L(i);
391
- try {
392
- return await fetch(t, {
393
- ...e,
394
- signal: r.signal
395
- });
396
- } catch (s) {
397
- throw clearTimeout(n), r.cleanup(), s != null && typeof s == "object" && "name" in s && s.name === "AbortError" ? new Error(
398
- `Mempool API request timed out after ${K}ms: ${t}`
399
- ) : s;
400
- }
401
- }
402
- const U = 1e4;
403
- function M(t) {
404
- return Number.isInteger(t) && t > 0 && t <= mt;
405
- }
406
- function pt(t) {
407
- return Number.isInteger(t) && t > 0 && t <= U;
408
- }
409
- function $(t, e) {
410
- return !Number.isInteger(t) || t < 0 ? !1 : e === void 0 || t < e;
411
- }
412
- function f(t) {
413
- if (!z.test(t))
414
- throw new Error(`Invalid transaction ID format: ${t}`);
415
- }
416
- function X(t) {
417
- if (!W.test(t))
418
- throw new Error(`Invalid Bitcoin address format: ${t}`);
419
- }
420
- function D(t, e) {
421
- if (!Q.test(t))
422
- throw new Error(
423
- `Invalid scriptPubKey: not valid hex for ${e}`
424
- );
425
- if (!j.some(
426
- (n) => t.toLowerCase().startsWith(n)
427
- ))
428
- throw new Error(
429
- `Unrecognized scriptPubKey type for ${e}: prefix ${t.slice(0, 6)} does not match any known Bitcoin script type`
430
- );
431
- }
432
- const gt = {
433
- mainnet: "https://mempool.space/api",
434
- testnet: "https://mempool.space/testnet/api",
435
- signet: "https://mempool.space/signet/api"
436
- };
437
- async function l(t, e) {
438
- try {
439
- const o = await P(t, e);
440
- if (!o.ok) {
441
- const i = await o.text();
442
- throw new Error(
443
- `Mempool API error (${o.status}): ${i || o.statusText}`
444
- );
445
- }
446
- const n = o.headers.get("content-type");
447
- return n != null && n.includes("application/json") ? await o.json() : await o.text();
448
- } catch (o) {
449
- throw o instanceof Error ? new Error(`Failed to fetch from mempool API: ${o.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
450
- }
451
- }
452
- async function _t(t, e) {
453
- try {
454
- const o = await P(`${e}/tx`, {
455
- method: "POST",
456
- body: t,
457
- headers: {
458
- "Content-Type": "text/plain"
459
- }
460
- });
461
- if (!o.ok) {
462
- const i = await o.text();
463
- let r;
464
- try {
465
- const s = JSON.parse(i);
466
- r = s.message ?? s.error;
467
- } catch {
468
- r = i;
469
- }
470
- throw new Error(
471
- r || `Failed to broadcast transaction: ${o.statusText}`
472
- );
473
- }
474
- return await o.text();
475
- } catch (o) {
476
- throw o instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${o.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
477
- }
478
- }
479
- async function dt(t, e) {
480
- return f(t), l(`${e}/tx/${t}`);
481
- }
482
- async function Bt(t) {
483
- const e = await l(`${t}/blocks/tip/height`), o = e.trim(), n = /^\d+$/.test(o) ? Number.parseInt(o, 10) : NaN;
484
- if (!Number.isSafeInteger(n) || n < 0)
485
- throw new Error(
486
- `Mempool API returned an invalid block tip height: "${e}"`
487
- );
488
- return n;
489
- }
490
- async function Ft(t, e, o) {
491
- if (f(t), !$(e))
492
- throw new Error(`Invalid vout ${e} for transaction ${t}`);
493
- return l(`${o}/tx/${t}/outspend/${e}`);
494
- }
495
- async function xt(t, e) {
496
- f(t);
497
- try {
498
- const o = await P(`${e}/tx/${t}/hex`);
499
- if (!o.ok) {
500
- const n = await o.text();
501
- throw new Error(
502
- `Mempool API error (${o.status}): ${n || o.statusText}`
503
- );
504
- }
505
- return await o.text();
506
- } catch (o) {
507
- throw o instanceof Error ? new Error(`Failed to get transaction hex for ${t}: ${o.message}`) : new Error(`Failed to get transaction hex for ${t}: Unknown error`);
508
- }
509
- }
510
- async function Ot(t, e, o) {
511
- f(t);
512
- const n = await dt(t, o);
513
- if (!$(e, n.vout.length))
514
- throw new Error(
515
- `Invalid vout ${e} for transaction ${t} (has ${n.vout.length} outputs)`
516
- );
517
- const i = n.vout[e];
518
- if (!M(i.value))
519
- throw new Error(`Invalid UTXO value ${i.value} for ${t}:${e}`);
520
- return D(i.scriptpubkey, `${t}:${e}`), {
521
- txid: t,
522
- vout: e,
523
- value: i.value,
524
- scriptPubKey: i.scriptpubkey
525
- };
526
- }
527
- async function Nt(t, e) {
528
- X(t);
529
- try {
530
- const o = await l(`${e}/address/${t}/utxo`), n = await l(`${e}/v1/validate-address/${t}`);
531
- if (!n.isvalid)
532
- throw new Error(
533
- `Invalid Bitcoin address: ${t}. Mempool API validation failed.`
534
- );
535
- D(n.scriptPubKey, t);
536
- for (const r of o) {
537
- if (f(r.txid), !$(r.vout))
538
- throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);
539
- if (!M(r.value))
540
- throw new Error(
541
- `Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`
542
- );
543
- }
544
- return o.sort((r, s) => s.value - r.value).map((r) => ({
545
- txid: r.txid,
546
- vout: r.vout,
547
- value: r.value,
548
- scriptPubKey: n.scriptPubKey,
549
- confirmed: r.status.confirmed
550
- }));
551
- } catch (o) {
552
- throw o instanceof Error ? new Error(
553
- `Failed to get UTXOs for address ${t}: ${o.message}`
554
- ) : new Error(
555
- `Failed to get UTXOs for address ${t}: Unknown error`
556
- );
557
- }
558
- }
559
- function Kt(t) {
560
- return gt[t];
561
- }
562
- async function kt(t, e) {
563
- return X(t), l(`${e}/address/${t}/txs`);
564
- }
565
- async function Rt(t) {
566
- const e = await P(`${t}/v1/fees/recommended`);
567
- if (!e.ok)
568
- throw new Error(
569
- `Failed to fetch network fees: ${e.status} ${e.statusText}`
570
- );
571
- const o = await e.json(), n = [
572
- "fastestFee",
573
- "halfHourFee",
574
- "hourFee",
575
- "economyFee",
576
- "minimumFee"
577
- ];
578
- for (const i of n)
579
- if (!pt(o[i]))
580
- throw new Error(
581
- `Invalid fee rate ${i}=${o[i]} from mempool API: expected a positive number ≤ ${U}`
582
- );
583
- if (o.minimumFee > o.economyFee || o.economyFee > o.hourFee || o.hourFee > o.halfHourFee || o.halfHourFee > o.fastestFee)
584
- throw new Error(
585
- `Fee rate ordering violation from mempool API: expected minimumFee (${o.minimumFee}) <= economyFee (${o.economyFee}) <= hourFee (${o.hourFee}) <= halfHourFee (${o.halfHourFee}) <= fastestFee (${o.fastestFee}).`
586
- );
587
- return o;
588
- }
589
- export {
590
- gt as M,
591
- tt as P,
592
- St as V,
593
- Nt as a,
594
- Kt as b,
595
- Rt as c,
596
- Ft as d,
597
- Bt as e,
598
- xt as f,
599
- kt as g,
600
- dt as h,
601
- Ot as i,
602
- vt as j,
603
- ft as k,
604
- Vt as l,
605
- et as m,
606
- Ct as n,
607
- ut as o,
608
- _t as p,
609
- lt as v
610
- };
611
- //# sourceMappingURL=mempoolApi-CKD_IbrM.js.map