@babylonlabs-io/ts-sdk 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -12
- package/dist/bitcoin-CNnPFU6Y.cjs +2 -0
- package/dist/bitcoin-CNnPFU6Y.cjs.map +1 -0
- package/dist/{constants-Q7v2O7Ps.js → bitcoin-nOOgeRyl.js} +64 -76
- package/dist/bitcoin-nOOgeRyl.js.map +1 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs +2 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js +1331 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js.map +1 -0
- package/dist/challengeAssert-D1lpvuMv.js +283 -0
- package/dist/challengeAssert-D1lpvuMv.js.map +1 -0
- package/dist/challengeAssert-nYlgeAI8.cjs +2 -0
- package/dist/challengeAssert-nYlgeAI8.cjs.map +1 -0
- package/dist/errors-BZON3Wmn.cjs +2 -0
- package/dist/errors-BZON3Wmn.cjs.map +1 -0
- package/dist/errors-CHY4WNi-.js +1226 -0
- package/dist/errors-CHY4WNi-.js.map +1 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js +70 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js.map +1 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs +2 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +1 -0
- package/dist/index-BpXpESWu.cjs +2 -0
- package/dist/index-BpXpESWu.cjs.map +1 -0
- package/dist/index-CFwoGJNQ.js +1141 -0
- package/dist/index-CFwoGJNQ.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +134 -100
- package/dist/payout-DzGsAnhf.js +261 -0
- package/dist/payout-DzGsAnhf.js.map +1 -0
- package/dist/payout-RFIh7GLN.cjs +2 -0
- package/dist/payout-RFIh7GLN.cjs.map +1 -0
- package/dist/psbtInputFields-C-zYR1z7.cjs +2 -0
- package/dist/psbtInputFields-C-zYR1z7.cjs.map +1 -0
- package/dist/psbtInputFields-Dx41_IoI.js +229 -0
- package/dist/psbtInputFields-Dx41_IoI.js.map +1 -0
- package/dist/signing-DeWVBl7m.js +64 -0
- package/dist/signing-DeWVBl7m.js.map +1 -0
- package/dist/signing-cl-lowxV.cjs +2 -0
- package/dist/signing-cl-lowxV.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts +18 -0
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/index.d.ts +4 -1
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +27 -0
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +37 -0
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/types.d.ts +80 -0
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +25 -21
- package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts +74 -0
- package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts.map +1 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +20 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +233 -0
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -0
- package/dist/tbv/core/contracts/index.d.ts +2 -0
- package/dist/tbv/core/contracts/index.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -1
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +129 -95
- package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +3 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +24 -23
- package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/index.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 +2 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +4 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts +2 -0
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts +77 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/index.d.ts +7 -0
- package/dist/tbv/core/services/activation/index.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts +5 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +4 -0
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +93 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/validation.d.ts +114 -0
- package/dist/tbv/core/services/deposit/validation.d.ts.map +1 -0
- package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts +2 -0
- package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts.map +1 -0
- package/dist/tbv/core/services/htlc/index.d.ts +25 -0
- package/dist/tbv/core/services/htlc/index.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +4 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +25 -5
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts +2 -0
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/index.d.ts +2 -0
- package/dist/tbv/core/services/pegout/index.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/state.d.ts +30 -0
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts +2 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +103 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/errors.d.ts +13 -0
- package/dist/tbv/core/services/refund/errors.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/index.d.ts +8 -0
- package/dist/tbv/core/services/refund/index.d.ts.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +30 -24
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts +62 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/index.d.ts +2 -0
- package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts +65 -0
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -0
- package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts +2 -0
- package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts.map +1 -0
- package/dist/tbv/core/wots/blockDerivation.d.ts +36 -0
- package/dist/tbv/core/wots/blockDerivation.d.ts.map +1 -0
- package/dist/tbv/core/wots/index.d.ts +1 -0
- package/dist/tbv/core/wots/index.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +129 -95
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +3 -3
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +145 -169
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -30
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/types-B-p4dhEH.cjs +2 -0
- package/dist/types-B-p4dhEH.cjs.map +1 -0
- package/dist/types-DWjaqVfP.js +608 -0
- package/dist/types-DWjaqVfP.js.map +1 -0
- package/package.json +5 -1
- package/dist/challengeAssert-D_k_ADgP.cjs +0 -2
- package/dist/challengeAssert-D_k_ADgP.cjs.map +0 -1
- package/dist/challengeAssert-k5_LWUtO.js +0 -362
- package/dist/challengeAssert-k5_LWUtO.js.map +0 -1
- package/dist/constants-EiyZkXce.cjs +0 -2
- package/dist/constants-EiyZkXce.cjs.map +0 -1
- package/dist/constants-Q7v2O7Ps.js.map +0 -1
- package/dist/errors-DAKpPfl7.cjs +0 -2
- package/dist/errors-DAKpPfl7.cjs.map +0 -1
- package/dist/errors-DARTQrP3.js +0 -1510
- package/dist/errors-DARTQrP3.js.map +0 -1
- package/dist/fundPeginTransaction-DpwnDslW.js +0 -50
- package/dist/fundPeginTransaction-DpwnDslW.js.map +0 -1
- package/dist/fundPeginTransaction-EbrZzlrh.cjs +0 -2
- package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +0 -1
- package/dist/index-DKfhZvdn.cjs +0 -2
- package/dist/index-DKfhZvdn.cjs.map +0 -1
- package/dist/index-qIcjkxLw.js +0 -911
- package/dist/index-qIcjkxLw.js.map +0 -1
- package/dist/payout-Ce9vSs9e.js +0 -164
- package/dist/payout-Ce9vSs9e.js.map +0 -1
- package/dist/payout-CfsDnjKI.cjs +0 -2
- package/dist/payout-CfsDnjKI.cjs.map +0 -1
- package/dist/psbtInputFields-C0nKn_GD.cjs +0 -2
- package/dist/psbtInputFields-C0nKn_GD.cjs.map +0 -1
- package/dist/psbtInputFields-DO0ELwiv.js +0 -116
- package/dist/psbtInputFields-DO0ELwiv.js.map +0 -1
- package/dist/signAndSubmitPayouts-CAOEAQp9.js +0 -490
- package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +0 -1
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +0 -2
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +0 -1
- package/dist/signing-Deg5lCoC.cjs +0 -2
- package/dist/signing-Deg5lCoC.cjs.map +0 -1
- package/dist/signing-Drwr3bXB.js +0 -16
- package/dist/signing-Drwr3bXB.js.map +0 -1
- package/dist/types-D1rYwwCu.js +0 -235
- package/dist/types-D1rYwwCu.js.map +0 -1
- package/dist/types-DEWiqXYp.cjs +0 -2
- package/dist/types-DEWiqXYp.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-qIcjkxLw.js","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts","../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n 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 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\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 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\n // Validate UTXO fields from the external API.\n // Note: upper-bound vout check is omitted because we don't fetch\n // full transactions here. Out-of-range indices surface downstream.\n for (const utxo of utxos) {\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 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","/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n { name: \"status\", type: \"uint8\", internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\" },\n { name: \"applicationEntryPoint\", type: \"address\", internalType: \"address\" },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * Runtime validation for vault provider RPC responses.\n *\n * All VP RPC methods return untyped JSON that TypeScript generics cast without\n * inspection. These validators check the critical top-level fields and\n * security-relevant values (status, txids, pubkeys). Optional progress\n * sub-fields (gc_data, ack_collection, claimer_graphs) are NOT validated\n * since they are informational and not used for signing or transaction\n * construction. Only `progress.presigning` sub-fields are checked.\n */\n\nimport { DaemonStatus } from \"./types\";\nimport type {\n GetPeginStatusResponse,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsResponse,\n} from \"./types\";\n\nconst DAEMON_STATUS_VALUES = new Set<string>(Object.values(DaemonStatus));\n\nconst VP_ERROR_PREVIEW_MAX_LEN = 200;\n\nfunction preview(value: unknown): string {\n return (\n JSON.stringify(value)?.slice(0, VP_ERROR_PREVIEW_MAX_LEN) ?? \"undefined\"\n );\n}\n\nconst VP_VALIDATION_USER_MESSAGE =\n \"The vault provider returned an unexpected response. Please try again or contact support.\";\n\n/**\n * Thrown when a VP RPC response fails runtime validation.\n *\n * `.message` is a user-facing string safe to display in the UI.\n * `.detail` contains the technical reason, suitable for logging.\n */\nexport class VpResponseValidationError extends Error {\n readonly detail: string;\n\n constructor(detail: string) {\n super(VP_VALIDATION_USER_MESSAGE);\n this.name = \"VpResponseValidationError\";\n this.detail = detail;\n }\n}\n\n/** Non-empty string of hexadecimal characters (case-insensitive). */\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\n/** Expected length (in hex chars) of an x-only Bitcoin public key (32 bytes). */\nconst X_ONLY_PUBKEY_HEX_LEN = 64;\n/** Expected length (in hex chars) of a compressed Bitcoin public key (33 bytes). */\nconst COMPRESSED_PUBKEY_HEX_LEN = 66;\n\n/** Expected length (in hex chars) of a Bitcoin transaction ID (32 bytes). */\nconst TXID_HEX_LEN = 64;\n\nfunction isNonEmptyHex(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && HEX_RE.test(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction assertNonEmptyHex(value: unknown, field: string): void {\n if (!isNonEmptyHex(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty hex string, got ${preview(value)}`,\n );\n }\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): void {\n if (!isNonEmptyString(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty string, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Accept both x-only (64-char) and compressed (66-char) pubkeys from VP responses.\n * The signing code normalizes to x-only via processPublicKeyToXOnly().\n */\nfunction assertBtcPubkey(value: unknown, field: string): void {\n if (\n !isNonEmptyHex(value) ||\n (value.length !== X_ONLY_PUBKEY_HEX_LEN &&\n value.length !== COMPRESSED_PUBKEY_HEX_LEN)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a ${X_ONLY_PUBKEY_HEX_LEN} or ${COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate the optional presigning progress fields returned inside PeginProgressDetails.\n */\nfunction validatePresigningProgressFields(\n progress: Record<string, unknown>,\n): void {\n const presigning = progress.presigning;\n if (presigning === undefined || presigning === null) return;\n if (typeof presigning !== \"object\" || Array.isArray(presigning)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning\" must be an object if present`,\n );\n }\n\n const p = presigning as Record<string, unknown>;\n\n if (\n p.depositor_graph_created !== undefined &&\n typeof p.depositor_graph_created !== \"boolean\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.depositor_graph_created\" must be a boolean if present, got ${preview(p.depositor_graph_created)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_completed !== undefined &&\n typeof p.vk_challenger_presigning_completed !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_completed\" must be a number if present, got ${preview(p.vk_challenger_presigning_completed)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_total !== undefined &&\n typeof p.vk_challenger_presigning_total !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_total\" must be a number if present, got ${preview(p.vk_challenger_presigning_total)}`,\n );\n }\n}\n\n/**\n * Validate a getPeginStatus response.\n *\n * Throws if the status field is not a recognized DaemonStatus value.\n */\nexport function validateGetPeginStatusResponse(\n response: unknown,\n): asserts response is GetPeginStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPeginStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"status\" must be a string`,\n );\n }\n\n if (!DAEMON_STATUS_VALUES.has(r.status)) {\n throw new VpResponseValidationError(\n `VP response validation failed: unrecognized status \"${r.status}\". Expected one of: ${[...DAEMON_STATUS_VALUES].join(\", \")}`,\n );\n }\n\n if (\n r.progress === null ||\n typeof r.progress !== \"object\" ||\n Array.isArray(r.progress)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress\" must be an object`,\n );\n }\n\n validatePresigningProgressFields(r.progress as Record<string, unknown>);\n\n if (typeof r.health_info !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"health_info\" must be a string`,\n );\n }\n\n if (r.last_error !== undefined && typeof r.last_error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"last_error\" must be a string if present, got ${preview(r.last_error)}`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorPresignTransactions response.\n */\nexport function validateRequestDepositorPresignTransactionsResponse(\n response: unknown,\n): asserts response is RequestDepositorPresignTransactionsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorPresignTransactions response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!Array.isArray(r.txs)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"txs\" must be an array`,\n );\n }\n\n for (let i = 0; i < r.txs.length; i++) {\n validateClaimerTransactions(r.txs[i], `txs[${i}]`);\n }\n\n if (r.depositor_graph === null || typeof r.depositor_graph !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph\" must be an object`,\n );\n }\n\n validateDepositorGraphTransactions(\n r.depositor_graph as Record<string, unknown>,\n );\n}\n\nfunction validateTransactionData(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n const tx = value as Record<string, unknown>;\n assertNonEmptyHex(tx.tx_hex, `${field}.tx_hex`);\n}\n\nfunction validateClaimerTransactions(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const tx = value as Record<string, unknown>;\n\n assertBtcPubkey(tx.claimer_pubkey, `${field}.claimer_pubkey`);\n validateTransactionData(tx.claim_tx, `${field}.claim_tx`);\n validateTransactionData(tx.assert_tx, `${field}.assert_tx`);\n validateTransactionData(tx.payout_tx, `${field}.payout_tx`);\n assertNonEmptyString(tx.payout_psbt, `${field}.payout_psbt`);\n}\n\nfunction validateChallengeAssertConnectorData(\n value: unknown,\n field: string,\n): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.wots_pks_json, `${field}.wots_pks_json`);\n assertNonEmptyString(c.gc_wots_keys_json, `${field}.gc_wots_keys_json`);\n}\n\nfunction validatePresignDataPerChallenger(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const d = value as Record<string, unknown>;\n\n assertBtcPubkey(d.challenger_pubkey, `${field}.challenger_pubkey`);\n validateTransactionData(\n d.challenge_assert_x_tx,\n `${field}.challenge_assert_x_tx`,\n );\n validateTransactionData(\n d.challenge_assert_y_tx,\n `${field}.challenge_assert_y_tx`,\n );\n validateTransactionData(d.nopayout_tx, `${field}.nopayout_tx`);\n assertNonEmptyString(d.nopayout_psbt, `${field}.nopayout_psbt`);\n\n if (!Array.isArray(d.challenge_assert_connectors)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.challenge_assert_connectors.length; i++) {\n validateChallengeAssertConnectorData(\n d.challenge_assert_connectors[i],\n `${field}.challenge_assert_connectors[${i}]`,\n );\n }\n\n if (!Array.isArray(d.output_label_hashes)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.output_label_hashes\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.output_label_hashes.length; i++) {\n assertNonEmptyHex(\n d.output_label_hashes[i],\n `${field}.output_label_hashes[${i}]`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorClaimerArtifacts response.\n */\nexport function validateRequestDepositorClaimerArtifactsResponse(\n response: unknown,\n): asserts response is RequestDepositorClaimerArtifactsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorClaimerArtifacts response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyString(r.tx_graph_json)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"tx_graph_json\" must be a non-empty string, got ${preview(r.tx_graph_json)}`,\n );\n }\n\n if (!isNonEmptyHex(r.verifying_key_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"verifying_key_hex\" must be a non-empty hex string, got ${preview(r.verifying_key_hex)}`,\n );\n }\n\n if (r.babe_sessions === null || typeof r.babe_sessions !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must be an object`,\n );\n }\n\n for (const [key, session] of Object.entries(\n r.babe_sessions as Record<string, unknown>,\n )) {\n if (session === null || typeof session !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}\" must be an object`,\n );\n }\n const s = session as Record<string, unknown>;\n if (!isNonEmptyHex(s.decryptor_artifacts_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}.decryptor_artifacts_hex\" must be a non-empty hex string, got ${preview(s.decryptor_artifacts_hex)}`,\n );\n }\n }\n}\n\n/**\n * Validate a getPegoutStatus response.\n */\nexport function validateGetPegoutStatusResponse(\n response: unknown,\n): asserts response is GetPegoutStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPegoutStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.found !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"found\" must be a boolean, got ${preview(r.found)}`,\n );\n }\n\n if (r.claimer !== undefined) {\n if (r.claimer === null || typeof r.claimer !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer\" must be an object if present`,\n );\n }\n const claimer = r.claimer as Record<string, unknown>;\n if (typeof claimer.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.status\" must be a string, got ${preview(claimer.status)}`,\n );\n }\n if (typeof claimer.failed !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.failed\" must be a boolean, got ${preview(claimer.failed)}`,\n );\n }\n }\n\n if (r.challenger !== undefined) {\n if (r.challenger === null || typeof r.challenger !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger\" must be an object if present`,\n );\n }\n const challenger = r.challenger as Record<string, unknown>;\n if (typeof challenger.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger.status\" must be a string, got ${preview(challenger.status)}`,\n );\n }\n }\n}\n\nfunction validateDepositorGraphTransactions(\n graph: Record<string, unknown>,\n): void {\n validateTransactionData(graph.claim_tx, \"depositor_graph.claim_tx\");\n validateTransactionData(graph.assert_tx, \"depositor_graph.assert_tx\");\n validateTransactionData(graph.payout_tx, \"depositor_graph.payout_tx\");\n assertNonEmptyString(graph.payout_psbt, \"depositor_graph.payout_psbt\");\n\n if (!Array.isArray(graph.challenger_presign_data)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.challenger_presign_data\" must be an array`,\n );\n }\n\n for (let i = 0; i < graph.challenger_presign_data.length; i++) {\n validatePresignDataPerChallenger(\n graph.challenger_presign_data[i],\n `depositor_graph.challenger_presign_data[${i}]`,\n );\n }\n\n if (typeof graph.offchain_params_version !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.offchain_params_version\" must be a number`,\n );\n }\n}\n","/**\n * JSON-RPC client for the Vault Provider API.\n *\n * Wraps {@link JsonRpcClient} with typed methods matching the\n * `vaultProvider_*` RPC namespace defined in the btc-vault pegin spec.\n *\n * Implements the narrow service interfaces (PeginStatusReader, WotsKeySubmitter,\n * PresignClient, ClaimerArtifactsReader) so it can be passed directly to\n * any deposit protocol service function.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\nimport type { PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader } from \"../../services/deposit/interfaces\";\n\nimport { JsonRpcClient, type JsonRpcClientConfig } from \"./json-rpc-client\";\nimport type {\n GetPeginStatusParams,\n GetPeginStatusResponse,\n GetPegoutStatusParams,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsParams,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsParams,\n RequestDepositorPresignTransactionsResponse,\n SubmitDepositorPresignaturesParams,\n SubmitDepositorWotsKeyParams,\n} from \"./types\";\nimport {\n validateGetPeginStatusResponse,\n validateGetPegoutStatusResponse,\n validateRequestDepositorClaimerArtifactsResponse,\n validateRequestDepositorPresignTransactionsResponse,\n} from \"./validators\";\n\nexport interface VaultProviderRpcClientOptions {\n /** Timeout in milliseconds per request (default: 60000) */\n timeout?: number;\n /** Number of retry attempts for safe methods (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** Custom retry predicate (default: only retry get* status methods) */\n retryableFor?: (method: string) => boolean;\n /** Custom headers */\n headers?: Record<string, string>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Concrete VP RPC client implementing all service interfaces.\n *\n * Usage:\n * ```ts\n * const client = new VaultProviderRpcClient(\"https://vp.example.com/rpc\");\n * const status = await client.getPeginStatus({ pegin_txid: \"abc...\" });\n * ```\n */\nexport class VaultProviderRpcClient\n implements PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader\n{\n private client: JsonRpcClient;\n\n constructor(baseUrl: string, options?: VaultProviderRpcClientOptions) {\n const config: JsonRpcClientConfig = {\n baseUrl,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries,\n retryDelay: options?.retryDelay,\n retryableFor: options?.retryableFor,\n headers: options?.headers,\n };\n this.client = new JsonRpcClient(config);\n }\n\n /**\n * Request the payout/claim/assert transactions that the depositor\n * needs to pre-sign before the vault can be activated on Bitcoin.\n */\n async requestDepositorPresignTransactions(\n params: RequestDepositorPresignTransactionsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorPresignTransactionsResponse> {\n const response = await this.client.call<\n RequestDepositorPresignTransactionsParams,\n unknown\n >(\"vaultProvider_requestDepositorPresignTransactions\", params, signal);\n validateRequestDepositorPresignTransactionsResponse(response);\n return response;\n }\n\n /**\n * Submit the depositor's pre-signatures for the payout transactions\n * and the depositor-as-claimer graph.\n */\n async submitDepositorPresignatures(\n params: SubmitDepositorPresignaturesParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorPresignaturesParams, void>(\n \"vaultProvider_submitDepositorPresignatures\",\n params,\n signal,\n );\n }\n\n /**\n * Submit the depositor's WOTS public key to the vault provider.\n * Called after the pegin is finalized on Ethereum, when the VP is in\n * `PendingDepositorWotsPK` status.\n */\n async submitDepositorWotsKey(\n params: SubmitDepositorWotsKeyParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorWotsKeyParams, void>(\n \"vaultProvider_submitDepositorWotsKey\",\n params,\n signal,\n );\n }\n\n /**\n * Request the BaBe DecryptorArtifacts needed for the depositor to\n * independently evaluate garbled circuits during a challenge.\n */\n async requestDepositorClaimerArtifacts(\n params: RequestDepositorClaimerArtifactsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorClaimerArtifactsResponse> {\n const response = await this.client.call<\n RequestDepositorClaimerArtifactsParams,\n unknown\n >(\"vaultProvider_requestDepositorClaimerArtifacts\", params, signal);\n validateRequestDepositorClaimerArtifactsResponse(response);\n return response;\n }\n\n /** Get the current pegin status from the vault provider daemon. */\n async getPeginStatus(\n params: GetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPeginStatusResponse> {\n const response = await this.client.call<GetPeginStatusParams, unknown>(\n \"vaultProvider_getPeginStatus\",\n params,\n signal,\n );\n validateGetPeginStatusResponse(response);\n return response;\n }\n\n /** Get the current pegout status from the vault provider daemon. */\n async getPegoutStatus(\n params: GetPegoutStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPegoutStatusResponse> {\n const response = await this.client.call<GetPegoutStatusParams, unknown>(\n \"vaultProvider_getPegoutStatus\",\n params,\n signal,\n );\n validateGetPegoutStatusResponse(response);\n return response;\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 { Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport type {\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\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 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 readonly [Address, Hex, bigint, Address, number, Address, bigint];\n\n return {\n depositor: result[0],\n depositorBtcPubKey: result[1],\n amount: result[2],\n vaultProvider: result[3],\n status: result[4],\n applicationEntryPoint: result[5],\n createdAt: result[6],\n };\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as readonly [\n Hex,\n number,\n number,\n number,\n bigint,\n Hex,\n Hex,\n number,\n Hex,\n Hex,\n number,\n ];\n\n return {\n depositorSignedPeginTx: result[0],\n universalChallengersVersion: result[1],\n appVaultKeepersVersion: result[2],\n offchainParamsVersion: result[3],\n verifiedAt: result[4],\n depositorWotsPkHash: result[5],\n hashlock: result[6],\n htlcVout: result[7],\n depositorPopSignature: result[8],\n prePeginTxHash: result[9],\n vaultProviderCommissionBps: result[10],\n };\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n}\n"],"names":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","txid","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","address","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field","BTCVaultRegistryABI","DAEMON_STATUS_VALUES","DaemonStatus","VP_ERROR_PREVIEW_MAX_LEN","preview","_a","VP_VALIDATION_USER_MESSAGE","VpResponseValidationError","detail","__publicField","HEX_RE","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","TXID_HEX_LEN","isNonEmptyHex","isNonEmptyString","assertNonEmptyHex","assertNonEmptyString","assertBtcPubkey","validatePresigningProgressFields","progress","presigning","p","validateGetPeginStatusResponse","r","validateRequestDepositorPresignTransactionsResponse","i","validateClaimerTransactions","validateDepositorGraphTransactions","validateTransactionData","tx","validateChallengeAssertConnectorData","c","validatePresignDataPerChallenger","d","validateRequestDepositorClaimerArtifactsResponse","key","session","s","validateGetPegoutStatusResponse","claimer","challenger","graph","DEFAULT_TIMEOUT_MS","VaultProviderRpcClient","baseUrl","config","JsonRpcClient","params","signal","ViemVaultRegistryReader","publicClient","contractAddress","vaultId","result","basic","protocol"],"mappings":";;;;AAYA,MAAMA,IAAe,OAAa,KAG5BC,IAA6B;AAMnC,eAAeC,EACbC,GACAC,GACmB;AACnB,QAAMC,IAAa,IAAI,gBAAA,GACjBC,IAAY;AAAA,IAChB,MAAMD,EAAW,MAAA;AAAA,IACjBJ;AAAA,EAAA,GAIIM,IAAU,CAACF,EAAW,QAAQD,KAAA,gBAAAA,EAAS,MAAM,EAAE;AAAA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O,CAAC;AAAA,MAClB,uBAAuBA,EAAO,CAAC;AAAA,MAC/B,gBAAgBA,EAAO,CAAC;AAAA,MACxB,4BAA4BA,EAAO,EAAE;AAAA,IAAA;AAAA,EAEzC;AAAA,EAEA,MAAM,aAAaD,GAAkC;AACnD,UAAM,CAACE,GAAOC,CAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,MAC1C,KAAK,kBAAkBH,CAAO;AAAA,MAC9B,KAAK,qBAAqBA,CAAO;AAAA,IAAA,CAClC;AAED,QACE,CAACG,EAAS,0BACVA,EAAS,2BAA2B;AAEpC,YAAM,IAAI;AAAA,QACR,SAASH,CAAO;AAAA,MAAA;AAIpB,WAAO,EAAE,OAAAE,GAAO,UAAAC,EAAA;AAAA,EAClB;AACF;"}
|
package/dist/payout-Ce9vSs9e.js
DELETED
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import { createPayoutConnector as E, tapInternalPubkey as B } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
2
|
-
import { Buffer as l } from "buffer";
|
|
3
|
-
import { Transaction as f, Psbt as $ } from "bitcoinjs-lib";
|
|
4
|
-
import { s as S, h as v, u as d, j as A } from "./constants-Q7v2O7Ps.js";
|
|
5
|
-
async function m(t) {
|
|
6
|
-
const r = await E(
|
|
7
|
-
{
|
|
8
|
-
depositor: t.depositor,
|
|
9
|
-
vaultProvider: t.vaultProvider,
|
|
10
|
-
vaultKeepers: t.vaultKeepers,
|
|
11
|
-
universalChallengers: t.universalChallengers,
|
|
12
|
-
timelockPegin: t.timelockPegin
|
|
13
|
-
},
|
|
14
|
-
t.network
|
|
15
|
-
);
|
|
16
|
-
return {
|
|
17
|
-
payoutScript: r.payoutScript,
|
|
18
|
-
taprootScriptHash: r.taprootScriptHash,
|
|
19
|
-
scriptPubKey: r.scriptPubKey,
|
|
20
|
-
address: r.address,
|
|
21
|
-
payoutControlBlock: r.payoutControlBlock
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
async function q(t) {
|
|
25
|
-
const r = S(t.payoutTxHex), e = S(t.peginTxHex), s = S(t.assertTxHex), o = await m({
|
|
26
|
-
depositor: t.depositorBtcPubkey,
|
|
27
|
-
vaultProvider: t.vaultProviderBtcPubkey,
|
|
28
|
-
vaultKeepers: t.vaultKeeperBtcPubkeys,
|
|
29
|
-
universalChallengers: t.universalChallengerBtcPubkeys,
|
|
30
|
-
timelockPegin: t.timelockPegin,
|
|
31
|
-
network: t.network
|
|
32
|
-
}), n = v(o.payoutScript), i = v(o.payoutControlBlock), c = f.fromHex(r), P = f.fromHex(e), w = f.fromHex(s), u = new $();
|
|
33
|
-
if (u.setVersion(c.version), u.setLocktime(c.locktime), c.ins.length !== 2)
|
|
34
|
-
throw new Error(
|
|
35
|
-
`Payout transaction must have exactly 2 inputs, got ${c.ins.length}`
|
|
36
|
-
);
|
|
37
|
-
const a = c.ins[0], p = c.ins[1], x = d(
|
|
38
|
-
new Uint8Array(a.hash).slice().reverse()
|
|
39
|
-
), k = P.getId();
|
|
40
|
-
if (x !== k)
|
|
41
|
-
throw new Error(
|
|
42
|
-
`Input 0 does not reference pegin transaction. Expected ${k}, got ${x}`
|
|
43
|
-
);
|
|
44
|
-
const h = d(
|
|
45
|
-
new Uint8Array(p.hash).slice().reverse()
|
|
46
|
-
), H = w.getId();
|
|
47
|
-
if (h !== H)
|
|
48
|
-
throw new Error(
|
|
49
|
-
`Input 1 does not reference assert transaction. Expected ${H}, got ${h}`
|
|
50
|
-
);
|
|
51
|
-
const y = P.outs[a.index];
|
|
52
|
-
if (!y)
|
|
53
|
-
throw new Error(
|
|
54
|
-
`Previous output not found for input 0 (txid: ${x}, index: ${a.index})`
|
|
55
|
-
);
|
|
56
|
-
const g = w.outs[p.index];
|
|
57
|
-
if (!g)
|
|
58
|
-
throw new Error(
|
|
59
|
-
`Previous output not found for input 1 (txid: ${h}, index: ${p.index})`
|
|
60
|
-
);
|
|
61
|
-
u.addInput({
|
|
62
|
-
hash: a.hash,
|
|
63
|
-
index: a.index,
|
|
64
|
-
sequence: a.sequence,
|
|
65
|
-
witnessUtxo: {
|
|
66
|
-
script: y.script,
|
|
67
|
-
value: y.value
|
|
68
|
-
},
|
|
69
|
-
tapLeafScript: [
|
|
70
|
-
{
|
|
71
|
-
leafVersion: A,
|
|
72
|
-
script: l.from(n),
|
|
73
|
-
controlBlock: l.from(i)
|
|
74
|
-
}
|
|
75
|
-
],
|
|
76
|
-
tapInternalKey: l.from(B)
|
|
77
|
-
// sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
78
|
-
}), u.addInput({
|
|
79
|
-
hash: p.hash,
|
|
80
|
-
index: p.index,
|
|
81
|
-
sequence: p.sequence,
|
|
82
|
-
witnessUtxo: {
|
|
83
|
-
script: g.script,
|
|
84
|
-
value: g.value
|
|
85
|
-
}
|
|
86
|
-
// No tapLeafScript - depositor doesn't sign this input
|
|
87
|
-
});
|
|
88
|
-
for (const T of c.outs)
|
|
89
|
-
u.addOutput({
|
|
90
|
-
script: T.script,
|
|
91
|
-
value: T.value
|
|
92
|
-
});
|
|
93
|
-
return {
|
|
94
|
-
psbtHex: u.toHex()
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
function W(t, r, e = 0) {
|
|
98
|
-
const s = $.fromHex(t);
|
|
99
|
-
if (e >= s.data.inputs.length)
|
|
100
|
-
throw new Error(
|
|
101
|
-
`Input index ${e} out of range (${s.data.inputs.length} inputs)`
|
|
102
|
-
);
|
|
103
|
-
const o = s.data.inputs[e];
|
|
104
|
-
if (o.tapScriptSig && o.tapScriptSig.length > 0) {
|
|
105
|
-
const n = v(r);
|
|
106
|
-
for (const i of o.tapScriptSig)
|
|
107
|
-
if (i.pubkey.equals(l.from(n)))
|
|
108
|
-
return b(i.signature, e);
|
|
109
|
-
throw new Error(
|
|
110
|
-
`No signature found for depositor pubkey: ${r} at input ${e}`
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
if (o.finalScriptWitness && o.finalScriptWitness.length > 0) {
|
|
114
|
-
const n = C(o.finalScriptWitness);
|
|
115
|
-
if (n.length >= 1)
|
|
116
|
-
return b(n[0], e);
|
|
117
|
-
}
|
|
118
|
-
throw new Error(
|
|
119
|
-
`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
function b(t, r) {
|
|
123
|
-
if (t.length === 64)
|
|
124
|
-
return d(new Uint8Array(t));
|
|
125
|
-
if (t.length === 65) {
|
|
126
|
-
const e = t[64];
|
|
127
|
-
if (e !== f.SIGHASH_ALL)
|
|
128
|
-
throw new Error(
|
|
129
|
-
`Unexpected sighash type 0x${e.toString(16).padStart(2, "0")} at input ${r}. Expected SIGHASH_ALL (0x01).`
|
|
130
|
-
);
|
|
131
|
-
return d(new Uint8Array(t.subarray(0, 64)));
|
|
132
|
-
}
|
|
133
|
-
throw new Error(
|
|
134
|
-
`Unexpected signature length at input ${r}: ${t.length}`
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
function C(t) {
|
|
138
|
-
const r = [];
|
|
139
|
-
let e = 0;
|
|
140
|
-
const s = () => {
|
|
141
|
-
const n = t[e++];
|
|
142
|
-
if (n < 253) return n;
|
|
143
|
-
if (n === 253) {
|
|
144
|
-
const i = t[e] | t[e + 1] << 8;
|
|
145
|
-
return e += 2, i;
|
|
146
|
-
}
|
|
147
|
-
if (n === 254) {
|
|
148
|
-
const i = t[e] | t[e + 1] << 8 | t[e + 2] << 16 | t[e + 3] << 24;
|
|
149
|
-
return e += 4, i;
|
|
150
|
-
}
|
|
151
|
-
return e += 8, 0;
|
|
152
|
-
}, o = s();
|
|
153
|
-
for (let n = 0; n < o; n++) {
|
|
154
|
-
const i = s();
|
|
155
|
-
r.push(t.subarray(e, e + i)), e += i;
|
|
156
|
-
}
|
|
157
|
-
return r;
|
|
158
|
-
}
|
|
159
|
-
export {
|
|
160
|
-
q as b,
|
|
161
|
-
m as c,
|
|
162
|
-
W as e
|
|
163
|
-
};
|
|
164
|
-
//# sourceMappingURL=payout-Ce9vSs9e.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"payout-Ce9vSs9e.js","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts"],"sourcesContent":["/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot script-path witness: [signature, script, controlBlock]\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length >= 1) {\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const readVarInt = (): number => {\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n const val = witness[offset] | (witness[offset + 1] << 8);\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n const val =\n witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24);\n offset += 4;\n return val;\n }\n // 0xff — 8-byte, won't happen for witness data\n offset += 8;\n return 0;\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n items.push(witness.subarray(offset, offset + len) as Buffer);\n offset += len;\n }\n\n return items;\n}\n\n"],"names":["createPayoutScript","params","connector","createPayoutConnector","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","sighashByte","witness","items","offset","readVarInt","first","val","count","i","len"],"mappings":";;;;AA8IA,eAAsBA,EACpBC,GAC6B;AAE7B,QAAMC,IAAY,MAAMC;AAAA,IACtB;AAAA,MACE,WAAWF,EAAO;AAAA,MAClB,eAAeA,EAAO;AAAA,MACtB,cAAcA,EAAO;AAAA,MACrB,sBAAsBA,EAAO;AAAA,MAC7B,eAAeA,EAAO;AAAA,IAAA;AAAA,IAExBA,EAAO;AAAA,EAAA;AAGT,SAAO;AAAA,IACL,cAAcC,EAAU;AAAA,IACxB,mBAAmBA,EAAU;AAAA,IAC7B,cAAcA,EAAU;AAAA,IACxB,SAASA,EAAU;AAAA,IACnB,oBAAoBA,EAAU;AAAA,EAAA;AAElC;ACnDA,eAAsBE,EACpBH,GAC2B;AAE3B,QAAMI,IAAcC,EAAeL,EAAO,WAAW,GAC/CM,IAAaD,EAAeL,EAAO,UAAU,GAC7CO,IAAcF,EAAeL,EAAO,WAAW,GAG/CQ,IAAkB,MAAMT,EAAmB;AAAA,IAC/C,WAAWC,EAAO;AAAA,IAClB,eAAeA,EAAO;AAAA,IACtB,cAAcA,EAAO;AAAA,IACrB,sBAAsBA,E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AAS,CAAC,KAAK,KACvBF,EAAQE,IAAS,CAAC,KAAK;AAC1B,aAAAA,KAAU,GACHG;AAAA,IACT;AAEA,WAAAH,KAAU,GACH;AAAA,EACT,GAEMI,IAAQH,EAAA;AACd,WAASI,IAAI,GAAGA,IAAID,GAAOC,KAAK;AAC9B,UAAMC,IAAML,EAAA;AACZ,IAAAF,EAAM,KAAKD,EAAQ,SAASE,GAAQA,IAASM,CAAG,CAAW,GAC3DN,KAAUM;AAAA,EACZ;AAEA,SAAOP;AACT;"}
|
package/dist/payout-CfsDnjKI.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const H=require("@babylonlabs-io/babylon-tbv-rust-wasm"),x=require("buffer"),f=require("bitcoinjs-lib"),s=require("./constants-EiyZkXce.cjs");async function k(t){const r=await H.createPayoutConnector({depositor:t.depositor,vaultProvider:t.vaultProvider,vaultKeepers:t.vaultKeepers,universalChallengers:t.universalChallengers,timelockPegin:t.timelockPegin},t.network);return{payoutScript:r.payoutScript,taprootScriptHash:r.taprootScriptHash,scriptPubKey:r.scriptPubKey,address:r.address,payoutControlBlock:r.payoutControlBlock}}async function $(t){const r=s.stripHexPrefix(t.payoutTxHex),e=s.stripHexPrefix(t.peginTxHex),u=s.stripHexPrefix(t.assertTxHex),o=await k({depositor:t.depositorBtcPubkey,vaultProvider:t.vaultProviderBtcPubkey,vaultKeepers:t.vaultKeeperBtcPubkeys,universalChallengers:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:t.network}),n=s.hexToUint8Array(o.payoutScript),i=s.hexToUint8Array(o.payoutControlBlock),c=f.Transaction.fromHex(r),P=f.Transaction.fromHex(e),S=f.Transaction.fromHex(u),a=new f.Psbt;if(a.setVersion(c.version),a.setLocktime(c.locktime),c.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${c.ins.length}`);const p=c.ins[0],l=c.ins[1],d=s.uint8ArrayToHex(new Uint8Array(p.hash).slice().reverse()),v=P.getId();if(d!==v)throw new Error(`Input 0 does not reference pegin transaction. Expected ${v}, got ${d}`);const y=s.uint8ArrayToHex(new Uint8Array(l.hash).slice().reverse()),T=S.getId();if(y!==T)throw new Error(`Input 1 does not reference assert transaction. Expected ${T}, got ${y}`);const h=P.outs[p.index];if(!h)throw new Error(`Previous output not found for input 0 (txid: ${d}, index: ${p.index})`);const g=S.outs[l.index];if(!g)throw new Error(`Previous output not found for input 1 (txid: ${y}, index: ${l.index})`);a.addInput({hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:h.script,value:h.value},tapLeafScript:[{leafVersion:s.TAPSCRIPT_LEAF_VERSION,script:x.Buffer.from(n),controlBlock:x.Buffer.from(i)}],tapInternalKey:x.Buffer.from(H.tapInternalPubkey)}),a.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:g.script,value:g.value}});for(const w of c.outs)a.addOutput({script:w.script,value:w.value});return{psbtHex:a.toHex()}}function A(t,r,e=0){const u=f.Psbt.fromHex(t);if(e>=u.data.inputs.length)throw new Error(`Input index ${e} out of range (${u.data.inputs.length} inputs)`);const o=u.data.inputs[e];if(o.tapScriptSig&&o.tapScriptSig.length>0){const n=s.hexToUint8Array(r);for(const i of o.tapScriptSig)if(i.pubkey.equals(x.Buffer.from(n)))return b(i.signature,e);throw new Error(`No signature found for depositor pubkey: ${r} at input ${e}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const n=B(o.finalScriptWitness);if(n.length>=1)return b(n[0],e)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`)}function b(t,r){if(t.length===64)return s.uint8ArrayToHex(new Uint8Array(t));if(t.length===65){const e=t[64];if(e!==f.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${e.toString(16).padStart(2,"0")} at input ${r}. Expected SIGHASH_ALL (0x01).`);return s.uint8ArrayToHex(new Uint8Array(t.subarray(0,64)))}throw new Error(`Unexpected signature length at input ${r}: ${t.length}`)}function B(t){const r=[];let e=0;const u=()=>{const n=t[e++];if(n<253)return n;if(n===253){const i=t[e]|t[e+1]<<8;return e+=2,i}if(n===254){const i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;return e+=4,i}return e+=8,0},o=u();for(let n=0;n<o;n++){const i=u();r.push(t.subarray(e,e+i)),e+=i}return r}exports.buildPayoutPsbt=$;exports.createPayoutScript=k;exports.extractPayoutSignature=A;
|
|
2
|
-
//# sourceMappingURL=payout-CfsDnjKI.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"payout-CfsDnjKI.cjs","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts"],"sourcesContent":["/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot script-path witness: [signature, script, controlBlock]\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length >= 1) {\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const readVarInt = (): number => {\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n const val = witness[offset] | (witness[offset + 1] << 8);\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n const val =\n witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24);\n offset += 4;\n return val;\n }\n // 0xff — 8-byte, won't happen for witness data\n offset += 8;\n return 0;\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n items.push(witness.subarray(offset, offset + len) as Buffer);\n offset += len;\n }\n\n return items;\n}\n\n"],"names":["createPayoutScript","params","connector","createPayoutConnector","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","sighashByte","witness","items","offset","readVarInt","first","val","count","i","len"],"mappings":"2JA8IA,eAAsBA,EACpBC,EAC6B,CAE7B,MAAMC,EAAY,MAAMC,EAAAA,sBACtB,CACE,UAAWF,EAAO,UAClB,cAAeA,EAAO,cACtB,aAAcA,EAAO,aACrB,qBAAsBA,EAAO,qBAC7B,cAAeA,EAAO,aAAA,EAExBA,EAAO,OAAA,EAGT,MAAO,CACL,aAAcC,EAAU,aACxB,kBAAmBA,EAAU,kBAC7B,aAAcA,EAAU,aACxB,QAASA,EAAU,QACnB,mBAAoBA,EAAU,kBAAA,CAElC,CCnDA,eAAsBE,EACpBH,EAC2B,CAE3B,MAAMI,EAAcC,EAAAA,eAAeL,EAAO,WAAW,EAC/CM,EAAaD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ACT,CAEA,OAAAH,GAAU,EACH,CACT,EAEMI,EAAQH,EAAA,EACd,QAASI,EAAI,EAAGA,EAAID,EAAOC,IAAK,CAC9B,MAAMC,EAAML,EAAA,EACZF,EAAM,KAAKD,EAAQ,SAASE,EAAQA,EAASM,CAAG,CAAW,EAC3DN,GAAUM,CACZ,CAEA,OAAOP,CACT"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const T=require("bitcoinjs-lib"),h=require("buffer"),i=require("./constants-EiyZkXce.cjs");function H(t,e,n,r){if(!Number.isInteger(r)||r<1)throw new Error(`Invalid numOutputs: expected a positive integer, got ${r}`);if(t.length===0)throw new Error("Insufficient funds: no UTXOs available");const d=t.filter(o=>{const c=h.Buffer.from(o.scriptPubKey,"hex");return!!T.script.decompile(c)});if(d.length===0)throw new Error("Insufficient funds: no valid UTXOs available (all have invalid scripts)");const P=[...d].sort((o,c)=>c.value-o.value),f=[];let a=0n,s=0n;for(const o of P){f.push(o),a+=BigInt(o.value);const c=f.length*i.P2TR_INPUT_SIZE,g=r*i.MAX_NON_LEGACY_OUTPUT_SIZE,w=c+g+i.TX_BUFFER_SIZE_OVERHEAD;if(s=BigInt(Math.ceil(w*n))+BigInt(i.rateBasedTxBufferFee(n)),a-e-s>i.DUST_THRESHOLD){const u=BigInt(Math.ceil(i.MAX_NON_LEGACY_OUTPUT_SIZE*n));s+=u}if(a>=e+s){const u=a-e-s;return{selectedUTXOs:f,totalValue:a,fee:s,changeAmount:u}}}throw new Error(`Insufficient funds: need ${e+s} sats (${e} pegin + ${s} fee), have ${a} sats`)}function U(t){return t>i.DUST_THRESHOLD}function I(){return i.BTC_DUST_SAT}function v(t){const e=t.startsWith("0x")?t.slice(2):t;return`0x${T.Transaction.fromHex(e).getId()}`}var l=(t=>(t.P2PKH="P2PKH",t.P2SH="P2SH",t.P2WPKH="P2WPKH",t.P2WSH="P2WSH",t.P2TR="P2TR",t.UNKNOWN="UNKNOWN",t))(l||{});function S(t){const e=t.length;return e===25&&t[0]===118&&t[1]===169&&t[2]===20&&t[23]===136&&t[24]===172?"P2PKH":e===23&&t[0]===169&&t[1]===20&&t[22]===135?"P2SH":e===22&&t[0]===0&&t[1]===20?"P2WPKH":e===34&&t[0]===0&&t[1]===32?"P2WSH":e===34&&t[0]===81&&t[1]===32?"P2TR":"UNKNOWN"}function E(t,e){const n=h.Buffer.from(t.scriptPubKey,"hex"),r=S(n);switch(r){case l.P2WPKH:return{witnessUtxo:{script:n,value:t.value}};case l.P2WSH:{if(!t.witnessScript)throw new Error("Missing witnessScript for P2WSH input");return{witnessUtxo:{script:n,value:t.value},witnessScript:h.Buffer.from(t.witnessScript,"hex")}}case l.P2TR:{if(e&&e.length!==32)throw new Error(`Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`);return{witnessUtxo:{script:n,value:t.value},...e&&{tapInternalKey:e}}}default:throw new Error(`Unsupported script type: ${r}`)}}exports.BitcoinScriptType=l;exports.calculateBtcTxHash=v;exports.getDustThreshold=I;exports.getPsbtInputFields=E;exports.getScriptType=S;exports.selectUtxosForPegin=H;exports.shouldAddChangeOutput=U;
|
|
2
|
-
//# sourceMappingURL=psbtInputFields-C0nKn_GD.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"psbtInputFields-C0nKn_GD.cjs","sources":["../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts"],"sourcesContent":["/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n BTC_DUST_SAT,\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs and recalculate fee\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n // Recalculate fee based on CURRENT number of inputs\n const inputSize = selectedUTXOs.length * P2TR_INPUT_SIZE;\n const outputSize = numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE;\n const baseTxSize = inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;\n\n // Calculate base fee with buffer\n estimatedFee =\n BigInt(Math.ceil(baseTxSize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate));\n\n // Check if there will be change left after pegin amount and fee\n const changeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n // If change is above dust, add fee for change output\n if (changeAmount > DUST_THRESHOLD) {\n const changeOutputFee = BigInt(\n Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate),\n );\n estimatedFee += changeOutputFee;\n }\n\n // Check if we have enough to cover pegin amount + fees\n if (accumulatedValue >= peginAmount + estimatedFee) {\n // Success! We have enough funds\n const finalChangeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: estimatedFee,\n changeAmount: finalChangeAmount,\n };\n }\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n"],"names":["selectUtxosForPegin","availableUTXOs","peginAmount","feeRate","numOutputs","validUTXOs","utxo","script","Buffer","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","estimatedFee","inputSize","P2TR_INPUT_SIZE","outputSize","MAX_NON_LEGACY_OUTPUT_SIZE","baseTxSize","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":"wGAqEO,SAASA,EACdC,EACAC,EACAC,EACAC,EACqB,CACrB,GAAI,CAAC,OAAO,UAAUA,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MACR,wDAAwDA,CAAU,EAAA,EAItE,GAAIH,EAAe,SAAW,EAC5B,MAAM,IAAI,MAAM,wCAAwC,EAK1D,MAAMI,EAAaJ,EAAe,OAAQK,GAAS,CACjD,MAAMC,EAASC,EAAAA,OAAO,KAAKF,EAAK,aAAc,KAAK,EAEnD,MAAO,CAAC,CADiBG,EAAAA,OAAc,UAAUF,CAAM,CAEzD,CAAC,EAED,GAAIF,EAAW,SAAW,EACxB,MAAM,IAAI,MACR,yEAAA,EAMJ,MAAMK,EAAc,CAAC,GAAGL,CAAU,EAAE,KAAK,CAACM,EAAGC,IAAMA,EAAE,MAAQD,EAAE,KAAK,EAE9DE,EAAwB,CAAA,EAC9B,IAAIC,EAAmB,GACnBC,EAAe,GAGnB,UAAWT,KAAQI,EAAa,CAC9BG,EAAc,KAAKP,CAAI,EACvBQ,GAAoB,OAAOR,EAAK,KAAK,EAGrC,MAAMU,EAAYH,EAAc,OAASI,EAAAA,gBACnCC,EAAad,EAAae,EAAAA,2BAC1BC,EAAaJ,EAAYE,EAAaG,EAAAA,wBAW5C,GARAN,E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AAa,CAAC,IAAM,GACpBA,EAAa,CAAC,IAAM,GAEb,SAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,GACpBA,EAAa,CAAC,IAAM,GAEb,QAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,IACpBA,EAAa,CAAC,IAAM,GAEb,OAGF,SACT,CCnCO,SAASE,EACdhC,EACAiC,EACiB,CACjB,MAAMH,EAAe5B,EAAAA,OAAO,KAAKF,EAAK,aAAc,KAAK,EACnDkC,EAAOL,EAAcC,CAAY,EAEvC,OAAQI,EAAA,CACN,KAAKN,EAAkB,OACrB,MAAO,CACL,YAAa,CACX,OAAQE,EACR,MAAO9B,EAAK,KAAA,CACd,EAIJ,KAAK4B,EAAkB,MAAO,CAC5B,GAAI,CAAC5B,EAAK,cACR,MAAM,IAAI,MAAM,uCAAuC,EAEzD,MAAO,CACL,YAAa,CACX,OAAQ8B,EACR,MAAO9B,EAAK,KAAA,EAEd,cAAeE,EAAAA,OAAO,KAAKF,EAAK,cAAe,KAAK,CAAA,CAExD,CAEA,KAAK4B,EAAkB,KAAM,CAC3B,GAAIK,GAAoBA,EAAiB,SAAW,GAClD,MAAM,IAAI,MACR,yDAAyDA,EAAiB,MAAM,EAAA,EAGpF,MAAO,CACL,YAAa,CACX,OAAQH,EACR,MAAO9B,EAAK,KAAA,EAGd,GAAIiC,GAAoB,CAAE,eAAgBA,CAAA,CAAiB,CAE/D,CAEA,QACE,MAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE,CAAA,CAExD"}
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import { script as T, Transaction as v } from "bitcoinjs-lib";
|
|
2
|
-
import { Buffer as h } from "buffer";
|
|
3
|
-
import { P as H, r as I, D as w, M as g, B as U, T as E } from "./constants-Q7v2O7Ps.js";
|
|
4
|
-
function N(t, e, n, s) {
|
|
5
|
-
if (!Number.isInteger(s) || s < 1)
|
|
6
|
-
throw new Error(
|
|
7
|
-
`Invalid numOutputs: expected a positive integer, got ${s}`
|
|
8
|
-
);
|
|
9
|
-
if (t.length === 0)
|
|
10
|
-
throw new Error("Insufficient funds: no UTXOs available");
|
|
11
|
-
const u = t.filter((i) => {
|
|
12
|
-
const o = h.from(i.scriptPubKey, "hex");
|
|
13
|
-
return !!T.decompile(o);
|
|
14
|
-
});
|
|
15
|
-
if (u.length === 0)
|
|
16
|
-
throw new Error(
|
|
17
|
-
"Insufficient funds: no valid UTXOs available (all have invalid scripts)"
|
|
18
|
-
);
|
|
19
|
-
const P = [...u].sort((i, o) => o.value - i.value), f = [];
|
|
20
|
-
let a = 0n, r = 0n;
|
|
21
|
-
for (const i of P) {
|
|
22
|
-
f.push(i), a += BigInt(i.value);
|
|
23
|
-
const o = f.length * H, d = s * g, S = o + d + E;
|
|
24
|
-
if (r = BigInt(Math.ceil(S * n)) + BigInt(I(n)), a - e - r > w) {
|
|
25
|
-
const c = BigInt(
|
|
26
|
-
Math.ceil(g * n)
|
|
27
|
-
);
|
|
28
|
-
r += c;
|
|
29
|
-
}
|
|
30
|
-
if (a >= e + r) {
|
|
31
|
-
const c = a - e - r;
|
|
32
|
-
return {
|
|
33
|
-
selectedUTXOs: f,
|
|
34
|
-
totalValue: a,
|
|
35
|
-
fee: r,
|
|
36
|
-
changeAmount: c
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
throw new Error(
|
|
41
|
-
`Insufficient funds: need ${e + r} sats (${e} pegin + ${r} fee), have ${a} sats`
|
|
42
|
-
);
|
|
43
|
-
}
|
|
44
|
-
function $(t) {
|
|
45
|
-
return t > w;
|
|
46
|
-
}
|
|
47
|
-
function p() {
|
|
48
|
-
return U;
|
|
49
|
-
}
|
|
50
|
-
function B(t) {
|
|
51
|
-
const e = t.startsWith("0x") ? t.slice(2) : t;
|
|
52
|
-
return `0x${v.fromHex(e).getId()}`;
|
|
53
|
-
}
|
|
54
|
-
var l = /* @__PURE__ */ ((t) => (t.P2PKH = "P2PKH", t.P2SH = "P2SH", t.P2WPKH = "P2WPKH", t.P2WSH = "P2WSH", t.P2TR = "P2TR", t.UNKNOWN = "UNKNOWN", t))(l || {});
|
|
55
|
-
function m(t) {
|
|
56
|
-
const e = t.length;
|
|
57
|
-
return e === 25 && t[0] === 118 && // OP_DUP
|
|
58
|
-
t[1] === 169 && // OP_HASH160
|
|
59
|
-
t[2] === 20 && // Push 20 bytes
|
|
60
|
-
t[23] === 136 && // OP_EQUALVERIFY
|
|
61
|
-
t[24] === 172 ? "P2PKH" : e === 23 && t[0] === 169 && // OP_HASH160
|
|
62
|
-
t[1] === 20 && // Push 20 bytes
|
|
63
|
-
t[22] === 135 ? "P2SH" : e === 22 && t[0] === 0 && // OP_0
|
|
64
|
-
t[1] === 20 ? "P2WPKH" : e === 34 && t[0] === 0 && // OP_0
|
|
65
|
-
t[1] === 32 ? "P2WSH" : e === 34 && t[0] === 81 && // OP_1
|
|
66
|
-
t[1] === 32 ? "P2TR" : "UNKNOWN";
|
|
67
|
-
}
|
|
68
|
-
function F(t, e) {
|
|
69
|
-
const n = h.from(t.scriptPubKey, "hex"), s = m(n);
|
|
70
|
-
switch (s) {
|
|
71
|
-
case l.P2WPKH:
|
|
72
|
-
return {
|
|
73
|
-
witnessUtxo: {
|
|
74
|
-
script: n,
|
|
75
|
-
value: t.value
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
case l.P2WSH: {
|
|
79
|
-
if (!t.witnessScript)
|
|
80
|
-
throw new Error("Missing witnessScript for P2WSH input");
|
|
81
|
-
return {
|
|
82
|
-
witnessUtxo: {
|
|
83
|
-
script: n,
|
|
84
|
-
value: t.value
|
|
85
|
-
},
|
|
86
|
-
witnessScript: h.from(t.witnessScript, "hex")
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
case l.P2TR: {
|
|
90
|
-
if (e && e.length !== 32)
|
|
91
|
-
throw new Error(
|
|
92
|
-
`Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`
|
|
93
|
-
);
|
|
94
|
-
return {
|
|
95
|
-
witnessUtxo: {
|
|
96
|
-
script: n,
|
|
97
|
-
value: t.value
|
|
98
|
-
},
|
|
99
|
-
// tapInternalKey is needed for Taproot signing
|
|
100
|
-
...e && { tapInternalKey: e }
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
default:
|
|
104
|
-
throw new Error(`Unsupported script type: ${s}`);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
export {
|
|
108
|
-
l as B,
|
|
109
|
-
$ as a,
|
|
110
|
-
m as b,
|
|
111
|
-
B as c,
|
|
112
|
-
F as d,
|
|
113
|
-
p as g,
|
|
114
|
-
N as s
|
|
115
|
-
};
|
|
116
|
-
//# sourceMappingURL=psbtInputFields-DO0ELwiv.js.map
|