@babylonlabs-io/ts-sdk 0.39.3 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PayoutManager-DnKRzWWb.cjs → PayoutManager-B5bovfkD.cjs} +2 -2
- package/dist/{PayoutManager-DnKRzWWb.cjs.map → PayoutManager-B5bovfkD.cjs.map} +1 -1
- package/dist/{PayoutManager-2XpjdLxE.js → PayoutManager-DChODEOJ.js} +2 -2
- package/dist/{PayoutManager-2XpjdLxE.js.map → PayoutManager-DChODEOJ.js.map} +1 -1
- package/dist/{PeginManager-CBQnWvX8.js → PeginManager-D9ZZ8wx2.js} +84 -82
- package/dist/PeginManager-D9ZZ8wx2.js.map +1 -0
- package/dist/{PeginManager-CPw28lAE.cjs → PeginManager-UqbOj2oV.cjs} +2 -2
- package/dist/PeginManager-UqbOj2oV.cjs.map +1 -0
- package/dist/{assertPsbtUnsignedTxMatches-CsawQGjC.js → assertPsbtUnsignedTxMatches-CzVv57QF.js} +12 -10
- package/dist/assertPsbtUnsignedTxMatches-CzVv57QF.js.map +1 -0
- package/dist/assertPsbtUnsignedTxMatches-r1svclbd.cjs +2 -0
- package/dist/assertPsbtUnsignedTxMatches-r1svclbd.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-Cj8JDI7F.cjs +2 -0
- package/dist/{buildAndBroadcastRefund-MoSpjUKJ.cjs.map → buildAndBroadcastRefund-Cj8JDI7F.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-BRMB7XyC.js → buildAndBroadcastRefund-fIHDHiFh.js} +345 -301
- package/dist/{buildAndBroadcastRefund-BRMB7XyC.js.map → buildAndBroadcastRefund-fIHDHiFh.js.map} +1 -1
- package/dist/{challengeAssert-D8-RwiDv.js → challengeAssert-DLEmAhT0.js} +2 -2
- package/dist/{challengeAssert-D8-RwiDv.js.map → challengeAssert-DLEmAhT0.js.map} +1 -1
- package/dist/{challengeAssert-BobHj1La.cjs → challengeAssert-rpDaS3fH.cjs} +2 -2
- package/dist/{challengeAssert-BobHj1La.cjs.map → challengeAssert-rpDaS3fH.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +78 -77
- package/dist/{mempoolApi-CAIge7Nj.js → mempoolApi-C7hkVkym.js} +31 -22
- package/dist/mempoolApi-C7hkVkym.js.map +1 -0
- package/dist/mempoolApi-DEAS9wVa.cjs +2 -0
- package/dist/mempoolApi-DEAS9wVa.cjs.map +1 -0
- package/dist/noPayout-B06Z9RTe.cjs +2 -0
- package/dist/noPayout-B06Z9RTe.cjs.map +1 -0
- package/dist/noPayout-CS2wnluA.js +154 -0
- package/dist/noPayout-CS2wnluA.js.map +1 -0
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +33 -32
- package/dist/tbv/core/clients/mempool/index.d.ts +1 -1
- package/dist/tbv/core/clients/mempool/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +11 -0
- package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +78 -77
- package/dist/tbv/core/managers/PeginManager.d.ts +7 -2
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +3 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +27 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
- package/dist/tbv/core/services/refund/index.d.ts +1 -1
- package/dist/tbv/core/services/refund/index.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +78 -77
- package/package.json +1 -1
- package/dist/PeginManager-CBQnWvX8.js.map +0 -1
- package/dist/PeginManager-CPw28lAE.cjs.map +0 -1
- package/dist/assertPsbtUnsignedTxMatches-CsawQGjC.js.map +0 -1
- package/dist/assertPsbtUnsignedTxMatches-u9yeeUFY.cjs +0 -2
- package/dist/assertPsbtUnsignedTxMatches-u9yeeUFY.cjs.map +0 -1
- package/dist/buildAndBroadcastRefund-MoSpjUKJ.cjs +0 -2
- package/dist/mempoolApi-CAIge7Nj.js.map +0 -1
- package/dist/mempoolApi-YNkKjQCU.cjs +0 -2
- package/dist/mempoolApi-YNkKjQCU.cjs.map +0 -1
- package/dist/noPayout-C5b34rs1.js +0 -145
- package/dist/noPayout-C5b34rs1.js.map +0 -1
- package/dist/noPayout-CtmOEauj.cjs +0 -2
- package/dist/noPayout-CtmOEauj.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"assertPsbtUnsignedTxMatches-u9yeeUFY.cjs","sources":["../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/constants.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.ts"],"sourcesContent":["/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n createPrePeginTransaction,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nexport function normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * Exclusive upper bound on VP commission (bps), and the bps denominator for\n * `floor(peginValue * bps / 10_000)`. Matches `BTCVaultRegistry._validateCommission`\n * (`commissionBps >= 10000` reverts). The minimum is version-locked\n * (`minVpCommissionBps`) and enforced upstream, not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n MAX_VP_COMMISSION_BPS_EXCLUSIVE,\n NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,\n PAYOUT_ANCHOR_DUST_SATS,\n PEGIN_VAULT_OUTPUT_INDEX,\n VP_CLAIMER_PAYOUT_OUTPUT_COUNT,\n} from \"./constants\";\n\n/**\n * Number of items in a Taproot script-path spend witness stack for a\n * single-signature script: [signature, script, controlBlock].\n *\n * The current payout script requires exactly one depositor signature. If the\n * protocol evolves to require multiple signatures in the payout script, this\n * invariant and the finalized-PSBT extraction path must be revisited because\n * the first witness item would no longer necessarily be the depositor's.\n */\nconst TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE = 3;\n\n/**\n * Coarse cap on a payout tx's implicit fee (inputs − outputs), as a fraction\n * of input value — blocks a VP deflating outputs and burning the remainder\n * as miner fee. A backstop only; the per-role structural checks in\n * {@link assertPayoutOutputLayout} are the primary value-diversion guard.\n */\nconst MAX_PAYOUT_FEE_FRACTION_NUMERATOR = 10;\nconst MAX_PAYOUT_FEE_FRACTION_DENOMINATOR = 100;\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n\n /**\n * Claimer's x-only BTC public key (64-char hex, no prefix). Drives role\n * inference (VP / depositor-as-claimer / VK-claimer) inside `buildPayoutPsbt`.\n */\n claimerBtcPubkey: string;\n\n /**\n * On-chain registered depositor payout scriptPubKey (hex, 0x optional).\n * Expected outs[0].script for VP- and depositor-claimer roles; unused for\n * VK-claimer (its outs[0].script is derived from `claimerBtcPubkey`).\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * VP commission in basis points (`BTCVaultRegistry.vaultProviderCommissionBps`).\n * Caps the VP-claimer outs[1].value. The protocol minimum is enforced\n * upstream; here only `0 <= bps < 10_000` is checked, for safe cap math.\n */\n commissionBps: number;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not spend PegIn:0 (vault UTXO)\n * @throws If input 1 does not spend Assert:0 (proof output)\n * @throws If previous output is not found for either input\n * @throws If sum of output values exceeds sum of input values (invalid tx)\n * @throws If implicit fee (inputs − outputs) exceeds the configured fraction\n * of total input value — see {@link MAX_PAYOUT_FEE_FRACTION_NUMERATOR}\n * @throws If `claimerBtcPubkey` is not VP, depositor, or a registered VK\n * @throws If payout output count, outs[0] script, outs[last] anchor value, or\n * (VP-claimer) outs[1] commission cap do not match the protocol layout\n * @throws If `commissionBps` is not a non-negative integer below 10_000\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 spends PegIn:0 (the vault UTXO).\n // Both txid AND vout must match the protocol contract — the vout is the\n // input-side anchor that prevents a malicious VP from binding the\n // depositor's signature to a different output of the same parent.\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n // Verify input 1 spends Assert:0 (the proof output).\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const assertTxid = assertTx.getId();\n\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Per-role output validation — blocks an extra attacker output or value\n // routed into a non-payout slot.\n assertPayoutOutputLayout({\n payoutTx,\n peginValueSats: peginPrevOut.value,\n claimerBtcPubkey: params.claimerBtcPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n depositorBtcPubkey: params.depositorBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n });\n\n // Bound the implicit fee — blocks a VP deflating output values and burning\n // the difference as miner fee.\n const inputValueSats = peginPrevOut.value + input1PrevOut.value;\n let outputValueSats = 0;\n for (const out of payoutTx.outs) outputValueSats += out.value;\n if (outputValueSats > inputValueSats) {\n throw new Error(\n `Payout outputs (${outputValueSats} sats) exceed inputs ` +\n `(${inputValueSats} sats); invalid transaction.`,\n );\n }\n const implicitFeeSats = inputValueSats - outputValueSats;\n const maxFeeSats = Math.floor(\n (inputValueSats * MAX_PAYOUT_FEE_FRACTION_NUMERATOR) /\n MAX_PAYOUT_FEE_FRACTION_DENOMINATOR,\n );\n if (implicitFeeSats > maxFeeSats) {\n throw new Error(\n `Payout implicit fee ${implicitFeeSats} sats exceeds the safety cap ` +\n `of ${maxFeeSats} sats ` +\n `(${MAX_PAYOUT_FEE_FRACTION_NUMERATOR}/${MAX_PAYOUT_FEE_FRACTION_DENOMINATOR} ` +\n `of inputs=${inputValueSats}); refusing to sign payout.`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Validate a payout transaction's output structure for the claimer's role,\n * keyed on `claimerBtcPubkey`. Pins per role: `outs.length`, `outs[0].script`,\n * `outs[last].value` (anchor dust), and (VP-claimer) `outs[1].value` capped at\n * `floor(peginValue × commissionBps / 10_000)`. Canonical layouts: VP-claimer\n * = [payout, commission, anchor]; depositor/VK-claimer = [payout, anchor].\n *\n * `outs[1].script` and `outs[last].script` are intentionally not pinned: the\n * value pins above bound depositor exposure regardless of where those outputs\n * are sent, so the value pins — not script pins — are load-bearing.\n *\n * @internal Helper invoked by {@link buildPayoutPsbt}.\n */\nfunction assertPayoutOutputLayout(args: {\n payoutTx: Transaction;\n peginValueSats: number;\n claimerBtcPubkey: string;\n vaultProviderBtcPubkey: string;\n depositorBtcPubkey: string;\n vaultKeeperBtcPubkeys: string[];\n registeredPayoutScriptPubKey: string;\n commissionBps: number;\n}): void {\n const {\n payoutTx,\n peginValueSats,\n claimerBtcPubkey,\n vaultProviderBtcPubkey,\n depositorBtcPubkey,\n vaultKeeperBtcPubkeys,\n registeredPayoutScriptPubKey,\n commissionBps,\n } = args;\n\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const claimer = stripHexPrefix(claimerBtcPubkey).toLowerCase();\n const vp = stripHexPrefix(vaultProviderBtcPubkey).toLowerCase();\n const dep = stripHexPrefix(depositorBtcPubkey).toLowerCase();\n const keepers = vaultKeeperBtcPubkeys.map((k) =>\n stripHexPrefix(k).toLowerCase(),\n );\n\n type Role = \"vp-claimer\" | \"depositor-as-claimer\" | \"vk-claimer\";\n let role: Role;\n let expectedOutCount: number;\n let expectedOut0ScriptHex: string;\n\n if (claimer === vp) {\n role = \"vp-claimer\";\n expectedOutCount = VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n expectedOut0ScriptHex = stripHexPrefix(registeredPayoutScriptPubKey);\n } else if (claimer === dep) {\n role = \"depositor-as-claimer\";\n expectedOutCount = NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n expectedOut0ScriptHex = stripHexPrefix(registeredPayoutScriptPubKey);\n } else if (keepers.includes(claimer)) {\n role = \"vk-claimer\";\n expectedOutCount = NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n expectedOut0ScriptHex = stripHexPrefix(deriveBip86ScriptPubKeyHex(claimer));\n } else {\n throw new Error(\n `Unknown claimer pubkey ${claimer}: not VP, depositor, or a registered vault keeper`,\n );\n }\n\n if (payoutTx.outs.length !== expectedOutCount) {\n throw new Error(\n `Payout transaction has ${payoutTx.outs.length} output(s), ` +\n `expected exactly ${expectedOutCount} for role ${role}.`,\n );\n }\n\n const expectedOut0Script = Buffer.from(expectedOut0ScriptHex, \"hex\");\n if (!payoutTx.outs[0].script.equals(expectedOut0Script)) {\n throw new Error(\n `Payout transaction output 0 does not pay the expected scriptPubKey for role ${role}`,\n );\n }\n\n const anchorIdx = expectedOutCount - 1;\n if (payoutTx.outs[anchorIdx].value !== PAYOUT_ANCHOR_DUST_SATS) {\n throw new Error(\n `Payout CPFP anchor (out ${anchorIdx}) value ${payoutTx.outs[anchorIdx].value} sats ` +\n `must equal ${PAYOUT_ANCHOR_DUST_SATS} sats`,\n );\n }\n\n if (role === \"vp-claimer\") {\n // Structural guard only — a non-negative integer below the bps\n // denominator, so the cap math `floor(peginValue * bps / 10_000)` is\n // meaningful. The protocol minimum is enforced at the trust boundary\n // (`prepareSigningContext`); a too-low value here is fail-safe.\n if (\n !Number.isInteger(commissionBps) ||\n commissionBps < 0 ||\n commissionBps >= MAX_VP_COMMISSION_BPS_EXCLUSIVE\n ) {\n throw new Error(\n `commissionBps must be an integer in ` +\n `[0, ${MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${commissionBps}`,\n );\n }\n const maxCommissionSats = Math.floor(\n (peginValueSats * commissionBps) / MAX_VP_COMMISSION_BPS_EXCLUSIVE,\n );\n if (payoutTx.outs[1].value > maxCommissionSats) {\n throw new Error(\n `Payout VP commission (out 1) value ${payoutTx.outs[1].value} sats ` +\n `exceeds cap ${maxCommissionSats} sats ` +\n `(${commissionBps} bps of peginValue=${peginValueSats})`,\n );\n }\n }\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters).\n * Payout signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot single-signature script-path witness: [signature, script, controlBlock].\n // Enforce the exact stack size so that if a wallet produces an unexpected\n // finalization (e.g. a multi-signature stack, an annex, or malformed data),\n // we fail loudly instead of silently returning witnessStack[0] which may\n // not be the depositor's signature.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length !== TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE) {\n throw new Error(\n `Unexpected finalized witness stack size at input ${inputIndex}: ` +\n `expected ${TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE} items (signature, script, controlBlock), ` +\n `got ${witnessStack.length}`,\n );\n }\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * Rejects 65-byte signatures because the appended sighash byte changes the\n * Taproot message being signed; stripping it would produce an unverifiable\n * SIGHASH_DEFAULT signature.\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} at input ${inputIndex}. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n *\n * Throws on malformed input (truncated buffer, 8-byte varints, or trailing\n * bytes) so callers never receive silently-corrupted witness items.\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const requireBytes = (n: number): void => {\n if (offset + n > witness.length) {\n throw new Error(\n `Malformed witness data: need ${n} byte(s) at offset ${offset}, only ${witness.length - offset} remaining`,\n );\n }\n };\n\n const readVarInt = (): number => {\n requireBytes(1);\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n requireBytes(2);\n const val = (witness[offset] | (witness[offset + 1] << 8)) >>> 0;\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n requireBytes(4);\n const val =\n (witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24)) >>>\n 0;\n offset += 4;\n return val;\n }\n // 0xff — 8-byte varint. Not used for witness sizes in practice and JS\n // numbers cannot represent all 64-bit values exactly, so reject rather\n // than risk silent truncation.\n throw new Error(\n `Malformed witness data: 8-byte varint (0xff) not supported at offset ${offset - 1}`,\n );\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n requireBytes(len);\n items.push(Buffer.from(witness.subarray(offset, offset + len)));\n offset += len;\n }\n\n if (offset !== witness.length) {\n throw new Error(\n `Malformed witness data: ${witness.length - offset} trailing byte(s) after parsing ${count} item(s)`,\n );\n }\n\n return items;\n}\n\n","/**\n * Asserts a wallet-returned PSBT encodes the same unsigned transaction\n * as the locally-built PSBT we asked the wallet to sign. Per-input PSBT\n * metadata (witnessUtxo, tapLeafScript, sighashType) is intentionally NOT\n * compared — those fields are committed to the Schnorr sighash and the\n * vault provider's `verify_depositor_signature` rejects mismatches there.\n * This primitive defends the path where a colluding VP would otherwise\n * accept a wallet-substituted signature.\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { Psbt } from \"bitcoinjs-lib\";\n\n/**\n * Thrown when a wallet-returned PSBT encodes a different unsigned\n * transaction than the one the caller asked the wallet to sign.\n */\nexport class PsbtSubstitutionError extends Error {\n constructor(detail: string) {\n super(\n `Wallet returned a PSBT for a different transaction: ${detail}`,\n );\n this.name = \"PsbtSubstitutionError\";\n }\n}\n\nexport interface AssertPsbtUnsignedTxMatchesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\nfunction parsePsbt(label: \"requested\" | \"returned\", hex: string): Psbt {\n try {\n return Psbt.fromHex(hex);\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`Failed to parse ${label} PSBT: ${reason}`);\n }\n}\n\n/**\n * Length of the hex prefix included in mismatch errors. Short enough that\n * full prevout txids and output scriptPubKeys never reach logs / error\n * trackers, long enough to disambiguate during forensic triage.\n */\nconst REDACTED_HEX_PREFIX_LEN = 8;\n\nfunction redactHex(buf: Buffer): string {\n return `${buf.toString(\"hex\").slice(0, REDACTED_HEX_PREFIX_LEN)}…`;\n}\n\n/**\n * `bitcoinjs-lib` exposes `txInputs[i].hash` in internal little-endian form;\n * a human reading logs expects the big-endian txid an explorer would show.\n * Reverse before truncating so the surfaced prefix matches what an operator\n * can search for.\n */\nfunction redactTxid(internalHash: Buffer): string {\n const reversed = Buffer.from(internalHash).reverse();\n return redactHex(reversed);\n}\n\n/**\n * Compare two PSBTs and throw `PsbtSubstitutionError` unless they encode\n * the same unsigned transaction (version, locktime, inputs, outputs).\n *\n * @throws PsbtSubstitutionError on any mismatch in the unsigned tx\n * @throws Error if either PSBT cannot be parsed\n */\nexport function assertPsbtUnsignedTxMatches(\n params: AssertPsbtUnsignedTxMatchesParams,\n): void {\n const requested = parsePsbt(\"requested\", params.requestedPsbtHex);\n const returned = parsePsbt(\"returned\", params.returnedPsbtHex);\n\n if (requested.version !== returned.version) {\n throw new PsbtSubstitutionError(\n `tx version differs (requested=${requested.version}, returned=${returned.version})`,\n );\n }\n if (requested.locktime !== returned.locktime) {\n throw new PsbtSubstitutionError(\n `tx locktime differs (requested=${requested.locktime}, returned=${returned.locktime})`,\n );\n }\n if (requested.txInputs.length !== returned.txInputs.length) {\n throw new PsbtSubstitutionError(\n `input count differs (requested=${requested.txInputs.length}, returned=${returned.txInputs.length})`,\n );\n }\n if (requested.txOutputs.length !== returned.txOutputs.length) {\n throw new PsbtSubstitutionError(\n `output count differs (requested=${requested.txOutputs.length}, returned=${returned.txOutputs.length})`,\n );\n }\n for (let i = 0; i < requested.txInputs.length; i++) {\n const r = requested.txInputs[i];\n const s = returned.txInputs[i];\n if (!r.hash.equals(s.hash)) {\n throw new PsbtSubstitutionError(\n `input ${i} prevout txid differs (requested=${redactTxid(r.hash)}, returned=${redactTxid(s.hash)})`,\n );\n }\n if (r.index !== s.index) {\n throw new PsbtSubstitutionError(\n `input ${i} prevout vout differs (requested=${r.index}, returned=${s.index})`,\n );\n }\n if (r.sequence !== s.sequence) {\n throw new PsbtSubstitutionError(\n `input ${i} sequence differs (requested=${r.sequence}, returned=${s.sequence})`,\n );\n }\n }\n for (let i = 0; i < requested.txOutputs.length; i++) {\n const r = requested.txOutputs[i];\n const s = returned.txOutputs[i];\n if (!r.script.equals(s.script)) {\n throw new PsbtSubstitutionError(\n `output ${i} scriptPubKey differs (requested=${redactHex(r.script)}, returned=${redactHex(s.script)})`,\n );\n }\n if (r.value !== s.value) {\n throw new PsbtSubstitutionError(\n `output ${i} value differs (requested=${r.value}, returned=${s.value})`,\n );\n }\n }\n}\n"],"names":["AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","createPayoutScript","connector","createPayoutConnector","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","PAYOUT_ANCHOR_DUST_SATS","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","MAX_VP_COMMISSION_BPS_EXCLUSIVE","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","MAX_PAYOUT_FEE_FRACTION_NUMERATOR","MAX_PAYOUT_FEE_FRACTION_DENOMINATOR","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","assertTxid","peginPrevOut","input1PrevOut","assertPayoutOutputLayout","inputValueSats","outputValueSats","out","implicitFeeSats","maxFeeSats","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","args","peginValueSats","claimerBtcPubkey","vaultProviderBtcPubkey","depositorBtcPubkey","vaultKeeperBtcPubkeys","registeredPayoutScriptPubKey","commissionBps","isValidHex","claimer","vp","dep","keepers","k","role","expectedOutCount","expectedOut0ScriptHex","deriveBip86ScriptPubKeyHex","expectedOut0Script","anchorIdx","maxCommissionSats","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","witness","items","offset","requireBytes","n","readVarInt","first","val","count","i","len","PsbtSubstitutionError","detail","parsePsbt","label","hex","cause","reason","REDACTED_HEX_PREFIX_LEN","redactHex","buf","redactTxid","internalHash","reversed","assertPsbtUnsignedTxMatches","requested","returned","r"],"mappings":"0MAkEMA,EAA2B,GAE3BC,EAAc,iBA2EpB,eAAsBC,EACpBC,EAC6B,CAC7B,MAAMC,EAAiBC,EAAwBF,EAAO,cAAc,EAE9DG,EAAS,MAAMC,4BAA0B,CAC7C,gBAAiBJ,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,UAAW,CAAC,GAAGA,EAAO,SAAS,EAC/B,eAAgBA,EAAO,eACvB,aAAc,CAAC,GAAGA,EAAO,YAAY,EACrC,QAASA,EAAO,QACh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,GAAA,EAGxG,QAASjB,EAAI,EAAGA,EAAIgB,EAAU,SAAS,OAAQhB,IAAK,CAClD,MAAMkB,EAAIF,EAAU,SAAShB,CAAC,EACxB,EAAIiB,EAAS,SAASjB,CAAC,EAC7B,GAAI,CAACkB,EAAE,KAAK,OAAO,EAAE,IAAI,EACvB,MAAM,IAAIhB,EACR,SAASF,CAAC,oCAAoCY,EAAWM,EAAE,IAAI,CAAC,cAAcN,EAAW,EAAE,IAAI,CAAC,GAAA,EAGpG,GAAIM,EAAE,QAAU,EAAE,MAChB,MAAM,IAAIhB,EACR,SAASF,CAAC,oCAAoCkB,EAAE,KAAK,cAAc,EAAE,KAAK,GAAA,EAG9E,GAAIA,EAAE,WAAa,EAAE,SACnB,MAAM,IAAIhB,EACR,SAASF,CAAC,gCAAgCkB,EAAE,QAAQ,cAAc,EAAE,QAAQ,GAAA,CAGlF,CACA,QAASlB,EAAI,EAAGA,EAAIgB,EAAU,UAAU,OAAQhB,IAAK,CACnD,MAAMkB,EAAIF,EAAU,UAAUhB,CAAC,EACzB,EAAIiB,EAAS,UAAUjB,CAAC,EAC9B,GAAI,CAACkB,EAAE,OAAO,OAAO,EAAE,MAAM,EAC3B,MAAM,IAAIhB,EACR,UAAUF,CAAC,oCAAoCU,EAAUQ,EAAE,MAAM,CAAC,cAAcR,EAAU,EAAE,MAAM,CAAC,GAAA,EAGvG,GAAIQ,EAAE,QAAU,EAAE,MAChB,MAAM,IAAIhB,EACR,UAAUF,CAAC,6BAA6BkB,EAAE,KAAK,cAAc,EAAE,KAAK,GAAA,CAG1E,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var Y=Object.defineProperty;var Z=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var A=(e,t,r)=>Z(e,typeof t!="symbol"?t+"":t,r);const J=require("./BTCVaultRegistry.abi-CHFGevwa.cjs"),d=require("./bitcoin-CHfKAhcI.cjs"),O=require("./PayoutManager-DnKRzWWb.cjs"),P=require("./types-eYlq0p1o.cjs"),S=require("bitcoinjs-lib"),v=require("./assertPsbtUnsignedTxMatches-u9yeeUFY.cjs"),V=require("./noPayout-CtmOEauj.cjs"),I=require("./signing-Bnsro0hE.cjs"),ee=/^0x[0-9a-fA-F]{64}$/,te=/^0x[0-9a-fA-F]{40}$/,re=/^0x([0-9a-fA-F]{2})*$/;function C(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!ee.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function ne(e,t){if(!te.test(e))throw new Error(`${t} must be a 20-byte 0x-prefixed hex address (42 chars)`)}function oe(e,t){if(!re.test(e))throw new Error(`${t} must be a 0x-prefixed hex string with an even number of hex chars`)}async function se(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,activationMetadata:s,writeContract:u,signal:i}=e;i==null||i.throwIfAborted(),ne(t,"btcVaultRegistryAddress"),C(r,"vaultId");const a=d.ensureHexPrefix(e.secret);if(C(a,"secret"),n!==void 0&&(C(n,"hashlock"),!O.validateSecretAgainstHashlock(a,n)))throw new Error("Invalid secret: SHA256(secret) does not match the provided hashlock");return oe(s,"activationMetadata"),u({address:t,abi:J.BTCVaultRegistryABI,functionName:"activateVaultWithSecret",args:[r,a,s]})}const ie=1e4;async function D(e){const{statusReader:t,peginTxid:r,targetStatuses:n,timeoutMs:s,pollIntervalMs:u=ie,signal:i}=e,a=Date.now();for(;;){if(i!=null&&i.aborted)throw new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);if(Date.now()-a>=s)throw new Error(`Polling timeout after ${s}ms for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);try{const o=await t.getPeginStatus({pegin_txid:r},i);if(o.pegin_txid.toLowerCase()!==r.toLowerCase())throw new Error(`getPeginStatus returned status for pegin ${o.pegin_txid.slice(0,8)}…, requested ${r.slice(0,8)}…`);const l=o.status;if(n.has(l)||l===P.DaemonStatus.ACTIVATED)return l;if(l===P.DaemonStatus.EXPIRED||P.VP_TERMINAL_FAILURE_STATUSES.has(l))throw new Error(`Pegin ${r.slice(0,8)}… reached terminal status "${l}" while waiting for ${[...n].join(", ")}`)}catch(o){if(!(o instanceof P.JsonRpcError&&o.code===P.RpcErrorCode.PEGIN_NOT_FOUND))throw o}await new Promise((o,l)=>{const p=()=>{clearTimeout(c),l(new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`))},c=setTimeout(()=>{i==null||i.removeEventListener("abort",p),o()},u);i==null||i.addEventListener("abort",p,{once:!0})})}}const ae=300*1e3,ue=new Set([P.DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,...P.POST_WOTS_STATUSES]);async function le(e){const{statusReader:t,wotsSubmitter:r,peginTxid:n,depositorPk:s,wotsPublicKeys:u,timeoutMs:i=ae,signal:a}=e;a==null||a.throwIfAborted();const o=await D({statusReader:t,peginTxid:n,targetStatuses:ue,timeoutMs:i,signal:a});P.POST_WOTS_STATUSES.has(o)||(a==null||a.throwIfAborted(),await r.submitDepositorWotsKey({pegin_txid:n,depositor_pk:s,wots_public_keys:u},a))}const F=1,ce=1;function de(e,t){const r=d.stripHexPrefix(t).toLowerCase(),s=e.map(u=>d.stripHexPrefix(u).toLowerCase()).filter(u=>u!==r);if(s.length===0)throw new Error("Cannot derive localChallengers: vault keeper set is empty (or contains only the depositor)");if(new Set(s).size!==s.length)throw new Error("Cannot derive localChallengers: duplicate vaultKeeper key — signing context is misconfigured");return s}function pe(e,t,r){const n=r.map(c=>d.stripHexPrefix(c).toLowerCase()),s=t.filter(c=>n.includes(c));if(s.length>0)throw new Error(`Cannot validate challenger set: vault keepers and universal challengers overlap (${s.join(", ")})`);const u=[...t,...n],i=e.map(c=>d.stripHexPrefix(c.challenger_pubkey).toLowerCase()),a=new Set(i);if(a.size!==i.length)throw new Error("Depositor graph contains duplicate challenger entries in challenger_presign_data");const o=new Set(u),l=u.filter(c=>!a.has(c)),p=i.filter(c=>!o.has(c));if(l.length>0||p.length>0)throw new Error("Depositor graph challenger set does not match expected (local ∪ universal)"+(l.length>0?` (missing: ${l.join(", ")})`:"")+(p.length>0?` (unexpected: ${p.join(", ")})`:""))}function he(e,t){const r=e.ins[t];return d.uint8ArrayToHex(new Uint8Array(r.hash).slice().reverse())}function B(e,t,r,n,s){const u=e.ins[t];if(u.index!==0)throw new Error(`NoPayout (challenger ${s}) input ${t} expected to spend ${n} vout 0, got vout ${u.index}`);const i=r.getId(),a=he(e,t);if(a!==i)throw new Error(`NoPayout (challenger ${s}) input ${t} does not reference ${n} (expected txid ${i}, got ${a})`)}async function fe(e,t,r){const n=[],s=[],u=[],i=de(r.vaultKeeperBtcPubkeys,r.depositorBtcPubkey);pe(e.challenger_presign_data,i,r.universalChallengerBtcPubkeys);const a=await v.buildPayoutPsbt({payoutTxHex:e.payout_tx.tx_hex,peginTxHex:r.peginTxHex,assertTxHex:e.assert_tx.tx_hex,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:r.network,claimerBtcPubkey:r.depositorBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:ce});n.push(a.psbtHex),s.push(I.createTaprootScriptPathSignOptions(t,F));const o=d.stripHexPrefix(r.depositorBtcPubkey),l=S.Transaction.fromHex(d.stripHexPrefix(e.assert_tx.tx_hex));for(const p of e.challenger_presign_data){const c=d.stripHexPrefix(p.challenger_pubkey),h=n.length,y=await ge({challenger:p,challengerPubkey:c,claimerPubkey:o,localChallengers:i,assertTxParsed:l,ctx:r});n.push(y),s.push(I.createTaprootScriptPathSignOptions(t,F)),u.push({challengerPubkey:c,noPayoutIdx:h})}return{psbtHexes:n,signOptions:s,challengerEntries:u}}async function ge(e){const{challenger:t,challengerPubkey:r,claimerPubkey:n,localChallengers:s,assertTxParsed:u,ctx:i}=e;V.assertNoPayoutOutputMatchesChallenger(t.nopayout_tx.tx_hex,r,i.network);const a=S.Transaction.fromHex(d.stripHexPrefix(t.nopayout_tx.tx_hex)),o=S.Transaction.fromHex(d.stripHexPrefix(t.challenge_assert_x_tx.tx_hex)),l=S.Transaction.fromHex(d.stripHexPrefix(t.challenge_assert_y_tx.tx_hex));if(a.ins.length!==3)throw new Error(`NoPayout (challenger ${r}) must have exactly 3 inputs, got ${a.ins.length}`);B(a,0,u,"Assert",r),B(a,1,o,"ChallengeAssertX",r),B(a,2,l,"ChallengeAssertY",r);const p=[u.outs[0],o.outs[0],l.outs[0]].map(c=>({script_pubkey:d.uint8ArrayToHex(new Uint8Array(c.script)),value:c.value}));return V.buildNoPayoutPsbt({noPayoutTxHex:t.nopayout_tx.tx_hex,challengerPubkey:r,prevouts:p,connectorParams:{claimer:n,localChallengers:s,universalChallengers:i.universalChallengerBtcPubkeys,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum}})}function Pe(e,t,r){v.assertPsbtUnsignedTxMatches(e[0]);const n=v.extractPayoutSignature(e[0].returnedPsbtHex,r),s={};for(const u of t)v.assertPsbtUnsignedTxMatches(e[u.noPayoutIdx]),s[u.challengerPubkey]={nopayout_signature:v.extractPayoutSignature(e[u.noPayoutIdx].returnedPsbtHex,r)};return{payout_signatures:{payout_signature:n},per_challenger:s}}async function ye(e,t,r){if(typeof e.signPsbts=="function")return e.signPsbts(t,r);const n=[];for(let s=0;s<t.length;s++)n.push(await e.signPsbt(t[s],r==null?void 0:r[s]));return n}async function X(e){const{depositorGraph:t,btcWallet:r,signingContext:n}=e,s=await r.getPublicKeyHex(),{depositorPubkey:u}=d.validateWalletPubkey(s,d.stripHexPrefix(n.depositorBtcPubkey)),{psbtHexes:i,signOptions:a,challengerEntries:o}=await fe(t,s,n),l=await ye(r,i,a);if(l.length!==i.length)throw new Error(`Wallet returned ${l.length} signed PSBTs, expected ${i.length}`);const p=i.map((c,h)=>({requestedPsbtHex:c,returnedPsbtHex:l[h]}));return Pe(p,o,u)}const me=1200*1e3,z=new Set([P.DaemonStatus.PENDING_ACKS,P.DaemonStatus.PENDING_ACTIVATION,P.DaemonStatus.ACTIVATED_PENDING_BROADCAST,P.DaemonStatus.ACTIVATED]),xe=new Set([P.DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,...z]);function be(e){return e.map(t=>({claimerPubkeyXOnly:d.processPublicKeyToXOnly(t.claimer_pubkey),payoutTxHex:t.payout_tx.tx_hex,assertTxHex:t.assert_tx.tx_hex}))}function w(e){return d.processPublicKeyToXOnly(e).toLowerCase()}function ve(e,t,r,n){const s=w(n),u=[w(t),...r.map(w)],i=new Set(u);if(i.size!==u.length)throw new Error("Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key");if(i.has(s))throw new Error("Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set");const a=e.map(h=>w(h.claimer_pubkey));if(new Set(a).size!==a.length)throw new Error("Presign response contains duplicate claimer entries");const o=a.filter(h=>h!==s),l=new Set(o),p=u.filter(h=>!l.has(h)),c=o.filter(h=>!i.has(h));if(p.length>0||c.length>0)throw new Error("Presign response claimer set does not match expected (vault provider ∪ vault keepers)"+(p.length>0?` (missing: ${p.join(", ")})`:"")+(c.length>0?` (unexpected: ${c.join(", ")})`:""))}function L(e,t){return{payoutTxHex:e.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:e.assertTxHex,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,depositorBtcPubkey:t.depositorBtcPubkey,timelockPegin:t.timelockPegin,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,claimerBtcPubkey:e.claimerPubkeyXOnly,commissionBps:t.commissionBps}}async function we(e,t,r,n){const s=new O.PayoutManager({network:t.network,btcWallet:e}),u=r.length;n==null||n(0,u);let i;if(s.supportsBatchSigning())i=(await s.signPayoutTransactionsBatch(r.map(l=>L(l,t)))).map(l=>l.payoutSignature);else{i=[];for(let o=0;o<r.length;o++){n==null||n(o,u);const l=await s.signPayoutTransaction(L(r[o],t));i.push(l.signature)}}const a={};for(let o=0;o<r.length;o++)a[r[o].claimerPubkeyXOnly]={payout_signature:i[o]};return n==null||n(u,u),a}async function Te(e){const{statusReader:t,presignClient:r,btcWallet:n,peginTxid:s,depositorPk:u,signingContext:i,timeoutMs:a=me,signal:o,onProgress:l}=e,p=await D({statusReader:t,peginTxid:s,targetStatuses:xe,timeoutMs:a,signal:o});if(z.has(p))return;o==null||o.throwIfAborted();const c=await r.requestDepositorPresignTransactions({pegin_txid:s,depositor_pk:u},o);o==null||o.throwIfAborted();const h=w(u);ve(c.txs,i.vaultProviderBtcPubkey,i.vaultKeeperBtcPubkeys,u);const y=c.txs.filter(b=>w(b.claimer_pubkey)!==h),x=be(y),g=await we(n,i,x,l);o==null||o.throwIfAborted();const T=await X({depositorGraph:c.depositor_graph,btcWallet:n,signingContext:{peginTxHex:i.peginTxHex,depositorBtcPubkey:u,vaultProviderBtcPubkey:i.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:i.universalChallengerBtcPubkeys,timelockPegin:i.timelockPegin,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum,network:i.network,registeredPayoutScriptPubKey:i.registeredPayoutScriptPubKey}});o==null||o.throwIfAborted();const m={...g};m[d.stripHexPrefix(u)]=T.payout_signatures,await r.submitDepositorPresignatures({pegin_txid:s,depositor_pk:u,signatures:m,depositor_claimer_presignatures:T},o)}function Ee(e){return/^[0-9a-fA-F]{64}$/.test(e)}function _e(e){const{amountSats:t,minDeposit:r,maxDeposit:n,btcBalance:s,estimatedFeeSats:u,depositorClaimValue:i}=e;return!(t<=0n||t<r||n&&n>0n&&t>n||u==null||i==null||t+u+i>s)}function Se(e,t,r){return e<=0n?{valid:!1,error:"Deposit amount must be greater than zero"}:e<t?{valid:!1,error:`Minimum deposit is ${d.formatSatoshisToBtc(t)} BTC`}:r&&r>0n&&e>r?{valid:!1,error:`Maximum deposit is ${d.formatSatoshisToBtc(r)} BTC`}:{valid:!0}}function ke(e){const{amount:t,effectiveRemaining:r}=e;return r===null?{valid:!0}:r===0n?{valid:!1,error:"Supply cap reached — deposits temporarily paused"}:t>r?{valid:!1,error:`Vault size exceeds remaining capacity (${d.formatSatoshisToBtc(r)} BTC)`}:{valid:!0}}function Ae(e,t){if(!e||e.length===0)return{valid:!1,error:"At least one vault provider must be selected"};const r=t.map(s=>s.toLowerCase());return e.filter(s=>!r.includes(s.toLowerCase())).length>0?{valid:!1,error:"Invalid vault provider selected"}:{valid:!0}}function q(e,t,r){if(!e||e.length===0)return{valid:!1,error:"At least one vault amount required"};for(let n=0;n<e.length;n++){const s=e[n];if(s<=0n)return{valid:!1,error:`Vault ${n+1} amount must be positive`};if(t&&s<t)return{valid:!1,error:`Vault ${n+1} amount ${d.formatSatoshisToBtc(s)} BTC is below minimum deposit ${d.formatSatoshisToBtc(t)} BTC`};if(r&&s>r)return{valid:!1,error:`Vault ${n+1} amount ${d.formatSatoshisToBtc(s)} BTC exceeds maximum deposit ${d.formatSatoshisToBtc(r)} BTC`}}return{valid:!0}}function G(e){const t=d.stripHexPrefix(e);return Ee(t)?{valid:!0}:{valid:!1,error:"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"}}function Ce(e){if(!e||e.length===0)throw new Error("No vault keepers available. The system requires at least one vault keeper to create a deposit.")}function Be(e){if(!e||e.length===0)throw new Error("No universal challengers available. The system requires at least one universal challenger to create a deposit.")}function Re(e){if(e.length===0)throw new Error("No spendable UTXOs available")}function Ve(e){const{vaultAmounts:t,confirmedUTXOs:r,vaultProviderBtcPubkey:n,vaultKeeperBtcPubkeys:s,universalChallengerBtcPubkeys:u,minDeposit:i,maxDeposit:a}=e,o=q(t,i,a);if(!o.valid)throw new Error(o.error);const l=G(n);if(!l.valid)throw new Error(l.error);Ce(s),Be(u),Re(r)}async function Ie(e){const{vaultRegistryReader:t,vaultKeeperReader:r,universalChallengerReader:n,vaultProviderEthAddress:s,applicationEntryPoint:u,expectedVaultProviderBtcPubkey:i,expectedVaultKeeperBtcPubkeys:a,expectedUniversalChallengerBtcPubkeys:o}=e,[l,p,c]=await Promise.all([t.getVaultProviderBtcPubKey(s),r.getCurrentVaultKeepersVersion(u),n.getLatestUniversalChallengersVersion()]),[h,y]=await Promise.all([r.getVaultKeepersByVersion(u,p),n.getUniversalChallengersByVersion(c)]),x=f=>d.processPublicKeyToXOnly(f).toLowerCase(),g=f=>f.map(x).sort();if(x(i)!==l)throw new Error(`Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${s}. Refresh and try again.`);const m=g(a),b=g(h.map(f=>f.btcPubKey));if(m.length!==b.length||m.some((f,k)=>f!==b[k]))throw new Error(`Vault keeper BTC pubkeys (v${p}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`);const E=g(o),_=g(y.map(f=>f.btcPubKey));if(E.length!==_.length||E.some((f,k)=>f!==_[k]))throw new Error(`Universal challenger BTC pubkeys (v${c}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`);return{vaultProviderBtcPubkeyXOnly:l,vaultKeeperBtcPubkeysSorted:b,universalChallengerBtcPubkeysSorted:_,expectedAppVaultKeepersVersion:p,expectedUniversalChallengersVersion:c}}class M extends Error{constructor(t){super(t),this.name="RegisteredVaultVersionMismatchError"}}function $e(e){return e instanceof M||e instanceof Error&&e.name==="RegisteredVaultVersionMismatchError"}async function He(e){const{vaultRegistryReader:t,vaultIds:r,expectedOffchainParamsVersion:n,expectedAppVaultKeepersVersion:s,expectedUniversalChallengersVersion:u}=e,i=await t.getProtocolInfoBatch(r),a=[];if(i.forEach((o,l)=>{const p=r[l];o.offchainParamsVersion!==n&&a.push(`vault ${p}: offchainParams expected v${n}, got v${o.offchainParamsVersion}`),o.appVaultKeepersVersion!==s&&a.push(`vault ${p}: appVaultKeepers expected v${s}, got v${o.appVaultKeepersVersion}`),o.universalChallengersVersion!==u&&a.push(`vault ${p}: universalChallengers expected v${u}, got v${o.universalChallengersVersion}`)}),a.length>0)throw new M(`Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${a.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}var K=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_BROADCAST="PayoutBroadcast",e.PAYOUT_BLOCKED="PayoutBlocked",e))(K||{});const Ne=new Set(["PayoutBroadcast","PayoutBlocked"]);function Oe(e){return Object.values(K).includes(e)}function De(e){return!!e&&Ne.has(e)}class W extends Error{constructor(r,n){super(`Refund not yet mature (BIP68 not final): ${n.message}`);A(this,"vaultId");A(this,"cause");this.name="BIP68NotMatureError",this.vaultId=r,this.cause=n}}const Me=/^0x[0-9a-fA-F]{64}$/,Ke=/^(?:0x)?(?:[0-9a-fA-F]{2})+$/,j=/^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/,U=160,$=2e3,H=10n,N=100n;function Ue(e){if(!Number.isFinite(e)||e<=0)throw new Error(`feeRateSatsVb must be a positive finite number, got ${e}`);return BigInt(Math.ceil(e*U))}const Fe=1,Le=/non-BIP68-final/i;function Q(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!Me.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function R(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer, got ${e}`)}function Xe(e){if(Q(e.hashlock,"hashlock"),!Number.isInteger(e.htlcVout)||e.htlcVout!==0)throw new Error(`Multi-vault Pre-PegIn refund is not supported by this SDK call (htlcVout=${e.htlcVout}, expected 0). Refund of batched-deposit vaults requires reconstructing all sibling HTLCs.`);if(R(e.offchainParamsVersion,"offchainParamsVersion"),R(e.appVaultKeepersVersion,"appVaultKeepersVersion"),R(e.universalChallengersVersion,"universalChallengersVersion"),typeof e.unsignedPrePeginTxHex!="string"||e.unsignedPrePeginTxHex.length===0)throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");if(!Ke.test(e.unsignedPrePeginTxHex))throw new Error("unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)");if(!e.depositorBtcPubkey||!j.test(e.depositorBtcPubkey))throw new Error("depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)");if(typeof e.amount!="bigint"||e.amount<=0n)throw new Error(`amount must be a positive bigint, got ${e.amount}`)}function ze(e){if(!e.vaultProviderPubkey||!j.test(e.vaultProviderPubkey))throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");if(e.vaultKeeperPubkeys.length===0)throw new Error("vaultKeeperPubkeys must be non-empty");if(e.universalChallengerPubkeys.length===0)throw new Error("universalChallengerPubkeys must be non-empty");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<=0)throw new Error(`timelockRefund must be a positive integer, got ${e.timelockRefund}`);if(typeof e.feeRate!="bigint"||e.feeRate<=0n)throw new Error(`protocol feeRate must be a positive bigint, got ${e.feeRate}`);if(!Number.isInteger(e.numLocalChallengers)||e.numLocalChallengers<0)throw new Error("numLocalChallengers must be a non-negative integer");if(!Number.isInteger(e.councilQuorum)||!Number.isInteger(e.councilSize)||e.councilQuorum<=0||e.councilSize<=0||e.councilQuorum>e.councilSize)throw new Error(`councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`)}function qe(e){const t=S.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(r){const n=r instanceof Error?r.message:String(r);if(!n.includes("already finalized"))throw new Error(`Failed to finalize refund PSBT: ${n}`)}return t.extractTransaction().toHex()}async function Ge(e){const{vaultId:t,readVault:r,readPrePeginContext:n,feeRate:s,signPsbt:u,broadcastTx:i,signal:a}=e;a==null||a.throwIfAborted(),Q(t,"vaultId");const o=await r();Xe(o),a==null||a.throwIfAborted();const l=await n(o);if(ze(l),a==null||a.throwIfAborted(),!Number.isFinite(s)||s<=0)throw new Error(`feeRate must be a positive number, got ${s}`);if(s>$)throw new Error(`feeRate ${s} sat/vB exceeds refund safety cap ${$} sat/vB; refusing to sign refund.`);const p=BigInt(Math.ceil(s*U)),c=o.amount*H/N;if(p>c)throw new Error(`Refund fee ${p} sats exceeds the per-vault safety cap of ${c} sats (${H}/${N} of vault.amount=${o.amount}); refusing to sign refund.`);a==null||a.throwIfAborted();const h=d.processPublicKeyToXOnly(o.depositorBtcPubkey),y=d.stripHexPrefix(o.unsignedPrePeginTxHex),x=1,g=O.findAuthAnchorOpReturn(y);if(g!==void 0&&g.vout!==x)throw new Error(`Multi-vault Pre-PegIn refund is not supported by this SDK call (auth-anchor OP_RETURN at vout ${g.vout}; single-vault refund expects vout ${x}). Refund of batched-deposit vaults requires reconstructing all sibling HTLCs.`);const T=g==null?void 0:g.hash,{psbtHex:m}=await V.buildRefundPsbt({prePeginParams:{depositorPubkey:h,vaultProviderPubkey:d.stripHexPrefix(l.vaultProviderPubkey),vaultKeeperPubkeys:l.vaultKeeperPubkeys.map(d.stripHexPrefix),universalChallengerPubkeys:l.universalChallengerPubkeys.map(d.stripHexPrefix),hashlocks:[d.stripHexPrefix(o.hashlock)],timelockRefund:l.timelockRefund,pegInAmounts:[o.amount],feeRate:l.feeRate,numLocalChallengers:l.numLocalChallengers,councilQuorum:l.councilQuorum,councilSize:l.councilSize,network:l.network,authAnchorHash:T},fundedPrePeginTxHex:y,htlcVout:o.htlcVout,refundFee:p,hashlock:d.stripHexPrefix(o.hashlock)});a==null||a.throwIfAborted();const b=I.createTaprootScriptPathSignOptions(o.depositorBtcPubkey,Fe),E=await u(m,b);v.assertPsbtUnsignedTxMatches({requestedPsbtHex:m,returnedPsbtHex:E});const _=qe(E);a==null||a.throwIfAborted();try{return await i(_)}catch(f){throw f instanceof Error&&Le.test(f.message)?new W(t,f):f}}exports.BIP68NotMatureError=W;exports.ClaimerPegoutStatusValue=K;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=N;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=H;exports.REFUND_MAX_FEE_RATE_SATS_VB=$;exports.REFUND_VSIZE=U;exports.RegisteredVaultVersionMismatchError=M;exports.activateVault=se;exports.buildAndBroadcastRefund=Ge;exports.estimateRefundFeeSats=Ue;exports.isDepositAmountValid=_e;exports.isPegoutTerminalStatus=De;exports.isRecognizedPegoutStatus=Oe;exports.isRegisteredVaultVersionMismatchError=$e;exports.runDepositorPresignFlow=Te;exports.signDepositorGraph=X;exports.submitWotsPublicKey=le;exports.validateDepositAmount=Se;exports.validateMultiVaultDepositInputs=Ve;exports.validateOnChainParticipantKeys=Ie;exports.validateProviderSelection=Ae;exports.validateRemainingCapacity=ke;exports.validateVaultAmounts=q;exports.validateVaultProviderPubkey=G;exports.verifyRegisteredVaultVersions=He;exports.waitForPeginStatus=D;
|
|
2
|
-
//# sourceMappingURL=buildAndBroadcastRefund-MoSpjUKJ.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mempoolApi-CAIge7Nj.js","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the 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":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":";AAmBA,MAAMA,IAAe,OAAa,KAG5BC,IAA6B;AAMnC,eAAeC,EACbC,GACAC,GACmB;AACnB,QAAMC,IAAa,IAAI,gBAAA,GACjBC,IAAY;AAAA,IAChB,MAAMD,EAAW,MAAA;AAAA,IACjBJ;AAAA,EAAA,GAIIM,IAAU,CAACF,EAAW,QAAQD,KAAA,gBAAAA,EAAS,MAAM,EAAE;AAAA,IACnD;AAAA,EAAA;AAGF,MAAI;AAEF,WAAO,MAAM,MAAMD,GAAK;AAAA,MACtB,GAAGC;AAAA,MACH,QAAQ,YAAY,IAAIG,CAAO;AAAA,IAAA,CAChC;AAAA,EACH,SAASC,GAAO;AAEd,UADA,aAAaF,CAAS,GAEpBE,KAAS,QACT,OAAOA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ACZ,UAAM,IAAI;AAAA,MACR,iCAAiCA,EAAS,MAAM,IAAIA,EAAS,UAAU;AAAA,IAAA;AAI3E,QAAMsB,IAAO,MAAMtB,EAAS,KAAA,GAEtBuB,IAAY;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,aAAWC,KAASD;AAClB,QAAI,CAACzC,EAAewC,EAAKE,CAAK,CAAC;AAC7B,YAAM,IAAI;AAAA,QACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmD7C,CAAY;AAAA,MAAA;AAK7G,MACE2C,EAAK,aAAaA,EAAK,cACvBA,EAAK,aAAaA,EAAK,WACvBA,EAAK,UAAUA,EAAK,eACpBA,EAAK,cAAcA,EAAK;AAExB,UAAM,IAAI;AAAA,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const a=require("./validation-u8W7Lp2x.cjs"),F=21e6*1e8,l=3e4;async function c(e,r){const t=new AbortController,n=setTimeout(()=>t.abort(),l),s=[t.signal,r==null?void 0:r.signal].filter(Boolean);try{return await fetch(e,{...r,signal:AbortSignal.any(s)})}catch(o){throw clearTimeout(n),o!=null&&typeof o=="object"&&"name"in o&&o.name==="AbortError"?new Error(`Mempool API request timed out after ${l}ms: ${e}`):o}}const w=1e4;function m(e){return Number.isInteger(e)&&e>0&&e<=F}function g(e){return Number.isInteger(e)&&e>0&&e<=w}function h(e,r){return!Number.isInteger(e)||e<0?!1:r===void 0||e<r}function f(e){if(!a.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function d(e){if(!a.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function $(e,r){if(!a.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${r}`);if(!a.KNOWN_SCRIPT_PREFIXES.some(n=>e.toLowerCase().startsWith(n)))throw new Error(`Unrecognized scriptPubKey type for ${r}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const p={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function i(e,r){try{const t=await c(e,r);if(!t.ok){const s=await t.text();throw new Error(`Mempool API error (${t.status}): ${s||t.statusText}`)}const n=t.headers.get("content-type");return n!=null&&n.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function I(e,r){try{const t=await c(`${r}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!t.ok){const s=await t.text();let o;try{o=JSON.parse(s).message}catch{o=s}throw new Error(o||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function E(e,r){return f(e),i(`${r}/tx/${e}`)}async function T(e,r){f(e);try{const t=await c(`${r}/tx/${e}/hex`);if(!t.ok){const n=await t.text();throw new Error(`Mempool API error (${t.status}): ${n||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${t.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function x(e,r,t){f(e);const n=await E(e,t);if(!h(r,n.vout.length))throw new Error(`Invalid vout ${r} for transaction ${e} (has ${n.vout.length} outputs)`);const s=n.vout[r];if(!m(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${e}:${r}`);return $(s.scriptpubkey,`${e}:${r}`),{txid:e,vout:r,value:s.value,scriptPubKey:s.scriptpubkey}}async function y(e,r){d(e);try{const t=await i(`${r}/address/${e}/utxo`),n=await i(`${r}/v1/validate-address/${e}`);if(!n.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);$(n.scriptPubKey,e);for(const o of t){if(f(o.txid),!h(o.vout))throw new Error(`Invalid vout ${o.vout} for ${o.txid}`);if(!m(o.value))throw new Error(`Invalid UTXO value ${o.value} for ${o.txid}:${o.vout}`)}return t.sort((o,u)=>u.value-o.value).map(o=>({txid:o.txid,vout:o.vout,value:o.value,scriptPubKey:n.scriptPubKey,confirmed:o.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${t.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function v(e){return p[e]}async function A(e,r){return d(e),i(`${r}/address/${e}/txs`)}async function P(e){const r=await c(`${e}/v1/fees/recommended`);if(!r.ok)throw new Error(`Failed to fetch network fees: ${r.status} ${r.statusText}`);const t=await r.json(),n=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const s of n)if(!g(t[s]))throw new Error(`Invalid fee rate ${s}=${t[s]} from mempool API: expected a positive number ≤ ${w}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}exports.MEMPOOL_API_URLS=p;exports.getAddressTxs=A;exports.getAddressUtxos=y;exports.getMempoolApiUrl=v;exports.getNetworkFees=P;exports.getTxHex=T;exports.getTxInfo=E;exports.getUtxoInfo=x;exports.pushTx=I;
|
|
2
|
-
//# sourceMappingURL=mempoolApi-YNkKjQCU.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mempoolApi-YNkKjQCU.cjs","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the 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":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"0DAmBMA,EAAe,KAAa,IAG5BC,EAA6B,IAMnC,eAAeC,EACbC,EACAC,EACmB,CACnB,MAAMC,EAAa,IAAI,gBACjBC,EAAY,WAChB,IAAMD,EAAW,MAAA,EACjBJ,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uB,EAAY,CAChB,aACA,cACA,UACA,aACA,YAAA,EAGF,UAAWC,KAASD,EAClB,GAAI,CAACzC,EAAewC,EAAKE,CAAK,CAAC,EAC7B,MAAM,IAAI,MACR,oBAAoBA,CAAK,IAAIF,EAAKE,CAAK,CAAC,mDAAmD7C,CAAY,EAAA,EAK7G,GACE2C,EAAK,WAAaA,EAAK,YACvBA,EAAK,WAAaA,EAAK,SACvBA,EAAK,QAAUA,EAAK,aACpBA,EAAK,YAAcA,EAAK,WAExB,MAAM,IAAI,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU,IAAA,EAIpC,OAAOA,CACT"}
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
import { initWasm as A, WasmPrePeginTx as R, getPrePeginHtlcConnectorInfo as B, tapInternalPubkey as T, getAssertNoPayoutScriptInfo as C } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
2
|
-
import { Buffer as u } from "buffer";
|
|
3
|
-
import { Transaction as x, Psbt as H, payments as E } from "bitcoinjs-lib";
|
|
4
|
-
import { u as S, T as I, h as p, s as g, p as $, j as N } from "./bitcoin-B5aNKtsk.js";
|
|
5
|
-
import { n as K } from "./assertPsbtUnsignedTxMatches-CsawQGjC.js";
|
|
6
|
-
async function F(r) {
|
|
7
|
-
await A();
|
|
8
|
-
const { prePeginParams: e, fundedPrePeginTxHex: o, htlcVout: n, refundFee: f, hashlock: i } = r, y = K(
|
|
9
|
-
e.authAnchorHash
|
|
10
|
-
), s = new R(
|
|
11
|
-
e.depositorPubkey,
|
|
12
|
-
e.vaultProviderPubkey,
|
|
13
|
-
e.vaultKeeperPubkeys,
|
|
14
|
-
e.universalChallengerPubkeys,
|
|
15
|
-
[...e.hashlocks],
|
|
16
|
-
new BigUint64Array(e.pegInAmounts),
|
|
17
|
-
e.timelockRefund,
|
|
18
|
-
e.feeRate,
|
|
19
|
-
e.numLocalChallengers,
|
|
20
|
-
e.councilQuorum,
|
|
21
|
-
e.councilSize,
|
|
22
|
-
e.network,
|
|
23
|
-
y
|
|
24
|
-
);
|
|
25
|
-
let t = null;
|
|
26
|
-
try {
|
|
27
|
-
t = s.fromFundedTransaction(o);
|
|
28
|
-
const d = t.buildRefundTx(f, n), a = await B({
|
|
29
|
-
depositorPubkey: e.depositorPubkey,
|
|
30
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
31
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
32
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
33
|
-
hashlock: i,
|
|
34
|
-
timelockRefund: e.timelockRefund,
|
|
35
|
-
network: e.network
|
|
36
|
-
}), h = o.startsWith("0x") ? o.slice(2) : o, m = x.fromHex(h), k = m.outs[n];
|
|
37
|
-
if (!k)
|
|
38
|
-
throw new Error(
|
|
39
|
-
`HTLC output at vout ${n} not found in funded Pre-PegIn tx (tx has ${m.outs.length} outputs)`
|
|
40
|
-
);
|
|
41
|
-
const c = x.fromHex(d);
|
|
42
|
-
if (c.ins.length !== 1)
|
|
43
|
-
throw new Error(
|
|
44
|
-
`Refund transaction must have exactly 1 input, got ${c.ins.length}`
|
|
45
|
-
);
|
|
46
|
-
const l = c.ins[0], v = m.getId(), w = S(
|
|
47
|
-
new Uint8Array(l.hash).slice().reverse()
|
|
48
|
-
);
|
|
49
|
-
if (w !== v)
|
|
50
|
-
throw new Error(
|
|
51
|
-
`Refund input does not reference the Pre-PegIn transaction. Expected ${v}, got ${w}`
|
|
52
|
-
);
|
|
53
|
-
if (l.index !== n)
|
|
54
|
-
throw new Error(
|
|
55
|
-
`Refund input index ${l.index} does not match expected htlcVout ${n}`
|
|
56
|
-
);
|
|
57
|
-
const P = new H();
|
|
58
|
-
P.setVersion(c.version), P.setLocktime(c.locktime), P.addInput({
|
|
59
|
-
hash: l.hash,
|
|
60
|
-
index: l.index,
|
|
61
|
-
sequence: l.sequence,
|
|
62
|
-
witnessUtxo: {
|
|
63
|
-
script: k.script,
|
|
64
|
-
value: k.value
|
|
65
|
-
},
|
|
66
|
-
tapLeafScript: [
|
|
67
|
-
{
|
|
68
|
-
leafVersion: I,
|
|
69
|
-
script: u.from(p(a.refundScript)),
|
|
70
|
-
controlBlock: u.from(
|
|
71
|
-
p(a.refundControlBlock)
|
|
72
|
-
)
|
|
73
|
-
}
|
|
74
|
-
],
|
|
75
|
-
tapInternalKey: u.from(T)
|
|
76
|
-
});
|
|
77
|
-
for (const b of c.outs)
|
|
78
|
-
P.addOutput({
|
|
79
|
-
script: b.script,
|
|
80
|
-
value: b.value
|
|
81
|
-
});
|
|
82
|
-
return { psbtHex: P.toHex() };
|
|
83
|
-
} finally {
|
|
84
|
-
t == null || t.free(), s.free();
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
async function z(r) {
|
|
88
|
-
const e = g(r.noPayoutTxHex), o = x.fromHex(e), { noPayoutScript: n, noPayoutControlBlock: f } = await C(
|
|
89
|
-
r.connectorParams,
|
|
90
|
-
r.challengerPubkey
|
|
91
|
-
), i = p(n), y = p(f), s = new H();
|
|
92
|
-
s.setVersion(o.version), s.setLocktime(o.locktime);
|
|
93
|
-
for (let t = 0; t < o.ins.length; t++) {
|
|
94
|
-
const d = o.ins[t], a = r.prevouts[t];
|
|
95
|
-
if (!a)
|
|
96
|
-
throw new Error(`Missing prevout data for input ${t}`);
|
|
97
|
-
const h = {
|
|
98
|
-
hash: d.hash,
|
|
99
|
-
index: d.index,
|
|
100
|
-
sequence: d.sequence,
|
|
101
|
-
witnessUtxo: {
|
|
102
|
-
script: u.from(p(g(a.script_pubkey))),
|
|
103
|
-
value: a.value
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
t === 0 && (h.tapLeafScript = [
|
|
107
|
-
{
|
|
108
|
-
leafVersion: I,
|
|
109
|
-
script: u.from(i),
|
|
110
|
-
controlBlock: u.from(y)
|
|
111
|
-
}
|
|
112
|
-
], h.tapInternalKey = u.from(T)), s.addInput(h);
|
|
113
|
-
}
|
|
114
|
-
for (const t of o.outs)
|
|
115
|
-
s.addOutput({
|
|
116
|
-
script: t.script,
|
|
117
|
-
value: t.value
|
|
118
|
-
});
|
|
119
|
-
return s.toHex();
|
|
120
|
-
}
|
|
121
|
-
function W(r, e, o) {
|
|
122
|
-
const n = x.fromHex(g(r));
|
|
123
|
-
if (n.outs.length !== 1)
|
|
124
|
-
throw new Error(
|
|
125
|
-
`NoPayout transaction must have exactly 1 output, got ${n.outs.length}`
|
|
126
|
-
);
|
|
127
|
-
const f = p($(e)), { output: i } = E.p2tr({
|
|
128
|
-
internalPubkey: u.from(f),
|
|
129
|
-
network: N(o)
|
|
130
|
-
});
|
|
131
|
-
if (!i)
|
|
132
|
-
throw new Error(
|
|
133
|
-
"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation"
|
|
134
|
-
);
|
|
135
|
-
if (!n.outs[0].script.equals(i))
|
|
136
|
-
throw new Error(
|
|
137
|
-
"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address"
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
export {
|
|
141
|
-
z as a,
|
|
142
|
-
F as b,
|
|
143
|
-
W as c
|
|
144
|
-
};
|
|
145
|
-
//# sourceMappingURL=noPayout-C5b34rs1.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-C5b34rs1.js","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 13th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor. Production peg-ins (PeginManager) always\n // commit an OP_RETURN <PUSH32 SHA256(authAnchor)> output at\n // `vout = hashlocks.length`; the unfunded template must include it so\n // `fromFundedTransaction` aligns with the funded tx's output shape.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n const unfundedTx = new (WasmPrePeginTx as unknown as new (\n depositor: string,\n vault_provider: string,\n vault_keepers: string[],\n universal_challengers: string[],\n hashlocks: string[],\n pegin_amounts: BigUint64Array,\n timelock_refund: number,\n fee_rate: bigint,\n num_local_challengers: number,\n council_quorum: number,\n council_size: number,\n network: string,\n auth_anchor_hash?: string,\n ) => typeof WasmPrePeginTx.prototype)(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;AAkEA,eAAsBA,EACpBC,GACgC;AAChC,QAAMC,EAAA;AAEN,QAAM,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEN,GAWIO,IAA2BC;AAAA,IAC/BN,EAAe;AAAA,EAAA,GAEXO,IAAa,IAAKC;AAAA,IAetBR,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACf,CAAC,GAAGA,EAAe,SAAS;AAAA,IAC5B,IAAI,eAAeA,EAAe,YAAY;AAAA,IAC9CA,EAAe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C,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("buffer"),a=require("bitcoinjs-lib"),n=require("./bitcoin-CHfKAhcI.cjs"),w=require("./assertPsbtUnsignedTxMatches-u9yeeUFY.cjs");async function H(s){await P.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:o,htlcVout:r,refundFee:d,hashlock:c}=s,b=w.normalizeAuthAnchorHash(e.authAnchorHash),u=new P.WasmPrePeginTx(e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(e.pegInAmounts),e.timelockRefund,e.feeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,b);let t=null;try{t=u.fromFundedTransaction(o);const h=t.buildRefundTx(d,r),l=await P.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:c,timelockRefund:e.timelockRefund,network:e.network}),x=o.startsWith("0x")?o.slice(2):o,k=a.Transaction.fromHex(x),g=k.outs[r];if(!g)throw new Error(`HTLC output at vout ${r} not found in funded Pre-PegIn tx (tx has ${k.outs.length} outputs)`);const f=a.Transaction.fromHex(h);if(f.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${f.ins.length}`);const p=f.ins[0],T=k.getId(),v=n.uint8ArrayToHex(new Uint8Array(p.hash).slice().reverse());if(v!==T)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${T}, got ${v}`);if(p.index!==r)throw new Error(`Refund input index ${p.index} does not match expected htlcVout ${r}`);const y=new a.Psbt;y.setVersion(f.version),y.setLocktime(f.locktime),y.addInput({hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:g.script,value:g.value},tapLeafScript:[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(n.hexToUint8Array(l.refundScript)),controlBlock:i.Buffer.from(n.hexToUint8Array(l.refundControlBlock))}],tapInternalKey:i.Buffer.from(P.tapInternalPubkey)});for(const m of f.outs)y.addOutput({script:m.script,value:m.value});return{psbtHex:y.toHex()}}finally{t==null||t.free(),u.free()}}async function A(s){const e=n.stripHexPrefix(s.noPayoutTxHex),o=a.Transaction.fromHex(e),{noPayoutScript:r,noPayoutControlBlock:d}=await P.getAssertNoPayoutScriptInfo(s.connectorParams,s.challengerPubkey),c=n.hexToUint8Array(r),b=n.hexToUint8Array(d),u=new a.Psbt;u.setVersion(o.version),u.setLocktime(o.locktime);for(let t=0;t<o.ins.length;t++){const h=o.ins[t],l=s.prevouts[t];if(!l)throw new Error(`Missing prevout data for input ${t}`);const x={hash:h.hash,index:h.index,sequence:h.sequence,witnessUtxo:{script:i.Buffer.from(n.hexToUint8Array(n.stripHexPrefix(l.script_pubkey))),value:l.value}};t===0&&(x.tapLeafScript=[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(c),controlBlock:i.Buffer.from(b)}],x.tapInternalKey=i.Buffer.from(P.tapInternalPubkey)),u.addInput(x)}for(const t of o.outs)u.addOutput({script:t.script,value:t.value});return u.toHex()}function I(s,e,o){const r=a.Transaction.fromHex(n.stripHexPrefix(s));if(r.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${r.outs.length}`);const d=n.hexToUint8Array(n.processPublicKeyToXOnly(e)),{output:c}=a.payments.p2tr({internalPubkey:i.Buffer.from(d),network:n.getNetwork(o)});if(!c)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!r.outs[0].script.equals(c))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=I;exports.buildNoPayoutPsbt=A;exports.buildRefundPsbt=H;
|
|
2
|
-
//# sourceMappingURL=noPayout-CtmOEauj.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-CtmOEauj.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 13th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor. Production peg-ins (PeginManager) always\n // commit an OP_RETURN <PUSH32 SHA256(authAnchor)> output at\n // `vout = hashlocks.length`; the unfunded template must include it so\n // `fromFundedTransaction` aligns with the funded tx's output shape.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n const unfundedTx = new (WasmPrePeginTx as unknown as new (\n depositor: string,\n vault_provider: string,\n vault_keepers: string[],\n universal_challengers: string[],\n hashlocks: string[],\n pegin_amounts: BigUint64Array,\n timelock_refund: number,\n fee_rate: bigint,\n num_local_challengers: number,\n council_quorum: number,\n council_size: number,\n network: string,\n auth_anchor_hash?: string,\n ) => typeof WasmPrePeginTx.prototype)(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"iNAkEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAWIO,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAEXO,EAAa,IAAKC,EAAAA,eAetBR,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eAAeA,EAAe,YAAY,EAC9CA,EAAe,eACfA,EAAe,QACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,QACfK,CAAA,EAGF,IAAII,EAAkC,KACtC,GAAI,CACFA,EAAWF,EAAW,sBAAsBN,CAAmB,EAE/D,MAAMS,EAAcD,EAAS,cAAcN,EAAWD,CAAQ,EAExDS,EAAgB,MAAMC,+BAA6B,CACvD,gBAAiBZ,EAAe,gBAChC,oBAAqBA,EAAe,oBACpC,mBAAoBA,EAAe,mBACnC,2BAA4BA,EAAe,2BAC3C,SAAAI,EACA,eAAgBJ,EAAe,eAC/B,QAASA,EAAe,OAAA,CACzB,EAEKa,EAAmBZ,EAAoB,WAAW,IAAI,EACxDA,EAAoB,MAAM,CAAC,EAC3BA,EACEa,EAAaC,EAAAA,YAAY,QAAQF,CAAgB,EAEjDG,EAAaF,EAAW,KAAKZ,CAAQ,EAC3C,GAAI,CAACc,EACH,MAAM,IAAI,MACR,uBAAuBd,CAAQ,6CAClBY,EAAW,KAAK,MAAM,WAAA,EAIvC,MAAMG,EAAWF,EAAAA,YAAY,QAAQL,CAAW,EAEhD,GAAIO,EAAS,IAAI,SAAW,EAC1B,MAAM,IAAI,MACR,qDAAqDA,EAAS,IAAI,MAAM,EAAA,EAI5E,MAAMC,EAAcD,EAAS,IAAI,CAAC,EAG5BE,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