@babylonlabs-io/ts-sdk 0.16.2 → 0.17.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.
Files changed (138) hide show
  1. package/dist/challengeAssert-D_k_ADgP.cjs +2 -0
  2. package/dist/challengeAssert-D_k_ADgP.cjs.map +1 -0
  3. package/dist/challengeAssert-k5_LWUtO.js +362 -0
  4. package/dist/challengeAssert-k5_LWUtO.js.map +1 -0
  5. package/dist/constants-EiyZkXce.cjs +2 -0
  6. package/dist/constants-EiyZkXce.cjs.map +1 -0
  7. package/dist/constants-Q7v2O7Ps.js +155 -0
  8. package/dist/constants-Q7v2O7Ps.js.map +1 -0
  9. package/dist/errors-DKLboMnq.cjs +2 -0
  10. package/dist/errors-DKLboMnq.cjs.map +1 -0
  11. package/dist/errors-KY63mgWT.js +1510 -0
  12. package/dist/errors-KY63mgWT.js.map +1 -0
  13. package/dist/fundPeginTransaction-DpwnDslW.js +50 -0
  14. package/dist/fundPeginTransaction-DpwnDslW.js.map +1 -0
  15. package/dist/fundPeginTransaction-EbrZzlrh.cjs +2 -0
  16. package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +1 -0
  17. package/dist/index-D3z3SZAj.cjs +2 -0
  18. package/dist/index-D3z3SZAj.cjs.map +1 -0
  19. package/dist/index-Dw7FAwne.js +913 -0
  20. package/dist/index-Dw7FAwne.js.map +1 -0
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +98 -74
  23. package/dist/index.js.map +1 -1
  24. package/dist/payout-Ce9vSs9e.js +164 -0
  25. package/dist/payout-Ce9vSs9e.js.map +1 -0
  26. package/dist/payout-CfsDnjKI.cjs +2 -0
  27. package/dist/payout-CfsDnjKI.cjs.map +1 -0
  28. package/dist/psbtInputFields-C0nKn_GD.cjs +2 -0
  29. package/dist/psbtInputFields-C0nKn_GD.cjs.map +1 -0
  30. package/dist/psbtInputFields-DO0ELwiv.js +116 -0
  31. package/dist/psbtInputFields-DO0ELwiv.js.map +1 -0
  32. package/dist/signAndSubmitPayouts-CAOEAQp9.js +490 -0
  33. package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +1 -0
  34. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +2 -0
  35. package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +1 -0
  36. package/dist/signing-Deg5lCoC.cjs +2 -0
  37. package/dist/signing-Deg5lCoC.cjs.map +1 -0
  38. package/dist/signing-Drwr3bXB.js +16 -0
  39. package/dist/signing-Drwr3bXB.js.map +1 -0
  40. package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts +2 -0
  41. package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts.map +1 -0
  42. package/dist/tbv/core/clients/eth/index.d.ts +3 -0
  43. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -0
  44. package/dist/tbv/core/clients/eth/types.d.ts +37 -0
  45. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -0
  46. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +20 -0
  47. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -0
  48. package/dist/tbv/core/clients/index.cjs +2 -0
  49. package/dist/tbv/core/clients/index.cjs.map +1 -0
  50. package/dist/tbv/core/clients/index.d.ts +2 -0
  51. package/dist/tbv/core/clients/index.d.ts.map +1 -1
  52. package/dist/tbv/core/clients/index.js +26 -0
  53. package/dist/tbv/core/clients/index.js.map +1 -0
  54. package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts +2 -0
  55. package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts.map +1 -0
  56. package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts +2 -0
  57. package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts.map +1 -0
  58. package/dist/tbv/core/clients/vault-provider/api.d.ts +53 -0
  59. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -0
  60. package/dist/tbv/core/clients/vault-provider/index.d.ts +7 -0
  61. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -0
  62. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +90 -0
  63. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -0
  64. package/dist/tbv/core/clients/vault-provider/types.d.ts +256 -0
  65. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -0
  66. package/dist/tbv/core/clients/vault-provider/validators.d.ts +30 -0
  67. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -0
  68. package/dist/tbv/core/index.cjs +1 -1
  69. package/dist/tbv/core/index.d.ts +1 -0
  70. package/dist/tbv/core/index.d.ts.map +1 -1
  71. package/dist/tbv/core/index.js +97 -73
  72. package/dist/tbv/core/index.js.map +1 -1
  73. package/dist/tbv/core/primitives/index.cjs +1 -1
  74. package/dist/tbv/core/primitives/index.d.ts +8 -0
  75. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  76. package/dist/tbv/core/primitives/index.js +26 -24
  77. package/dist/tbv/core/primitives/index.js.map +1 -1
  78. package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts +2 -0
  79. package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts.map +1 -0
  80. package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts +2 -0
  81. package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts.map +1 -0
  82. package/dist/tbv/core/services/deposit/index.d.ts +10 -0
  83. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -0
  84. package/dist/tbv/core/services/deposit/interfaces.d.ts +21 -0
  85. package/dist/tbv/core/services/deposit/interfaces.d.ts.map +1 -0
  86. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts +55 -0
  87. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +1 -0
  88. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +21 -0
  89. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -0
  90. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts +25 -0
  91. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts.map +1 -0
  92. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts +24 -0
  93. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -0
  94. package/dist/tbv/core/services/index.cjs +2 -0
  95. package/dist/tbv/core/services/index.cjs.map +1 -0
  96. package/dist/tbv/core/services/index.d.ts +10 -0
  97. package/dist/tbv/core/services/index.d.ts.map +1 -0
  98. package/dist/tbv/core/services/index.js +8 -0
  99. package/dist/tbv/core/services/index.js.map +1 -0
  100. package/dist/tbv/core/utils/index.cjs +2 -0
  101. package/dist/tbv/core/utils/index.cjs.map +1 -0
  102. package/dist/tbv/core/utils/index.js +30 -0
  103. package/dist/tbv/core/utils/index.js.map +1 -0
  104. package/dist/tbv/index.cjs +1 -1
  105. package/dist/tbv/index.js +97 -73
  106. package/dist/tbv/index.js.map +1 -1
  107. package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +28 -18
  108. package/dist/tbv/integrations/aave/clients/spoke.d.ts +2 -2
  109. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
  110. package/dist/tbv/integrations/aave/constants.d.ts +7 -0
  111. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  112. package/dist/tbv/integrations/aave/index.cjs +1 -1
  113. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  114. package/dist/tbv/integrations/aave/index.d.ts +2 -2
  115. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  116. package/dist/tbv/integrations/aave/index.js +124 -120
  117. package/dist/tbv/integrations/aave/index.js.map +1 -1
  118. package/dist/tbv/integrations/aave/types.d.ts +4 -6
  119. package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
  120. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts +10 -1
  121. package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts.map +1 -1
  122. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts +0 -1
  123. package/dist/tbv/integrations/aave/utils/debtUtils.d.ts.map +1 -1
  124. package/dist/tbv/integrations/aave/utils/index.d.ts +1 -1
  125. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  126. package/dist/types-D1rYwwCu.js +235 -0
  127. package/dist/types-D1rYwwCu.js.map +1 -0
  128. package/dist/types-DEWiqXYp.cjs +2 -0
  129. package/dist/types-DEWiqXYp.cjs.map +1 -0
  130. package/package.json +11 -1
  131. package/dist/challengeAssert-CTajvPAY.cjs +0 -2
  132. package/dist/challengeAssert-CTajvPAY.cjs.map +0 -1
  133. package/dist/challengeAssert-DtrQLG0c.js +0 -711
  134. package/dist/challengeAssert-DtrQLG0c.js.map +0 -1
  135. package/dist/errors-BeFfs5_J.js +0 -2250
  136. package/dist/errors-BeFfs5_J.js.map +0 -1
  137. package/dist/errors-CAFiRPYI.cjs +0 -2
  138. package/dist/errors-CAFiRPYI.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-Dw7FAwne.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] 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 * ABI for getBtcVaultProtocolInfo — not in the SDK's minimal ABI since\n * it's only needed by this optional reader, not by core SDK operations.\n */\nconst GET_BTC_VAULT_PROTOCOL_INFO_ABI = [\n {\n type: \"function\" as const,\n name: \"getBtcVaultProtocolInfo\" as const,\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\" as const,\n internalType: \"bytes32\" as const,\n },\n ],\n outputs: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\" as const,\n internalType: \"bytes\" as const,\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint32\" as const,\n internalType: \"uint32\" as const,\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint32\" as const,\n internalType: \"uint32\" as const,\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint32\" as const,\n internalType: \"uint32\" as const,\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\" as const,\n internalType: \"uint256\" as const,\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\" as const,\n internalType: \"bytes32\" as const,\n },\n {\n name: \"hashlock\",\n type: \"bytes32\" as const,\n internalType: \"bytes32\" as const,\n },\n {\n name: \"htlcVout\",\n type: \"uint8\" as const,\n internalType: \"uint8\" as const,\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\" as const,\n internalType: \"bytes\" as const,\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\" as const,\n internalType: \"bytes32\" as const,\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\" as const,\n internalType: \"uint16\" as const,\n },\n ],\n stateMutability: \"view\" as const,\n },\n] as const;\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: GET_BTC_VAULT_PROTOCOL_INFO_ABI,\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","GET_BTC_VAULT_PROTOCOL_INFO_ABI","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,IACnD;AAAA,EAAA;AAGF,MAAI;AAEF,WAAO,MAAM,MAAMD,GAAK;AAAA,MACtB,GAAGC;AAAA,MACH,QAAQ,YAAY,IAAIG,CAAO;AAAA,IAAA,CAChC;AAAA,EACH,SAASC,GAAO;AAEd,UADA,aAAaF,CAAS,GAEpBE,KAAS,QACT,OAAOA,KAAU,YACjB,UAAUA,KACVA,EAAM,SAAS,eAET,IAAI;AAAA,MACR,uCAAuCP,CAA0B,OAAOE,CAAG;AAAA,IAAA,IAGzEK;AAAA,EACR;AACF;AAMA,MAAMC,IAAe;AAErB,SAASC,EAAoBC,GAAwB;AACnD,SAAO,OAAO,UAAUA,CAAK,KAAKA,IAAQ,KAAKA,KAASX;AA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AAO,EAAE,OAAAE,GAAO,UAAAC,EAAA;AAAA,EAClB;AACF;"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./shared/index.cjs"),e=require("./challengeAssert-CTajvPAY.cjs"),r=require("@babylonlabs-io/babylon-tbv-rust-wasm"),t=require("./errors-CAFiRPYI.cjs");exports.BitcoinNetworks=i.BitcoinNetworks;exports.BTC_DUST_SAT=e.BTC_DUST_SAT;exports.DUST_THRESHOLD=e.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=e.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=e.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=e.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=e.P2TR_INPUT_SIZE;exports.PEGIN_FIXED_OUTPUTS=e.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=e.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=e.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=e.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.buildChallengeAssertPsbt=e.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=e.buildDepositorPayoutPsbt;exports.buildNoPayoutPsbt=e.buildNoPayoutPsbt;exports.buildPayoutPsbt=e.buildPayoutPsbt;exports.buildPeginInputPsbt=e.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=e.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=e.buildPrePeginPsbt;exports.buildRefundPsbt=e.buildRefundPsbt;exports.computeNumLocalChallengers=e.computeNumLocalChallengers;exports.createPayoutScript=e.createPayoutScript;exports.deriveNativeSegwitAddress=e.deriveNativeSegwitAddress;exports.deriveTaprootAddress=e.deriveTaprootAddress;exports.ensureHexPrefix=e.ensureHexPrefix;exports.extractPayoutSignature=e.extractPayoutSignature;exports.extractPeginInputSignature=e.extractPeginInputSignature;exports.finalizePeginInputPsbt=e.finalizePeginInputPsbt;exports.fundPeginTransaction=e.fundPeginTransaction;exports.getNetwork=e.getNetwork;exports.hexToUint8Array=e.hexToUint8Array;exports.isAddressFromPublicKey=e.isAddressFromPublicKey;exports.isValidHex=e.isValidHex;exports.parseUnfundedWasmTransaction=e.parseUnfundedWasmTransaction;exports.peginOutputCount=e.peginOutputCount;exports.processPublicKeyToXOnly=e.processPublicKeyToXOnly;exports.rateBasedTxBufferFee=e.rateBasedTxBufferFee;exports.stripHexPrefix=e.stripHexPrefix;exports.toXOnly=e.toXOnly;exports.uint8ArrayToHex=e.uint8ArrayToHex;exports.validateWalletPubkey=e.validateWalletPubkey;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>r.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>r.deriveVaultId});exports.BTCVaultRegistryABI=t.BTCVaultRegistryABI;exports.BitcoinScriptType=t.BitcoinScriptType;exports.CONTRACT_ERRORS=t.CONTRACT_ERRORS;exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.PayoutManager=t.PayoutManager;exports.PeginManager=t.PeginManager;exports.calculateBtcTxHash=t.calculateBtcTxHash;exports.computeWotsPkHash=t.computeWotsPkHash;exports.createTaprootScriptPathSignOptions=t.createTaprootScriptPathSignOptions;exports.deriveWotsKeypair=t.deriveWotsKeypair;exports.deriveWotsPkHash=t.deriveWotsPkHash;exports.extractErrorData=t.extractErrorData;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getContractErrorMessage=t.getContractErrorMessage;exports.getDustThreshold=t.getDustThreshold;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getPsbtInputFields=t.getPsbtInputFields;exports.getScriptType=t.getScriptType;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.handleContractError=t.handleContractError;exports.isKnownContractError=t.isKnownContractError;exports.isWotsMismatchError=t.isWotsMismatchError;exports.keypairToPublicKey=t.keypairToPublicKey;exports.mnemonicToWotsSeed=t.mnemonicToWotsSeed;exports.pushTx=t.pushTx;exports.selectUtxosForPegin=t.selectUtxosForPegin;exports.shouldAddChangeOutput=t.shouldAddChangeOutput;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./shared/index.cjs"),i=require("./challengeAssert-D_k_ADgP.cjs"),u=require("@babylonlabs-io/babylon-tbv-rust-wasm"),a=require("./payout-CfsDnjKI.cjs"),e=require("./constants-EiyZkXce.cjs"),s=require("./psbtInputFields-C0nKn_GD.cjs"),T=require("./fundPeginTransaction-EbrZzlrh.cjs"),d=require("./signing-Deg5lCoC.cjs"),r=require("./errors-DKLboMnq.cjs"),n=require("./signAndSubmitPayouts-CSJmcPQN.cjs"),t=require("./index-D3z3SZAj.cjs"),o=require("./types-DEWiqXYp.cjs");exports.BitcoinNetworks=P.BitcoinNetworks;exports.buildChallengeAssertPsbt=i.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=i.buildDepositorPayoutPsbt;exports.buildNoPayoutPsbt=i.buildNoPayoutPsbt;exports.buildPeginInputPsbt=i.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=i.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=i.buildPrePeginPsbt;exports.buildRefundPsbt=i.buildRefundPsbt;exports.computeNumLocalChallengers=i.computeNumLocalChallengers;exports.extractPeginInputSignature=i.extractPeginInputSignature;exports.finalizePeginInputPsbt=i.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>u.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>u.deriveVaultId});exports.buildPayoutPsbt=a.buildPayoutPsbt;exports.createPayoutScript=a.createPayoutScript;exports.extractPayoutSignature=a.extractPayoutSignature;exports.BTC_DUST_SAT=e.BTC_DUST_SAT;exports.DUST_THRESHOLD=e.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=e.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=e.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=e.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=e.P2TR_INPUT_SIZE;exports.PEGIN_FIXED_OUTPUTS=e.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=e.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=e.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=e.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.deriveNativeSegwitAddress=e.deriveNativeSegwitAddress;exports.deriveTaprootAddress=e.deriveTaprootAddress;exports.ensureHexPrefix=e.ensureHexPrefix;exports.getNetwork=e.getNetwork;exports.hexToUint8Array=e.hexToUint8Array;exports.isAddressFromPublicKey=e.isAddressFromPublicKey;exports.isValidHex=e.isValidHex;exports.peginOutputCount=e.peginOutputCount;exports.processPublicKeyToXOnly=e.processPublicKeyToXOnly;exports.rateBasedTxBufferFee=e.rateBasedTxBufferFee;exports.stripHexPrefix=e.stripHexPrefix;exports.toXOnly=e.toXOnly;exports.uint8ArrayToHex=e.uint8ArrayToHex;exports.validateWalletPubkey=e.validateWalletPubkey;exports.BitcoinScriptType=s.BitcoinScriptType;exports.calculateBtcTxHash=s.calculateBtcTxHash;exports.getDustThreshold=s.getDustThreshold;exports.getPsbtInputFields=s.getPsbtInputFields;exports.getScriptType=s.getScriptType;exports.selectUtxosForPegin=s.selectUtxosForPegin;exports.shouldAddChangeOutput=s.shouldAddChangeOutput;exports.fundPeginTransaction=T.fundPeginTransaction;exports.parseUnfundedWasmTransaction=T.parseUnfundedWasmTransaction;exports.createTaprootScriptPathSignOptions=d.createTaprootScriptPathSignOptions;exports.CONTRACT_ERRORS=r.CONTRACT_ERRORS;exports.PeginManager=r.PeginManager;exports.computeWotsPkHash=r.computeWotsPkHash;exports.deriveWotsKeypair=r.deriveWotsKeypair;exports.deriveWotsPkHash=r.deriveWotsPkHash;exports.extractErrorData=r.extractErrorData;exports.getContractErrorMessage=r.getContractErrorMessage;exports.handleContractError=r.handleContractError;exports.isKnownContractError=r.isKnownContractError;exports.isWotsMismatchError=r.isWotsMismatchError;exports.keypairToPublicKey=r.keypairToPublicKey;exports.mnemonicToWotsSeed=r.mnemonicToWotsSeed;exports.PayoutManager=n.PayoutManager;exports.pollAndSignPayouts=n.pollAndSignPayouts;exports.signDepositorGraph=n.signDepositorGraph;exports.submitWotsPublicKey=n.submitWotsPublicKey;exports.waitForPeginStatus=n.waitForPeginStatus;exports.BTCVaultRegistryABI=t.BTCVaultRegistryABI;exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.VaultProviderRpcClient=t.VaultProviderRpcClient;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.VpResponseValidationError=t.VpResponseValidationError;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.DaemonStatus=o.DaemonStatus;exports.JSON_RPC_ERROR_CODES=o.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=o.JsonRpcClient;exports.JsonRpcError=o.JsonRpcError;exports.POST_WOTS_STATUSES=o.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=o.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=o.RpcErrorCode;exports.VP_TERMINAL_STATUSES=o.VP_TERMINAL_STATUSES;exports.VP_TRANSIENT_STATUSES=o.VP_TRANSIENT_STATUSES;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,80 +1,104 @@
