@babylonlabs-io/ts-sdk 0.44.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/{BTCVaultRegistry.abi-Cq9-JlqT.js → BTCVaultRegistry.abi-Chs4AFBj.js} +125 -2
- package/dist/BTCVaultRegistry.abi-Chs4AFBj.js.map +1 -0
- package/dist/{BTCVaultRegistry.abi-CHFGevwa.cjs → BTCVaultRegistry.abi-JdeqLz4x.cjs} +2 -2
- package/dist/BTCVaultRegistry.abi-JdeqLz4x.cjs.map +1 -0
- package/dist/{PeginManager-D-8vmqzq.cjs → PeginManager-CeloRUHV.cjs} +2 -2
- package/dist/{PeginManager-D-8vmqzq.cjs.map → PeginManager-CeloRUHV.cjs.map} +1 -1
- package/dist/{PeginManager-BezsAEDe.js → PeginManager-CxSbzoYs.js} +4 -4
- package/dist/{PeginManager-BezsAEDe.js.map → PeginManager-CxSbzoYs.js.map} +1 -1
- package/dist/{buildAndBroadcastRefund-37Bs7-V1.js → buildAndBroadcastRefund-CZj2z7PJ.js} +2 -2
- package/dist/{buildAndBroadcastRefund-37Bs7-V1.js.map → buildAndBroadcastRefund-CZj2z7PJ.js.map} +1 -1
- package/dist/{buildAndBroadcastRefund-DbcNEsOv.cjs → buildAndBroadcastRefund-Ux587SFf.cjs} +2 -2
- package/dist/{buildAndBroadcastRefund-DbcNEsOv.cjs.map → buildAndBroadcastRefund-Ux587SFf.cjs.map} +1 -1
- package/dist/{errors-CznAK5NB.js → errors-Blc-JWnI.js} +71 -46
- package/dist/errors-Blc-JWnI.js.map +1 -0
- package/dist/errors-CGcNP0rV.cjs +2 -0
- package/dist/errors-CGcNP0rV.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +106 -107
- package/dist/mempoolApi-BxT89SAq.js +471 -0
- package/dist/mempoolApi-BxT89SAq.js.map +1 -0
- package/dist/mempoolApi-C_9JhjCI.cjs +2 -0
- package/dist/mempoolApi-C_9JhjCI.cjs.map +1 -0
- package/dist/primeVpAuth-7EYTPSTj.cjs +2 -0
- package/dist/{primeVpAuth-Duds3vAO.cjs.map → primeVpAuth-7EYTPSTj.cjs.map} +1 -1
- package/dist/{primeVpAuth-qEC9TTO_.js → primeVpAuth-DZlsu0di.js} +369 -341
- package/dist/{primeVpAuth-qEC9TTO_.js.map → primeVpAuth-DZlsu0di.js.map} +1 -1
- package/dist/reservation-BxvKbQH2.js +107 -0
- package/dist/reservation-BxvKbQH2.js.map +1 -0
- package/dist/reservation-xTL2a9Q-.cjs +2 -0
- package/dist/reservation-xTL2a9Q-.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +6 -0
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts +12 -0
- package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts +8 -0
- package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +8 -0
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +42 -13
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +14 -4
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -1
- package/dist/tbv/core/contracts/__tests__/errors.test.d.ts +2 -0
- package/dist/tbv/core/contracts/__tests__/errors.test.d.ts.map +1 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +292 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/errors.d.ts.map +1 -1
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +102 -103
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +32 -33
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +0 -1
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/availability.d.ts +22 -1
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts +11 -86
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +102 -103
- package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/oracle.d.ts +8 -1
- package/dist/tbv/integrations/aave/clients/oracle.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/spoke.d.ts +27 -0
- package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/constants.d.ts +3 -3
- package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +276 -212
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/BTCVaultRegistry.abi-CHFGevwa.cjs.map +0 -1
- package/dist/BTCVaultRegistry.abi-Cq9-JlqT.js.map +0 -1
- package/dist/errors-BP73_stm.cjs +0 -2
- package/dist/errors-BP73_stm.cjs.map +0 -1
- package/dist/errors-CznAK5NB.js.map +0 -1
- package/dist/mempoolApi-CknccHKg.cjs +0 -2
- package/dist/mempoolApi-CknccHKg.cjs.map +0 -1
- package/dist/mempoolApi-DI9HISqi.js +0 -451
- package/dist/mempoolApi-DI9HISqi.js.map +0 -1
- package/dist/primeVpAuth-Duds3vAO.cjs +0 -2
- package/dist/reservation-Cwf2u4vu.cjs +0 -2
- package/dist/reservation-Cwf2u4vu.cjs.map +0 -1
- package/dist/reservation-DNOGLBt4.js +0 -143
- package/dist/reservation-DNOGLBt4.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-CznAK5NB.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};\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 if (!error || typeof error !== \"object\") return undefined;\n\n const err = error as Record<string, unknown>;\n\n // Check direct properties first\n if (typeof err.data === \"string\" && err.data.startsWith(\"0x\")) {\n return err.data;\n }\n if (typeof err.details === \"string\" && err.details.startsWith(\"0x\")) {\n return err.details;\n }\n\n // Walk the cause chain (viem wraps errors multiple levels deep)\n let current: unknown = err.cause;\n let depth = 0;\n const maxDepth = 5;\n\n while (current && typeof current === \"object\" && depth < maxDepth) {\n const cause = current as Record<string, unknown>;\n if (typeof cause.data === \"string\" && cause.data.startsWith(\"0x\")) {\n return cause.data;\n }\n current = cause.cause;\n depth++;\n }\n\n // Check error message for embedded hex error selector\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) {\n 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","err","current","depth","maxDepth","cause","hexMatch","getContractErrorMessage","errorData","selector","isKnownContractError","handleContractError","knownError","errorMsg","errorHint"],"mappings":"AAeO,MAAMA,IAA0C;AAAA;AAAA,EAErD,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,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,UAAMC,IAAWD,EAAU,UAAU,GAAG,EAAE,GACpCI,IAAad,EAAgBU,CAAS,KAAKV,EAAgBW,CAAQ;AACzE,QAAIG;AACF,oBAAQ,MAAM,iCAAiCA,CAAU,GACnD,IAAI,MAAMA,CAAU;AAAA,EAE9B;AAGA,QAAMC,KAAYb,KAAA,gBAAAA,EAAiB,YAAW;AAC9C,MACEa,EAAS,SAAS,oBAAoB,KACtCA,EAAS,SAAS,UAAU,KAC5BA,EAAS,SAAS,yBAAyB,GAC3C;AAEA,UAAMC,IAAYN,IAAY,iBAAiBA,CAAS,MAAM;AAC9D,kBAAQ;AAAA,MACN;AAAA,MACAA;AAAA,MACA;AAAA,MACAK;AAAA,IAAA,GAEI,IAAI;AAAA,MACR,6DAA6DC,CAAS;AAAA,IAAA;AAAA,EAK1E;AAGA,QAAId,aAAiB,SACnB,QAAQ,MAAM,qCAAqCA,EAAM,OAAO,GAC1DA,KAEF,IAAI,MAAM,yBAAyB,OAAOA,CAAK,CAAC,EAAE;AAC1D;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const C=require("@bitcoin-js/tiny-secp256k1-asmjs"),E=require("./bitcoin-CHfKAhcI.cjs"),s=require("./BTCVaultRegistry.abi-CHFGevwa.cjs"),l=require("./validation-u8W7Lp2x.cjs");function B(e){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(o,t,r.get?r:{enumerable:!0,get:()=>e[t]})}}return o.default=e,Object.freeze(o)}const F=B(C),m=65535,d=1e4,f=4294967295,p=255;function u(e){if(!Number.isInteger(e)||e<0||e>f)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`)}function b(e){const o=[];if(e.timelockAssert<=0n&&o.push(`timelockAssert must be positive, got ${e.timelockAssert}`),e.timelockAssert>BigInt(m)&&o.push(`timelockAssert ${e.timelockAssert} exceeds uint16 max (${m})`),e.timelockChallengeAssert<=0n&&o.push(`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`),e.tRefund<=0&&o.push(`tRefund must be positive, got ${e.tRefund}`),e.tStale<=0&&o.push(`tStale must be positive, got ${e.tStale}`),e.securityCouncilKeys.length===0&&o.push("securityCouncilKeys must not be empty"),e.councilQuorum<=0&&o.push(`councilQuorum must be positive, got ${e.councilQuorum}`),e.councilQuorum>e.securityCouncilKeys.length&&o.push(`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`),e.feeRate<=0n&&o.push(`feeRate must be positive, got ${e.feeRate}`),e.minPeginFeeRate<=0n&&o.push(`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`),(!Number.isInteger(e.proverCircuitVersion)||e.proverCircuitVersion<0||e.proverCircuitVersion>m)&&o.push(`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`),(!Number.isInteger(e.minPrepeginDepth)||e.minPrepeginDepth<=0||e.minPrepeginDepth>f)&&o.push(`minPrepeginDepth must be a uint32 in [1, ${f}], got ${e.minPrepeginDepth}`),e.babeTotalInstances<=0&&o.push(`babeTotalInstances must be positive, got ${e.babeTotalInstances}`),e.babeInstancesToFinalize<=0&&o.push(`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`),e.babeInstancesToFinalize>e.babeTotalInstances&&o.push(`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`),(e.minVpCommissionBps<0||e.minVpCommissionBps>d)&&o.push(`minVpCommissionBps must be in [0, ${d}], got ${e.minVpCommissionBps}`),o.length>0)throw new Error(`Invalid offchain protocol parameters: ${o.join("; ")}`)}function I(e){const o=[];if(e.minimumPegInAmount<=0n&&o.push(`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`),e.maxPegInAmount<e.minimumPegInAmount&&o.push(`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`),e.pegInAckTimeout<=0n&&o.push(`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`),e.pegInActivationTimeout<=0n&&o.push(`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`),(!Number.isInteger(e.maxHtlcOutputCount)||e.maxHtlcOutputCount<=0||e.maxHtlcOutputCount>p)&&o.push(`maxHtlcOutputCount must be an integer in [1, ${p}], got ${e.maxHtlcOutputCount}`),(typeof e.expiredPegInGraceBlocks!="bigint"||e.expiredPegInGraceBlocks<=0n)&&o.push(`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`),o.length>0)throw new Error(`Invalid TBV protocol parameters: ${o.join("; ")}`)}function k(e){if(I(e),b(e.offchainParams),!Number.isInteger(e.offchainParamsVersion)||e.offchainParamsVersion<0||e.offchainParamsVersion>f)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`)}const P=9999;class S{constructor(o,t){this.publicClient=o,this.contractAddress=t}async getVaultProviderBtcPubKey(o){const r=(await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderBTCKey",args:[o]})).toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`getVaultProviderBTCKey returned an unexpected value (vp=${o}, length ${r.length}, prefix "${r.slice(0,2)}")`);const i=r.slice(2);if(!F.isXOnlyPoint(E.hexToUint8Array(i)))throw new Error(`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${o})`);return i}async getVaultBasicInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[o]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]}),r=Number(t.offchainParamsVersion);return u(r),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:r,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,claimExpiredUntil:t.claimExpiredUntil,vaultCoreVersion:t.vaultCoreVersion}}async getProtocolInfoBatch(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map((r,i)=>{const n=r;if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o[i]} not found on-chain or has no pegin transaction`);const a=Number(n.offchainParamsVersion);return u(a),{depositorSignedPeginTx:n.depositorSignedPeginTx,universalChallengersVersion:n.universalChallengersVersion,appVaultKeepersVersion:n.appVaultKeepersVersion,offchainParamsVersion:a,verifiedAt:n.verifiedAt,depositorWotsPkHash:n.depositorWotsPkHash,hashlock:n.hashlock,htlcVout:n.htlcVout,depositorPopSignature:n.depositorPopSignature,prePeginTxHash:n.prePeginTxHash,vaultProviderCommissionBps:n.vaultProviderCommissionBps,claimExpiredUntil:n.claimExpiredUntil,vaultCoreVersion:n.vaultCoreVersion}})}async getPegInFee(o){return await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}async getVaultProviderCommission(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[o]});if(!Number.isInteger(t)||t<0||t>P)throw new Error(`getVaultProviderCommission returned ${t} bps for ${o}, outside the protocol range [0, ${P}]`);return t}async getVaultData(o){const[t,r]=await Promise.all([this.getVaultBasicInfo(o),this.getVaultProtocolInfo(o)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}async getOffchainParamsVersionsByVaultIds(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map(r=>{const i=r;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error("Vault not found on-chain or has no pegin transaction while reading offchain params version");const n=Number(i.offchainParamsVersion);return u(n),n})}}const O=21e6*1e8,w=3e4;async function h(e,o){const t=new AbortController,r=setTimeout(()=>t.abort(),w),i=[t.signal,o==null?void 0:o.signal].filter(Boolean);try{return await fetch(e,{...o,signal:AbortSignal.any(i)})}catch(n){throw clearTimeout(r),n!=null&&typeof n=="object"&&"name"in n&&n.name==="AbortError"?new Error(`Mempool API request timed out after ${w}ms: ${e}`):n}}const $=1e4;function T(e){return Number.isInteger(e)&&e>0&&e<=O}function N(e){return Number.isInteger(e)&&e>0&&e<=$}function v(e,o){return!Number.isInteger(e)||e<0?!1:o===void 0||e<o}function g(e){if(!l.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function V(e){if(!l.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function y(e,o){if(!l.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${o}`);if(!l.KNOWN_SCRIPT_PREFIXES.some(r=>e.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${o}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const x={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(e,o){try{const t=await h(e,o);if(!t.ok){const i=await t.text();throw new Error(`Mempool API error (${t.status}): ${i||t.statusText}`)}const r=t.headers.get("content-type");return r!=null&&r.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function R(e,o){try{const t=await h(`${o}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!t.ok){const i=await t.text();let n;try{n=JSON.parse(i).message}catch{n=i}throw new Error(n||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function A(e,o){return g(e),c(`${o}/tx/${e}`)}async function U(e){const o=await c(`${e}/blocks/tip/height`),t=o.trim();if(!/^\d+$/.test(t))throw new Error(`Mempool API returned an invalid block tip height: "${o}"`);return Number.parseInt(t,10)}async function _(e,o){g(e);try{const t=await h(`${o}/tx/${e}/hex`);if(!t.ok){const r=await t.text();throw new Error(`Mempool API error (${t.status}): ${r||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${t.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function M(e,o,t){g(e);const r=await A(e,t);if(!v(o,r.vout.length))throw new Error(`Invalid vout ${o} for transaction ${e} (has ${r.vout.length} outputs)`);const i=r.vout[o];if(!T(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${e}:${o}`);return y(i.scriptpubkey,`${e}:${o}`),{txid:e,vout:o,value:i.value,scriptPubKey:i.scriptpubkey}}async function H(e,o){V(e);try{const t=await c(`${o}/address/${e}/utxo`),r=await c(`${o}/v1/validate-address/${e}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);y(r.scriptPubKey,e);for(const n of t){if(g(n.txid),!v(n.vout))throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);if(!T(n.value))throw new Error(`Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`)}return t.sort((n,a)=>a.value-n.value).map(n=>({txid:n.txid,vout:n.vout,value:n.value,scriptPubKey:r.scriptPubKey,confirmed:n.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${t.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function K(e){return x[e]}async function X(e,o){return V(e),c(`${o}/address/${e}/txs`)}async function D(e){const o=await h(`${e}/v1/fees/recommended`);if(!o.ok)throw new Error(`Failed to fetch network fees: ${o.status} ${o.statusText}`);const t=await o.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of r)if(!N(t[i]))throw new Error(`Invalid fee rate ${i}=${t[i]} from mempool API: expected a positive number ≤ ${$}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}exports.MEMPOOL_API_URLS=x;exports.ViemVaultRegistryReader=S;exports.assertValidOffchainParamsVersion=u;exports.getAddressTxs=X;exports.getAddressUtxos=H;exports.getMempoolApiUrl=K;exports.getNetworkFees=D;exports.getTipHeight=U;exports.getTxHex=_;exports.getTxInfo=A;exports.getUtxoInfo=M;exports.pushTx=R;exports.validateOffchainParams=b;exports.validatePegInConfiguration=k;exports.validateTBVProtocolParams=I;
|
|
2
|
-
//# sourceMappingURL=mempoolApi-CknccHKg.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mempoolApi-CknccHKg.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 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","/**\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/**\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 {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n };\n\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\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 {\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\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n\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 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 const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\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 { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } 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;\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 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","MAX_VP_COMMISSION_BPS","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","result","offchainParamsVersion","vaultIds","info","vaultProvider","bps","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","getTxInfo","getTipHeight","raw","trimmed","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"udAsBMA,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,K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ACA,aACA,YAAA,EAGF,UAAWC,KAASD,EAClB,GAAI,CAAC5C,EAAe2C,EAAKE,CAAK,CAAC,EAC7B,MAAM,IAAI,MACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmDhD,CAAY,EAAA,EAK7G,GACE8C,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,451 +0,0 @@
|
|
|
1
|
-
import * as T from "@bitcoin-js/tiny-secp256k1-asmjs";
|
|
2
|
-
import { h as V } from "./bitcoin-B5aNKtsk.js";
|
|
3
|
-
import { B as s } from "./BTCVaultRegistry.abi-Cq9-JlqT.js";
|
|
4
|
-
import { B as x, H as y, K as A, T as C } from "./validation-CxqROCno.js";
|
|
5
|
-
const h = 65535, d = 1e4, u = 4294967295, g = 255;
|
|
6
|
-
function m(e) {
|
|
7
|
-
if (!Number.isInteger(e) || e < 0 || e > u)
|
|
8
|
-
throw new Error(
|
|
9
|
-
`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`
|
|
10
|
-
);
|
|
11
|
-
}
|
|
12
|
-
function E(e) {
|
|
13
|
-
const o = [];
|
|
14
|
-
if (e.timelockAssert <= 0n && o.push(
|
|
15
|
-
`timelockAssert must be positive, got ${e.timelockAssert}`
|
|
16
|
-
), e.timelockAssert > BigInt(h) && o.push(
|
|
17
|
-
`timelockAssert ${e.timelockAssert} exceeds uint16 max (${h})`
|
|
18
|
-
), e.timelockChallengeAssert <= 0n && o.push(
|
|
19
|
-
`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`
|
|
20
|
-
), e.tRefund <= 0 && o.push(`tRefund must be positive, got ${e.tRefund}`), e.tStale <= 0 && o.push(`tStale must be positive, got ${e.tStale}`), e.securityCouncilKeys.length === 0 && o.push("securityCouncilKeys must not be empty"), e.councilQuorum <= 0 && o.push(`councilQuorum must be positive, got ${e.councilQuorum}`), e.councilQuorum > e.securityCouncilKeys.length && o.push(
|
|
21
|
-
`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`
|
|
22
|
-
), e.feeRate <= 0n && o.push(`feeRate must be positive, got ${e.feeRate}`), e.minPeginFeeRate <= 0n && o.push(
|
|
23
|
-
`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`
|
|
24
|
-
), (!Number.isInteger(e.proverCircuitVersion) || e.proverCircuitVersion < 0 || e.proverCircuitVersion > h) && o.push(
|
|
25
|
-
`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`
|
|
26
|
-
), (!Number.isInteger(e.minPrepeginDepth) || e.minPrepeginDepth <= 0 || e.minPrepeginDepth > u) && o.push(
|
|
27
|
-
`minPrepeginDepth must be a uint32 in [1, ${u}], got ${e.minPrepeginDepth}`
|
|
28
|
-
), e.babeTotalInstances <= 0 && o.push(
|
|
29
|
-
`babeTotalInstances must be positive, got ${e.babeTotalInstances}`
|
|
30
|
-
), e.babeInstancesToFinalize <= 0 && o.push(
|
|
31
|
-
`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`
|
|
32
|
-
), e.babeInstancesToFinalize > e.babeTotalInstances && o.push(
|
|
33
|
-
`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`
|
|
34
|
-
), (e.minVpCommissionBps < 0 || e.minVpCommissionBps > d) && o.push(
|
|
35
|
-
`minVpCommissionBps must be in [0, ${d}], got ${e.minVpCommissionBps}`
|
|
36
|
-
), o.length > 0)
|
|
37
|
-
throw new Error(
|
|
38
|
-
`Invalid offchain protocol parameters: ${o.join("; ")}`
|
|
39
|
-
);
|
|
40
|
-
}
|
|
41
|
-
function F(e) {
|
|
42
|
-
const o = [];
|
|
43
|
-
if (e.minimumPegInAmount <= 0n && o.push(
|
|
44
|
-
`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`
|
|
45
|
-
), e.maxPegInAmount < e.minimumPegInAmount && o.push(
|
|
46
|
-
`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`
|
|
47
|
-
), e.pegInAckTimeout <= 0n && o.push(
|
|
48
|
-
`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`
|
|
49
|
-
), e.pegInActivationTimeout <= 0n && o.push(
|
|
50
|
-
`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`
|
|
51
|
-
), (!Number.isInteger(e.maxHtlcOutputCount) || e.maxHtlcOutputCount <= 0 || e.maxHtlcOutputCount > g) && o.push(
|
|
52
|
-
`maxHtlcOutputCount must be an integer in [1, ${g}], got ${e.maxHtlcOutputCount}`
|
|
53
|
-
), (typeof e.expiredPegInGraceBlocks != "bigint" || e.expiredPegInGraceBlocks <= 0n) && o.push(
|
|
54
|
-
`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`
|
|
55
|
-
), o.length > 0)
|
|
56
|
-
throw new Error(`Invalid TBV protocol parameters: ${o.join("; ")}`);
|
|
57
|
-
}
|
|
58
|
-
function H(e) {
|
|
59
|
-
if (F(e), E(e.offchainParams), !Number.isInteger(e.offchainParamsVersion) || e.offchainParamsVersion < 0 || e.offchainParamsVersion > u)
|
|
60
|
-
throw new Error(
|
|
61
|
-
`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
const p = 9999;
|
|
65
|
-
class M {
|
|
66
|
-
constructor(o, t) {
|
|
67
|
-
this.publicClient = o, this.contractAddress = t;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Read the VP's persistent x-only BTC pubkey from the on-chain
|
|
71
|
-
* registry. Validates length, hex form, and secp256k1 curve
|
|
72
|
-
* membership before minting the brand. Returns 64-char lowercase
|
|
73
|
-
* hex without the `0x` prefix.
|
|
74
|
-
*/
|
|
75
|
-
async getVaultProviderBtcPubKey(o) {
|
|
76
|
-
const r = (await this.publicClient.readContract({
|
|
77
|
-
address: this.contractAddress,
|
|
78
|
-
abi: s,
|
|
79
|
-
functionName: "getVaultProviderBTCKey",
|
|
80
|
-
args: [o]
|
|
81
|
-
})).toLowerCase();
|
|
82
|
-
if (!/^0x[0-9a-f]{64}$/.test(r))
|
|
83
|
-
throw new Error(
|
|
84
|
-
`getVaultProviderBTCKey returned an unexpected value (vp=${o}, length ${r.length}, prefix "${r.slice(0, 2)}")`
|
|
85
|
-
);
|
|
86
|
-
const i = r.slice(2);
|
|
87
|
-
if (!T.isXOnlyPoint(V(i)))
|
|
88
|
-
throw new Error(
|
|
89
|
-
`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${o})`
|
|
90
|
-
);
|
|
91
|
-
return i;
|
|
92
|
-
}
|
|
93
|
-
async getVaultBasicInfo(o) {
|
|
94
|
-
const t = await this.publicClient.readContract({
|
|
95
|
-
address: this.contractAddress,
|
|
96
|
-
abi: s,
|
|
97
|
-
functionName: "getBtcVaultBasicInfo",
|
|
98
|
-
args: [o]
|
|
99
|
-
});
|
|
100
|
-
return {
|
|
101
|
-
depositor: t.depositor,
|
|
102
|
-
depositorBtcPubKey: t.depositorBtcPubKey,
|
|
103
|
-
amount: t.amount,
|
|
104
|
-
vaultProvider: t.vaultProvider,
|
|
105
|
-
status: t.status,
|
|
106
|
-
applicationEntryPoint: t.applicationEntryPoint,
|
|
107
|
-
createdAt: t.createdAt
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
async getVaultProtocolInfo(o) {
|
|
111
|
-
const t = await this.publicClient.readContract({
|
|
112
|
-
address: this.contractAddress,
|
|
113
|
-
abi: s,
|
|
114
|
-
functionName: "getBtcVaultProtocolInfo",
|
|
115
|
-
args: [o]
|
|
116
|
-
}), r = Number(t.offchainParamsVersion);
|
|
117
|
-
return m(r), {
|
|
118
|
-
depositorSignedPeginTx: t.depositorSignedPeginTx,
|
|
119
|
-
universalChallengersVersion: t.universalChallengersVersion,
|
|
120
|
-
appVaultKeepersVersion: t.appVaultKeepersVersion,
|
|
121
|
-
offchainParamsVersion: r,
|
|
122
|
-
verifiedAt: t.verifiedAt,
|
|
123
|
-
depositorWotsPkHash: t.depositorWotsPkHash,
|
|
124
|
-
hashlock: t.hashlock,
|
|
125
|
-
htlcVout: t.htlcVout,
|
|
126
|
-
depositorPopSignature: t.depositorPopSignature,
|
|
127
|
-
prePeginTxHash: t.prePeginTxHash,
|
|
128
|
-
vaultProviderCommissionBps: t.vaultProviderCommissionBps,
|
|
129
|
-
claimExpiredUntil: t.claimExpiredUntil,
|
|
130
|
-
vaultCoreVersion: t.vaultCoreVersion
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
async getProtocolInfoBatch(o) {
|
|
134
|
-
return o.length === 0 ? [] : (await this.publicClient.multicall({
|
|
135
|
-
contracts: o.map((r) => ({
|
|
136
|
-
address: this.contractAddress,
|
|
137
|
-
abi: s,
|
|
138
|
-
functionName: "getBtcVaultProtocolInfo",
|
|
139
|
-
args: [r]
|
|
140
|
-
})),
|
|
141
|
-
allowFailure: !1
|
|
142
|
-
})).map((r, i) => {
|
|
143
|
-
const n = r;
|
|
144
|
-
if (!n.depositorSignedPeginTx || n.depositorSignedPeginTx === "0x")
|
|
145
|
-
throw new Error(
|
|
146
|
-
`Vault ${o[i]} not found on-chain or has no pegin transaction`
|
|
147
|
-
);
|
|
148
|
-
const a = Number(n.offchainParamsVersion);
|
|
149
|
-
return m(a), {
|
|
150
|
-
depositorSignedPeginTx: n.depositorSignedPeginTx,
|
|
151
|
-
universalChallengersVersion: n.universalChallengersVersion,
|
|
152
|
-
appVaultKeepersVersion: n.appVaultKeepersVersion,
|
|
153
|
-
offchainParamsVersion: a,
|
|
154
|
-
verifiedAt: n.verifiedAt,
|
|
155
|
-
depositorWotsPkHash: n.depositorWotsPkHash,
|
|
156
|
-
hashlock: n.hashlock,
|
|
157
|
-
htlcVout: n.htlcVout,
|
|
158
|
-
depositorPopSignature: n.depositorPopSignature,
|
|
159
|
-
prePeginTxHash: n.prePeginTxHash,
|
|
160
|
-
vaultProviderCommissionBps: n.vaultProviderCommissionBps,
|
|
161
|
-
claimExpiredUntil: n.claimExpiredUntil,
|
|
162
|
-
vaultCoreVersion: n.vaultCoreVersion
|
|
163
|
-
};
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Read the protocol pegin fee (in wei) for a given vault provider.
|
|
168
|
-
* Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.
|
|
169
|
-
*/
|
|
170
|
-
async getPegInFee(o) {
|
|
171
|
-
return await this.publicClient.readContract({
|
|
172
|
-
address: this.contractAddress,
|
|
173
|
-
abi: s,
|
|
174
|
-
functionName: "getPegInFee",
|
|
175
|
-
args: [o]
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* Read a vault provider's current commission in basis points from
|
|
180
|
-
* BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the
|
|
181
|
-
* legitimate range is `[0, 9999]`; anything outside indicates a wrong
|
|
182
|
-
* contract address or ABI drift and is surfaced as an error rather than
|
|
183
|
-
* trusted.
|
|
184
|
-
*/
|
|
185
|
-
async getVaultProviderCommission(o) {
|
|
186
|
-
const t = await this.publicClient.readContract({
|
|
187
|
-
address: this.contractAddress,
|
|
188
|
-
abi: s,
|
|
189
|
-
functionName: "getVaultProviderCommission",
|
|
190
|
-
args: [o]
|
|
191
|
-
});
|
|
192
|
-
if (!Number.isInteger(t) || t < 0 || t > p)
|
|
193
|
-
throw new Error(
|
|
194
|
-
`getVaultProviderCommission returned ${t} bps for ${o}, outside the protocol range [0, ${p}]`
|
|
195
|
-
);
|
|
196
|
-
return t;
|
|
197
|
-
}
|
|
198
|
-
async getVaultData(o) {
|
|
199
|
-
const [t, r] = await Promise.all([
|
|
200
|
-
this.getVaultBasicInfo(o),
|
|
201
|
-
this.getVaultProtocolInfo(o)
|
|
202
|
-
]);
|
|
203
|
-
if (!r.depositorSignedPeginTx || r.depositorSignedPeginTx === "0x")
|
|
204
|
-
throw new Error(
|
|
205
|
-
`Vault ${o} not found on-chain or has no pegin transaction`
|
|
206
|
-
);
|
|
207
|
-
return { basic: t, protocol: r };
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Read `offchainParamsVersion` for many vaults in a single multicall.
|
|
211
|
-
* Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault
|
|
212
|
-
* batch costs one RPC round-trip instead of 2N parallel `eth_call`s.
|
|
213
|
-
*/
|
|
214
|
-
async getOffchainParamsVersionsByVaultIds(o) {
|
|
215
|
-
return o.length === 0 ? [] : (await this.publicClient.multicall({
|
|
216
|
-
contracts: o.map((r) => ({
|
|
217
|
-
address: this.contractAddress,
|
|
218
|
-
abi: s,
|
|
219
|
-
functionName: "getBtcVaultProtocolInfo",
|
|
220
|
-
args: [r]
|
|
221
|
-
})),
|
|
222
|
-
allowFailure: !1
|
|
223
|
-
})).map((r) => {
|
|
224
|
-
const i = r;
|
|
225
|
-
if (!i.depositorSignedPeginTx || i.depositorSignedPeginTx === "0x")
|
|
226
|
-
throw new Error(
|
|
227
|
-
"Vault not found on-chain or has no pegin transaction while reading offchain params version"
|
|
228
|
-
);
|
|
229
|
-
const n = Number(i.offchainParamsVersion);
|
|
230
|
-
return m(n), n;
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
const B = 21e6 * 1e8, w = 3e4;
|
|
235
|
-
async function l(e, o) {
|
|
236
|
-
const t = new AbortController(), r = setTimeout(
|
|
237
|
-
() => t.abort(),
|
|
238
|
-
w
|
|
239
|
-
), i = [t.signal, o == null ? void 0 : o.signal].filter(
|
|
240
|
-
Boolean
|
|
241
|
-
);
|
|
242
|
-
try {
|
|
243
|
-
return await fetch(e, {
|
|
244
|
-
...o,
|
|
245
|
-
signal: AbortSignal.any(i)
|
|
246
|
-
});
|
|
247
|
-
} catch (n) {
|
|
248
|
-
throw clearTimeout(r), n != null && typeof n == "object" && "name" in n && n.name === "AbortError" ? new Error(
|
|
249
|
-
`Mempool API request timed out after ${w}ms: ${e}`
|
|
250
|
-
) : n;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
const P = 1e4;
|
|
254
|
-
function b(e) {
|
|
255
|
-
return Number.isInteger(e) && e > 0 && e <= B;
|
|
256
|
-
}
|
|
257
|
-
function k(e) {
|
|
258
|
-
return Number.isInteger(e) && e > 0 && e <= P;
|
|
259
|
-
}
|
|
260
|
-
function $(e, o) {
|
|
261
|
-
return !Number.isInteger(e) || e < 0 ? !1 : o === void 0 || e < o;
|
|
262
|
-
}
|
|
263
|
-
function f(e) {
|
|
264
|
-
if (!C.test(e))
|
|
265
|
-
throw new Error(`Invalid transaction ID format: ${e}`);
|
|
266
|
-
}
|
|
267
|
-
function I(e) {
|
|
268
|
-
if (!x.test(e))
|
|
269
|
-
throw new Error(`Invalid Bitcoin address format: ${e}`);
|
|
270
|
-
}
|
|
271
|
-
function v(e, o) {
|
|
272
|
-
if (!y.test(e))
|
|
273
|
-
throw new Error(
|
|
274
|
-
`Invalid scriptPubKey: not valid hex for ${o}`
|
|
275
|
-
);
|
|
276
|
-
if (!A.some(
|
|
277
|
-
(r) => e.toLowerCase().startsWith(r)
|
|
278
|
-
))
|
|
279
|
-
throw new Error(
|
|
280
|
-
`Unrecognized scriptPubKey type for ${o}: prefix ${e.slice(0, 6)} does not match any known Bitcoin script type`
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
const S = {
|
|
284
|
-
mainnet: "https://mempool.space/api",
|
|
285
|
-
testnet: "https://mempool.space/testnet/api",
|
|
286
|
-
signet: "https://mempool.space/signet/api"
|
|
287
|
-
};
|
|
288
|
-
async function c(e, o) {
|
|
289
|
-
try {
|
|
290
|
-
const t = await l(e, o);
|
|
291
|
-
if (!t.ok) {
|
|
292
|
-
const i = await t.text();
|
|
293
|
-
throw new Error(
|
|
294
|
-
`Mempool API error (${t.status}): ${i || t.statusText}`
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
const r = t.headers.get("content-type");
|
|
298
|
-
return r != null && r.includes("application/json") ? await t.json() : await t.text();
|
|
299
|
-
} catch (t) {
|
|
300
|
-
throw t instanceof Error ? new Error(`Failed to fetch from mempool API: ${t.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
async function R(e, o) {
|
|
304
|
-
try {
|
|
305
|
-
const t = await l(`${o}/tx`, {
|
|
306
|
-
method: "POST",
|
|
307
|
-
body: e,
|
|
308
|
-
headers: {
|
|
309
|
-
"Content-Type": "text/plain"
|
|
310
|
-
}
|
|
311
|
-
});
|
|
312
|
-
if (!t.ok) {
|
|
313
|
-
const i = await t.text();
|
|
314
|
-
let n;
|
|
315
|
-
try {
|
|
316
|
-
n = JSON.parse(i).message;
|
|
317
|
-
} catch {
|
|
318
|
-
n = i;
|
|
319
|
-
}
|
|
320
|
-
throw new Error(
|
|
321
|
-
n || `Failed to broadcast transaction: ${t.statusText}`
|
|
322
|
-
);
|
|
323
|
-
}
|
|
324
|
-
return await t.text();
|
|
325
|
-
} catch (t) {
|
|
326
|
-
throw t instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${t.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
async function N(e, o) {
|
|
330
|
-
return f(e), c(`${o}/tx/${e}`);
|
|
331
|
-
}
|
|
332
|
-
async function _(e) {
|
|
333
|
-
const o = await c(`${e}/blocks/tip/height`), t = o.trim();
|
|
334
|
-
if (!/^\d+$/.test(t))
|
|
335
|
-
throw new Error(
|
|
336
|
-
`Mempool API returned an invalid block tip height: "${o}"`
|
|
337
|
-
);
|
|
338
|
-
return Number.parseInt(t, 10);
|
|
339
|
-
}
|
|
340
|
-
async function X(e, o) {
|
|
341
|
-
f(e);
|
|
342
|
-
try {
|
|
343
|
-
const t = await l(`${o}/tx/${e}/hex`);
|
|
344
|
-
if (!t.ok) {
|
|
345
|
-
const r = await t.text();
|
|
346
|
-
throw new Error(
|
|
347
|
-
`Mempool API error (${t.status}): ${r || t.statusText}`
|
|
348
|
-
);
|
|
349
|
-
}
|
|
350
|
-
return await t.text();
|
|
351
|
-
} catch (t) {
|
|
352
|
-
throw t instanceof Error ? new Error(`Failed to get transaction hex for ${e}: ${t.message}`) : new Error(`Failed to get transaction hex for ${e}: Unknown error`);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
async function D(e, o, t) {
|
|
356
|
-
f(e);
|
|
357
|
-
const r = await N(e, t);
|
|
358
|
-
if (!$(o, r.vout.length))
|
|
359
|
-
throw new Error(
|
|
360
|
-
`Invalid vout ${o} for transaction ${e} (has ${r.vout.length} outputs)`
|
|
361
|
-
);
|
|
362
|
-
const i = r.vout[o];
|
|
363
|
-
if (!b(i.value))
|
|
364
|
-
throw new Error(`Invalid UTXO value ${i.value} for ${e}:${o}`);
|
|
365
|
-
return v(i.scriptpubkey, `${e}:${o}`), {
|
|
366
|
-
txid: e,
|
|
367
|
-
vout: o,
|
|
368
|
-
value: i.value,
|
|
369
|
-
scriptPubKey: i.scriptpubkey
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
async function j(e, o) {
|
|
373
|
-
I(e);
|
|
374
|
-
try {
|
|
375
|
-
const t = await c(`${o}/address/${e}/utxo`), r = await c(`${o}/v1/validate-address/${e}`);
|
|
376
|
-
if (!r.isvalid)
|
|
377
|
-
throw new Error(
|
|
378
|
-
`Invalid Bitcoin address: ${e}. Mempool API validation failed.`
|
|
379
|
-
);
|
|
380
|
-
v(r.scriptPubKey, e);
|
|
381
|
-
for (const n of t) {
|
|
382
|
-
if (f(n.txid), !$(n.vout))
|
|
383
|
-
throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);
|
|
384
|
-
if (!b(n.value))
|
|
385
|
-
throw new Error(
|
|
386
|
-
`Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`
|
|
387
|
-
);
|
|
388
|
-
}
|
|
389
|
-
return t.sort((n, a) => a.value - n.value).map((n) => ({
|
|
390
|
-
txid: n.txid,
|
|
391
|
-
vout: n.vout,
|
|
392
|
-
value: n.value,
|
|
393
|
-
scriptPubKey: r.scriptPubKey,
|
|
394
|
-
confirmed: n.status.confirmed
|
|
395
|
-
}));
|
|
396
|
-
} catch (t) {
|
|
397
|
-
throw t instanceof Error ? new Error(
|
|
398
|
-
`Failed to get UTXOs for address ${e}: ${t.message}`
|
|
399
|
-
) : new Error(
|
|
400
|
-
`Failed to get UTXOs for address ${e}: Unknown error`
|
|
401
|
-
);
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
function z(e) {
|
|
405
|
-
return S[e];
|
|
406
|
-
}
|
|
407
|
-
async function Q(e, o) {
|
|
408
|
-
return I(e), c(`${o}/address/${e}/txs`);
|
|
409
|
-
}
|
|
410
|
-
async function W(e) {
|
|
411
|
-
const o = await l(`${e}/v1/fees/recommended`);
|
|
412
|
-
if (!o.ok)
|
|
413
|
-
throw new Error(
|
|
414
|
-
`Failed to fetch network fees: ${o.status} ${o.statusText}`
|
|
415
|
-
);
|
|
416
|
-
const t = await o.json(), r = [
|
|
417
|
-
"fastestFee",
|
|
418
|
-
"halfHourFee",
|
|
419
|
-
"hourFee",
|
|
420
|
-
"economyFee",
|
|
421
|
-
"minimumFee"
|
|
422
|
-
];
|
|
423
|
-
for (const i of r)
|
|
424
|
-
if (!k(t[i]))
|
|
425
|
-
throw new Error(
|
|
426
|
-
`Invalid fee rate ${i}=${t[i]} from mempool API: expected a positive number ≤ ${P}`
|
|
427
|
-
);
|
|
428
|
-
if (t.minimumFee > t.economyFee || t.economyFee > t.hourFee || t.hourFee > t.halfHourFee || t.halfHourFee > t.fastestFee)
|
|
429
|
-
throw new Error(
|
|
430
|
-
`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`
|
|
431
|
-
);
|
|
432
|
-
return t;
|
|
433
|
-
}
|
|
434
|
-
export {
|
|
435
|
-
S as M,
|
|
436
|
-
M as V,
|
|
437
|
-
j as a,
|
|
438
|
-
z as b,
|
|
439
|
-
W as c,
|
|
440
|
-
_ as d,
|
|
441
|
-
X as e,
|
|
442
|
-
N as f,
|
|
443
|
-
Q as g,
|
|
444
|
-
D as h,
|
|
445
|
-
H as i,
|
|
446
|
-
F as j,
|
|
447
|
-
m as k,
|
|
448
|
-
R as p,
|
|
449
|
-
E as v
|
|
450
|
-
};
|
|
451
|
-
//# sourceMappingURL=mempoolApi-DI9HISqi.js.map
|