@babylonlabs-io/ts-sdk 0.62.0 → 0.62.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PeginManager-BLBB_vMl.cjs → PeginManager-BgBt4hqp.cjs} +2 -2
- package/dist/{PeginManager-BLBB_vMl.cjs.map → PeginManager-BgBt4hqp.cjs.map} +1 -1
- package/dist/{PeginManager-Dj6_tWRA.js → PeginManager-C8kIl0gw.js} +2 -2
- package/dist/{PeginManager-Dj6_tWRA.js.map → PeginManager-C8kIl0gw.js.map} +1 -1
- package/dist/{batchPoll-C3eKPYOC.js → batchPoll-9w-Gv5dt.js} +2 -2
- package/dist/batchPoll-9w-Gv5dt.js.map +1 -0
- package/dist/{batchPoll-CbbCcNZP.cjs → batchPoll-WMXweT_O.cjs} +2 -2
- package/dist/batchPoll-WMXweT_O.cjs.map +1 -0
- package/dist/{errors-lMX8Q6zb.js → errors-BxL9QObN.js} +2 -2
- package/dist/{errors-lMX8Q6zb.js.map → errors-BxL9QObN.js.map} +1 -1
- package/dist/{errors-D2zp7Vzk.cjs → errors-DwjbI9h1.cjs} +2 -2
- package/dist/{errors-D2zp7Vzk.cjs.map → errors-DwjbI9h1.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/{mempoolApi-DC7pID6B.js → mempoolApi-BXaOZL_I.js} +29 -53
- package/dist/mempoolApi-BXaOZL_I.js.map +1 -0
- package/dist/mempoolApi-Bsurcl43.cjs +2 -0
- package/dist/mempoolApi-Bsurcl43.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/types.d.ts +0 -6
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +0 -6
- 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/index.cjs +1 -1
- package/dist/tbv/core/index.js +4 -4
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +4 -4
- package/package.json +1 -1
- package/dist/batchPoll-C3eKPYOC.js.map +0 -1
- package/dist/batchPoll-CbbCcNZP.cjs.map +0 -1
- package/dist/mempoolApi-BxhMqJ4f.cjs +0 -2
- package/dist/mempoolApi-BxhMqJ4f.cjs.map +0 -1
- package/dist/mempoolApi-DC7pID6B.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-D2zp7Vzk.cjs","sources":["../src/tbv/core/deposit-terms/depositTermsErrors.ts","../src/tbv/core/deposit-terms/rebuildDepositTermsCore.ts","../src/tbv/core/wots/errors.ts"],"sourcesContent":["/**\n * Typed rejection contract for deposit-terms approval. Providers cannot import\n * this class (no dependency edge between the packages), so the cross-package\n * contract is the error SHAPE on {@link DepositTermsApprover}. Consumers land\n * with the first provider (#2109) and its app error mapping (#2110).\n *\n * @module deposit-terms/depositTermsErrors\n */\n\n/** The `name` value providers must set on envelope rejections (the wire contract). */\nexport const DEPOSIT_TERMS_REJECTED_ERROR_NAME = \"DepositTermsRejectedError\";\n\n/** Why the terms were rejected before approval. */\nexport type DepositTermsRejectionReason = \"device-envelope\";\n\n/** SDK-owned typed rejection thrown when deposit terms fail pre-approval validation. */\nexport class DepositTermsRejectedError extends Error {\n readonly reason: DepositTermsRejectionReason;\n\n constructor(\n message: string,\n reason: DepositTermsRejectionReason = \"device-envelope\",\n ) {\n super(message);\n this.name = DEPOSIT_TERMS_REJECTED_ERROR_NAME;\n this.reason = reason;\n }\n}\n\n/**\n * Guard for app-side error mapping. Matches `instanceof` OR the documented\n * `name` — providers and foreign realms throw structurally-conforming plain\n * errors that `instanceof` cannot see.\n */\nexport function isDepositTermsRejectedError(\n err: unknown,\n): err is DepositTermsRejectedError {\n if (err instanceof DepositTermsRejectedError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n const shaped = err as { name?: unknown; reason?: unknown };\n // The documented provider shape REQUIRES the reason; a name-only match is\n // a contract violation and propagates unnormalized.\n return (\n shaped.name === DEPOSIT_TERMS_REJECTED_ERROR_NAME &&\n shaped.reason === \"device-envelope\"\n );\n}\n","/**\n * Pure core of the resume-broadcast DepositTerms rebuild (#2220 Part 2).\n *\n * Takes plain chain-derived data (the app orchestrator does the chain reads +\n * sibling discovery) and: (1) asserts sibling completeness against the funded\n * tx's auth-anchor OP_RETURN, (2) recomputes the amount-independent sizing\n * (depositorClaimValue, peginMaxFee, anchor) via WASM, (3) byte-matches each\n * HTLC output's value + scriptPubKey against the funded tx (Gate 1), then (4)\n * projects into DepositTerms. No chain access, no browser state — unit-testable.\n *\n * btc-vault is the protocol source of truth (`compute_min_htlc_value`,\n * `derive_challengers_for`).\n */\n\nimport {\n computeMinClaimValue,\n computeMinPeginFee,\n getPrePeginHtlcConnectorInfo,\n peginP2aAnchorOutput,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport { findAuthAnchorOpReturn } from \"../managers/pegin/assertAuthAnchorOpReturn\";\nimport { assertEncodedHtlcOutputsMatch } from \"../primitives/psbt/assertWasmPeginSizing\";\nimport { stripHexPrefix } from \"../primitives/utils/bitcoin\";\nimport { MAX_REASONABLE_PEGIN_VBYTES } from \"../utils/fee/constants\";\nimport { calculateBtcTxHash } from \"../utils/transaction/btcTxHash\";\n\nimport { buildDepositTerms } from \"./buildDepositTerms\";\nimport type { DepositTerms } from \"./depositTerms\";\n\n/** One HTLC in the shared Pre-PegIn tx, ordered by (and contiguous in) htlcVout. */\nexport interface RebuildSibling {\n /** 32-byte hex hashlock (0x prefix optional), per-vault (feeds the HTLC scriptPubKey). */\n hashlock: string;\n /** btc-vault `pegin_amount` for this sibling (satoshis). */\n amount: bigint;\n}\n\nexport interface RebuildDepositTermsCoreInput {\n /** Stamped tx-graph version (NOT chain-active). */\n vaultCoreVersion: number;\n /** Sibling HTLCs ordered by htlcVout; index === htlcVout (asserted by the app). */\n siblings: readonly RebuildSibling[];\n /** Funded Pre-PegIn tx hex. Gate 0 (hash vs prepeginTxid) is SELF-verified below — callers need not pre-verify. */\n fundedPrePeginTxHex: string;\n\n // Stamped-version participant data (already resolved + sorted by the app).\n depositorBtcPubkey: string;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n\n // Version-locked scalars.\n protocolFeeRate: bigint;\n minPeginFeeRate: bigint;\n councilQuorum: number;\n councilSize: number;\n timelockPegin: number;\n timelockAssert: number;\n timelockRefund: number;\n\n // Pass-through into DepositTerms.\n prepeginTxid: string;\n /** Funded-tx fee (Σin − Σout), computed by the app; the device's `prepegin_max_fee` bound. */\n prepeginMaxFee: bigint;\n maxAcceptableCommissionBps: number;\n\n /** WASM network descriptor for scriptPubKey derivation. */\n network: Parameters<typeof getPrePeginHtlcConnectorInfo>[0][\"network\"];\n}\n\nexport async function rebuildDepositTermsCore(\n input: RebuildDepositTermsCoreInput,\n): Promise<DepositTerms> {\n const siblingCount = input.siblings.length;\n if (siblingCount === 0) {\n throw new Error(\n \"rebuildDepositTermsCore: at least one sibling is required\",\n );\n }\n for (const [i, sibling] of input.siblings.entries()) {\n if (sibling.amount <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: sibling[${i}] has non-positive on-chain pegin ` +\n `amount ${sibling.amount}; the chain-read vault record is invalid. Resume refused.`,\n );\n }\n }\n if (input.prepeginMaxFee <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${input.prepeginMaxFee}`,\n );\n }\n\n // Gate 0, self-verified: everything below trusts these bytes, and a\n // substituted tx replicating the HTLC outputs would pass Gate 1 with a\n // different fee/txid.\n const expectedTxid = stripHexPrefix(input.prepeginTxid).toLowerCase();\n const actualTxid = stripHexPrefix(\n calculateBtcTxHash(input.fundedPrePeginTxHex),\n ).toLowerCase();\n if (actualTxid !== expectedTxid) {\n throw new Error(\n `Funded Pre-PegIn tx hashes to ${actualTxid}, expected ${expectedTxid} ` +\n `(on-chain prepeginTxid). Resume refused.`,\n );\n }\n\n // Completeness anchor: the single auth-anchor OP_RETURN sits at vout === HTLC\n // count — the only guard against an indexer-lagged partial sibling set.\n const found = findAuthAnchorOpReturn(\n stripHexPrefix(input.fundedPrePeginTxHex),\n );\n if (found === undefined) {\n throw new Error(\n `Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN ` +\n `commitment — it either predates auth anchoring or is malformed. The ` +\n `intent resume path requires the anchor to prove sibling completeness. ` +\n `Resume refused.`,\n );\n }\n if (found.vout !== siblingCount) {\n throw new Error(\n `Auth-anchor OP_RETURN at vout ${found.vout} does not match the ` +\n `discovered sibling count ${siblingCount}; the discovered sibling set ` +\n `does not cover this transaction's HTLC outputs (a lagging index can ` +\n `cause this — retry later). Resume refused.`,\n );\n }\n\n // Amount-independent sizing. Depositor-as-claimer: numLocalChallengers ===\n // numVks (VP excluded) — btc-vault graph.rs derive_challengers_for.\n const numVks = input.vaultKeeperBtcPubkeys.length;\n const numUcs = input.universalChallengerBtcPubkeys.length;\n const depositorClaimValue = await computeMinClaimValue(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.councilQuorum,\n input.councilSize,\n input.protocolFeeRate,\n );\n const peginMaxFee = await computeMinPeginFee(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.minPeginFeeRate,\n );\n const anchor = await peginP2aAnchorOutput(input.vaultCoreVersion);\n const anchorValue = anchor?.value ?? 0n;\n\n // Independent bounds on the WASM outputs (mirrors assertWasmPeginSizing):\n // Gate 1 only proves the DCV+fee+anchor SUM — these constrain the\n // decomposition the device is shown.\n if (depositorClaimValue <= 0n) {\n throw new Error(\n `WASM returned non-positive depositorClaimValue ${depositorClaimValue}; ` +\n `expected > 0. Resume refused.`,\n );\n }\n if (peginMaxFee <= 0n) {\n throw new Error(\n `WASM returned non-positive peginMaxFee ${peginMaxFee}; expected > 0. ` +\n `Resume refused.`,\n );\n }\n // Explicit anchor check: the sum bound alone would let a negative anchor\n // offset an inflated peginMaxFee (kept local, not inherited from the facade).\n if (anchorValue < 0n) {\n throw new Error(\n `WASM returned negative P2A anchor value ${anchorValue}. Resume refused.`,\n );\n }\n const impliedReserve = peginMaxFee + anchorValue;\n const maxImpliedReserve = input.minPeginFeeRate * MAX_REASONABLE_PEGIN_VBYTES;\n if (impliedReserve <= 0n || impliedReserve > maxImpliedReserve) {\n throw new Error(\n `WASM implied PegIn reserve ${impliedReserve} sat is outside ` +\n `(0, ${maxImpliedReserve}] (minPeginFeeRate=${input.minPeginFeeRate} × ` +\n `${MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`,\n );\n }\n\n // Gate 1: per sibling, value = amount + DCV + peginMaxFee + anchor (btc-vault\n // compute_min_htlc_value) + scriptPubKey from the on-chain hashlock,\n // byte-matched against outputs 0..N-1.\n const expectedHtlcValues = input.siblings.map(\n (s) => s.amount + depositorClaimValue + peginMaxFee + anchorValue,\n );\n const expectedHtlcScriptPubKeys = await Promise.all(\n input.siblings.map(async (s) => {\n const connector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: input.vaultCoreVersion,\n depositorPubkey: input.depositorBtcPubkey,\n vaultProviderPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperPubkeys: [...input.vaultKeeperBtcPubkeys],\n universalChallengerPubkeys: [...input.universalChallengerBtcPubkeys],\n hashlock: stripHexPrefix(s.hashlock),\n timelockRefund: input.timelockRefund,\n network: input.network,\n });\n return connector.scriptPubKey;\n }),\n );\n const fundedOutputs = Transaction.fromHex(\n stripHexPrefix(input.fundedPrePeginTxHex),\n ).outs.map((o) => ({ value: o.value, script: o.script }));\n assertEncodedHtlcOutputsMatch(\n fundedOutputs,\n expectedHtlcValues,\n expectedHtlcScriptPubKeys,\n );\n\n return buildDepositTerms({\n vaultCoreVersion: input.vaultCoreVersion,\n protocolFeeRate: input.protocolFeeRate,\n timelockPegin: input.timelockPegin,\n timelockAssert: input.timelockAssert,\n timelockRefund: input.timelockRefund,\n prepeginTxid: input.prepeginTxid,\n prepeginMaxFee: input.prepeginMaxFee,\n vaultProviderBtcPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: input.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: input.universalChallengerBtcPubkeys,\n maxAcceptableCommissionBps: input.maxAcceptableCommissionBps,\n peginAmounts: input.siblings.map((s) => s.amount),\n depositorClaimValue,\n peginMaxFee,\n });\n}\n","/**\n * Check whether an error from the vault provider indicates that the\n * submitted WOTS public key hash does not match the on-chain\n * commitment. This signals that the wrong wallet is connected (its\n * `deriveContextHash` produces a different vault root and therefore\n * different WOTS keys).\n */\nexport function isWotsMismatchError(error: unknown): boolean {\n const msg = (\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\"\n ).toLowerCase();\n\n return (\n msg.includes(\"wots\") &&\n msg.includes(\"hash\") &&\n msg.includes(\"does not match\")\n );\n}\n"],"names":["DEPOSIT_TERMS_REJECTED_ERROR_NAME","DepositTermsRejectedError","message","reason","__publicField","isDepositTermsRejectedError","err","shaped","rebuildDepositTermsCore","input","siblingCount","i","sibling","expectedTxid","stripHexPrefix","actualTxid","calculateBtcTxHash","found","findAuthAnchorOpReturn","numVks","numUcs","depositorClaimValue","computeMinClaimValue","peginMaxFee","computeMinPeginFee","anchor","peginP2aAnchorOutput","anchorValue","impliedReserve","maxImpliedReserve","MAX_REASONABLE_PEGIN_VBYTES","expectedHtlcValues","expectedHtlcScriptPubKeys","getPrePeginHtlcConnectorInfo","fundedOutputs","Transaction","o","assertEncodedHtlcOutputsMatch","buildDepositTerms","isWotsMismatchError","error","msg"],"mappings":"kjBAUaA,EAAoC,4BAM1C,MAAMC,UAAkC,KAAM,CAGnD,YACEC,EACAC,EAAsC,kBACtC,CACA,MAAMD,CAAO,EANNE,EAAA,e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gBA,EAAM,eACtB,eAAgBA,EAAM,eACtB,aAAcA,EAAM,aACpB,eAAgBA,EAAM,eACtB,uBAAwBA,EAAM,uBAC9B,sBAAuBA,EAAM,sBAC7B,8BAA+BA,EAAM,8BACrC,2BAA4BA,EAAM,2BAClC,aAAcA,EAAM,SAAS,IAAK,GAAM,EAAE,MAAM,EAChD,oBAAAY,EACA,YAAAE,CAAA,CACD,CACH,CC/NO,SAASgB,EAAoBC,EAAyB,CAC3D,MAAMC,GACJD,aAAiB,MACbA,EAAM,QACN,OAAOA,GAAU,SACfA,EACA,IACN,YAAA,EAEF,OACEC,EAAI,SAAS,MAAM,GACnBA,EAAI,SAAS,MAAM,GACnBA,EAAI,SAAS,gBAAgB,CAEjC"}
|
|
1
|
+
{"version":3,"file":"errors-DwjbI9h1.cjs","sources":["../src/tbv/core/deposit-terms/depositTermsErrors.ts","../src/tbv/core/deposit-terms/rebuildDepositTermsCore.ts","../src/tbv/core/wots/errors.ts"],"sourcesContent":["/**\n * Typed rejection contract for deposit-terms approval. Providers cannot import\n * this class (no dependency edge between the packages), so the cross-package\n * contract is the error SHAPE on {@link DepositTermsApprover}. Consumers land\n * with the first provider (#2109) and its app error mapping (#2110).\n *\n * @module deposit-terms/depositTermsErrors\n */\n\n/** The `name` value providers must set on envelope rejections (the wire contract). */\nexport const DEPOSIT_TERMS_REJECTED_ERROR_NAME = \"DepositTermsRejectedError\";\n\n/** Why the terms were rejected before approval. */\nexport type DepositTermsRejectionReason = \"device-envelope\";\n\n/** SDK-owned typed rejection thrown when deposit terms fail pre-approval validation. */\nexport class DepositTermsRejectedError extends Error {\n readonly reason: DepositTermsRejectionReason;\n\n constructor(\n message: string,\n reason: DepositTermsRejectionReason = \"device-envelope\",\n ) {\n super(message);\n this.name = DEPOSIT_TERMS_REJECTED_ERROR_NAME;\n this.reason = reason;\n }\n}\n\n/**\n * Guard for app-side error mapping. Matches `instanceof` OR the documented\n * `name` — providers and foreign realms throw structurally-conforming plain\n * errors that `instanceof` cannot see.\n */\nexport function isDepositTermsRejectedError(\n err: unknown,\n): err is DepositTermsRejectedError {\n if (err instanceof DepositTermsRejectedError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n const shaped = err as { name?: unknown; reason?: unknown };\n // The documented provider shape REQUIRES the reason; a name-only match is\n // a contract violation and propagates unnormalized.\n return (\n shaped.name === DEPOSIT_TERMS_REJECTED_ERROR_NAME &&\n shaped.reason === \"device-envelope\"\n );\n}\n","/**\n * Pure core of the resume-broadcast DepositTerms rebuild (#2220 Part 2).\n *\n * Takes plain chain-derived data (the app orchestrator does the chain reads +\n * sibling discovery) and: (1) asserts sibling completeness against the funded\n * tx's auth-anchor OP_RETURN, (2) recomputes the amount-independent sizing\n * (depositorClaimValue, peginMaxFee, anchor) via WASM, (3) byte-matches each\n * HTLC output's value + scriptPubKey against the funded tx (Gate 1), then (4)\n * projects into DepositTerms. No chain access, no browser state — unit-testable.\n *\n * btc-vault is the protocol source of truth (`compute_min_htlc_value`,\n * `derive_challengers_for`).\n */\n\nimport {\n computeMinClaimValue,\n computeMinPeginFee,\n getPrePeginHtlcConnectorInfo,\n peginP2aAnchorOutput,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Transaction } from \"bitcoinjs-lib\";\n\nimport { findAuthAnchorOpReturn } from \"../managers/pegin/assertAuthAnchorOpReturn\";\nimport { assertEncodedHtlcOutputsMatch } from \"../primitives/psbt/assertWasmPeginSizing\";\nimport { stripHexPrefix } from \"../primitives/utils/bitcoin\";\nimport { MAX_REASONABLE_PEGIN_VBYTES } from \"../utils/fee/constants\";\nimport { calculateBtcTxHash } from \"../utils/transaction/btcTxHash\";\n\nimport { buildDepositTerms } from \"./buildDepositTerms\";\nimport type { DepositTerms } from \"./depositTerms\";\n\n/** One HTLC in the shared Pre-PegIn tx, ordered by (and contiguous in) htlcVout. */\nexport interface RebuildSibling {\n /** 32-byte hex hashlock (0x prefix optional), per-vault (feeds the HTLC scriptPubKey). */\n hashlock: string;\n /** btc-vault `pegin_amount` for this sibling (satoshis). */\n amount: bigint;\n}\n\nexport interface RebuildDepositTermsCoreInput {\n /** Stamped tx-graph version (NOT chain-active). */\n vaultCoreVersion: number;\n /** Sibling HTLCs ordered by htlcVout; index === htlcVout (asserted by the app). */\n siblings: readonly RebuildSibling[];\n /** Funded Pre-PegIn tx hex. Gate 0 (hash vs prepeginTxid) is SELF-verified below — callers need not pre-verify. */\n fundedPrePeginTxHex: string;\n\n // Stamped-version participant data (already resolved + sorted by the app).\n depositorBtcPubkey: string;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n\n // Version-locked scalars.\n protocolFeeRate: bigint;\n minPeginFeeRate: bigint;\n councilQuorum: number;\n councilSize: number;\n timelockPegin: number;\n timelockAssert: number;\n timelockRefund: number;\n\n // Pass-through into DepositTerms.\n prepeginTxid: string;\n /** Funded-tx fee (Σin − Σout), computed by the app; the device's `prepegin_max_fee` bound. */\n prepeginMaxFee: bigint;\n maxAcceptableCommissionBps: number;\n\n /** WASM network descriptor for scriptPubKey derivation. */\n network: Parameters<typeof getPrePeginHtlcConnectorInfo>[0][\"network\"];\n}\n\nexport async function rebuildDepositTermsCore(\n input: RebuildDepositTermsCoreInput,\n): Promise<DepositTerms> {\n const siblingCount = input.siblings.length;\n if (siblingCount === 0) {\n throw new Error(\n \"rebuildDepositTermsCore: at least one sibling is required\",\n );\n }\n for (const [i, sibling] of input.siblings.entries()) {\n if (sibling.amount <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: sibling[${i}] has non-positive on-chain pegin ` +\n `amount ${sibling.amount}; the chain-read vault record is invalid. Resume refused.`,\n );\n }\n }\n if (input.prepeginMaxFee <= 0n) {\n throw new Error(\n `rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${input.prepeginMaxFee}`,\n );\n }\n\n // Gate 0, self-verified: everything below trusts these bytes, and a\n // substituted tx replicating the HTLC outputs would pass Gate 1 with a\n // different fee/txid.\n const expectedTxid = stripHexPrefix(input.prepeginTxid).toLowerCase();\n const actualTxid = stripHexPrefix(\n calculateBtcTxHash(input.fundedPrePeginTxHex),\n ).toLowerCase();\n if (actualTxid !== expectedTxid) {\n throw new Error(\n `Funded Pre-PegIn tx hashes to ${actualTxid}, expected ${expectedTxid} ` +\n `(on-chain prepeginTxid). Resume refused.`,\n );\n }\n\n // Completeness anchor: the single auth-anchor OP_RETURN sits at vout === HTLC\n // count — the only guard against an indexer-lagged partial sibling set.\n const found = findAuthAnchorOpReturn(\n stripHexPrefix(input.fundedPrePeginTxHex),\n );\n if (found === undefined) {\n throw new Error(\n `Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN ` +\n `commitment — it either predates auth anchoring or is malformed. The ` +\n `intent resume path requires the anchor to prove sibling completeness. ` +\n `Resume refused.`,\n );\n }\n if (found.vout !== siblingCount) {\n throw new Error(\n `Auth-anchor OP_RETURN at vout ${found.vout} does not match the ` +\n `discovered sibling count ${siblingCount}; the discovered sibling set ` +\n `does not cover this transaction's HTLC outputs (a lagging index can ` +\n `cause this — retry later). Resume refused.`,\n );\n }\n\n // Amount-independent sizing. Depositor-as-claimer: numLocalChallengers ===\n // numVks (VP excluded) — btc-vault graph.rs derive_challengers_for.\n const numVks = input.vaultKeeperBtcPubkeys.length;\n const numUcs = input.universalChallengerBtcPubkeys.length;\n const depositorClaimValue = await computeMinClaimValue(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.councilQuorum,\n input.councilSize,\n input.protocolFeeRate,\n );\n const peginMaxFee = await computeMinPeginFee(\n input.vaultCoreVersion,\n numVks,\n numUcs,\n input.minPeginFeeRate,\n );\n const anchor = await peginP2aAnchorOutput(input.vaultCoreVersion);\n const anchorValue = anchor?.value ?? 0n;\n\n // Independent bounds on the WASM outputs (mirrors assertWasmPeginSizing):\n // Gate 1 only proves the DCV+fee+anchor SUM — these constrain the\n // decomposition the device is shown.\n if (depositorClaimValue <= 0n) {\n throw new Error(\n `WASM returned non-positive depositorClaimValue ${depositorClaimValue}; ` +\n `expected > 0. Resume refused.`,\n );\n }\n if (peginMaxFee <= 0n) {\n throw new Error(\n `WASM returned non-positive peginMaxFee ${peginMaxFee}; expected > 0. ` +\n `Resume refused.`,\n );\n }\n // Explicit anchor check: the sum bound alone would let a negative anchor\n // offset an inflated peginMaxFee (kept local, not inherited from the facade).\n if (anchorValue < 0n) {\n throw new Error(\n `WASM returned negative P2A anchor value ${anchorValue}. Resume refused.`,\n );\n }\n const impliedReserve = peginMaxFee + anchorValue;\n const maxImpliedReserve = input.minPeginFeeRate * MAX_REASONABLE_PEGIN_VBYTES;\n if (impliedReserve <= 0n || impliedReserve > maxImpliedReserve) {\n throw new Error(\n `WASM implied PegIn reserve ${impliedReserve} sat is outside ` +\n `(0, ${maxImpliedReserve}] (minPeginFeeRate=${input.minPeginFeeRate} × ` +\n `${MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`,\n );\n }\n\n // Gate 1: per sibling, value = amount + DCV + peginMaxFee + anchor (btc-vault\n // compute_min_htlc_value) + scriptPubKey from the on-chain hashlock,\n // byte-matched against outputs 0..N-1.\n const expectedHtlcValues = input.siblings.map(\n (s) => s.amount + depositorClaimValue + peginMaxFee + anchorValue,\n );\n const expectedHtlcScriptPubKeys = await Promise.all(\n input.siblings.map(async (s) => {\n const connector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: input.vaultCoreVersion,\n depositorPubkey: input.depositorBtcPubkey,\n vaultProviderPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperPubkeys: [...input.vaultKeeperBtcPubkeys],\n universalChallengerPubkeys: [...input.universalChallengerBtcPubkeys],\n hashlock: stripHexPrefix(s.hashlock),\n timelockRefund: input.timelockRefund,\n network: input.network,\n });\n return connector.scriptPubKey;\n }),\n );\n const fundedOutputs = Transaction.fromHex(\n stripHexPrefix(input.fundedPrePeginTxHex),\n ).outs.map((o) => ({ value: o.value, script: o.script }));\n assertEncodedHtlcOutputsMatch(\n fundedOutputs,\n expectedHtlcValues,\n expectedHtlcScriptPubKeys,\n );\n\n return buildDepositTerms({\n vaultCoreVersion: input.vaultCoreVersion,\n protocolFeeRate: input.protocolFeeRate,\n timelockPegin: input.timelockPegin,\n timelockAssert: input.timelockAssert,\n timelockRefund: input.timelockRefund,\n prepeginTxid: input.prepeginTxid,\n prepeginMaxFee: input.prepeginMaxFee,\n vaultProviderBtcPubkey: input.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: input.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: input.universalChallengerBtcPubkeys,\n maxAcceptableCommissionBps: input.maxAcceptableCommissionBps,\n peginAmounts: input.siblings.map((s) => s.amount),\n depositorClaimValue,\n peginMaxFee,\n });\n}\n","/**\n * Check whether an error from the vault provider indicates that the\n * submitted WOTS public key hash does not match the on-chain\n * commitment. This signals that the wrong wallet is connected (its\n * `deriveContextHash` produces a different vault root and therefore\n * different WOTS keys).\n */\nexport function isWotsMismatchError(error: unknown): boolean {\n const msg = (\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\"\n ).toLowerCase();\n\n return (\n msg.includes(\"wots\") &&\n msg.includes(\"hash\") &&\n msg.includes(\"does not match\")\n );\n}\n"],"names":["DEPOSIT_TERMS_REJECTED_ERROR_NAME","DepositTermsRejectedError","message","reason","__publicField","isDepositTermsRejectedError","err","shaped","rebuildDepositTermsCore","input","siblingCount","i","sibling","expectedTxid","stripHexPrefix","actualTxid","calculateBtcTxHash","found","findAuthAnchorOpReturn","numVks","numUcs","depositorClaimValue","computeMinClaimValue","peginMaxFee","computeMinPeginFee","anchor","peginP2aAnchorOutput","anchorValue","impliedReserve","maxImpliedReserve","MAX_REASONABLE_PEGIN_VBYTES","expectedHtlcValues","expectedHtlcScriptPubKeys","getPrePeginHtlcConnectorInfo","fundedOutputs","Transaction","o","assertEncodedHtlcOutputsMatch","buildDepositTerms","isWotsMismatchError","error","msg"],"mappings":"kjBAUaA,EAAoC,4BA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AGKM,oBAAkB,CACvB,iBAAkB7B,EAAM,iBACxB,gBAAiBA,EAAM,gBACvB,cAAeA,EAAM,cACrB,eAAgBA,EAAM,eACtB,eAAgBA,EAAM,eACtB,aAAcA,EAAM,aACpB,eAAgBA,EAAM,eACtB,uBAAwBA,EAAM,uBAC9B,sBAAuBA,EAAM,sBAC7B,8BAA+BA,EAAM,8BACrC,2BAA4BA,EAAM,2BAClC,aAAcA,EAAM,SAAS,IAAK,GAAM,EAAE,MAAM,EAChD,oBAAAY,EACA,YAAAE,CAAA,CACD,CACH,CC/NO,SAASgB,EAAoBC,EAAyB,CAC3D,MAAMC,GACJD,aAAiB,MACbA,EAAM,QACN,OAAOA,GAAU,SACfA,EACA,IACN,YAAA,EAEF,OACEC,EAAI,SAAS,MAAM,GACnBA,EAAI,SAAS,MAAM,GACnBA,EAAI,SAAS,gBAAgB,CAEjC"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("./challengeAssert-BFRE2DM-.cjs"),m=require("./constants-DU5CGcqO.cjs"),n=require("@babylonlabs-io/babylon-tbv-rust-wasm"),l=require("./verifyScriptPathSchnorrSignature-B8zK1ctE.cjs"),A=require("./peginInput-Ci921gTl.cjs"),S=require("./noPayout-CbxQqBw1.cjs"),t=require("./bitcoin-m84N5a8o.cjs"),c=require("./validation-CDbOaDj7.cjs"),O=require("./signing-Bnsro0hE.cjs"),u=require("./PeginManager-BLBB_vMl.cjs"),d=require("./signPsbtsWithFallback-DbOmw8Ou.cjs"),_=require("./ProtocolParams.abi-C8U7BHCS.cjs"),C=require("./BTCVaultRegistry.abi-3VLWva2x.cjs"),b=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),p=require("./errors-CGcNP0rV.cjs"),P=require("./parseFundingOutpoints-CIO9Ok1L.cjs"),y=require("./shared/index.cjs"),o=require("./waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),i=require("./fundPeginTransaction-BLD8FRL9.cjs"),E=require("./reservation-CDbInVw0.cjs"),a=require("./mempoolApi-BxhMqJ4f.cjs"),r=require("./batchPoll-CbbCcNZP.cjs"),s=require("./json-rpc-client-BiAmg_ho.cjs"),I=require("./onChainBtcPubkey-C_a2L3kL.cjs"),T=require("./errors-D2zp7Vzk.cjs"),e=require("./buildAndBroadcastRefund-CYzhA_B8.cjs"),g=require("./peginState-eaQ4IO_R.cjs");exports.buildChallengeAssertPsbt=R.buildChallengeAssertPsbt;exports.computeNumLocalChallengers=R.computeNumLocalChallengers;exports.assertValidVaultCoreVersion=m.assertValidVaultCoreVersion;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>n.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>n.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>n.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>n.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>n.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>n.expandWotsSeed});Object.defineProperty(exports,"peginP2aAnchorOutput",{enumerable:!0,get:()=>n.peginP2aAnchorOutput});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>n.supportedTxGraphVersions});Object.defineProperty(exports,"validatePeginP2aAnchor",{enumerable:!0,get:()=>n.validatePeginP2aAnchor});exports.PsbtSubstitutionError=l.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=l.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=l.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=l.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=l.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=l.buildPrePeginPsbt;exports.createPayoutScript=l.createPayoutScript;exports.extractPayoutSignature=l.extractPayoutSignature;exports.buildPeginInputPsbt=A.buildPeginInputPsbt;exports.extractPeginInputSignature=A.extractPeginInputSignature;exports.finalizePeginInputPsbt=A.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=S.buildNoPayoutPsbt;exports.buildRefundPsbt=S.buildRefundPsbt;exports.canonicalizeBtcPubkey=t.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=t.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=t.deriveNativeSegwitAddress;exports.deriveTaprootAddress=t.deriveTaprootAddress;exports.ensureHexPrefix=t.ensureHexPrefix;exports.formatSatoshisToBtc=t.formatSatoshisToBtc;exports.getNetwork=t.getNetwork;exports.getSortedXOnlyPubkeys=t.getSortedXOnlyPubkeys;exports.hexToUint8Array=t.hexToUint8Array;exports.isAddressFromPublicKey=t.isAddressFromPublicKey;exports.isValidHex=t.isValidHex;exports.processPublicKeyToXOnly=t.processPublicKeyToXOnly;exports.stripHexPrefix=t.stripHexPrefix;exports.toXOnly=t.toXOnly;exports.uint8ArrayToHex=t.uint8ArrayToHex;exports.validateWalletPubkey=t.validateWalletPubkey;exports.BITCOIN_ADDRESS_RE=c.BITCOIN_ADDRESS_RE;exports.HEX_RE=c.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=c.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=c.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=c.TXID_RE;exports.combineAbortSignals=c.combineAbortSignals;exports.createTaprootScriptPathSignOptions=O.createTaprootScriptPathSignOptions;exports.COMMISSION_BPS_HEADROOM=u.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=u.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.PeginManager=u.PeginManager;exports.buildDepositTerms=u.buildDepositTerms;exports.capMaxAcceptableCommissionBps=u.capMaxAcceptableCommissionBps;exports.computeWotsBlockPublicKeysHash=u.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=u.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=u.ensurePrePeginTermsApproval;exports.estimateSubmitPeginRequestBatchGas=u.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=d.PayoutManager;exports.computeHashlock=d.computeHashlock;exports.forwardDepositApproval=d.forwardDepositApproval;exports.supportsDepositApproval=d.supportsDepositApproval;exports.validateSecretAgainstHashlock=d.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=_.ApplicationRegistryABI;exports.ProtocolParamsABI=_.ProtocolParamsABI;exports.BTCVaultRegistryABI=C.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=b.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=p.CONTRACT_ERRORS;exports.extractErrorData=p.extractErrorData;exports.getContractErrorMessage=p.getContractErrorMessage;exports.handleContractError=p.handleContractError;exports.isKnownContractError=p.isKnownContractError;exports.VAULT_APP_NAME=P.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=P.buildFundingOutpointsCommitment;exports.buildVaultContext=P.buildVaultContext;exports.deriveVaultRoot=P.deriveVaultRoot;exports.forwardDeriveContextHash=P.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=P.parseFundingOutpointsFromTx;exports.BitcoinNetworks=y.BitcoinNetworks;exports.BitcoinScriptType=o.BitcoinScriptType;exports.applyChangeOutputPolicy=o.applyChangeOutputPolicy;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.computeChangeOutputFeeSats=o.computeChangeOutputFeeSats;exports.computeMaxDeposit=o.computeMaxDeposit;exports.computePeginBaseFeeSats=o.computePeginBaseFeeSats;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=o.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=i.BTC_DUST_SAT;exports.DUST_THRESHOLD=i.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=i.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=i.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=i.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=i.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=i.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=i.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=i.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=i.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=i.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=i.fundPeginTransaction;exports.parseUnfundedWasmTransaction=i.parseUnfundedWasmTransaction;exports.peginOutputCount=i.peginOutputCount;exports.rateBasedTxBufferFee=i.rateBasedTxBufferFee;exports.UtxoNotAvailableError=E.UtxoNotAvailableError;exports.assertUtxosAvailable=E.assertUtxosAvailable;exports.extractInputsFromTransaction=E.extractInputsFromTransaction;exports.findOverlappingPendingVaults=E.findOverlappingPendingVaults;exports.validateUtxosAvailable=E.validateUtxosAvailable;exports.MEMPOOL_API_URLS=a.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=a.ViemVaultRegistryReader;exports.getAddressTxs=a.getAddressTxs;exports.getAddressUtxos=a.getAddressUtxos;exports.getMempoolApiUrl=a.getMempoolApiUrl;exports.getNetworkFees=a.getNetworkFees;exports.getOutspend=a.getOutspend;exports.getTipHeight=a.getTipHeight;exports.getTxHex=a.getTxHex;exports.getTxInfo=a.getTxInfo;exports.getUtxoInfo=a.getUtxoInfo;exports.pushTx=a.pushTx;exports.validateOffchainParams=a.validateOffchainParams;exports.validatePegInConfiguration=a.validatePegInConfiguration;exports.validateTBVProtocolParams=a.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=r.OnChainBtcVaultStatus;exports.ServerIdentityError=r.ServerIdentityError;exports.VaultProviderRpcClient=r.VaultProviderRpcClient;exports.ViemOperationKeyReader=r.ViemOperationKeyReader;exports.ViemProtocolParamsReader=r.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=r.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=r.ViemVaultKeeperReader;exports.VpResponseValidationError=r.VpResponseValidationError;exports.VpTokenRegistry=r.VpTokenRegistry;exports.batchPollByProvider=r.batchPollByProvider;exports.createAuthenticatedVpClient=r.createAuthenticatedVpClient;exports.primeVpTokenRegistry=r.primeVpTokenRegistry;exports.resolveProtocolAddresses=r.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=r.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=r.verifyServerIdentity;exports.vpTokenRegistry=r.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=s.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=s.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=s.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=s.isAuthRejectedError;exports.assertOnChainBtcPubkey=I.assertOnChainBtcPubkey;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=T.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=T.DepositTermsRejectedError;exports.isDepositTermsRejectedError=T.isDepositTermsRejectedError;exports.isWotsMismatchError=T.isWotsMismatchError;exports.rebuildDepositTermsCore=T.rebuildDepositTermsCore;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=g.ContractStatus;exports.PeginAction=g.PeginAction;exports.canPerformAction=g.canPerformAction;exports.getPeginProtocolState=g.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=g.isActivationDeadlinePassedOnChain;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("./challengeAssert-BFRE2DM-.cjs"),m=require("./constants-DU5CGcqO.cjs"),n=require("@babylonlabs-io/babylon-tbv-rust-wasm"),l=require("./verifyScriptPathSchnorrSignature-B8zK1ctE.cjs"),A=require("./peginInput-Ci921gTl.cjs"),S=require("./noPayout-CbxQqBw1.cjs"),t=require("./bitcoin-m84N5a8o.cjs"),c=require("./validation-CDbOaDj7.cjs"),O=require("./signing-Bnsro0hE.cjs"),u=require("./PeginManager-BgBt4hqp.cjs"),d=require("./signPsbtsWithFallback-DbOmw8Ou.cjs"),_=require("./ProtocolParams.abi-C8U7BHCS.cjs"),C=require("./BTCVaultRegistry.abi-3VLWva2x.cjs"),b=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),p=require("./errors-CGcNP0rV.cjs"),P=require("./parseFundingOutpoints-CIO9Ok1L.cjs"),y=require("./shared/index.cjs"),o=require("./waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),i=require("./fundPeginTransaction-BLD8FRL9.cjs"),E=require("./reservation-CDbInVw0.cjs"),a=require("./mempoolApi-Bsurcl43.cjs"),r=require("./batchPoll-WMXweT_O.cjs"),s=require("./json-rpc-client-BiAmg_ho.cjs"),I=require("./onChainBtcPubkey-C_a2L3kL.cjs"),T=require("./errors-DwjbI9h1.cjs"),e=require("./buildAndBroadcastRefund-CYzhA_B8.cjs"),g=require("./peginState-eaQ4IO_R.cjs");exports.buildChallengeAssertPsbt=R.buildChallengeAssertPsbt;exports.computeNumLocalChallengers=R.computeNumLocalChallengers;exports.assertValidVaultCoreVersion=m.assertValidVaultCoreVersion;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>n.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>n.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>n.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>n.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>n.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>n.expandWotsSeed});Object.defineProperty(exports,"peginP2aAnchorOutput",{enumerable:!0,get:()=>n.peginP2aAnchorOutput});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>n.supportedTxGraphVersions});Object.defineProperty(exports,"validatePeginP2aAnchor",{enumerable:!0,get:()=>n.validatePeginP2aAnchor});exports.PsbtSubstitutionError=l.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=l.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=l.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=l.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=l.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=l.buildPrePeginPsbt;exports.createPayoutScript=l.createPayoutScript;exports.extractPayoutSignature=l.extractPayoutSignature;exports.buildPeginInputPsbt=A.buildPeginInputPsbt;exports.extractPeginInputSignature=A.extractPeginInputSignature;exports.finalizePeginInputPsbt=A.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=S.buildNoPayoutPsbt;exports.buildRefundPsbt=S.buildRefundPsbt;exports.canonicalizeBtcPubkey=t.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=t.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=t.deriveNativeSegwitAddress;exports.deriveTaprootAddress=t.deriveTaprootAddress;exports.ensureHexPrefix=t.ensureHexPrefix;exports.formatSatoshisToBtc=t.formatSatoshisToBtc;exports.getNetwork=t.getNetwork;exports.getSortedXOnlyPubkeys=t.getSortedXOnlyPubkeys;exports.hexToUint8Array=t.hexToUint8Array;exports.isAddressFromPublicKey=t.isAddressFromPublicKey;exports.isValidHex=t.isValidHex;exports.processPublicKeyToXOnly=t.processPublicKeyToXOnly;exports.stripHexPrefix=t.stripHexPrefix;exports.toXOnly=t.toXOnly;exports.uint8ArrayToHex=t.uint8ArrayToHex;exports.validateWalletPubkey=t.validateWalletPubkey;exports.BITCOIN_ADDRESS_RE=c.BITCOIN_ADDRESS_RE;exports.HEX_RE=c.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=c.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=c.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=c.TXID_RE;exports.combineAbortSignals=c.combineAbortSignals;exports.createTaprootScriptPathSignOptions=O.createTaprootScriptPathSignOptions;exports.COMMISSION_BPS_HEADROOM=u.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=u.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.PeginManager=u.PeginManager;exports.buildDepositTerms=u.buildDepositTerms;exports.capMaxAcceptableCommissionBps=u.capMaxAcceptableCommissionBps;exports.computeWotsBlockPublicKeysHash=u.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=u.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=u.ensurePrePeginTermsApproval;exports.estimateSubmitPeginRequestBatchGas=u.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=d.PayoutManager;exports.computeHashlock=d.computeHashlock;exports.forwardDepositApproval=d.forwardDepositApproval;exports.supportsDepositApproval=d.supportsDepositApproval;exports.validateSecretAgainstHashlock=d.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=_.ApplicationRegistryABI;exports.ProtocolParamsABI=_.ProtocolParamsABI;exports.BTCVaultRegistryABI=C.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=b.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=p.CONTRACT_ERRORS;exports.extractErrorData=p.extractErrorData;exports.getContractErrorMessage=p.getContractErrorMessage;exports.handleContractError=p.handleContractError;exports.isKnownContractError=p.isKnownContractError;exports.VAULT_APP_NAME=P.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=P.buildFundingOutpointsCommitment;exports.buildVaultContext=P.buildVaultContext;exports.deriveVaultRoot=P.deriveVaultRoot;exports.forwardDeriveContextHash=P.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=P.parseFundingOutpointsFromTx;exports.BitcoinNetworks=y.BitcoinNetworks;exports.BitcoinScriptType=o.BitcoinScriptType;exports.applyChangeOutputPolicy=o.applyChangeOutputPolicy;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.computeChangeOutputFeeSats=o.computeChangeOutputFeeSats;exports.computeMaxDeposit=o.computeMaxDeposit;exports.computePeginBaseFeeSats=o.computePeginBaseFeeSats;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=o.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=i.BTC_DUST_SAT;exports.DUST_THRESHOLD=i.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=i.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=i.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=i.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=i.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=i.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=i.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=i.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=i.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=i.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=i.fundPeginTransaction;exports.parseUnfundedWasmTransaction=i.parseUnfundedWasmTransaction;exports.peginOutputCount=i.peginOutputCount;exports.rateBasedTxBufferFee=i.rateBasedTxBufferFee;exports.UtxoNotAvailableError=E.UtxoNotAvailableError;exports.assertUtxosAvailable=E.assertUtxosAvailable;exports.extractInputsFromTransaction=E.extractInputsFromTransaction;exports.findOverlappingPendingVaults=E.findOverlappingPendingVaults;exports.validateUtxosAvailable=E.validateUtxosAvailable;exports.MEMPOOL_API_URLS=a.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=a.ViemVaultRegistryReader;exports.getAddressTxs=a.getAddressTxs;exports.getAddressUtxos=a.getAddressUtxos;exports.getMempoolApiUrl=a.getMempoolApiUrl;exports.getNetworkFees=a.getNetworkFees;exports.getOutspend=a.getOutspend;exports.getTipHeight=a.getTipHeight;exports.getTxHex=a.getTxHex;exports.getTxInfo=a.getTxInfo;exports.getUtxoInfo=a.getUtxoInfo;exports.pushTx=a.pushTx;exports.validateOffchainParams=a.validateOffchainParams;exports.validatePegInConfiguration=a.validatePegInConfiguration;exports.validateTBVProtocolParams=a.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=r.OnChainBtcVaultStatus;exports.ServerIdentityError=r.ServerIdentityError;exports.VaultProviderRpcClient=r.VaultProviderRpcClient;exports.ViemOperationKeyReader=r.ViemOperationKeyReader;exports.ViemProtocolParamsReader=r.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=r.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=r.ViemVaultKeeperReader;exports.VpResponseValidationError=r.VpResponseValidationError;exports.VpTokenRegistry=r.VpTokenRegistry;exports.batchPollByProvider=r.batchPollByProvider;exports.createAuthenticatedVpClient=r.createAuthenticatedVpClient;exports.primeVpTokenRegistry=r.primeVpTokenRegistry;exports.resolveProtocolAddresses=r.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=r.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=r.verifyServerIdentity;exports.vpTokenRegistry=r.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=s.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=s.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=s.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=s.isAuthRejectedError;exports.assertOnChainBtcPubkey=I.assertOnChainBtcPubkey;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=T.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=T.DepositTermsRejectedError;exports.isDepositTermsRejectedError=T.isDepositTermsRejectedError;exports.isWotsMismatchError=T.isWotsMismatchError;exports.rebuildDepositTermsCore=T.rebuildDepositTermsCore;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=g.ContractStatus;exports.PeginAction=g.PeginAction;exports.canPerformAction=g.canPerformAction;exports.getPeginProtocolState=g.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=g.isActivationDeadlinePassedOnChain;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { a as V, b as y } from "./noPayout-oaUVsEjk.js";
|
|
|
7
7
|
import { c as N, d as M, a as F, b as B, e as U, f as H, k as L, g as K, h as k, i as X, j as w, p as W, s as G, t as j, u as J, v as Y } from "./bitcoin-d9eaaZB_.js";
|
|
8
8
|
import { B as z, H as q, K as Q, M as $, T as aa, c as ea } from "./validation-Dj3dqYtl.js";
|
|
9
9
|
import { c as ta } from "./signing-DaLvGwQe.js";
|
|
10
|
-
import { C as ia, M as oa, P as na, b as pa, a as ua, c as la, d as Pa, f as ca, e as da } from "./PeginManager-
|
|
10
|
+
import { C as ia, M as oa, P as na, b as pa, a as ua, c as la, d as Pa, f as ca, e as da } from "./PeginManager-C8kIl0gw.js";
|
|
11
11
|
import { P as Aa, c as Ta, f as ga, s as Ra, v as Sa } from "./signPsbtsWithFallback-DC4rUCsy.js";
|
|
12
12
|
import { A as ma, P as fa } from "./ProtocolParams.abi-CV938AYZ.js";
|
|
13
13
|
import { B as Ca } from "./BTCVaultRegistry.abi-B3BLhpJ4.js";
|
|
@@ -18,11 +18,11 @@ import { BitcoinNetworks as ka } from "./shared/index.js";
|
|
|
18
18
|
import { B as wa, a as Wa, f as Ga, c as ja, b as Ja, d as Ya, g as Za, i as za, h as qa, s as Qa, e as $a, w as ae } from "./waitForTransactionReceiptSmartAware-lobLm0q0.js";
|
|
19
19
|
import { B as se, D as te, L as re, M as ie, c as oe, P as ne, b as pe, a as ue, S as le, T as Pe, W as ce, f as de, d as Ee, p as Ae, r as Te } from "./fundPeginTransaction-B2wyjqp0.js";
|
|
20
20
|
import { U as Re, a as Se, e as _e, f as me, v as fe } from "./reservation-B4i_PQhY.js";
|
|
21
|
-
import { M as Ce, V as Oe, g as be, a as Ie, b as ve, c as he, d as Ve, e as ye, f as De, h as Ne, i as Me, p as Fe, v as Be, j as Ue, k as He } from "./mempoolApi-
|
|
22
|
-
import { O as Ke, S as ke, V as Xe, g as we, h as We, i as Ge, j as je, a as Je, d as Ye, b as Ze, f as ze, p as qe, r as Qe, v as $e, c as as, e as es } from "./batchPoll-
|
|
21
|
+
import { M as Ce, V as Oe, g as be, a as Ie, b as ve, c as he, d as Ve, e as ye, f as De, h as Ne, i as Me, p as Fe, v as Be, j as Ue, k as He } from "./mempoolApi-BXaOZL_I.js";
|
|
22
|
+
import { O as Ke, S as ke, V as Xe, g as we, h as We, i as Ge, j as je, a as Je, d as Ye, b as Ze, f as ze, p as qe, r as Qe, v as $e, c as as, e as es } from "./batchPoll-9w-Gv5dt.js";
|
|
23
23
|
import { A as ts, D as rs, J as is, a as os, b as ns, d as ps, P as us, R as ls, e as Ps, c as cs, V as ds, i as Es } from "./json-rpc-client-DuUARJvV.js";
|
|
24
24
|
import { a as Ts } from "./onChainBtcPubkey-DeF4cKoO.js";
|
|
25
|
-
import { D as Rs, a as Ss, b as _s, i as ms, r as fs } from "./errors-
|
|
25
|
+
import { D as Rs, a as Ss, b as _s, i as ms, r as fs } from "./errors-BxL9QObN.js";
|
|
26
26
|
import { H as Cs, E as Os, P as bs, o as Is, c as vs, d as hs, K as Vs, L as ys, M as Ds, N as Ns, R as Ms, a as Fs, b as Bs, y as Us, I as Hs, J as Ls, g as Ks, z as ks, p as Xs, i as ws, e as Ws, G as Gs, F as js, t as Js, A as Ys, B as Zs, C as zs, D as qs, r as Qs, s as $s, f as at, h as et, j as st, v as tt, k as rt, l as it, m as ot, n as nt, q as pt, u as ut, w as lt, x as Pt } from "./buildAndBroadcastRefund-CH2awK6h.js";
|
|
27
27
|
import { C as dt, P as Et, c as At, g as Tt, i as gt } from "./peginState-CxDiaKuk.js";
|
|
28
28
|
export {
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { B as a } from "./BTCVaultRegistry.abi-B3BLhpJ4.js";
|
|
2
2
|
import { B as d } from "./BTCVaultRegistryKeyEpochs.abi-CXjhRZbm.js";
|
|
3
3
|
import { a as w } from "./onChainBtcPubkey-DeF4cKoO.js";
|
|
4
|
-
import { a as
|
|
5
|
-
import { B as F, H as
|
|
4
|
+
import { a as x } from "./constants-GjWXdaqV.js";
|
|
5
|
+
import { B as F, H as B, K, T as k, c as N } from "./validation-Dj3dqYtl.js";
|
|
6
6
|
const h = 65535, b = 1e4, l = 4294967295, $ = 255;
|
|
7
|
-
function
|
|
7
|
+
function O(t) {
|
|
8
8
|
if (!Number.isInteger(t) || t < 0 || t > l)
|
|
9
9
|
throw new Error(
|
|
10
10
|
`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`
|
|
11
11
|
);
|
|
12
12
|
}
|
|
13
|
-
function
|
|
13
|
+
function S(t) {
|
|
14
14
|
const e = [];
|
|
15
15
|
if (t.timelockAssert <= 0n && e.push(
|
|
16
16
|
`timelockAssert must be positive, got ${t.timelockAssert}`
|
|
@@ -57,17 +57,17 @@ function R(t) {
|
|
|
57
57
|
throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`);
|
|
58
58
|
}
|
|
59
59
|
function L(t) {
|
|
60
|
-
if (R(t),
|
|
60
|
+
if (R(t), S(t.offchainParams), !Number.isInteger(t.offchainParamsVersion) || t.offchainParamsVersion < 0 || t.offchainParamsVersion > l)
|
|
61
61
|
throw new Error(
|
|
62
62
|
`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`
|
|
63
63
|
);
|
|
64
|
-
|
|
64
|
+
x(
|
|
65
65
|
t.activeVaultCoreVersion,
|
|
66
66
|
"ProtocolParams.activeVaultCoreVersion()"
|
|
67
67
|
);
|
|
68
68
|
}
|
|
69
|
-
const
|
|
70
|
-
function
|
|
69
|
+
const I = 9999;
|
|
70
|
+
function P(t) {
|
|
71
71
|
return {
|
|
72
72
|
depositor: t.depositor,
|
|
73
73
|
depositorBtcPubKey: t.depositorBtcPubKey,
|
|
@@ -80,7 +80,7 @@ function I(t) {
|
|
|
80
80
|
}
|
|
81
81
|
function m(t) {
|
|
82
82
|
const e = Number(t.offchainParamsVersion);
|
|
83
|
-
return
|
|
83
|
+
return O(e), {
|
|
84
84
|
depositorSignedPeginTx: t.depositorSignedPeginTx,
|
|
85
85
|
universalChallengersVersion: t.universalChallengersVersion,
|
|
86
86
|
appVaultKeepersVersion: t.appVaultKeepersVersion,
|
|
@@ -222,7 +222,7 @@ class W {
|
|
|
222
222
|
functionName: "getBtcVaultBasicInfo",
|
|
223
223
|
args: [e]
|
|
224
224
|
});
|
|
225
|
-
return
|
|
225
|
+
return P(o);
|
|
226
226
|
}
|
|
227
227
|
async getVaultProtocolInfo(e) {
|
|
228
228
|
const o = await this.publicClient.readContract({
|
|
@@ -277,9 +277,9 @@ class W {
|
|
|
277
277
|
functionName: "getVaultProviderCommission",
|
|
278
278
|
args: [e]
|
|
279
279
|
});
|
|
280
|
-
if (!Number.isInteger(o) || o < 0 || o >
|
|
280
|
+
if (!Number.isInteger(o) || o < 0 || o > I)
|
|
281
281
|
throw new Error(
|
|
282
|
-
`getVaultProviderCommission returned ${o} bps for ${e}, outside the protocol range [0, ${
|
|
282
|
+
`getVaultProviderCommission returned ${o} bps for ${e}, outside the protocol range [0, ${I}]`
|
|
283
283
|
);
|
|
284
284
|
return o;
|
|
285
285
|
}
|
|
@@ -300,37 +300,13 @@ class W {
|
|
|
300
300
|
}
|
|
301
301
|
],
|
|
302
302
|
allowFailure: !1
|
|
303
|
-
}), i =
|
|
303
|
+
}), i = P(o), r = m(n);
|
|
304
304
|
if (!r.depositorSignedPeginTx || r.depositorSignedPeginTx === "0x")
|
|
305
305
|
throw new Error(
|
|
306
306
|
`Vault ${e} not found on-chain or has no pegin transaction`
|
|
307
307
|
);
|
|
308
308
|
return { basic: i, protocol: r };
|
|
309
309
|
}
|
|
310
|
-
/**
|
|
311
|
-
* Read `offchainParamsVersion` for many vaults in a single multicall.
|
|
312
|
-
* Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault
|
|
313
|
-
* batch costs one RPC round-trip instead of 2N parallel `eth_call`s.
|
|
314
|
-
*/
|
|
315
|
-
async getOffchainParamsVersionsByVaultIds(e) {
|
|
316
|
-
return e.length === 0 ? [] : (await this.publicClient.multicall({
|
|
317
|
-
contracts: e.map((n) => ({
|
|
318
|
-
address: this.contractAddress,
|
|
319
|
-
abi: a,
|
|
320
|
-
functionName: "getBtcVaultProtocolInfo",
|
|
321
|
-
args: [n]
|
|
322
|
-
})),
|
|
323
|
-
allowFailure: !1
|
|
324
|
-
})).map((n) => {
|
|
325
|
-
const i = n;
|
|
326
|
-
if (!i.depositorSignedPeginTx || i.depositorSignedPeginTx === "0x")
|
|
327
|
-
throw new Error(
|
|
328
|
-
"Vault not found on-chain or has no pegin transaction while reading offchain params version"
|
|
329
|
-
);
|
|
330
|
-
const r = Number(i.offchainParamsVersion);
|
|
331
|
-
return T(r), r;
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
310
|
}
|
|
335
311
|
const U = 21e6 * 1e8, V = 3e4;
|
|
336
312
|
async function f(t, e) {
|
|
@@ -339,7 +315,7 @@ async function f(t, e) {
|
|
|
339
315
|
V
|
|
340
316
|
), i = [o.signal, e == null ? void 0 : e.signal].filter(
|
|
341
317
|
Boolean
|
|
342
|
-
), r =
|
|
318
|
+
), r = N(i);
|
|
343
319
|
try {
|
|
344
320
|
return await fetch(t, {
|
|
345
321
|
...e,
|
|
@@ -352,7 +328,7 @@ async function f(t, e) {
|
|
|
352
328
|
}
|
|
353
329
|
}
|
|
354
330
|
const A = 1e4;
|
|
355
|
-
function
|
|
331
|
+
function T(t) {
|
|
356
332
|
return Number.isInteger(t) && t > 0 && t <= U;
|
|
357
333
|
}
|
|
358
334
|
function M(t) {
|
|
@@ -362,19 +338,19 @@ function g(t, e) {
|
|
|
362
338
|
return !Number.isInteger(t) || t < 0 ? !1 : e === void 0 || t < e;
|
|
363
339
|
}
|
|
364
340
|
function u(t) {
|
|
365
|
-
if (!
|
|
341
|
+
if (!k.test(t))
|
|
366
342
|
throw new Error(`Invalid transaction ID format: ${t}`);
|
|
367
343
|
}
|
|
368
|
-
function
|
|
344
|
+
function C(t) {
|
|
369
345
|
if (!F.test(t))
|
|
370
346
|
throw new Error(`Invalid Bitcoin address format: ${t}`);
|
|
371
347
|
}
|
|
372
|
-
function
|
|
373
|
-
if (!
|
|
348
|
+
function v(t, e) {
|
|
349
|
+
if (!B.test(t))
|
|
374
350
|
throw new Error(
|
|
375
351
|
`Invalid scriptPubKey: not valid hex for ${e}`
|
|
376
352
|
);
|
|
377
|
-
if (!
|
|
353
|
+
if (!K.some(
|
|
378
354
|
(n) => t.toLowerCase().startsWith(n)
|
|
379
355
|
))
|
|
380
356
|
throw new Error(
|
|
@@ -467,9 +443,9 @@ async function tt(t, e, o) {
|
|
|
467
443
|
`Invalid vout ${e} for transaction ${t} (has ${n.vout.length} outputs)`
|
|
468
444
|
);
|
|
469
445
|
const i = n.vout[e];
|
|
470
|
-
if (!
|
|
446
|
+
if (!T(i.value))
|
|
471
447
|
throw new Error(`Invalid UTXO value ${i.value} for ${t}:${e}`);
|
|
472
|
-
return
|
|
448
|
+
return v(i.scriptpubkey, `${t}:${e}`), {
|
|
473
449
|
txid: t,
|
|
474
450
|
vout: e,
|
|
475
451
|
value: i.value,
|
|
@@ -477,18 +453,18 @@ async function tt(t, e, o) {
|
|
|
477
453
|
};
|
|
478
454
|
}
|
|
479
455
|
async function et(t, e) {
|
|
480
|
-
|
|
456
|
+
C(t);
|
|
481
457
|
try {
|
|
482
458
|
const o = await c(`${e}/address/${t}/utxo`), n = await c(`${e}/v1/validate-address/${t}`);
|
|
483
459
|
if (!n.isvalid)
|
|
484
460
|
throw new Error(
|
|
485
461
|
`Invalid Bitcoin address: ${t}. Mempool API validation failed.`
|
|
486
462
|
);
|
|
487
|
-
|
|
463
|
+
v(n.scriptPubKey, t);
|
|
488
464
|
for (const r of o) {
|
|
489
465
|
if (u(r.txid), !g(r.vout))
|
|
490
466
|
throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);
|
|
491
|
-
if (!
|
|
467
|
+
if (!T(r.value))
|
|
492
468
|
throw new Error(
|
|
493
469
|
`Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`
|
|
494
470
|
);
|
|
@@ -512,7 +488,7 @@ function ot(t) {
|
|
|
512
488
|
return H[t];
|
|
513
489
|
}
|
|
514
490
|
async function nt(t, e) {
|
|
515
|
-
return
|
|
491
|
+
return C(t), c(`${e}/address/${t}/txs`);
|
|
516
492
|
}
|
|
517
493
|
async function rt(t) {
|
|
518
494
|
const e = await f(`${t}/v1/fees/recommended`);
|
|
@@ -552,8 +528,8 @@ export {
|
|
|
552
528
|
tt as i,
|
|
553
529
|
L as j,
|
|
554
530
|
R as k,
|
|
555
|
-
|
|
531
|
+
O as l,
|
|
556
532
|
J as p,
|
|
557
|
-
|
|
533
|
+
S as v
|
|
558
534
|
};
|
|
559
|
-
//# sourceMappingURL=mempoolApi-
|
|
535
|
+
//# sourceMappingURL=mempoolApi-BXaOZL_I.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mempoolApi-BXaOZL_I.js","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, VP_GENESIS_KEY_EPOCH],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${VP_GENESIS_KEY_EPOCH})`,\n );\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server signs its BIP-322 auth tokens with — a\n * live per-operator identity, not a per-vault binding, so the auth pin uses\n * the current key rather than any vault's frozen epoch.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\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: BTCVaultRegistryKeyEpochsABI 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 mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n}\n","/**\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 { combineAbortSignals } from \"../../utils/abortSignals\";\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","BTCVaultRegistryABI","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","combined","combineAbortSignals","error","MAX_FEE_RATE","isValidSatoshiValue","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields"],"mappings":";;;;;AAwBA,MAAMA,IAAa,OAGbC,IAAmB,KAGnBC,IAAa,YAGbC,IAAY;AAQX,SAASC,EAAiCC,GAAuB;AACtE,MACE,CAAC,OAAO,UAAUA,CAAO,KACzBA,IAAU,KACVA,IAAUH;AAEV,UAAM,IAAI;AAAA,MACR,sEAAsEG,CAAO;AAAA,IAAA;AAGnF;AAMO,SAASC,EAAuBC,GAAuC;AAC5E,QAAMC,IAAmB,CAAA;AA+FzB,MA7FID,EAAO,kBAAkB,MAC3BC,EAAO;AAAA,IACL,wCAAwCD,EAAO,cAAc;AAAA,EAAA,GAG7DA,EAAO,iBAAiB,OAAOP,CAAU,KAC3CQ,EAAO;AAAA,IACL,kBAAkBD,EAAO,cAAc,wBAAwBP,CAAU;AAAA,EAAA,GAIzEO,EAAO,2BAA2B,MACpCC,EAAO;AAAA,IACL,iDAAiDD,EAAO,uBAAuB;AAAA,EAAA,GAI/EA,EAAO,WAAW,KACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,GAG3DA,EAAO,UAAU,KACnBC,EAAO,KAAK,gCAAgCD,EAAO,MAAM,EAAE,GAGzDA,EAAO,oBAAoB,WAAW,KACxCC,EAAO,KAAK,uCAAuC,GAGjDD,EAAO,iBAAiB,KAC1BC,EAAO,KAAK,uCAAuCD,EAAO,aAAa,EAAE,GAEvEA,EAAO,gBAAgBA,EAAO,oBAAoB,UACpDC,EAAO;AAAA,IACL,kBAAkBD,EAAO,aAAa,wCAAwCA,EAAO,oBAAoB,MAAM;AAAA,EAAA,GAI/GA,EAAO,WAAW,MACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,GAG3DA,EAAO,mBAAm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@
|
|
|
1
|
+
"use strict";const a=require("./BTCVaultRegistry.abi-3VLWva2x.cjs"),w=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),I=require("./onChainBtcPubkey-C_a2L3kL.cjs"),k=require("./constants-DU5CGcqO.cjs"),u=require("./validation-CDbOaDj7.cjs"),g=65535,b=1e4,f=4294967295,P=255;function E(e){if(!Number.isInteger(e)||e<0||e>f)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`)}function C(e){const t=[];if(e.timelockAssert<=0n&&t.push(`timelockAssert must be positive, got ${e.timelockAssert}`),e.timelockAssert>BigInt(g)&&t.push(`timelockAssert ${e.timelockAssert} exceeds uint16 max (${g})`),e.timelockChallengeAssert<=0n&&t.push(`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`),e.tRefund<=0&&t.push(`tRefund must be positive, got ${e.tRefund}`),e.tStale<=0&&t.push(`tStale must be positive, got ${e.tStale}`),e.securityCouncilKeys.length===0&&t.push("securityCouncilKeys must not be empty"),e.councilQuorum<=0&&t.push(`councilQuorum must be positive, got ${e.councilQuorum}`),e.councilQuorum>e.securityCouncilKeys.length&&t.push(`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`),e.feeRate<=0n&&t.push(`feeRate must be positive, got ${e.feeRate}`),e.minPeginFeeRate<=0n&&t.push(`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`),(!Number.isInteger(e.proverCircuitVersion)||e.proverCircuitVersion<0||e.proverCircuitVersion>g)&&t.push(`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`),(!Number.isInteger(e.minPrepeginDepth)||e.minPrepeginDepth<=0||e.minPrepeginDepth>f)&&t.push(`minPrepeginDepth must be a uint32 in [1, ${f}], got ${e.minPrepeginDepth}`),e.babeTotalInstances<=0&&t.push(`babeTotalInstances must be positive, got ${e.babeTotalInstances}`),e.babeInstancesToFinalize<=0&&t.push(`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`),e.babeInstancesToFinalize>e.babeTotalInstances&&t.push(`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`),(e.minVpCommissionBps<0||e.minVpCommissionBps>b)&&t.push(`minVpCommissionBps must be in [0, ${b}], got ${e.minVpCommissionBps}`),t.length>0)throw new Error(`Invalid offchain protocol parameters: ${t.join("; ")}`)}function B(e){const t=[];if(e.minimumPegInAmount<=0n&&t.push(`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`),e.maxPegInAmount<e.minimumPegInAmount&&t.push(`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`),e.pegInAckTimeout<=0n&&t.push(`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`),e.pegInActivationTimeout<=0n&&t.push(`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`),(!Number.isInteger(e.maxHtlcOutputCount)||e.maxHtlcOutputCount<=0||e.maxHtlcOutputCount>P)&&t.push(`maxHtlcOutputCount must be an integer in [1, ${P}], got ${e.maxHtlcOutputCount}`),(typeof e.expiredPegInGraceBlocks!="bigint"||e.expiredPegInGraceBlocks<=0n)&&t.push(`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`),t.length>0)throw new Error(`Invalid TBV protocol parameters: ${t.join("; ")}`)}function N(e){if(B(e),C(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}`);k.assertValidVaultCoreVersion(e.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const $=9999;function y(e){return{depositor:e.depositor,depositorBtcPubKey:e.depositorBtcPubKey,amount:e.amount,vaultProvider:e.vaultProvider,status:e.status,applicationEntryPoint:e.applicationEntryPoint,createdAt:e.createdAt}}function m(e){const t=Number(e.offchainParamsVersion);return E(t),{depositorSignedPeginTx:e.depositorSignedPeginTx,universalChallengersVersion:e.universalChallengersVersion,appVaultKeepersVersion:e.appVaultKeepersVersion,offchainParamsVersion:t,verifiedAt:e.verifiedAt,depositorWotsPkHash:e.depositorWotsPkHash,hashlock:e.hashlock,htlcVout:e.htlcVout,depositorPopSignature:e.depositorPopSignature,prePeginTxHash:e.prePeginTxHash,vaultProviderCommissionBps:e.vaultProviderCommissionBps,claimExpiredUntil:e.claimExpiredUntil,vaultCoreVersion:e.vaultCoreVersion}}const S=1n<<64n,V=0n;function p(e,t,o){if(e<0n||e>=S)throw new Error(`getBtcVaultProtocolInfo returned ${t}=${e} for vault ${o}, outside the uint64 range — the registry may predate RFC-006`);return e}function T(e,t){return{vpKeyEpoch:p(e.vpKeyEpoch,"vpKeyEpoch",t),appKeeperKeyEpoch:p(e.appKeeperKeyEpoch,"appKeeperKeyEpoch",t),ucKeyEpoch:p(e.ucKeyEpoch,"ucKeyEpoch",t)}}class _{constructor(t,o){this.publicClient=t,this.contractAddress=o}async getVaultProviderGenesisBtcPubKey(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[t,V]});return I.assertOnChainBtcPubkey(o,`getOperationBtcKeyAtEpoch (vp=${t}, epoch=${V})`)}async getCurrentVaultProviderOperationBtcKey(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[t]});return I.assertOnChainBtcPubkey(o,`getCurrentOperationBtcKey (vp=${t})`)}async getVaultKeyEpochs(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:w.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return T(o,t)}async getVaultKeyEpochsBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(n=>({address:this.contractAddress,abi:w.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>T(n,t[i]))}async getVaultBasicInfo(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]});return y(o)}async getVaultProtocolInfo(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return m(o)}async getProtocolInfoBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(n=>({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>{const r=n;if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t[i]} not found on-chain or has no pegin transaction`);return m(r)})}async getPegInFee(t){return await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}async getVaultProviderCommission(t){const o=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[t]});if(!Number.isInteger(o)||o<0||o>$)throw new Error(`getVaultProviderCommission returned ${o} bps for ${t}, outside the protocol range [0, ${$}]`);return o}async getVaultData(t){const[o,n]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]},{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]}],allowFailure:!1}),i=y(o),r=m(n);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:i,protocol:r}}}const U=21e6*1e8,A=3e4;async function h(e,t){const o=new AbortController,n=setTimeout(()=>o.abort(),A),i=[o.signal,t==null?void 0:t.signal].filter(Boolean),r=u.combineAbortSignals(i);try{return await fetch(e,{...t,signal:r.signal})}catch(s){throw clearTimeout(n),r.cleanup(),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${A}ms: ${e}`):s}}const v=1e4;function x(e){return Number.isInteger(e)&&e>0&&e<=U}function M(e){return Number.isInteger(e)&&e>0&&e<=v}function d(e,t){return!Number.isInteger(e)||e<0?!1:t===void 0||e<t}function l(e){if(!u.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function F(e){if(!u.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function K(e,t){if(!u.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${t}`);if(!u.KNOWN_SCRIPT_PREFIXES.some(n=>e.toLowerCase().startsWith(n)))throw new Error(`Unrecognized scriptPubKey type for ${t}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const R={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(e,t){try{const o=await h(e,t);if(!o.ok){const i=await o.text();throw new Error(`Mempool API error (${o.status}): ${i||o.statusText}`)}const n=o.headers.get("content-type");return n!=null&&n.includes("application/json")?await o.json():await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to fetch from mempool API: ${o.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function H(e,t){try{const o=await h(`${t}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!o.ok){const i=await o.text();let r;try{const s=JSON.parse(i);r=s.message??s.error}catch{r=i}throw new Error(r||`Failed to broadcast transaction: ${o.statusText}`)}return await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to broadcast BTC transaction: ${o.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function O(e,t){return l(e),c(`${t}/tx/${e}`)}async function X(e){const t=await c(`${e}/blocks/tip/height`),o=t.trim();if(!/^\d+$/.test(o))throw new Error(`Mempool API returned an invalid block tip height: "${t}"`);return Number.parseInt(o,10)}async function D(e,t,o){if(l(e),!d(t))throw new Error(`Invalid vout ${t} for transaction ${e}`);return c(`${o}/tx/${e}/outspend/${t}`)}async function z(e,t){l(e);try{const o=await h(`${t}/tx/${e}/hex`);if(!o.ok){const n=await o.text();throw new Error(`Mempool API error (${o.status}): ${n||o.statusText}`)}return await o.text()}catch(o){throw o instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${o.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function L(e,t,o){l(e);const n=await O(e,o);if(!d(t,n.vout.length))throw new Error(`Invalid vout ${t} for transaction ${e} (has ${n.vout.length} outputs)`);const i=n.vout[t];if(!x(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${e}:${t}`);return K(i.scriptpubkey,`${e}:${t}`),{txid:e,vout:t,value:i.value,scriptPubKey:i.scriptpubkey}}async function Q(e,t){F(e);try{const o=await c(`${t}/address/${e}/utxo`),n=await c(`${t}/v1/validate-address/${e}`);if(!n.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);K(n.scriptPubKey,e);for(const r of o){if(l(r.txid),!d(r.vout))throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);if(!x(r.value))throw new Error(`Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`)}return o.sort((r,s)=>s.value-r.value).map(r=>({txid:r.txid,vout:r.vout,value:r.value,scriptPubKey:n.scriptPubKey,confirmed:r.status.confirmed}))}catch(o){throw o instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${o.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function j(e){return R[e]}async function q(e,t){return F(e),c(`${t}/address/${e}/txs`)}async function G(e){const t=await h(`${e}/v1/fees/recommended`);if(!t.ok)throw new Error(`Failed to fetch network fees: ${t.status} ${t.statusText}`);const o=await t.json(),n=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of n)if(!M(o[i]))throw new Error(`Invalid fee rate ${i}=${o[i]} from mempool API: expected a positive number ≤ ${v}`);if(o.minimumFee>o.economyFee||o.economyFee>o.hourFee||o.hourFee>o.halfHourFee||o.halfHourFee>o.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${o.minimumFee}) <= economyFee (${o.economyFee}) <= hourFee (${o.hourFee}) <= halfHourFee (${o.halfHourFee}) <= fastestFee (${o.fastestFee}).`);return o}exports.MEMPOOL_API_URLS=R;exports.ViemVaultRegistryReader=_;exports.assertValidOffchainParamsVersion=E;exports.getAddressTxs=q;exports.getAddressUtxos=Q;exports.getMempoolApiUrl=j;exports.getNetworkFees=G;exports.getOutspend=D;exports.getTipHeight=X;exports.getTxHex=z;exports.getTxInfo=O;exports.getUtxoInfo=L;exports.pushTx=H;exports.validateOffchainParams=C;exports.validatePegInConfiguration=N;exports.validateTBVProtocolParams=B;
|
|
2
|
+
//# sourceMappingURL=mempoolApi-Bsurcl43.cjs.map
|