1
1
  import { BitcoinNetworks as e } from "./shared/index.js";
2
- import { B as r, D as o, F as i, L as n, M as u, P, z as T, S as d, T as l, W as g, l as p, j as E, k as c, h as _, d as A, a as x, b as S, g as b, c as y, m as I, n as R, o as m, s as C, i as F, e as U, f as O, E as f, G as h, p as L, q as M, r as H, C as N, A as B, t as D, y as W, u as k, v, w, x as X } from "./challengeAssert-DtrQLG0c.js";
3
- import { computeMinClaimValue as V, deriveVaultId as Y } from "@babylonlabs-io/babylon-tbv-rust-wasm";
4
- import { o as z, B as Z, C as j, M as q, f as J, P as Q, c as $, y as ss, e as as, w as es, z as ts, q as rs, h as os, i as is, r as ns, g as us, j as Ps, k as Ts, d as ds, b as ls, l as gs, m as ps, n as Es, u as cs, t as _s, A as As, x as xs, v as Ss, p as bs, s as ys, a as Is } from "./errors-BeFfs5_J.js";
2
+ import { j as r, h as o, i, d as n, a as T, b as P, g as u, c as p, e as d, f as E } from "./challengeAssert-k5_LWUtO.js";
3
+ import { computeMinClaimValue as l, deriveVaultId as c } from "@babylonlabs-io/babylon-tbv-rust-wasm";
4
+ import { b as g, c as R, e as A } from "./payout-Ce9vSs9e.js";
5
+ import { B as b, D as m, F as f, L as I, M as O, P as y, c as C, S as U, T as h, W as F, d as N, a as D, e as L, g as M, h as V, i as B, b as H, f as W, p as v, r as k, s as w, t as K, u as X, v as G } from "./constants-Q7v2O7Ps.js";
6
+ import { B as J, c as Z, g as j, d as z, b as q, s as Q, a as $ } from "./psbtInputFields-DO0ELwiv.js";
7
+ import { f as sa, p as ea } from "./fundPeginTransaction-DpwnDslW.js";
8
+ import { c as ra } from "./signing-Drwr3bXB.js";
9
+ import { C as ia, P as na, c as Ta, d as Pa, a as ua, e as pa, g as da, h as Ea, i as Sa, b as la, k as ca, m as _a } from "./errors-KY63mgWT.js";
10
+ import { P as Ra, p as Aa, a as xa, s as ba, w as ma } from "./signAndSubmitPayouts-CAOEAQp9.js";
11
+ import { B as Ia, M as Oa, V as ya, i as Ca, h as Ua, g as ha, a as Fa, b as Na, c as Da, d as La, e as Ma, f as Va, p as Ba } from "./index-Dw7FAwne.js";
12
+ import { D as Wa, b as va, J as ka, a as wa, d as Ka, P as Xa, R as Ga, c as Ya, V as Ja } from "./types-D1rYwwCu.js";
5
13
  export {
6
- z as BTCVaultRegistryABI,
7
- r as BTC_DUST_SAT,
14
+ Ia as BTCVaultRegistryABI,
15
+ b as BTC_DUST_SAT,
8
16
  e as BitcoinNetworks,
9
- Z as BitcoinScriptType,
10
- j as CONTRACT_ERRORS,
11
- o as DUST_THRESHOLD,
12
- i as FEE_SAFETY_MARGIN,
13
- n as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
14
- u as MAX_NON_LEGACY_OUTPUT_SIZE,
15
- q as MEMPOOL_API_URLS,
16
- P as P2TR_INPUT_SIZE,
17
- T as PEGIN_FIXED_OUTPUTS,
18
- J as PayoutManager,
19
- Q as PeginManager,
20
- d as SPLIT_TX_FEE_SAFETY_MULTIPLIER,
21
- l as TX_BUFFER_SIZE_OVERHEAD,
22
- g as WALLET_RELAY_FEE_RATE_THRESHOLD,
23
- p as buildChallengeAssertPsbt,
24
- E as buildDepositorPayoutPsbt,
25
- c as buildNoPayoutPsbt,
26
- _ as buildPayoutPsbt,
27
- A as buildPeginInputPsbt,
28
- x as buildPeginTxFromFundedPrePegin,
29
- S as buildPrePeginPsbt,
30
- b as buildRefundPsbt,
31
- $ as calculateBtcTxHash,
32
- V as computeMinClaimValue,
33
- y as computeNumLocalChallengers,
34
- ss as computeWotsPkHash,
35
- I as createPayoutScript,
36
- as as createTaprootScriptPathSignOptions,
37
- R as deriveNativeSegwitAddress,
38
- m as deriveTaprootAddress,
39
- Y as deriveVaultId,
40
- es as deriveWotsKeypair,
41
- ts as deriveWotsPkHash,
42
- C as ensureHexPrefix,
43
- rs as extractErrorData,
44
- F as extractPayoutSignature,
45
- U as extractPeginInputSignature,
46
- O as finalizePeginInputPsbt,
47
- f as fundPeginTransaction,
48
- os as getAddressTxs,
49
- is as getAddressUtxos,
50
- ns as getContractErrorMessage,
51
- us as getDustThreshold,
52
- Ps as getMempoolApiUrl,
53
- h as getNetwork,
54
- Ts as getNetworkFees,
55
- ds as getPsbtInputFields,
56
- ls as getScriptType,
57
- gs as getTxHex,
58
- ps as getTxInfo,
59
- Es as getUtxoInfo,
60
- cs as handleContractError,
61
- L as hexToUint8Array,
62
- M as isAddressFromPublicKey,
63
- _s as isKnownContractError,
17
+ J as BitcoinScriptType,
18
+ ia as CONTRACT_ERRORS,
19
+ m as DUST_THRESHOLD,
20
+ Wa as DaemonStatus,
21
+ f as FEE_SAFETY_MARGIN,
22
+ va as JSON_RPC_ERROR_CODES,
23
+ ka as JsonRpcClient,
24
+ wa as JsonRpcError,
25
+ I as LOW_RATE_ESTIMATION_ACCURACY_BUFFER,
26
+ O as MAX_NON_LEGACY_OUTPUT_SIZE,
27
+ Oa as MEMPOOL_API_URLS,
28
+ y as P2TR_INPUT_SIZE,
29
+ C as PEGIN_FIXED_OUTPUTS,
30
+ Ka as POST_WOTS_STATUSES,
31
+ Xa as PRE_DEPOSITOR_SIGNATURES_STATES,
32
+ Ra as PayoutManager,
33
+ na as PeginManager,
34
+ Ga as RpcErrorCode,
35
+ U as SPLIT_TX_FEE_SAFETY_MULTIPLIER,
36
+ h as TX_BUFFER_SIZE_OVERHEAD,
37
+ Ya as VP_TERMINAL_STATUSES,
38
+ Ja as VP_TRANSIENT_STATUSES,
39
+ ya as VaultProviderRpcClient,
40
+ Ca as ViemVaultRegistryReader,
41
+ Ua as VpResponseValidationError,
42
+ F as WALLET_RELAY_FEE_RATE_THRESHOLD,
43
+ r as buildChallengeAssertPsbt,
44
+ o as buildDepositorPayoutPsbt,
45
+ i as buildNoPayoutPsbt,
46
+ g as buildPayoutPsbt,
47
+ n as buildPeginInputPsbt,
48
+ T as buildPeginTxFromFundedPrePegin,
49
+ P as buildPrePeginPsbt,
50
+ u as buildRefundPsbt,
51
+ Z as calculateBtcTxHash,
52
+ l as computeMinClaimValue,
53
+ p as computeNumLocalChallengers,
54
+ Ta as computeWotsPkHash,
55
+ R as createPayoutScript,
56
+ ra as createTaprootScriptPathSignOptions,
57
+ N as deriveNativeSegwitAddress,
58
+ D as deriveTaprootAddress,
59
+ c as deriveVaultId,
60
+ Pa as deriveWotsKeypair,
61
+ ua as deriveWotsPkHash,
62
+ L as ensureHexPrefix,
63
+ pa as extractErrorData,
64
+ A as extractPayoutSignature,
65
+ d as extractPeginInputSignature,
66
+ E as finalizePeginInputPsbt,
67
+ sa as fundPeginTransaction,
68
+ ha as getAddressTxs,
69
+ Fa as getAddressUtxos,
70
+ da as getContractErrorMessage,
71
+ j as getDustThreshold,
72
+ Na as getMempoolApiUrl,
73
+ M as getNetwork,
74
+ Da as getNetworkFees,
75
+ z as getPsbtInputFields,
76
+ q as getScriptType,
77
+ La as getTxHex,
78
+ Ma as getTxInfo,
79
+ Va as getUtxoInfo,
80
+ Ea as handleContractError,
81
+ V as hexToUint8Array,
82
+ B as isAddressFromPublicKey,
83
+ Sa as isKnownContractError,
64
84
  H as isValidHex,
65
- As as isWotsMismatchError,
66
- xs as keypairToPublicKey,
67
- Ss as mnemonicToWotsSeed,
68
- N as parseUnfundedWasmTransaction,
69
- B as peginOutputCount,
70
- D as processPublicKeyToXOnly,
71
- bs as pushTx,
72
- W as rateBasedTxBufferFee,
73
- ys as selectUtxosForPegin,
74
- Is as shouldAddChangeOutput,
75
- k as stripHexPrefix,
76
- v as toXOnly,
77
- w as uint8ArrayToHex,
78
- X as validateWalletPubkey
85
+ la as isWotsMismatchError,
86
+ ca as keypairToPublicKey,
87
+ _a as mnemonicToWotsSeed,
88
+ ea as parseUnfundedWasmTransaction,
89
+ W as peginOutputCount,
90
+ Aa as pollAndSignPayouts,
91
+ v as processPublicKeyToXOnly,
92
+ Ba as pushTx,
93
+ k as rateBasedTxBufferFee,
94
+ Q as selectUtxosForPegin,
95
+ $ as shouldAddChangeOutput,
96
+ xa as signDepositorGraph,
97
+ w as stripHexPrefix,
98
+ ba as submitWotsPublicKey,
99
+ K as toXOnly,
100
+ X as uint8ArrayToHex,
101
+ G as validateWalletPubkey,
102
+ ma as waitForPeginStatus
79
103
  };
80
104
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"}
@@ -0,0 +1,164 @@
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
@@ -0,0 +1 @@
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,cAA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AAS,CAAC,KAAK,IACvBF,EAAQE,IAAS,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;"}
@@ -0,0 +1,2 @@
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