@babylonlabs-io/ts-sdk 0.71.2 → 0.72.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PeginManager-Bn8FxM35.cjs → PeginManager-Bwjqb0_6.cjs} +2 -2
- package/dist/{PeginManager-Bn8FxM35.cjs.map → PeginManager-Bwjqb0_6.cjs.map} +1 -1
- package/dist/{PeginManager-C3ojNTlv.js → PeginManager-DjatPUPS.js} +2 -2
- package/dist/{PeginManager-C3ojNTlv.js.map → PeginManager-DjatPUPS.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-HX2xQlbM.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-HX2xQlbM.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-YvWDRAN8.js → buildAndBroadcastReclaim-QIN8Mcwq.js} +366 -357
- package/dist/buildAndBroadcastReclaim-QIN8Mcwq.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/mempoolApi-BJvC9nPF.cjs +2 -0
- package/dist/mempoolApi-BJvC9nPF.cjs.map +1 -0
- package/dist/{mempoolApi-CKD_IbrM.js → mempoolApi-_CoQH5vH.js} +6 -5
- package/dist/mempoolApi-_CoQH5vH.js.map +1 -0
- package/dist/noPayout-DpGRzidi.js.map +1 -1
- package/dist/noPayout-zEifyecV.cjs.map +1 -1
- package/dist/{primeVpAuth-tLRjdHwZ.js → primeVpAuth-BI63kgdd.js} +55 -43
- package/dist/primeVpAuth-BI63kgdd.js.map +1 -0
- package/dist/primeVpAuth-D3xbar3j.cjs +2 -0
- package/dist/primeVpAuth-D3xbar3j.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/operation-key-reader.d.ts +1 -1
- package/dist/tbv/core/clients/eth/operation-key-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +6 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +4 -4
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +29 -8
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +5 -5
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts +3 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts +20 -0
- package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +8 -0
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +5 -5
- package/dist/{toRefundInputs-Df1vi23S.js → toRefundInputs-BG-qHCEu.js} +2 -2
- package/dist/{toRefundInputs-Df1vi23S.js.map → toRefundInputs-BG-qHCEu.js.map} +1 -1
- package/dist/{toRefundInputs-CY9u84U9.cjs → toRefundInputs-kVR-3EdD.cjs} +2 -2
- package/dist/{toRefundInputs-CY9u84U9.cjs.map → toRefundInputs-kVR-3EdD.cjs.map} +1 -1
- package/package.json +1 -1
- package/dist/buildAndBroadcastReclaim-YvWDRAN8.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs.map +0 -1
- package/dist/mempoolApi-CKD_IbrM.js.map +0 -1
- package/dist/mempoolApi-DronQ5xn.cjs +0 -2
- package/dist/mempoolApi-DronQ5xn.cjs.map +0 -1
- package/dist/primeVpAuth-Cjq6qFHq.cjs +0 -2
- package/dist/primeVpAuth-Cjq6qFHq.cjs.map +0 -1
- package/dist/primeVpAuth-tLRjdHwZ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mempoolApi-CKD_IbrM.js","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/**\n * Raw `getBtcVaultProtocolInfo` tuple as decoded by viem.\n *\n * Mirrors the ABI's components except `claimExpiredUntil`, which nothing\n * consumes: it is the post-expiry grace deadline for `claimExpired`, scoped to\n * vaults that expired without activating, and it is not a deadline on the\n * depositor's claim right. The ABI still declares it — the decode is\n * positional, so removing it there would shift `vaultCoreVersion`.\n */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, VP_GENESIS_KEY_EPOCH],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${VP_GENESIS_KEY_EPOCH})`,\n );\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server signs its BIP-322 auth tokens with — a\n * live per-operator identity, not a per-vault binding, so the auth pin uses\n * the current key rather than any vault's frozen epoch.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) =>\n mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport { combineAbortSignals } from \"../../utils/abortSignals\";\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * The digit check alone is not enough to honour the contract below. A long\n * enough run of digits passes `/^\\d+$/` and then parses to a value no caller\n * can use: 400 digits yields `Infinity`, and 20 digits yields a finite but\n * unsafe integer. Callers subtract this from a confirmed block height to get a\n * confirmation depth, so either one produces an enormous depth and clears any\n * threshold it is compared against. Bound it to a safe integer here rather\n * than leaving each caller to discover the gap.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number a caller can compute on\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n const height = /^\\d+$/.test(trimmed) ? Number.parseInt(trimmed, 10) : NaN;\n if (!Number.isSafeInteger(height) || height < 0) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return height;\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","BTCVaultRegistryABI","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","combined","combineAbortSignals","error","MAX_FEE_RATE","isValidSatoshiValue","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","height","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","feeFields"],"mappings":";;;;;;;;;;AA6CA,MAAMA,IAAa,0BAGbC,IAAe,YAEfC,IAAqB,IACrBC,IAAmB,IAEnBC,IAAyB,IAQlBC,KAAyB,IACzBC,KAAyB,IAQhCC,IAAY,GAIZC,IAAoB,GACpBC,IAAqB,GACrBC,IAAwB,GAExBC,KAA8B,IAC9BC,KAAy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AAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const Q=require("@bitcoin-js/tiny-secp256k1-asmjs"),a=require("bitcoinjs-lib"),E=require("./sha2-DsrLC4NM.cjs"),u=require("buffer"),c=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),$=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),A=require("./onChainBtcPubkey-B5ZvWCCF.cjs"),Y=require("./vaultCoreVersion-DYfw3qed.cjs"),Z=require("./abortSignals-msbmbqFe.cjs"),p=require("./validation-C6XTfZak.cjs");function J(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const m=J(Q),tt="BIP0322-signed-message",et="TapTweak",K=32,nt=64,ot=33,k=71,R=72,d=0,V=0,B=0,C=0,rt=32,it=4294967295,st=0,at=0,ct=32,ut=106;function U(t,e){const n=new TextEncoder().encode(t),o=E.sha256(n),i=new Uint8Array(o.length*2+e.length);return i.set(o,0),i.set(o,o.length),i.set(e,o.length*2),E.sha256(i)}function lt(t){if(t.length!==K)return null;const e=U(et,t),n=m.xOnlyPointAddTweak(t,e);return n?n.xOnlyPubkey:null}function H(t,e){const n=U(tt,t),o=new a.Transaction;o.version=V,o.locktime=B;const i=u.Buffer.concat([u.Buffer.from([at,ct]),u.Buffer.from(n)]);o.addInput(u.Buffer.alloc(rt,0),it,C,i),o.addOutput(e,d);const r=new a.Transaction;return r.version=V,r.locktime=B,r.addInput(o.getHash(),st,C),r.addOutput(u.Buffer.from([ut]),d),r}function ft(t,e,n,o=a.Transaction.SIGHASH_DEFAULT){if(e.length!==K||n.length!==nt||o!==a.Transaction.SIGHASH_DEFAULT&&o!==a.Transaction.SIGHASH_ALL)return!1;try{const i=a.payments.p2tr({internalPubkey:u.Buffer.from(e)});if(!i.output)return!1;const r=i.output,h=H(t,r).hashForWitnessV1(0,[r],[d],o),g=lt(e);return g?m.verifySchnorr(h,g,n):!1}catch{return!1}}function ht(t,e,n){if(e.length!==ot||n.length<k||n.length>R)return!1;try{if(!m.isPointCompressed(e))return!1;const{signature:o,hashType:i}=a.script.signature.decode(u.Buffer.from(n));if(!a.script.signature.encode(o,i).equals(u.Buffer.from(n))||i!==a.Transaction.SIGHASH_ALL)return!1;const r=a.payments.p2wpkh({pubkey:u.Buffer.from(e)});if(!r.output||!r.hash)return!1;const s=H(t,r.output),h=a.payments.p2pkh({hash:r.hash}).output;if(!h)return!1;const g=s.hashForWitnessV0(0,h,d,i);return m.verify(g,e,o,!0)}catch{return!1}}const w=65535,_=1e4,I=4294967295,v=255;function M(t){if(!Number.isInteger(t)||t<0||t>I)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function D(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(w)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${w})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>w)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>I)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${I}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>_)&&e.push(`minVpCommissionBps must be in [0, ${_}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function X(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>v)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${v}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function gt(t){if(X(t),D(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>I)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);Y.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const S=9999;function O(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function b(t){const e=Number(t.offchainParamsVersion);return M(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,vaultCoreVersion:t.vaultCoreVersion}}const pt=1n<<64n,x=0n;function T(t,e,n){if(t<0n||t>=pt)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${n}, outside the uint64 range — the registry may predate RFC-006`);return t}function F(t,e){return{vpKeyEpoch:T(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:T(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:T(t.ucKeyEpoch,"ucKeyEpoch",e)}}class mt{constructor(e,n){this.publicClient=e,this.contractAddress=n}async getVaultProviderGenesisBtcPubKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,x]});return A.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${x})`)}async getCurrentVaultProviderOperationBtcKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return A.assertOnChainBtcPubkey(n,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return F(n,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>F(o,e[i]))}async getVaultBasicInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return O(n)}async getVaultProtocolInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return b(n)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>{const r=o;if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return b(r)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(n)||n<0||n>S)throw new Error(`getVaultProviderCommission returned ${n} bps for ${e}, outside the protocol range [0, ${S}]`);return n}async getVaultData(e){const[n,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=O(n),r=b(o);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:r}}}const dt=21e6*1e8,N=3e4;async function P(t,e){const n=new AbortController,o=setTimeout(()=>n.abort(),N),i=[n.signal,e==null?void 0:e.signal].filter(Boolean),r=Z.combineAbortSignals(i);try{return await fetch(t,{...e,signal:r.signal})}catch(s){throw clearTimeout(o),r.cleanup(),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${N}ms: ${t}`):s}}const G=1e4;function L(t){return Number.isInteger(t)&&t>0&&t<=dt}function It(t){return Number.isInteger(t)&&t>0&&t<=G}function y(t,e){return!Number.isInteger(t)||t<0?!1:e===void 0||t<e}function f(t){if(!p.TXID_RE.test(t))throw new Error(`Invalid transaction ID format: ${t}`)}function q(t){if(!p.BITCOIN_ADDRESS_RE.test(t))throw new Error(`Invalid Bitcoin address format: ${t}`)}function W(t,e){if(!p.HEX_RE.test(t))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!p.KNOWN_SCRIPT_PREFIXES.some(o=>t.toLowerCase().startsWith(o)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${t.slice(0,6)} does not match any known Bitcoin script type`)}const j={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function l(t,e){try{const n=await P(t,e);if(!n.ok){const i=await n.text();throw new Error(`Mempool API error (${n.status}): ${i||n.statusText}`)}const o=n.headers.get("content-type");return o!=null&&o.includes("application/json")?await n.json():await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to fetch from mempool API: ${n.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function Pt(t,e){try{const n=await P(`${e}/tx`,{method:"POST",body:t,headers:{"Content-Type":"text/plain"}});if(!n.ok){const i=await n.text();let r;try{const s=JSON.parse(i);r=s.message??s.error}catch{r=i}throw new Error(r||`Failed to broadcast transaction: ${n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to broadcast BTC transaction: ${n.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function z(t,e){return f(t),l(`${e}/tx/${t}`)}async function wt(t){const e=await l(`${t}/blocks/tip/height`),n=e.trim(),o=/^\d+$/.test(n)?Number.parseInt(n,10):NaN;if(!Number.isSafeInteger(o)||o<0)throw new Error(`Mempool API returned an invalid block tip height: "${e}"`);return o}async function bt(t,e,n){if(f(t),!y(e))throw new Error(`Invalid vout ${e} for transaction ${t}`);return l(`${n}/tx/${t}/outspend/${e}`)}async function Tt(t,e){f(t);try{const n=await P(`${e}/tx/${t}/hex`);if(!n.ok){const o=await n.text();throw new Error(`Mempool API error (${n.status}): ${o||n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to get transaction hex for ${t}: ${n.message}`):new Error(`Failed to get transaction hex for ${t}: Unknown error`)}}async function yt(t,e,n){f(t);const o=await z(t,n);if(!y(e,o.vout.length))throw new Error(`Invalid vout ${e} for transaction ${t} (has ${o.vout.length} outputs)`);const i=o.vout[e];if(!L(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${t}:${e}`);return W(i.scriptpubkey,`${t}:${e}`),{txid:t,vout:e,value:i.value,scriptPubKey:i.scriptpubkey}}async function Et(t,e){q(t);try{const n=await l(`${e}/address/${t}/utxo`),o=await l(`${e}/v1/validate-address/${t}`);if(!o.isvalid)throw new Error(`Invalid Bitcoin address: ${t}. Mempool API validation failed.`);W(o.scriptPubKey,t);for(const r of n){if(f(r.txid),!y(r.vout))throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);if(!L(r.value))throw new Error(`Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`)}return n.sort((r,s)=>s.value-r.value).map(r=>({txid:r.txid,vout:r.vout,value:r.value,scriptPubKey:o.scriptPubKey,confirmed:r.status.confirmed}))}catch(n){throw n instanceof Error?new Error(`Failed to get UTXOs for address ${t}: ${n.message}`):new Error(`Failed to get UTXOs for address ${t}: Unknown error`)}}function $t(t){return j[t]}async function At(t,e){return q(t),l(`${e}/address/${t}/txs`)}async function Vt(t){const e=await P(`${t}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const n=await e.json(),o=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of o)if(!It(n[i]))throw new Error(`Invalid fee rate ${i}=${n[i]} from mempool API: expected a positive number ≤ ${G}`);if(n.minimumFee>n.economyFee||n.economyFee>n.hourFee||n.hourFee>n.halfHourFee||n.halfHourFee>n.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${n.minimumFee}) <= economyFee (${n.economyFee}) <= hourFee (${n.hourFee}) <= halfHourFee (${n.halfHourFee}) <= fastestFee (${n.fastestFee}).`);return n}exports.MEMPOOL_API_URLS=j;exports.P2WPKH_ENCODED_SIG_MAX=R;exports.P2WPKH_ENCODED_SIG_MIN=k;exports.ViemVaultRegistryReader=mt;exports.assertValidOffchainParamsVersion=M;exports.getAddressTxs=At;exports.getAddressUtxos=Et;exports.getMempoolApiUrl=$t;exports.getNetworkFees=Vt;exports.getOutspend=bt;exports.getTipHeight=wt;exports.getTxHex=Tt;exports.getTxInfo=z;exports.getUtxoInfo=yt;exports.pushTx=Pt;exports.validateOffchainParams=D;exports.validatePegInConfiguration=gt;exports.validateTBVProtocolParams=X;exports.verifyBip322P2wpkhSimple=ht;exports.verifyBip322Simple=ft;
|
|
2
|
-
//# sourceMappingURL=mempoolApi-DronQ5xn.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mempoolApi-DronQ5xn.cjs","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/**\n * Raw `getBtcVaultProtocolInfo` tuple as decoded by viem.\n *\n * Mirrors the ABI's components except `claimExpiredUntil`, which nothing\n * consumes: it is the post-expiry grace deadline for `claimExpired`, scoped to\n * vaults that expired without activating, and it is not a deadline on the\n * depositor's claim right. The ABI still declares it — the decode is\n * positional, so removing it there would shift `vaultCoreVersion`.\n */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, VP_GENESIS_KEY_EPOCH],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${VP_GENESIS_KEY_EPOCH})`,\n );\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server signs its BIP-322 auth tokens with — a\n * live per-operator identity, not a per-vault binding, so the auth pin uses\n * the current key rather than any vault's frozen epoch.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) =>\n mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport { combineAbortSignals } from \"../../utils/abortSignals\";\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * The digit check alone is not enough to honour the contract below. A long\n * enough run of digits passes `/^\\d+$/` and then parses to a value no caller\n * can use: 400 digits yields `Infinity`, and 20 digits yields a finite but\n * unsafe integer. Callers subtract this from a confirmed block height to get a\n * confirmation depth, so either one produces an enormous depth and clears any\n * threshold it is compared against. Bound it to a safe integer here rather\n * than leaving each caller to discover the gap.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number a caller can compute on\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n const height = /^\\d+$/.test(trimmed) ? Number.parseInt(trimmed, 10) : NaN;\n if (!Number.isSafeInteger(height) || height < 0) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return height;\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","BTCVaultRegistryABI","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","combined","combineAbortSignals","error","MAX_FEE_RATE","isValidSatoshiValue","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","height","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","feeFields"],"mappings":"gsBA6CMA,GAAa,yBAGbC,GAAe,WAEfC,EAAqB,GACrBC,GAAmB,GAEnBC,GAAyB,GAQlBC,EAAyB,GACzBC,EAAyB,GAQhCC,EAAY,EAIZC,EAAoB,EACpBC,EAAqB,EACrBC,EAAwB,EAExBC,GAA8B,GAC9BC,GAAyB,WAEzBC,GAAwB,EACxBC,GAAO,EAEPC,GAAkB,GAClBC,GAAY,IAMlB,SAASC,EAAWC,EAAaC,EAA8B,CAC7D,MAAMC,EAAW,IAAI,cAAc,OAAOF,CAAG,EACvCG,EAAUC,EAAAA,OAAOF,CAAQ,EACzBG,EAAW,IAAI,WAAWF,EAAQ,OAAS,EAAIF,EAAK,MAAM,EAChE,OAAAI,EAAS,IAAIF,EAAS,CAAC,EACvBE,EAAS,IAAIF,EAASA,EAAQ,MAAM,EACpCE,EAAS,IAAIJ,EAAME,EAAQ,OAAS,CAAC,EAC9BC,EAAAA,OAAOC,CAAQ,CACxB,CAYA,SAASC,GAAcC,EAAsC,CAC3D,GAAIA,EAAM,SAAWvB,EAAoB,OAAO,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A,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,2 +0,0 @@
|
|
|
1
|
-
"use strict";var ae=Object.defineProperty;var ce=(r,e,t)=>e in r?ae(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var h=(r,e,t)=>ce(r,typeof e!="symbol"?e+"":e,t);const x=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),l=require("./ProtocolParams.abi-CYZoV2EI.cjs"),_=require("./mempoolApi-DronQ5xn.cjs"),y=require("./bitcoin-D-O2GjbC.cjs"),le=require("./index-Cs7_Evtk.cjs"),ue=require("./json-rpc-client-BiAmg_ho.cjs"),de=require("@bitcoin-js/tiny-secp256k1-asmjs"),f=require("./validation-C6XTfZak.cjs"),pe=require("./sha2-DsrLC4NM.cjs");function he(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const q=he(de);async function ge(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:x.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:x.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}function M(r,e,t){if(r!==e)throw new Error(`${t}: multicall returned ${r} results for ${e} calls, so the results are not roster-aligned; refusing to use them`)}function me(r,e){return{vaultProvider:r[0],vaultKeepers:r.slice(1,1+e),universalChallengers:r.slice(1+e)}}class fe{constructor(e,t){this.publicClient=e,this.contracts=t}async readAll(e,t,n,i){const s=await this.publicClient.multicall({contracts:e,allowFailure:!1});return M(s.length,1+t+n,i),me(s,t)}async getCurrentOperationKeys(e){const t=[{address:this.contracts.btcVaultRegistry,abi:x.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.vaultProviderEthAddress]},...e.vaultKeepers.map(n=>({address:this.contracts.applicationRegistry,abi:l.ApplicationRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.applicationEntryPoint,n.ethAddress]})),...e.universalChallengers.map(n=>({address:this.contracts.protocolParams,abi:l.ProtocolParamsABI,functionName:"getCurrentOperationBtcKey",args:[n.ethAddress]}))];return this.readAll(t,e.vaultKeepers.length,e.universalChallengers.length,"getCurrentOperationKeys")}async getOperationKeysAtEpochs(e,t){const n=[{address:this.contracts.btcVaultRegistry,abi:x.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:l.ApplicationRegistryABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch,i.btcPubKey]})),...e.universalChallengers.map(i=>({address:this.contracts.protocolParams,abi:l.ProtocolParamsABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[i.ethAddress,t.ucKeyEpoch,i.btcPubKey]}))];return this.readAll(n,e.vaultKeepers.length,e.universalChallengers.length,"getOperationKeysAtEpochs")}async getPayoutScriptsAtEpochs(e,t){const n=await this.publicClient.multicall({contracts:[{address:this.contracts.btcVaultRegistry,abi:x.BTCVaultRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:l.ApplicationRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch]}))],allowFailure:!1});return M(n.length,1+e.vaultKeepers.length,"getPayoutScriptsAtEpochs"),{vaultProvider:n[0],vaultKeepers:[...n.slice(1)]}}}const K=65535;function v(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverCircuitVersion:r.proverCircuitVersion,minPrepeginDepth:r.minPrepeginDepth}}function L(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function X(r){if(r>BigInt(K))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${K})`);return Number(r)}class ye{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getTBVProtocolParams"}),t=L(e);return _.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=v(e);return _.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=v(t);return _.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return _.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return X(t.timelockAssert)}async getPeginActivationDelay(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"peginActivationDelay"});if(typeof e!="bigint")throw new Error(`Invalid peginActivationDelay from contract: must be a bigint, got ${typeof e}`);return e}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"},{address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"activeVaultCoreVersion"}],allowFailure:!1}),t=L(e[0]),n=v(e[1]),i=Number(e[2]),s=Number(e[3]),o={minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,timelockPegin:X(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i,activeVaultCoreVersion:s};return _.validatePegInConfiguration(o),o}async fetchAllOffchainParams(e){const t=await this.getLatestOffchainParamsVersion();if(t===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:t},(a,d)=>d+1),i=n.map(a=>({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[a]})),s=await this.publicClient.multicall({contracts:i,allowFailure:!1}),o=new Map;for(let a=0;a<n.length;a++){const d=v(s[a]);try{_.validateOffchainParams(d),o.set(n[a],d)}catch(p){e==null||e(n[a],p instanceof Error?p:new Error(String(p)))}}return{byVersion:o,latestVersion:t}}}function C(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ae{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:l.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return C(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:l.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return C(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:l.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class be{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return C(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return C(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:l.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var Q=(r=>(r[r.PENDING=0]="PENDING",r[r.VERIFIED=1]="VERIFIED",r[r.ACTIVE=2]="ACTIVE",r[r.REDEEMED=3]="REDEEMED",r[r.EXPIRED=4]="EXPIRED",r))(Q||{});function k(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const s=Number(n);return new Uint8Array([t|25,s>>>8&255,s&255])}if(n<0x100000000n){const s=Number(n);return new Uint8Array([t|26,s>>>24&255,s>>>16&255,s>>>8&255,s&255])}const i=new Uint8Array(9);i[0]=t|27;for(let s=7;s>=0;s--)i[1+s]=Number(n>>BigInt((7-s)*8))&255;return i}function Z(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function G(r){const t=[k(4,r.length)];for(const n of r)t.push(k(0,n));return Z(...t)}function _e(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=k(4,3),i=G(r),s=G(e),o=k(0,t);return Z(n,i,s,o)}const Pe=new TextEncoder().encode("btc-auth.server-identity.v1"),we=2*3600;class m extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function E(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function ee(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??we,s=y.stripHexPrefix(t).toLowerCase();if(s.length!==f.X_ONLY_PUBKEY_HEX_LEN||!f.HEX_RE.test(s))throw new m(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const o=y.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==f.X_ONLY_PUBKEY_HEX_LEN||!f.HEX_RE.test(o))throw new m(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==s)throw new m(`server_pubkey does not match pinned value: expected ${s}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new m(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new m(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new m(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new m(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new m(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const a=y.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(a.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!f.HEX_RE.test(a))throw new m(`ephemeral_pubkey must be 33-byte compressed hex; got ${a.length} chars`,"invalid_ephemeral_pubkey");const d=a.slice(0,2);if(d!=="02"&&d!=="03")throw new m(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const p=E(a);if(!q.isPoint(p))throw new m("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const g=y.stripHexPrefix(e.signature).toLowerCase();if(g.length!==y.SCHNORR_SIG_HEX_LEN||!f.HEX_RE.test(g))throw new m(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const b=_e(Pe,E(a),e.expires_at);if(!_.verifyBip322Simple(b,E(o),E(g)))throw new m("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const xe=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),ve=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),Ee=6e4,B="auth_createDepositorToken",N="auth_createDepositorTokenGrpc";function te(r,e){return new ue.JsonRpcClient({baseUrl:r,timeout:Ee,headers:e,retryableFor:t=>t===B||t===N})}const Ce=0,ke=1,I=2,Te=3,Se=4,Ie=5,Re=6,Oe=7,U=24,Be=28,Ne=20,Ve=21,$e=22,D=256;class A extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class re{constructor(e){h(this,"buf");h(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new A("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<U)return{major:t,arg:n};if(n>=Be)throw new A(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-U;let s=0n;for(let o=0;o<i;o++)s=s<<8n|BigInt(this.nextByte());if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new A(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new A("length overruns end of input");const t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}readByteString(){const e=this.readHead();if(e.major!==I)throw new A(`expected byte string (major ${I}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>D)throw new A(`nesting exceeds maximum depth ${D}`);const t=this.readHead();switch(t.major){case Ce:return t.arg;case ke:return-1-t.arg;case I:return this.readBytes(t.arg);case Te:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case Se:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case Ie:{const n=new Map;for(let i=0;i<t.arg;i++){const s=this.readValue(e+1),o=this.readValue(e+1);n.set(s,o)}return n}case Re:return{tag:t.arg,value:this.readValue(e+1)};case Oe:if(t.arg===Ne)return!1;if(t.arg===Ve)return!0;if(t.arg===$e)return null;throw new A(`unsupported simple/float value ${t.arg}`);default:throw new A(`unsupported major type ${t.major}`)}}}function ne(r){const e=new re(r),t=e.readValue();if(e.pos!==r.length)throw new A("trailing bytes after top-level item");return t}const He="vaultd-jsonrpc",Me="vaultd-grpc",F=18,V=4,j=-47,Ke=1,J=64,Le=128,Xe=96,Ge=64,Ue=1,De=2,Fe=3,je=4,Je=5,Ye=6,We=7,Y=new TextEncoder().encode("Signature1");class c extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function ze(r){const e=W(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=W(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=tt(r.ephemeralPubkeyHex),i=nt(r.token),s=new re(i),o=s.readHead();if(o.major!==6||o.arg!==F)throw new c(`token is not a COSE Sign1 tagged value (tag ${F})`,"invalid_token_structure");const a=s.readHead();if(a.major!==4||a.arg!==V)throw new c(`COSE Sign1 must be a ${V}-element array`,"invalid_token_structure");const d=s.pos,p=s.readByteString(),g=i.subarray(d,s.pos);s.readValue();const b=s.pos,P=s.readByteString(),T=i.subarray(b,s.pos),S=s.readByteString();if(S.length!==J)throw new c(`COSE signature must be ${J} bytes, got ${S.length}`,"invalid_token_structure");if(s.pos!==i.length)throw new c("COSE Sign1 token has trailing bytes after the signature","invalid_token_structure");const H=qe(p);if(H!==j)throw new c(`unexpected COSE algorithm ${H} (expected ES256K ${j})`,"unexpected_algorithm");const ie=Qe(g,T),oe=pe.sha256(ie);if(!q.verify(oe,n,S,!0))throw new c("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const u=Ze(P),w=u.audience.toLowerCase();if(w.length!==f.X_ONLY_PUBKEY_HEX_LEN||!f.HEX_RE.test(w))throw new c("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(u.issuedAt>u.expiresAt)throw new c(`token iat (${u.issuedAt}) is after exp (${u.expiresAt})`,"invalid_claims");if(u.issuer.toLowerCase()!==e)throw new c(`token issuer does not match pinned server pubkey: expected ${e}, got ${u.issuer.toLowerCase()}`,"issuer_mismatch");if(u.subject!==r.expectedSubject)throw new c(`token subject mismatch: expected ${r.expectedSubject}, got ${u.subject}`,"subject_mismatch");if(w!==t)throw new c(`token audience does not match depositor pubkey: expected ${t}, got ${w}`,"audience_mismatch");if(u.expiresAt<=r.now)throw new c(`token expired: exp ${u.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==u.expiresAt)throw new c(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${u.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<u.expiresAt)throw new c(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${u.expiresAt})`,"server_identity_expires_before_token");return{issuer:u.issuer,subject:u.subject,audience:w,expiresAt:u.expiresAt,notBefore:u.notBefore,issuedAt:u.issuedAt}}function qe(r){if(r.length===0)throw new c("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=ne(r);if(!(e instanceof Map))throw new c("COSE protected header is not a map","invalid_token_structure");const t=e.get(Ke);if(typeof t!="number")throw new c("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function Qe(r,e){return st(Uint8Array.of(Le|V),Uint8Array.of(Xe|Y.length),Y,r,Uint8Array.of(Ge),e)}function Ze(r){const e=ne(r);if(!(e instanceof Map))throw new c("CWT claims root is not a map","invalid_claims");if(et(e,We,"cti").length===0)throw new c("token cti is empty","invalid_claims");return{issuer:R(e,Ue,"iss"),subject:R(e,De,"sub"),audience:R(e,Fe,"aud"),expiresAt:O(e,je,"exp"),notBefore:O(e,Je,"nbf"),issuedAt:O(e,Ye,"iat")}}function R(r,e,t){const n=r.get(e);if(typeof n!="string")throw new c(`token claim ${t} is missing or not a text string`,"invalid_claims");return n}function et(r,e,t){const n=r.get(e);if(!(n instanceof Uint8Array))throw new c(`token claim ${t} is missing or not a byte string`,"invalid_claims");return n}function O(r,e,t){const n=r.get(e);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new c(`token claim ${t} is missing or not a non-negative integer timestamp`,"invalid_claims");return n}function W(r,e){const t=y.stripHexPrefix(r).toLowerCase();if(t.length!==f.X_ONLY_PUBKEY_HEX_LEN||!f.HEX_RE.test(t))throw new c(`${e} must be 32-byte x-only hex; got ${t.length} chars`,"invalid_input");return t}function tt(r){const e=y.stripHexPrefix(r).toLowerCase(),t=e.slice(0,2);if(e.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!f.HEX_RE.test(e)||t!=="02"&&t!=="03")throw new c("ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)","invalid_input");return y.hexToUint8Array(e)}const rt=(()=>{const r=new Int16Array(128).fill(-1),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let t=0;t<e.length;t++)r[e.charCodeAt(t)]=t;return r})();function nt(r){const e=r.length,t=Math.floor(e/4),n=e%4;if(n===1)throw new c("invalid base64url length","invalid_token_structure");const i=t*3+(n===0?0:n-1),s=new Uint8Array(i),o=p=>{const g=p<128?rt[p]:-1;if(g<0)throw new c("invalid base64url character","invalid_token_structure");return g};let a=0,d=0;for(let p=0;p<t;p++){const g=o(r.charCodeAt(a++)),b=o(r.charCodeAt(a++)),P=o(r.charCodeAt(a++)),T=o(r.charCodeAt(a++));s[d++]=g<<2|b>>4,s[d++]=(b&15)<<4|P>>2,s[d++]=(P&3)<<6|T}if(n===2){const p=o(r.charCodeAt(a++)),g=o(r.charCodeAt(a++));s[d++]=p<<2|g>>4}else if(n===3){const p=o(r.charCodeAt(a++)),g=o(r.charCodeAt(a++)),b=o(r.charCodeAt(a++));s[d++]=p<<2|g>>4,s[d++]=(g&15)<<4|b>>2}return s}function st(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}const z=4102444800,it=30;class ot{constructor(e){h(this,"client");h(this,"peginTxid");h(this,"authAnchorHex");h(this,"pinnedServerPubkey");h(this,"expectedAudienceXOnlyPubkey");h(this,"authGatedMethods");h(this,"grpcGatedMethods");h(this,"refreshSkewSecs");h(this,"now");h(this,"cachedJsonRpc",null);h(this,"inFlightJsonRpc",null);h(this,"cachedGrpc",null);h(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.expectedAudienceXOnlyPubkey=e.expectedAudienceXOnlyPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??it,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===B||e===N?null:this.grpcGatedMethods.has(e)?this.getTokenForSubject("grpc"):this.authGatedMethods.has(e)?this.getTokenForSubject("jsonrpc"):null}invalidate(){this.cachedJsonRpc=null,this.cachedGrpc=null}async getTokenForSubject(e){const t=e==="grpc"?this.cachedGrpc:this.cachedJsonRpc;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight(e)).token}setClient(e){this.client=e}acquireSingleFlight(e){const t=e==="grpc"?this.inFlightGrpc:this.inFlightJsonRpc;if(t)return t;const n=e==="grpc"?N:B,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(ee({proof:s.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof s.token!="string"||s.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof s.token})`);const o=this.now();if(!Number.isSafeInteger(s.expires_at)||s.expires_at<=o||s.expires_at>z)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${o}, ${z}])`);ze({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?Me:He,expectedAudienceXOnlyPubkey:this.expectedAudienceXOnlyPubkey,responseExpiresAt:s.expires_at,serverIdentityExpiresAt:s.server_identity.expires_at,now:o});const a={token:s.token,expiresAt:s.expires_at};return e==="grpc"?this.cachedGrpc=a:this.cachedJsonRpc=a,a}finally{e==="grpc"?this.inFlightGrpc=null:this.inFlightJsonRpc=null}})();return e==="grpc"?this.inFlightGrpc=i:this.inFlightJsonRpc=i,i}}class se{constructor(){h(this,"entries",new Map)}getOrCreate(e){const t=this.entries.get(e.peginTxid);if(t){if(t.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${t.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(t.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${t.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(t.expectedAudienceXOnlyPubkey!==e.expectedAudienceXOnlyPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to expectedAudienceXOnlyPubkey ${t.expectedAudienceXOnlyPubkey.slice(0,8)}…; got ${e.expectedAudienceXOnlyPubkey.slice(0,8)}…`);return t.provider.setClient(e.client),t.provider}const n=new ot({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:xe,grpcGatedMethods:ve});return this.entries.set(e.peginTxid,{provider:n,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey}),n}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const $=new se;function at(r){var n;const e=te(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=$.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:y.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new le.VaultProviderRpcClient(r.baseUrl,{...r.options,tokenProvider:t})}function ct(r){$.getOrCreate({client:te(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:y.processPublicKeyToXOnly(r.depositorBtcPubkey)})}exports.OnChainBtcVaultStatus=Q;exports.ServerIdentityError=m;exports.ViemOperationKeyReader=fe;exports.ViemProtocolParamsReader=ye;exports.ViemUniversalChallengerReader=be;exports.ViemVaultKeeperReader=Ae;exports.VpTokenRegistry=se;exports.createAuthenticatedVpClient=at;exports.primeVpTokenRegistry=ct;exports.resolveProtocolAddresses=ge;exports.verifyServerIdentity=ee;exports.vpTokenRegistry=$;
|
|
2
|
-
//# sourceMappingURL=primeVpAuth-Cjq6qFHq.cjs.map
|