@babylonlabs-io/ts-sdk 0.70.1 → 0.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PeginManager-BIKAnZ-X.cjs +2 -0
- package/dist/PeginManager-BIKAnZ-X.cjs.map +1 -0
- package/dist/{PeginManager-BNtg6jgY.js → PeginManager-Byvmccdd.js} +10 -10
- package/dist/PeginManager-Byvmccdd.js.map +1 -0
- package/dist/abortSignals-BPpAUL1Z.js +18 -0
- package/dist/abortSignals-BPpAUL1Z.js.map +1 -0
- package/dist/abortSignals-msbmbqFe.cjs +2 -0
- package/dist/abortSignals-msbmbqFe.cjs.map +1 -0
- package/dist/{bitcoin-Ch_jxnDa.js → bitcoin-C-TuHb-v.js} +21 -22
- package/dist/bitcoin-C-TuHb-v.js.map +1 -0
- package/dist/bitcoin-D-O2GjbC.cjs +2 -0
- package/dist/bitcoin-D-O2GjbC.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js → buildAndBroadcastReclaim-C0TdwO2M.js} +60 -59
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js.map → buildAndBroadcastReclaim-C0TdwO2M.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-kRx7-o2y.cjs +2 -0
- package/dist/{buildAndBroadcastReclaim-iNJfx0ZG.cjs.map → buildAndBroadcastReclaim-kRx7-o2y.cjs.map} +1 -1
- package/dist/{challengeAssert-BNQ8sToz.js → challengeAssert-Cp_GeRg8.js} +3 -3
- package/dist/challengeAssert-Cp_GeRg8.js.map +1 -0
- package/dist/challengeAssert-Z7_YULBb.cjs +2 -0
- package/dist/challengeAssert-Z7_YULBb.cjs.map +1 -0
- package/dist/constants-Bh38W9mq.cjs +2 -0
- package/dist/constants-Bh38W9mq.cjs.map +1 -0
- package/dist/constants-CPzppOdq.js +17 -0
- package/dist/constants-CPzppOdq.js.map +1 -0
- package/dist/index-Cs7_Evtk.cjs +2 -0
- package/dist/index-Cs7_Evtk.cjs.map +1 -0
- package/dist/index-LgmJhdEN.js +505 -0
- package/dist/index-LgmJhdEN.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +230 -226
- package/dist/index.js.map +1 -1
- package/dist/mempoolApi-BQllf-ji.cjs +2 -0
- package/dist/{mempoolApi-Q90mz17e.cjs.map → mempoolApi-BQllf-ji.cjs.map} +1 -1
- package/dist/{mempoolApi-CfOFmov6.js → mempoolApi-CRNMOsbC.js} +36 -35
- package/dist/{mempoolApi-CfOFmov6.js.map → mempoolApi-CRNMOsbC.js.map} +1 -1
- package/dist/noPayout--lxo7qe4.js +300 -0
- package/dist/noPayout--lxo7qe4.js.map +1 -0
- package/dist/noPayout-CegnEwfp.cjs +2 -0
- package/dist/noPayout-CegnEwfp.cjs.map +1 -0
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs → onChainBtcPubkey-B5ZvWCCF.cjs} +2 -2
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs.map → onChainBtcPubkey-B5ZvWCCF.cjs.map} +1 -1
- package/dist/{onChainBtcPubkey-BAHZyKQL.js → onChainBtcPubkey-DATNfAAl.js} +2 -2
- package/dist/{onChainBtcPubkey-BAHZyKQL.js.map → onChainBtcPubkey-DATNfAAl.js.map} +1 -1
- package/dist/parseFundingOutpoints-BkgGihaY.cjs +2 -0
- package/dist/parseFundingOutpoints-BkgGihaY.cjs.map +1 -0
- package/dist/{parseFundingOutpoints-CO-f6IHK.js → parseFundingOutpoints-DlINgQ3X.js} +30 -29
- package/dist/parseFundingOutpoints-DlINgQ3X.js.map +1 -0
- package/dist/{batchPoll-BM4iQ9jT.js → primeVpAuth-D1qbOkhb.js} +311 -803
- package/dist/primeVpAuth-D1qbOkhb.js.map +1 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs +2 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs.map +1 -0
- package/dist/{reservation-CBAvoF3U.js → reservation-Cj9F0rP9.js} +2 -2
- package/dist/{reservation-CBAvoF3U.js.map → reservation-Cj9F0rP9.js.map} +1 -1
- package/dist/{reservation-CDbInVw0.cjs → reservation-Dr2HLCxx.cjs} +2 -2
- package/dist/{reservation-CDbInVw0.cjs.map → reservation-Dr2HLCxx.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js → signPsbtsWithFallback-BjXdnI0X.js} +18 -19
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js.map → signPsbtsWithFallback-BjXdnI0X.js.map} +1 -1
- package/dist/signPsbtsWithFallback-zOQWokmk.cjs +2 -0
- package/dist/{signPsbtsWithFallback-Bo1PJX90.cjs.map → signPsbtsWithFallback-zOQWokmk.cjs.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +36 -35
- package/dist/tbv/core/clients/index.js.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +2 -0
- package/dist/tbv/core/clients/vault-provider/status/index.cjs.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts +18 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js +17 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js.map +1 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +224 -220
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +2 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +7 -7
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/primitives/scripts/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +0 -10
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +47 -44
- package/dist/tbv/core/utils/index.js.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -1
- package/dist/tbv/core/utils/validation.d.ts +4 -0
- package/dist/tbv/core/utils/validation.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +2 -2
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/constants.d.ts +11 -0
- package/dist/tbv/core/wasm/constants.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.cjs +2 -0
- package/dist/tbv/core/wasm/index.cjs.map +1 -0
- package/dist/tbv/core/wasm/index.d.ts +191 -0
- package/dist/tbv/core/wasm/index.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.js +144 -0
- package/dist/tbv/core/wasm/index.js.map +1 -0
- package/dist/tbv/core/wasm/value-guards.d.ts +30 -0
- package/dist/tbv/core/wasm/value-guards.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +224 -220
- package/dist/tbv/index.js.map +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/toRefundInputs-Bdtz8p27.cjs +2 -0
- package/dist/toRefundInputs-Bdtz8p27.cjs.map +1 -0
- package/dist/{toRefundInputs-DPNYBFkP.js → toRefundInputs-CgXMcHrk.js} +7 -7
- package/dist/toRefundInputs-CgXMcHrk.js.map +1 -0
- package/dist/validation-C6XTfZak.cjs +2 -0
- package/dist/validation-C6XTfZak.cjs.map +1 -0
- package/dist/validation-OSC0xTHB.js +17 -0
- package/dist/validation-OSC0xTHB.js.map +1 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs +2 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs.map +1 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js +10 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +1 -0
- package/dist/{verifyKeyPathSchnorrSignature-C6Cmk0R1.js → verifyKeyPathSchnorrSignature-BrgUJmV0.js} +3 -3
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-CQYucnJA.js → verifyScriptPathSchnorrSignature-ZAZfFJ6S.js} +35 -34
- package/dist/verifyScriptPathSchnorrSignature-ZAZfFJ6S.js.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs.map +1 -0
- package/package.json +12 -2
- package/dist/PeginManager-BNtg6jgY.js.map +0 -1
- package/dist/PeginManager-CvI99Uhd.cjs +0 -2
- package/dist/PeginManager-CvI99Uhd.cjs.map +0 -1
- package/dist/batchPoll-BM4iQ9jT.js.map +0 -1
- package/dist/batchPoll-cqpEfBjr.cjs +0 -2
- package/dist/batchPoll-cqpEfBjr.cjs.map +0 -1
- package/dist/bitcoin-Ch_jxnDa.js.map +0 -1
- package/dist/bitcoin-m84N5a8o.cjs +0 -2
- package/dist/bitcoin-m84N5a8o.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-iNJfx0ZG.cjs +0 -2
- package/dist/challengeAssert-BNQ8sToz.js.map +0 -1
- package/dist/challengeAssert-BrpC3-cQ.cjs +0 -2
- package/dist/challengeAssert-BrpC3-cQ.cjs.map +0 -1
- package/dist/constants-BCdDRd_Y.cjs +0 -2
- package/dist/constants-BCdDRd_Y.cjs.map +0 -1
- package/dist/constants-DRiWbItj.js +0 -24
- package/dist/constants-DRiWbItj.js.map +0 -1
- package/dist/mempoolApi-Q90mz17e.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs.map +0 -1
- package/dist/noPayout-BdATUPjF.js +0 -280
- package/dist/noPayout-BdATUPjF.js.map +0 -1
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs +0 -2
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs.map +0 -1
- package/dist/parseFundingOutpoints-CO-f6IHK.js.map +0 -1
- package/dist/signPsbtsWithFallback-Bo1PJX90.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs.map +0 -1
- package/dist/toRefundInputs-DPNYBFkP.js.map +0 -1
- package/dist/validation-CDbOaDj7.cjs +0 -2
- package/dist/validation-CDbOaDj7.cjs.map +0 -1
- package/dist/validation-Dj3dqYtl.js +0 -30
- package/dist/validation-Dj3dqYtl.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-CQYucnJA.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bitcoin-C-TuHb-v.js","sources":["../src/tbv/core/primitives/utils/bitcoin.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { networks, payments } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../utils/validation\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Hex-string length of a 65-byte SEC1-uncompressed secp256k1 public\n * key (`0x04` prefix + 32-byte x + 32-byte y). `2 * 65 = 130`.\n */\nconst UNCOMPRESSED_PUBKEY_HEX_LEN = 130;\n\n/**\n * Hex-string length of a 64-byte BIP-340 Schnorr signature. `2 * 64 = 128`.\n */\nexport const SCHNORR_SIG_HEX_LEN = 128;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n if (hex.startsWith(\"0x\")) return hex as Hex;\n if (hex.startsWith(\"0X\")) return `0x${hex.slice(2)}` as Hex;\n return `0x${hex}` as Hex;\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Read the prevout txid (big-endian hex) from a bitcoinjs-lib transaction input.\n *\n * bitcoinjs-lib stores `hash` in little-endian internal byte order; txids are\n * displayed in big-endian, so the bytes must be reversed before hex-encoding.\n *\n * @param input - Transaction input with a `hash` field (Buffer or Uint8Array)\n * @returns Prevout txid as a hex string (big-endian, no 0x prefix)\n */\nexport function inputTxidHex(input: { hash: Buffer | Uint8Array }): string {\n return uint8ArrayToHex(new Uint8Array(input.hash).slice().reverse());\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === X_ONLY_PUBKEY_HEX_LEN) {\n return cleanHex;\n }\n\n // Validate public key length (compressed SEC1 or uncompressed SEC1)\n if (\n cleanHex.length !== COMPRESSED_PUBKEY_HEX_LEN &&\n cleanHex.length !== UNCOMPRESSED_PUBKEY_HEX_LEN\n ) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected ${X_ONLY_PUBKEY_HEX_LEN}, ${COMPRESSED_PUBKEY_HEX_LEN}, or ${UNCOMPRESSED_PUBKEY_HEX_LEN} hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Normalize a public key to the one form two keys can be compared in:\n * lowercase x-only hex, no `0x`.\n *\n * `processPublicKeyToXOnly` returns already-x-only input untouched, so it\n * preserves case on that path — comparing its output directly is a latent\n * false mismatch for any source that serves uppercase hex. Every comparison\n * site therefore has to pair it with `.toLowerCase()`, and that pairing is\n * what this function exists to stop people re-deriving by hand.\n *\n * @param publicKeyHex - x-only, compressed, or uncompressed key, `0x` optional\n * @throws If the key is not valid hex or has an unexpected length\n */\nexport function canonicalizeBtcPubkey(publicKeyHex: string): string {\n return processPublicKeyToXOnly(publicKeyHex).toLowerCase();\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Validates the wallet x-only pubkey matches the expected depositor pubkey\n * (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only).\n * Required: omitting it would degrade this check to a self-comparison.\n * @returns Validation result with both pubkey formats\n * @throws If `expectedDepositorPubkey` is missing/empty\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey: string,\n): WalletPubkeyValidationResult {\n if (!expectedDepositorPubkey) {\n throw new Error(\n \"validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.\",\n );\n }\n\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`,\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// BTC formatting\n// ============================================================================\n\nconst SATOSHIS_PER_BTC = 100_000_000n;\n\n/**\n * Format satoshis as a human-readable BTC string with trailing zeros removed.\n */\nexport function formatSatoshisToBtc(satoshis: bigint): string {\n if (satoshis < 0n) {\n return `-${formatSatoshisToBtc(-satoshis)}`;\n }\n const whole = satoshis / SATOSHIS_PER_BTC;\n const fraction = satoshis % SATOSHIS_PER_BTC;\n let fractionStr = fraction.toString().padStart(8, \"0\");\n fractionStr = fractionStr.replace(/0+$/, \"\");\n return fractionStr.length > 0 ? `${whole}.${fractionStr}` : whole.toString();\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nexport function assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Strip `0x` prefixes and lex-sort an array of x-only public keys.\n *\n * Used to produce the canonical (Rust-parity) keeper / challenger ordering\n * the protocol expects in payout and refund signing contexts.\n *\n * @param pubkeys - Array of x-only public keys (with or without `0x` prefix)\n * @returns Lex-sorted array of pubkeys with `0x` prefix stripped\n */\nexport function getSortedXOnlyPubkeys(pubkeys: string[]): string[] {\n return pubkeys.map(stripHexPrefix).sort();\n}\n\n/**\n * Derive the BIP-86 P2TR scriptPubKey (`0x`-prefixed hex) from an x-only\n * public key.\n *\n * Matches Rust `Bip86KeyConnector::generate_taproot_script_pubkey`: a\n * keypath-only P2TR output with no script tree. Used to compute the expected\n * payout address for vault keeper claimers, whose payout goes to their own\n * BIP-86 address rather than the depositor's registered payout address.\n *\n * Network-agnostic: P2TR scriptPubKey bytes are `OP_1 <32-byte tweaked-key>`\n * regardless of network.\n *\n * @param xOnlyPubkeyHex - X-only public key (64 hex chars, with or without `0x` prefix)\n * @returns `0x`-prefixed P2TR scriptPubKey hex\n * @throws If `xOnlyPubkeyHex` is not exactly 64 hex chars after prefix stripping\n */\nexport function deriveBip86ScriptPubKeyHex(xOnlyPubkeyHex: string): string {\n assertEccInitialized();\n const cleanHex = stripHexPrefix(xOnlyPubkeyHex);\n if (!/^[0-9a-fA-F]{64}$/.test(cleanHex)) {\n throw new Error(\n \"Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)\",\n );\n }\n const { output } = payments.p2tr({\n internalPubkey: Buffer.from(cleanHex, \"hex\"),\n });\n if (!output) {\n throw new Error(\"Failed to derive BIP-86 P2TR scriptPubKey\");\n }\n return `0x${output.toString(\"hex\")}`;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive native segwit address from public key\");\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * P2WPKH derivation requires the full compressed key with explicit y-parity.\n * When only an x-only key is supplied, the y-parity is unknown and trying\n * both `02|x` and `03|x` would let an opposite-parity P2WPKH address — a\n * script the caller does NOT control — pass validation. We fail closed for\n * P2WPKH in that case; P2TR (which depends only on the x-coordinate) is\n * still validated and remains the supported path for Taproot wallets.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // P2WPKH — only attempt when the caller supplied a parity-bearing\n // compressed key. An x-only input is fail-closed here on purpose.\n if (cleanHex.length === COMPRESSED_PUBKEY_HEX_LEN) {\n try {\n if (address === deriveNativeSegwitAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n"],"names":["TAPSCRIPT_LEAF_VERSION","UNCOMPRESSED_PUBKEY_HEX_LEN","SCHNORR_SIG_HEX_LEN","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","inputTxidHex","input","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","pubkeyBytes","canonicalizeBtcPubkey","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","SATOSHIS_PER_BTC","formatSatoshisToBtc","satoshis","whole","fractionStr","assertEccInitialized","payments","Buffer","e","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","getSortedXOnlyPubkeys","pubkeys","deriveBip86ScriptPubKeyHex","xOnlyPubkeyHex","output","deriveNativeSegwitAddress","isAddressFromPublicKey"],"mappings":";;;AA+BO,MAAMA,IAAyB,KAMhCC,IAA8B,KAKvBC,IAAsB;AAW5B,SAASC,EAAeC,GAAqB;AAClD,SAAOA,EAAI,WAAW,IAAI,KAAKA,EAAI,WAAW,IAAI,IAAIA,EAAI,MAAM,CAAC,IAAIA;AACvE;AAWO,SAASC,EAAgBD,GAAkB;AAChD,SAAIA,EAAI,WAAW,IAAI,IAAUA,IAC7BA,EAAI,WAAW,IAAI,IAAU,KAAKA,EAAI,MAAM,CAAC,CAAC,KAC3C,KAAKA,CAAG;AACjB;AASO,SAASE,EAAgBF,GAAyB;AACvD,QAAMG,IAAWJ,EAAeC,CAAG;AACnC,MAAI,CAACI,EAAcD,CAAQ;AACzB,UAAM,IAAI,MAAM,uBAAuBH,CAAG,EAAE;AAE9C,QAAMK,IAAQ,IAAI,WAAW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Q;AAAA,EAER;AAIA,MAAIhC,EAAS,WAAWa;AACtB,QAAI;AACF,UAAIuB,MAAYM,EAA0B1C,GAAUgC,CAAO;AACzD,eAAO;AAAA,IAEX,QAAQ;AAAA,IAER;AAGF,SAAO;AACT;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const o=require("bitcoinjs-lib"),c=require("buffer"),s=require("./validation-C6XTfZak.cjs"),S=192,y=130,x=128;function i(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function g(e){return e.startsWith("0x")?e:e.startsWith("0X")?`0x${e.slice(2)}`:`0x${e}`}function a(e){const t=i(e);if(!f(t))throw new Error(`Invalid hex string: ${e}`);const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}function l(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function _(e){return l(new Uint8Array(e.hash).slice().reverse())}function p(e){return e.length===32?e:e.slice(1,33)}function f(e){return/^[0-9a-fA-F]*$/.test(e)&&e.length%2===0}function u(e){const t=i(e);if(!f(t))throw new Error(`Invalid hex characters in public key: ${e}`);if(t.length===s.X_ONLY_PUBKEY_HEX_LEN)return t;if(t.length!==s.COMPRESSED_PUBKEY_HEX_LEN&&t.length!==y)throw new Error(`Invalid public key length: ${t.length} (expected ${s.X_ONLY_PUBKEY_HEX_LEN}, ${s.COMPRESSED_PUBKEY_HEX_LEN}, or ${y} hex chars)`);const n=a(t);return l(p(n))}function k(e){return u(e).toLowerCase()}function H(e){const t=i(e);return f(t)}function v(e,t){if(!t)throw new Error("validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.");const n=u(e),r=t;if(n.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${n}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:e,walletPubkeyXOnly:n,depositorPubkey:r}}const h=100000000n;function w(e){if(e<0n)return`-${w(-e)}`;const t=e/h;let r=(e%h).toString().padStart(8,"0");return r=r.replace(/0+$/,""),r.length>0?`${t}.${r}`:t.toString()}function d(){try{o.payments.p2tr({internalPubkey:c.Buffer.alloc(32,1)})}catch(e){if(e instanceof Error&&e.message.includes("No ECC Library provided"))throw new Error('ECC library not initialized. You must call initEccLib(ecc) from "bitcoinjs-lib" before using the SDK. See the ts-sdk README for setup instructions.')}}function E(e){switch(e){case"bitcoin":return o.networks.bitcoin;case"testnet":case"signet":return o.networks.testnet;case"regtest":return o.networks.regtest;default:throw new Error(`Unknown network: ${e}`)}}function P(e,t){d();const n=a(u(e)),{address:r}=o.payments.p2tr({internalPubkey:c.Buffer.from(n),network:E(t)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function m(e){return e.map(i).sort()}function A(e){d();const t=i(e);if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)");const{output:n}=o.payments.p2tr({internalPubkey:c.Buffer.from(t,"hex")});if(!n)throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");return`0x${n.toString("hex")}`}function b(e,t){const n=i(e);if(n.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`);const{address:r}=o.payments.p2wpkh({pubkey:c.Buffer.from(a(n)),network:E(t)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function N(e,t,n){const r=i(t);try{if(e===P(r,n))return!0}catch{}if(r.length===s.COMPRESSED_PUBKEY_HEX_LEN)try{if(e===b(r,n))return!0}catch{}return!1}exports.SCHNORR_SIG_HEX_LEN=x;exports.TAPSCRIPT_LEAF_VERSION=S;exports.assertEccInitialized=d;exports.canonicalizeBtcPubkey=k;exports.deriveBip86ScriptPubKeyHex=A;exports.deriveNativeSegwitAddress=b;exports.deriveTaprootAddress=P;exports.ensureHexPrefix=g;exports.formatSatoshisToBtc=w;exports.getNetwork=E;exports.getSortedXOnlyPubkeys=m;exports.hexToUint8Array=a;exports.inputTxidHex=_;exports.isAddressFromPublicKey=N;exports.isValidHex=H;exports.processPublicKeyToXOnly=u;exports.stripHexPrefix=i;exports.toXOnly=p;exports.uint8ArrayToHex=l;exports.validateWalletPubkey=v;
|
|
2
|
+
//# sourceMappingURL=bitcoin-D-O2GjbC.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bitcoin-D-O2GjbC.cjs","sources":["../src/tbv/core/primitives/utils/bitcoin.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { networks, payments } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../utils/validation\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Hex-string length of a 65-byte SEC1-uncompressed secp256k1 public\n * key (`0x04` prefix + 32-byte x + 32-byte y). `2 * 65 = 130`.\n */\nconst UNCOMPRESSED_PUBKEY_HEX_LEN = 130;\n\n/**\n * Hex-string length of a 64-byte BIP-340 Schnorr signature. `2 * 64 = 128`.\n */\nexport const SCHNORR_SIG_HEX_LEN = 128;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n if (hex.startsWith(\"0x\")) return hex as Hex;\n if (hex.startsWith(\"0X\")) return `0x${hex.slice(2)}` as Hex;\n return `0x${hex}` as Hex;\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Read the prevout txid (big-endian hex) from a bitcoinjs-lib transaction input.\n *\n * bitcoinjs-lib stores `hash` in little-endian internal byte order; txids are\n * displayed in big-endian, so the bytes must be reversed before hex-encoding.\n *\n * @param input - Transaction input with a `hash` field (Buffer or Uint8Array)\n * @returns Prevout txid as a hex string (big-endian, no 0x prefix)\n */\nexport function inputTxidHex(input: { hash: Buffer | Uint8Array }): string {\n return uint8ArrayToHex(new Uint8Array(input.hash).slice().reverse());\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === X_ONLY_PUBKEY_HEX_LEN) {\n return cleanHex;\n }\n\n // Validate public key length (compressed SEC1 or uncompressed SEC1)\n if (\n cleanHex.length !== COMPRESSED_PUBKEY_HEX_LEN &&\n cleanHex.length !== UNCOMPRESSED_PUBKEY_HEX_LEN\n ) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected ${X_ONLY_PUBKEY_HEX_LEN}, ${COMPRESSED_PUBKEY_HEX_LEN}, or ${UNCOMPRESSED_PUBKEY_HEX_LEN} hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Normalize a public key to the one form two keys can be compared in:\n * lowercase x-only hex, no `0x`.\n *\n * `processPublicKeyToXOnly` returns already-x-only input untouched, so it\n * preserves case on that path — comparing its output directly is a latent\n * false mismatch for any source that serves uppercase hex. Every comparison\n * site therefore has to pair it with `.toLowerCase()`, and that pairing is\n * what this function exists to stop people re-deriving by hand.\n *\n * @param publicKeyHex - x-only, compressed, or uncompressed key, `0x` optional\n * @throws If the key is not valid hex or has an unexpected length\n */\nexport function canonicalizeBtcPubkey(publicKeyHex: string): string {\n return processPublicKeyToXOnly(publicKeyHex).toLowerCase();\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Validates the wallet x-only pubkey matches the expected depositor pubkey\n * (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only).\n * Required: omitting it would degrade this check to a self-comparison.\n * @returns Validation result with both pubkey formats\n * @throws If `expectedDepositorPubkey` is missing/empty\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey: string,\n): WalletPubkeyValidationResult {\n if (!expectedDepositorPubkey) {\n throw new Error(\n \"validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison.\",\n );\n }\n\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`,\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// BTC formatting\n// ============================================================================\n\nconst SATOSHIS_PER_BTC = 100_000_000n;\n\n/**\n * Format satoshis as a human-readable BTC string with trailing zeros removed.\n */\nexport function formatSatoshisToBtc(satoshis: bigint): string {\n if (satoshis < 0n) {\n return `-${formatSatoshisToBtc(-satoshis)}`;\n }\n const whole = satoshis / SATOSHIS_PER_BTC;\n const fraction = satoshis % SATOSHIS_PER_BTC;\n let fractionStr = fraction.toString().padStart(8, \"0\");\n fractionStr = fractionStr.replace(/0+$/, \"\");\n return fractionStr.length > 0 ? `${whole}.${fractionStr}` : whole.toString();\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nexport function assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Strip `0x` prefixes and lex-sort an array of x-only public keys.\n *\n * Used to produce the canonical (Rust-parity) keeper / challenger ordering\n * the protocol expects in payout and refund signing contexts.\n *\n * @param pubkeys - Array of x-only public keys (with or without `0x` prefix)\n * @returns Lex-sorted array of pubkeys with `0x` prefix stripped\n */\nexport function getSortedXOnlyPubkeys(pubkeys: string[]): string[] {\n return pubkeys.map(stripHexPrefix).sort();\n}\n\n/**\n * Derive the BIP-86 P2TR scriptPubKey (`0x`-prefixed hex) from an x-only\n * public key.\n *\n * Matches Rust `Bip86KeyConnector::generate_taproot_script_pubkey`: a\n * keypath-only P2TR output with no script tree. Used to compute the expected\n * payout address for vault keeper claimers, whose payout goes to their own\n * BIP-86 address rather than the depositor's registered payout address.\n *\n * Network-agnostic: P2TR scriptPubKey bytes are `OP_1 <32-byte tweaked-key>`\n * regardless of network.\n *\n * @param xOnlyPubkeyHex - X-only public key (64 hex chars, with or without `0x` prefix)\n * @returns `0x`-prefixed P2TR scriptPubKey hex\n * @throws If `xOnlyPubkeyHex` is not exactly 64 hex chars after prefix stripping\n */\nexport function deriveBip86ScriptPubKeyHex(xOnlyPubkeyHex: string): string {\n assertEccInitialized();\n const cleanHex = stripHexPrefix(xOnlyPubkeyHex);\n if (!/^[0-9a-fA-F]{64}$/.test(cleanHex)) {\n throw new Error(\n \"Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)\",\n );\n }\n const { output } = payments.p2tr({\n internalPubkey: Buffer.from(cleanHex, \"hex\"),\n });\n if (!output) {\n throw new Error(\"Failed to derive BIP-86 P2TR scriptPubKey\");\n }\n return `0x${output.toString(\"hex\")}`;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive native segwit address from public key\");\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * P2WPKH derivation requires the full compressed key with explicit y-parity.\n * When only an x-only key is supplied, the y-parity is unknown and trying\n * both `02|x` and `03|x` would let an opposite-parity P2WPKH address — a\n * script the caller does NOT control — pass validation. We fail closed for\n * P2WPKH in that case; P2TR (which depends only on the x-coordinate) is\n * still validated and remains the supported path for Taproot wallets.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // P2WPKH — only attempt when the caller supplied a parity-bearing\n // compressed key. An x-only input is fail-closed here on purpose.\n if (cleanHex.length === COMPRESSED_PUBKEY_HEX_LEN) {\n try {\n if (address === deriveNativeSegwitAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n"],"names":["TAPSCRIPT_LEAF_VERSION","UNCOMPRESSED_PUBKEY_HEX_LEN","SCHNORR_SIG_HEX_LEN","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","inputTxidHex","input","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","pubkeyBytes","canonicalizeBtcPubkey","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","SATOSHIS_PER_BTC","formatSatoshisToBtc","satoshis","whole","fractionStr","assertEccInitialized","payments","Buffer","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","getSortedXOnlyPubkeys","pubkeys","deriveBip86ScriptPubKeyHex","xOnlyPubkey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,SAAW,GACtB,MAAM,IAAI,MACR,sEAAsEA,EAAS,MAAM,EAAA,EAGzF,KAAM,CAAE,QAAAmC,CAAA,EAAYP,EAAAA,SAAS,OAAO,CAClC,OAAQC,EAAAA,OAAO,KAAK9B,EAAgBC,CAAQ,CAAC,EAC7C,QAAS8B,EAAWC,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MAAM,wDAAwD,EAE1E,OAAOA,CACT,CAoBO,SAASO,EACdP,EACAxB,EACAoB,EACS,CACT,MAAM/B,EAAWJ,EAAee,CAAY,EAG5C,GAAI,CACF,GAAIwB,IAAYF,EAAqBjC,EAAU+B,CAAO,EACpD,MAAO,EAEX,MAAQ,CAER,CAIA,GAAI/B,EAAS,SAAWa,4BACtB,GAAI,CACF,GAAIsB,IAAYM,EAA0BzC,EAAU+B,CAAO,EACzD,MAAO,EAEX,MAAQ,CAER,CAGF,MAAO,EACT"}
|
|
@@ -2,16 +2,17 @@ var Ee = Object.defineProperty;
|
|
|
2
2
|
var ke = (e, t, r) => t in e ? Ee(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
|
|
3
3
|
var C = (e, t, r) => ke(e, typeof t != "symbol" ? t + "" : t, r);
|
|
4
4
|
import { B as ae } from "./BTCVaultRegistry.abi-CJwWI2EO.js";
|
|
5
|
-
import { e as xe, v as Te, s as y, u as ie, p as O, c as x, f as R } from "./bitcoin-
|
|
6
|
-
import { v as Ae, d as Re, s as Ce, P as _e, a as Se } from "./signPsbtsWithFallback-
|
|
5
|
+
import { e as xe, v as Te, s as y, u as ie, p as O, c as x, f as R } from "./bitcoin-C-TuHb-v.js";
|
|
6
|
+
import { v as Ae, d as Re, s as Ce, P as _e, a as Se } from "./signPsbtsWithFallback-BjXdnI0X.js";
|
|
7
7
|
import { zeroAddress as $e } from "viem";
|
|
8
8
|
import { D as T, c as Be, b as Ie, R as Ve, d as ue } from "./json-rpc-client-DuUARJvV.js";
|
|
9
9
|
import { Transaction as _, Psbt as le } from "bitcoinjs-lib";
|
|
10
|
-
import { m as Ke, f as Oe, i as B, g as I, j as V } from "./verifyScriptPathSchnorrSignature-
|
|
11
|
-
import { D as X
|
|
12
|
-
import { d as
|
|
10
|
+
import { m as Ke, f as Oe, i as B, g as I, j as V } from "./verifyScriptPathSchnorrSignature-ZAZfFJ6S.js";
|
|
11
|
+
import { D as X } from "./constants-CPzppOdq.js";
|
|
12
|
+
import { d as Ne, c as He, b as De, e as Fe, a as Me } from "./noPayout--lxo7qe4.js";
|
|
13
13
|
import { c as K } from "./signing-DaLvGwQe.js";
|
|
14
|
-
import { a as G } from "./onChainBtcPubkey-
|
|
14
|
+
import { a as G } from "./onChainBtcPubkey-DATNfAAl.js";
|
|
15
|
+
import { a as Ue } from "./vaultCoreVersion-D_fP9P3C.js";
|
|
15
16
|
const Le = /^0x[0-9a-fA-F]{64}$/, ze = /^0x[0-9a-fA-F]{40}$/, Xe = /^0x([0-9a-fA-F]{2})*$/;
|
|
16
17
|
function N(e, t) {
|
|
17
18
|
if (e.length !== 66)
|
|
@@ -44,7 +45,7 @@ function ce(e) {
|
|
|
44
45
|
);
|
|
45
46
|
return t;
|
|
46
47
|
}
|
|
47
|
-
async function
|
|
48
|
+
async function jt(e) {
|
|
48
49
|
const {
|
|
49
50
|
btcVaultRegistryAddress: t,
|
|
50
51
|
vaultId: r,
|
|
@@ -67,7 +68,7 @@ async function qt(e) {
|
|
|
67
68
|
args: [r, n, a]
|
|
68
69
|
});
|
|
69
70
|
}
|
|
70
|
-
async function
|
|
71
|
+
async function Qt(e) {
|
|
71
72
|
const { btcVaultRegistryAddress: t, vaultId: r, hashlock: o, writeContract: a, signal: l } = e;
|
|
72
73
|
l == null || l.throwIfAborted();
|
|
73
74
|
const s = ce({
|
|
@@ -97,14 +98,14 @@ class de extends Error {
|
|
|
97
98
|
function Je(e) {
|
|
98
99
|
return e instanceof he || e instanceof Error && e.name === "PeginRegistrationMissingError";
|
|
99
100
|
}
|
|
100
|
-
function
|
|
101
|
+
function Wt(e) {
|
|
101
102
|
return e instanceof de || e instanceof Error && e.name === "PeginRegistrationNotFinalError";
|
|
102
103
|
}
|
|
103
104
|
function q(e) {
|
|
104
105
|
const { currentBlock: t, createdAtBlock: r } = e, o = t - r + 1n;
|
|
105
106
|
return o < 0n ? 0 : Number(o);
|
|
106
107
|
}
|
|
107
|
-
async function
|
|
108
|
+
async function Yt(e) {
|
|
108
109
|
const {
|
|
109
110
|
vaultRegistryReader: t,
|
|
110
111
|
getBlockNumber: r,
|
|
@@ -291,7 +292,7 @@ async function ot(e) {
|
|
|
291
292
|
assertTxParsed: l,
|
|
292
293
|
ctx: s
|
|
293
294
|
} = e;
|
|
294
|
-
|
|
295
|
+
Ne(
|
|
295
296
|
t.nopayout_tx.tx_hex,
|
|
296
297
|
r,
|
|
297
298
|
s.network
|
|
@@ -334,7 +335,7 @@ async function ot(e) {
|
|
|
334
335
|
script_pubkey: ie(new Uint8Array(c.script)),
|
|
335
336
|
value: c.value
|
|
336
337
|
}));
|
|
337
|
-
return
|
|
338
|
+
return He({
|
|
338
339
|
noPayoutTxHex: t.nopayout_tx.tx_hex,
|
|
339
340
|
challengerPubkey: r,
|
|
340
341
|
prevouts: h,
|
|
@@ -590,7 +591,7 @@ async function dt(e, t, r, o) {
|
|
|
590
591
|
};
|
|
591
592
|
return o == null || o(l, l), n;
|
|
592
593
|
}
|
|
593
|
-
async function
|
|
594
|
+
async function Jt(e) {
|
|
594
595
|
const {
|
|
595
596
|
statusReader: t,
|
|
596
597
|
presignClient: r,
|
|
@@ -679,7 +680,7 @@ const pt = 300 * 1e3, gt = /* @__PURE__ */ new Set([
|
|
|
679
680
|
T.PENDING_DEPOSITOR_WOTS_PK,
|
|
680
681
|
...ue
|
|
681
682
|
]);
|
|
682
|
-
async function
|
|
683
|
+
async function Zt(e) {
|
|
683
684
|
const {
|
|
684
685
|
statusReader: t,
|
|
685
686
|
wotsSubmitter: r,
|
|
@@ -729,7 +730,7 @@ function F(e) {
|
|
|
729
730
|
function W(e, t) {
|
|
730
731
|
return e.length === t.length && e.every((r, o) => r === t[o]);
|
|
731
732
|
}
|
|
732
|
-
async function
|
|
733
|
+
async function er(e) {
|
|
733
734
|
const {
|
|
734
735
|
vaultProviderEthAddress: t,
|
|
735
736
|
hintBtcPubkey: r,
|
|
@@ -820,7 +821,7 @@ async function vt(e) {
|
|
|
820
821
|
});
|
|
821
822
|
}
|
|
822
823
|
const Y = (e) => e.map(x).sort();
|
|
823
|
-
async function
|
|
824
|
+
async function tr(e) {
|
|
824
825
|
const {
|
|
825
826
|
vaultRegistryReader: t,
|
|
826
827
|
vaultKeeperReader: r,
|
|
@@ -915,7 +916,7 @@ async function er(e) {
|
|
|
915
916
|
function yt(e) {
|
|
916
917
|
return /^[0-9a-fA-F]{64}$/.test(e);
|
|
917
918
|
}
|
|
918
|
-
function
|
|
919
|
+
function rr(e) {
|
|
919
920
|
const {
|
|
920
921
|
amountSats: t,
|
|
921
922
|
minDeposit: r,
|
|
@@ -926,7 +927,7 @@ function tr(e) {
|
|
|
926
927
|
} = e;
|
|
927
928
|
return !(t <= 0n || t < r || o && o > 0n && t > o || l == null || s == null || t + l + s > a);
|
|
928
929
|
}
|
|
929
|
-
function
|
|
930
|
+
function or(e, t, r) {
|
|
930
931
|
return e <= 0n ? {
|
|
931
932
|
valid: !1,
|
|
932
933
|
error: "Deposit amount must be greater than zero"
|
|
@@ -938,7 +939,7 @@ function rr(e, t, r) {
|
|
|
938
939
|
error: `Maximum deposit is ${R(r)} BTC`
|
|
939
940
|
} : { valid: !0 };
|
|
940
941
|
}
|
|
941
|
-
function
|
|
942
|
+
function nr(e) {
|
|
942
943
|
const { amount: t, effectiveRemaining: r } = e;
|
|
943
944
|
return r === null ? { valid: !0 } : r === 0n ? {
|
|
944
945
|
valid: !1,
|
|
@@ -948,7 +949,7 @@ function or(e) {
|
|
|
948
949
|
error: `Vault size exceeds remaining capacity (${R(r)} BTC)`
|
|
949
950
|
} : { valid: !0 };
|
|
950
951
|
}
|
|
951
|
-
function
|
|
952
|
+
function sr(e, t) {
|
|
952
953
|
if (!e || e.length === 0)
|
|
953
954
|
return {
|
|
954
955
|
valid: !1,
|
|
@@ -1013,7 +1014,7 @@ function xt(e) {
|
|
|
1013
1014
|
if (e.length === 0)
|
|
1014
1015
|
throw new Error("No spendable UTXOs available");
|
|
1015
1016
|
}
|
|
1016
|
-
function
|
|
1017
|
+
function ar(e) {
|
|
1017
1018
|
const {
|
|
1018
1019
|
vaultAmounts: t,
|
|
1019
1020
|
confirmedUTXOs: r,
|
|
@@ -1039,13 +1040,13 @@ class me extends Error {
|
|
|
1039
1040
|
super(t), this.name = "ParticipantKeyDriftError";
|
|
1040
1041
|
}
|
|
1041
1042
|
}
|
|
1042
|
-
function
|
|
1043
|
+
function ir(e) {
|
|
1043
1044
|
return e instanceof me || e instanceof Error && e.name === "ParticipantKeyDriftError";
|
|
1044
1045
|
}
|
|
1045
1046
|
function J(e, t, r) {
|
|
1046
1047
|
return t.length === r.length && t.every((o, a) => o === r[a]) ? null : `${e} expected [${t.join(", ")}], got [${r.join(", ")}]`;
|
|
1047
1048
|
}
|
|
1048
|
-
async function
|
|
1049
|
+
async function ur(e) {
|
|
1049
1050
|
const { vaultRegistryReader: t, operationKeyReader: r, vaultIds: o, expected: a } = e, l = a.query;
|
|
1050
1051
|
if (o.length === 0) return;
|
|
1051
1052
|
const s = await t.getVaultKeyEpochsBatch(o), n = [];
|
|
@@ -1090,10 +1091,10 @@ class Pe extends Error {
|
|
|
1090
1091
|
super(t), this.name = "RegisteredVaultVersionMismatchError";
|
|
1091
1092
|
}
|
|
1092
1093
|
}
|
|
1093
|
-
function
|
|
1094
|
+
function lr(e) {
|
|
1094
1095
|
return e instanceof Pe || e instanceof Error && e.name === "RegisteredVaultVersionMismatchError";
|
|
1095
1096
|
}
|
|
1096
|
-
async function
|
|
1097
|
+
async function cr(e) {
|
|
1097
1098
|
const {
|
|
1098
1099
|
vaultRegistryReader: t,
|
|
1099
1100
|
vaultIds: r,
|
|
@@ -1124,12 +1125,12 @@ const Tt = /* @__PURE__ */ new Set([
|
|
|
1124
1125
|
"PayoutBlocked"
|
|
1125
1126
|
/* PAYOUT_BLOCKED */
|
|
1126
1127
|
]);
|
|
1127
|
-
function
|
|
1128
|
+
function hr(e) {
|
|
1128
1129
|
return Object.values(ve).includes(
|
|
1129
1130
|
e
|
|
1130
1131
|
);
|
|
1131
1132
|
}
|
|
1132
|
-
function
|
|
1133
|
+
function dr(e) {
|
|
1133
1134
|
return !!e && Tt.has(e);
|
|
1134
1135
|
}
|
|
1135
1136
|
class At extends Error {
|
|
@@ -1141,7 +1142,7 @@ class At extends Error {
|
|
|
1141
1142
|
}
|
|
1142
1143
|
}
|
|
1143
1144
|
const Rt = /^0x[0-9a-fA-F]{64}$/, Ct = /^(?:0x)?(?:[0-9a-fA-F]{2})+$/, ye = /^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/, be = 160, Z = 2e3, ee = 10n, te = 100n;
|
|
1144
|
-
function
|
|
1145
|
+
function pr(e) {
|
|
1145
1146
|
if (!Number.isFinite(e) || e <= 0)
|
|
1146
1147
|
throw new Error(
|
|
1147
1148
|
`feeRateSatsVb must be a positive finite number, got ${e}`
|
|
@@ -1197,7 +1198,7 @@ function $t(e) {
|
|
|
1197
1198
|
if (U(e.offchainParamsVersion, "offchainParamsVersion"), U(e.appVaultKeepersVersion, "appVaultKeepersVersion"), U(
|
|
1198
1199
|
e.universalChallengersVersion,
|
|
1199
1200
|
"universalChallengersVersion"
|
|
1200
|
-
),
|
|
1201
|
+
), Ue(
|
|
1201
1202
|
e.vaultCoreVersion,
|
|
1202
1203
|
"VaultRefundData.vaultCoreVersion"
|
|
1203
1204
|
), typeof e.unsignedPrePeginTxHex != "string" || e.unsignedPrePeginTxHex.length === 0)
|
|
@@ -1250,7 +1251,7 @@ function It(e) {
|
|
|
1250
1251
|
}
|
|
1251
1252
|
return t.extractTransaction().toHex();
|
|
1252
1253
|
}
|
|
1253
|
-
async function
|
|
1254
|
+
async function gr(e) {
|
|
1254
1255
|
const {
|
|
1255
1256
|
vaultId: t,
|
|
1256
1257
|
readVault: r,
|
|
@@ -1296,7 +1297,7 @@ async function pr(e) {
|
|
|
1296
1297
|
throw new Error(
|
|
1297
1298
|
`Funded Pre-PegIn tx has ${f.outs.length} outputs but batch requires at least ${i.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`
|
|
1298
1299
|
);
|
|
1299
|
-
const { psbtHex: P } = await
|
|
1300
|
+
const { psbtHex: P } = await De({
|
|
1300
1301
|
prePeginParams: {
|
|
1301
1302
|
vaultCoreVersion: i.vaultCoreVersion,
|
|
1302
1303
|
depositorPubkey: d,
|
|
@@ -1367,7 +1368,7 @@ class re extends Error {
|
|
|
1367
1368
|
this.name = "ReclaimUneconomicalError", this.feeSats = o, this.sweptTotalSats = a;
|
|
1368
1369
|
}
|
|
1369
1370
|
}
|
|
1370
|
-
const oe = 2e3, ne = 25n, se = 100n,
|
|
1371
|
+
const oe = 2e3, ne = 25n, se = 100n, fr = 10n;
|
|
1371
1372
|
function Vt(e) {
|
|
1372
1373
|
const t = le.fromHex(e);
|
|
1373
1374
|
try {
|
|
@@ -1379,7 +1380,7 @@ function Vt(e) {
|
|
|
1379
1380
|
}
|
|
1380
1381
|
return t.extractTransaction().toHex();
|
|
1381
1382
|
}
|
|
1382
|
-
async function
|
|
1383
|
+
async function mr(e) {
|
|
1383
1384
|
const {
|
|
1384
1385
|
vaultIds: t,
|
|
1385
1386
|
depositorBtcPubkey: r,
|
|
@@ -1408,7 +1409,7 @@ async function fr(e) {
|
|
|
1408
1409
|
depositorSignedPeginTxHex: v.depositorSignedPeginTxHex,
|
|
1409
1410
|
observed: v.observed,
|
|
1410
1411
|
expectedValue: v.expectedClaimValue
|
|
1411
|
-
})), c =
|
|
1412
|
+
})), c = Fe(a, h.length), d = h.reduce((v, m) => v + m.expectedValue, 0n), p = d * ne / se;
|
|
1412
1413
|
if (c > p)
|
|
1413
1414
|
throw new re(
|
|
1414
1415
|
`Reclaim fee ${c} sats exceeds ${ne}/${se} of the swept total (${d} sats, cap ${p} sats). The reserve is not at risk — it stays where it is until fee rates fall.`,
|
|
@@ -1416,7 +1417,7 @@ async function fr(e) {
|
|
|
1416
1417
|
d
|
|
1417
1418
|
);
|
|
1418
1419
|
n == null || n.throwIfAborted();
|
|
1419
|
-
const { psbtHex: g } =
|
|
1420
|
+
const { psbtHex: g } = Me({
|
|
1420
1421
|
depositorPubkey: u,
|
|
1421
1422
|
inputs: h,
|
|
1422
1423
|
feeSats: c
|
|
@@ -1451,48 +1452,48 @@ export {
|
|
|
1451
1452
|
Pt as C,
|
|
1452
1453
|
vt as D,
|
|
1453
1454
|
ve as E,
|
|
1454
|
-
|
|
1455
|
-
|
|
1455
|
+
hr as F,
|
|
1456
|
+
dr as G,
|
|
1456
1457
|
At as H,
|
|
1457
|
-
|
|
1458
|
-
|
|
1458
|
+
gr as I,
|
|
1459
|
+
pr as J,
|
|
1459
1460
|
te as K,
|
|
1460
1461
|
ee as L,
|
|
1461
1462
|
Z as M,
|
|
1462
1463
|
be as N,
|
|
1463
1464
|
re as O,
|
|
1464
1465
|
je as P,
|
|
1465
|
-
|
|
1466
|
+
mr as Q,
|
|
1466
1467
|
Pe as R,
|
|
1467
1468
|
se as S,
|
|
1468
1469
|
ne as T,
|
|
1469
1470
|
oe as U,
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1471
|
+
fr as V,
|
|
1472
|
+
jt as a,
|
|
1473
|
+
Qt as b,
|
|
1473
1474
|
he as c,
|
|
1474
1475
|
de as d,
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1476
|
+
Wt as e,
|
|
1477
|
+
Zt as f,
|
|
1478
|
+
rr as g,
|
|
1479
|
+
or as h,
|
|
1479
1480
|
Je as i,
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1481
|
+
ar as j,
|
|
1482
|
+
sr as k,
|
|
1483
|
+
nr as l,
|
|
1483
1484
|
bt as m,
|
|
1484
1485
|
wt as n,
|
|
1485
1486
|
me as o,
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1487
|
+
ir as p,
|
|
1488
|
+
ur as q,
|
|
1489
|
+
Jt as r,
|
|
1489
1490
|
st as s,
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1491
|
+
lr as t,
|
|
1492
|
+
cr as u,
|
|
1493
|
+
tr as v,
|
|
1494
|
+
Yt as w,
|
|
1494
1495
|
pe as x,
|
|
1495
|
-
|
|
1496
|
+
er as y,
|
|
1496
1497
|
D as z
|
|
1497
1498
|
};
|
|
1498
|
-
//# sourceMappingURL=buildAndBroadcastReclaim-
|
|
1499
|
+
//# sourceMappingURL=buildAndBroadcastReclaim-C0TdwO2M.js.map
|