@babylonlabs-io/ts-sdk 0.37.3 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BTCVaultRegistry.abi-CHFGevwa.cjs +2 -0
- package/dist/BTCVaultRegistry.abi-CHFGevwa.cjs.map +1 -0
- package/dist/{BTCVaultRegistry.abi-DbJ5lsFJ.js → BTCVaultRegistry.abi-Cq9-JlqT.js} +38 -2
- package/dist/BTCVaultRegistry.abi-Cq9-JlqT.js.map +1 -0
- package/dist/PeginManager-BRHJZYmE.cjs +2 -0
- package/dist/PeginManager-BRHJZYmE.cjs.map +1 -0
- package/dist/{PeginManager-HCYTUzh6.js → PeginManager-C1en2vwr.js} +431 -371
- package/dist/PeginManager-C1en2vwr.js.map +1 -0
- package/dist/{ProtocolParams.abi-DXu8L0Fn.js → ProtocolParams.abi-C2brDWTI.js} +8 -3
- package/dist/ProtocolParams.abi-C2brDWTI.js.map +1 -0
- package/dist/ProtocolParams.abi-DQhcqsNr.cjs +2 -0
- package/dist/ProtocolParams.abi-DQhcqsNr.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-CEKwFY8l.cjs +2 -0
- package/dist/buildAndBroadcastRefund-CEKwFY8l.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-CI_x6OtX.js → buildAndBroadcastRefund-vwfVgJeA.js} +201 -200
- package/dist/buildAndBroadcastRefund-vwfVgJeA.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +16 -16
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +12 -1
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +9 -9
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +0 -9
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/types.d.ts +38 -21
- package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +36 -2
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +6 -2
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +7 -7
- package/dist/tbv/core/managers/PeginManager.d.ts +5 -0
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts +4 -2
- package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/core/services/pegout/state.d.ts +5 -8
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +7 -7
- package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.js +23 -22
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/types.d.ts +6 -0
- package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
- package/dist/types-D2jcXfm7.cjs +2 -0
- package/dist/types-D2jcXfm7.cjs.map +1 -0
- package/dist/types-TOmEvvRy.js +322 -0
- package/dist/types-TOmEvvRy.js.map +1 -0
- package/dist/{vault-registry-reader-Blhu9FW2.js → vault-registry-reader-BrARgFre.js} +207 -202
- package/dist/vault-registry-reader-BrARgFre.js.map +1 -0
- package/dist/vault-registry-reader-CbJHSxVe.cjs +2 -0
- package/dist/vault-registry-reader-CbJHSxVe.cjs.map +1 -0
- package/package.json +3 -3
- package/dist/BTCVaultRegistry.abi-DbJ5lsFJ.js.map +0 -1
- package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs +0 -2
- package/dist/BTCVaultRegistry.abi-ZdPpION2.cjs.map +0 -1
- package/dist/PeginManager-CTznAVPT.cjs +0 -2
- package/dist/PeginManager-CTznAVPT.cjs.map +0 -1
- package/dist/PeginManager-HCYTUzh6.js.map +0 -1
- package/dist/ProtocolParams.abi-BmvHwQJV.cjs +0 -2
- package/dist/ProtocolParams.abi-BmvHwQJV.cjs.map +0 -1
- package/dist/ProtocolParams.abi-DXu8L0Fn.js.map +0 -1
- package/dist/buildAndBroadcastRefund-Bj2e94CC.cjs +0 -2
- package/dist/buildAndBroadcastRefund-Bj2e94CC.cjs.map +0 -1
- package/dist/buildAndBroadcastRefund-CI_x6OtX.js.map +0 -1
- package/dist/types-DnyyBNcC.cjs +0 -2
- package/dist/types-DnyyBNcC.cjs.map +0 -1
- package/dist/types-TiIjyo2b.js +0 -320
- package/dist/types-TiIjyo2b.js.map +0 -1
- package/dist/vault-registry-reader-7gOYnrQD.cjs +0 -2
- package/dist/vault-registry-reader-7gOYnrQD.cjs.map +0 -1
- package/dist/vault-registry-reader-Blhu9FW2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/tbv/integrations/aave/constants.ts","../../../../src/tbv/integrations/aave/clients/query.ts","../../../../src/tbv/integrations/aave/utils/debtUtils.ts","../../../../src/tbv/integrations/aave/clients/spoke.ts","../../../../src/tbv/integrations/aave/clients/transaction.ts","../../../../src/tbv/integrations/aave/utils/aaveConversions.ts","../../../../src/tbv/integrations/aave/utils/borrowRatio.ts","../../../../src/tbv/integrations/aave/utils/healthFactor.ts","../../../../src/tbv/integrations/aave/utils/vaultSelection.ts","../../../../src/tbv/integrations/aave/utils/cascadeSimulation.ts","../../../../src/tbv/integrations/aave/utils/optimalOrder.ts","../../../../src/tbv/integrations/aave/utils/vaultSplit.ts","../../../../src/tbv/integrations/aave/utils/seizureSimulation.ts"],"sourcesContent":["/**\n * Aave Protocol Constants\n *\n * Constants for interacting with Aave v4 protocol.\n * Reference: https://github.com/aave/aave-v4 ISpoke.sol\n */\n\n/**\n * Aave contract function names\n * Centralized constants for contract interactions\n */\nexport const AAVE_FUNCTION_NAMES = {\n /** Withdraw selected vaults from position (partial withdrawal) */\n WITHDRAW_COLLATERALS: \"withdrawCollaterals\",\n /** Borrow from Core Spoke position */\n BORROW: \"borrowFromCorePosition\",\n /** Repay debt to Core Spoke position */\n REPAY: \"repayToCorePosition\",\n /** Reorder vault prefix ordering for liquidation priority */\n REORDER_VAULTS: \"reorderVaults\",\n} as const;\n\n/**\n * BTC token decimals (satoshis)\n * 1 BTC = 100,000,000 satoshis\n */\nexport const BTC_DECIMALS = 8;\n\n/**\n * USDC token decimals\n * Used for debt calculations\n */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Divisor to convert basis points (BPS) to percentage\n *\n * In Aave v4, risk parameters like collateralRisk are stored in BPS\n * where 10000 BPS = 100%.\n *\n * Example: 8000 BPS / 100 = 80%\n *\n * Reference: ISpoke.sol - \"collateralRisk The risk associated with a\n * collateral asset, expressed in BPS\"\n */\nexport const BPS_TO_PERCENT_DIVISOR = 100;\n\n/**\n * Full basis points scale (10000 BPS = 100%)\n *\n * Use this when converting BPS directly to decimal:\n * Example: 8000 BPS / 10000 = 0.80\n */\nexport const BPS_SCALE = 10000;\n\n/**\n * Aave base currency decimals\n * Account data values (collateral, debt) use 1e26 = $1 USD\n *\n * Reference: ISpoke.sol UserAccountData\n */\nexport const AAVE_BASE_CURRENCY_DECIMALS = 26;\n\n/**\n * Aave RAY-scaled base currency decimals\n * Debt values (totalDebtValueRay) use 1e53 = $1 USD\n * (base currency 1e26 scaled by RAY 1e27).\n *\n * Reference: IAaveSpoke.sol UserAccountData.totalDebtValueRay\n */\nexport const AAVE_BASE_CURRENCY_RAY_DECIMALS = 53;\n\n/**\n * WAD decimals (1e18 = 1.0)\n * Used for health factor and collateral factor values\n *\n * Reference: ISpoke.sol - \"healthFactor expressed in WAD. 1e18 represents a health factor of 1.00\"\n */\nexport const WAD_DECIMALS = 18;\n\n/**\n * Health factor warning threshold\n * Positions below this are considered at risk of liquidation\n */\nexport const HEALTH_FACTOR_WARNING_THRESHOLD = 1.5;\n\n/**\n * Minimum health factor allowed for borrowing\n * Prevents users from borrowing if resulting health factor would be below this.\n */\nexport const MIN_HEALTH_FACTOR_FOR_BORROW = 1.2;\n\n/**\n * Buffer for full repayment to account for interest accrual\n * between fetching debt and transaction execution.\n *\n * 0.5% buffer (50 basis points). Sized to absorb hours of execution delay\n * (e.g. Safe-multisig quorum collection) without leaving residual dust.\n * The adapter only pulls what's actually owed; excess approval/balance\n * stays with the user.\n *\n * Users whose wallet balance covers the debt but not the full buffer are\n * routed through the \"max-capped\" repay path instead of `repayFull`, so\n * a larger buffer never blocks a legitimate max-repay.\n */\nexport const FULL_REPAY_BUFFER_DIVISOR = 200n; // 1/200 = 0.5% buffer\n\n/**\n * Same buffer as `FULL_REPAY_BUFFER_DIVISOR`, expressed as a float fraction\n * for UI-side comparisons that operate in `number` rather than `bigint`.\n */\nexport const FULL_REPAY_BUFFER_FRACTION =\n 1 / Number(FULL_REPAY_BUFFER_DIVISOR);\n\n","/**\n * Aave Integration Adapter - Read operations (queries)\n *\n * Only includes functions that provide data NOT available from the indexer.\n * Most position/vault data should be fetched from the GraphQL indexer instead.\n */\n\nimport { type Address, type Hex, type PublicClient, zeroAddress } from \"viem\";\n\nimport type { AaveMarketPosition, PositionSizeParams } from \"../types.js\";\nimport AaveIntegrationAdapterABI from \"./abis/AaveIntegrationAdapter.abi.json\";\n\n/**\n * Get a position by user address.\n *\n * The adapter resolves the user's proxy contract and collateralized vault IDs.\n *\n * NOTE: Prefer using the indexer (fetchAavePositionWithCollaterals) for position data.\n * This function is only needed when you need data not available in the indexer,\n * or when you need to verify on-chain state.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param user - User's Ethereum address\n * @returns Market position data or null if position doesn't exist\n */\nexport async function getPosition(\n publicClient: PublicClient,\n contractAddress: Address,\n user: Address,\n): Promise<AaveMarketPosition | null> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationAdapterABI,\n functionName: \"getPosition\",\n args: [user],\n });\n\n type PositionResult = {\n proxyContract: Address;\n vaultIds: Hex[];\n };\n\n const position = result as PositionResult;\n\n // Check if position exists (proxyContract should not be zero address)\n if (position.proxyContract === zeroAddress) {\n return null;\n }\n\n return {\n proxyContract: position.proxyContract,\n vaultIds: position.vaultIds,\n };\n}\n\n/**\n * Get position size parameters from the adapter contract.\n *\n * Returns the maximum BTC position size and maximum vaults per position\n * as configured on-chain.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @returns Position size parameters (maxPositionBTC, maxVaultsPerPosition)\n */\nexport async function getPositionSizeParams(\n publicClient: PublicClient,\n contractAddress: Address,\n): Promise<PositionSizeParams> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationAdapterABI,\n functionName: \"getPositionSizeParams\",\n });\n\n const [maxPositionBTC, maxVaultsPerPosition] = result as [bigint, bigint];\n\n return {\n maxPositionBTC,\n maxVaultsPerPosition,\n };\n}\n","/**\n * Aave Debt Utilities\n *\n * Shared utility functions for debt calculations.\n */\n\nimport type { AaveSpokeUserPosition } from \"../types.js\";\n\n/**\n * Check if a position has any debt based on Spoke position data.\n *\n * A position is considered to have debt if any of:\n * - drawnShares > 0 (borrowed principal)\n * - premiumShares > 0 (accrued interest shares)\n *\n * @param position - User position data from Spoke\n * @returns true if the position has any debt\n */\nexport function hasDebtFromPosition(position: AaveSpokeUserPosition): boolean {\n return position.drawnShares > 0n || position.premiumShares > 0n;\n}\n","/**\n * Aave Spoke Client - Read operations\n *\n * Provides read operations for interacting with Aave v4 Spoke contracts.\n * Used to fetch live user position data (debt, collateral) from the Core Spoke.\n *\n * Note: Reserve data should be fetched from the indexer via fetchReserves.ts\n * since it doesn't need to be live and benefits from caching.\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport type {\n AaveSpokeUserAccountData,\n AaveSpokeUserPosition,\n} from \"../types.js\";\nimport { hasDebtFromPosition } from \"../utils/debtUtils.js\";\nimport AaveSpokeABI from \"./abis/AaveSpoke.abi.json\";\n\n/** Account data result type from contract */\ntype AccountDataResult = {\n riskPremium: bigint;\n avgCollateralFactor: bigint;\n healthFactor: bigint;\n totalCollateralValue: bigint;\n totalDebtValueRay: bigint;\n activeCollateralCount: bigint;\n borrowCount: bigint;\n};\n\n/** Position result type from contract */\ntype PositionResult = {\n drawnShares: bigint;\n premiumShares: bigint;\n premiumOffsetRay: bigint;\n suppliedShares: bigint;\n dynamicConfigKey: number;\n};\n\n/**\n * Maps contract result to AaveSpokeUserPosition\n */\nfunction mapPositionResult(result: PositionResult): AaveSpokeUserPosition {\n return {\n drawnShares: result.drawnShares,\n premiumShares: result.premiumShares,\n premiumOffsetRay: result.premiumOffsetRay,\n suppliedShares: result.suppliedShares,\n dynamicConfigKey: result.dynamicConfigKey,\n };\n}\n\n/**\n * Get aggregated user account health data from AAVE spoke.\n *\n * **Live data** - Fetches real-time account health including health factor, total collateral,\n * and total debt across all reserves. Values are calculated on-chain using AAVE oracles\n * and are the authoritative source for liquidation decisions.\n *\n * @param publicClient - Viem public client for reading contracts (from `createPublicClient()`)\n * @param spokeAddress - AAVE Spoke contract address (BTC Vault Core Spoke for vBTC collateral)\n * @param userAddress - User's proxy contract address (NOT user's wallet address)\n * @returns User account data with health metrics, collateral, and debt values\n *\n * @example\n * ```typescript\n * import { getUserAccountData } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { createPublicClient, http } from \"viem\";\n * import { sepolia } from \"viem/chains\";\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http()\n * });\n *\n * const accountData = await getUserAccountData(\n * publicClient,\n * \"0x123...\", // AAVE Spoke address\n * \"0x456...\" // User's AAVE proxy address (from getPosition)\n * );\n *\n * console.log(\"Health Factor:\", accountData.healthFactor);\n * console.log(\"Collateral (USD):\", accountData.totalCollateralValue);\n * console.log(\"Debt (USD):\", accountData.totalDebtValueRay);\n * ```\n *\n * @remarks\n * **Return values:**\n * - `healthFactor` - WAD format (1e18 = 1.0). Below 1.0 = liquidatable\n * - `totalCollateralValue` - USD value in base currency (1e26 = $1)\n * - `totalDebtValueRay` - USD value in RAY-scaled base currency (1e53 = $1)\n * - `avgCollateralFactor` - Weighted average collateral factor in WAD (1e18 = 100%)\n * - `riskPremium` - Additional risk premium\n *\n * **Use cases:**\n * - Check liquidation risk before borrowing\n * - Calculate safe borrow amount\n * - Monitor position health\n * - Display UI health indicators\n */\nexport async function getUserAccountData(\n publicClient: PublicClient,\n spokeAddress: Address,\n userAddress: Address,\n): Promise<AaveSpokeUserAccountData> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserAccountData\",\n args: [userAddress],\n });\n\n const data = result as AccountDataResult;\n return {\n riskPremium: data.riskPremium,\n avgCollateralFactor: data.avgCollateralFactor,\n healthFactor: data.healthFactor,\n totalCollateralValue: data.totalCollateralValue,\n totalDebtValueRay: data.totalDebtValueRay,\n activeCollateralCount: data.activeCollateralCount,\n borrowCount: data.borrowCount,\n };\n}\n\n/**\n * Get user position from the Spoke\n *\n * This fetches live data from the contract because debt accrues interest\n * and needs to be current for accurate health factor calculations.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns User position data\n */\nexport async function getUserPosition(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<AaveSpokeUserPosition> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserPosition\",\n args: [reserveId, userAddress],\n });\n\n return mapPositionResult(result as PositionResult);\n}\n\n/**\n * Check if a user has any debt in a reserve\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns true if user has debt\n */\nexport async function hasDebt(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<boolean> {\n const position = await getUserPosition(\n publicClient,\n spokeAddress,\n reserveId,\n userAddress,\n );\n return hasDebtFromPosition(position);\n}\n\n/**\n * Check if a user has supplied collateral in a reserve\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns true if user has supplied collateral\n */\nexport async function hasCollateral(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<boolean> {\n const position = await getUserPosition(\n publicClient,\n spokeAddress,\n reserveId,\n userAddress,\n );\n return position.suppliedShares > 0n;\n}\n\n/**\n * Get user's exact total debt in a reserve (token units, not shares).\n *\n * Returns the precise amount owed including accrued interest. Essential for full repayment.\n * Debt accrues interest every block, so this must be fetched live from the contract.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - AAVE Spoke contract address\n * @param reserveId - Reserve ID for the debt asset (e.g., `2n` for USDC)\n * @param userAddress - User's proxy contract address\n * @returns Total debt amount in token units (e.g., for USDC: `100000000n` = 100 USDC)\n *\n * @example\n * ```typescript\n * import { getUserTotalDebt, FULL_REPAY_BUFFER_DIVISOR } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { formatUnits } from \"viem\";\n *\n * const totalDebt = await getUserTotalDebt(\n * publicClient,\n * AAVE_SPOKE_ADDRESS,\n * 2n, // USDC reserve\n * proxyAddress\n * );\n *\n * // For full repayment, add buffer to account for interest accrual\n * const repayAmount = totalDebt + (totalDebt / FULL_REPAY_BUFFER_DIVISOR);\n *\n * console.log(\"Debt:\", formatUnits(totalDebt, 6), \"USDC\");\n * ```\n *\n * @remarks\n * **Important for full repayment:**\n * - Add `FULL_REPAY_BUFFER_DIVISOR` buffer to account for interest between fetch and tx execution\n * - Contract only takes what's owed; excess stays in wallet\n * - For partial repayment, use any amount less than total debt\n */\nexport async function getUserTotalDebt(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserTotalDebt\",\n args: [reserveId, userAddress],\n });\n\n return result as bigint;\n}\n\n/** Result type from the `getReserve` contract call.\n *\n * Matches the on-chain `Reserve` struct defined in `ITBVAaveSpoke.sol`:\n * struct Reserve {\n * address underlying;\n * address hub;\n * uint16 assetId;\n * uint8 decimals;\n * uint24 collateralRisk;\n * ReserveFlags flags; // uint8 bitmap\n * uint32 dynamicConfigKey;\n * }\n *\n * Note: this is the `Reserve` struct, NOT `ReserveConfig` — the contract\n * exposes both as separate functions and they return different shapes.\n */\ntype ReserveResult = {\n underlying: Address;\n hub: Address;\n assetId: number;\n decimals: number;\n collateralRisk: number;\n flags: number;\n dynamicConfigKey: number;\n};\n\n/**\n * Get reserve data from the Core Spoke contract via the `getReserve` selector.\n *\n * Returns static reserve properties including the `dynamicConfigKey` needed\n * for `getDynamicReserveConfig` calls. Use this as a fallback when reserve\n * data is not available from the GraphQL indexer.\n *\n * Do NOT confuse with the contract's separate `getReserveConfig` function,\n * which returns `{collateralRisk, paused, frozen, borrowable, receiveSharesEnabled}`.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @param reserveId - Reserve ID\n * @returns Reserve data including `dynamicConfigKey`\n */\nexport async function getReserve(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n): Promise<ReserveResult> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getReserve\",\n args: [reserveId],\n });\n return result as ReserveResult;\n}\n\n/** Result type from getLiquidationConfig contract call */\ntype LiquidationConfigResult = {\n targetHealthFactor: bigint;\n healthFactorForMaxBonus: bigint;\n liquidationBonusFactor: bigint;\n};\n\n/** Result type from getDynamicReserveConfig contract call */\ntype DynamicReserveConfigResult = {\n collateralFactor: bigint;\n maxLiquidationBonus: bigint;\n liquidationFee: bigint;\n};\n\n/**\n * Get the target health factor (THF) from the Core Spoke contract.\n *\n * Per-spoke governance parameter. After a liquidation, the protocol targets\n * restoring the position to this health factor.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @returns Target health factor in WAD (1e18 = 1.0). Example: 1.10 = 1_100_000_000_000_000_000n\n */\nexport async function getTargetHealthFactor(\n publicClient: PublicClient,\n spokeAddress: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getLiquidationConfig\",\n });\n const config = result as LiquidationConfigResult;\n return config.targetHealthFactor;\n}\n\n/**\n * Get the dynamic reserve config from the Core Spoke contract.\n *\n * Returns collateral factor, max liquidation bonus, and liquidation fee\n * for a specific reserve and dynamic config key.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @param reserveId - Reserve ID (e.g., vBTC reserve ID from indexer config)\n * @param dynamicConfigKey - Dynamic config key (from reserve data)\n * @returns Dynamic reserve config with collateralFactor (BPS), maxLiquidationBonus (BPS), liquidationFee (BPS)\n */\nexport async function getDynamicReserveConfig(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n dynamicConfigKey: number,\n): Promise<DynamicReserveConfigResult> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getDynamicReserveConfig\",\n args: [reserveId, dynamicConfigKey],\n });\n return result as DynamicReserveConfigResult;\n}\n","/**\n * Aave Integration Adapter - Transaction builders\n *\n * Provides transaction builders for the AaveIntegrationAdapter contract.\n * Only includes Core Spoke operations for regular users (no Arbitrageur operations).\n *\n * These functions return unsigned transaction parameters that can be executed\n * by the vault service using its wallet client and transaction factory.\n */\n\nimport { type Address, type Hex, encodeFunctionData } from \"viem\";\n\nimport { AAVE_FUNCTION_NAMES } from \"../config.js\";\nimport type { TransactionParams } from \"../types.js\";\nimport AaveIntegrationAdapterABI from \"./abis/AaveIntegrationAdapter.abi.json\";\n\n/**\n * Build transaction to reorder vaults for liquidation priority.\n *\n * The permuted array must contain exactly the same vault IDs as the\n * current position, in the desired new order. Vaults are seized in\n * prefix order (index 0 first) during liquidation.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param permutedVaultIds - Vault IDs in desired new order (must be a permutation of current vaults)\n * @returns Unsigned transaction parameters\n */\nexport function buildReorderVaultsTx(\n contractAddress: Address,\n permutedVaultIds: Hex[],\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.REORDER_VAULTS,\n args: [permutedVaultIds],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to withdraw selected vaults from AAVE position.\n *\n * Withdraws specific vaults (partial withdrawal) and redeems them back to the depositor.\n * **Requires zero debt** - position must have no outstanding borrows.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param vaultIds - Array of vault IDs (bytes32) to withdraw\n * @returns Unsigned transaction parameters for execution with viem wallet\n */\nexport function buildWithdrawCollateralsTx(\n contractAddress: Address,\n vaultIds: Hex[],\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.WITHDRAW_COLLATERALS,\n args: [vaultIds],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to borrow assets against vBTC collateral.\n *\n * Borrows stablecoins (e.g., USDC) against your BTC collateral position.\n * Health factor must remain above 1.0 after borrowing, otherwise transaction will revert.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param debtReserveId - AAVE reserve ID for the debt asset (e.g., `2n` for USDC reserve)\n * @param amount - Amount to borrow in token units with decimals (e.g., for USDC with 6 decimals: `100000000n` = 100 USDC). Use `parseUnits()` from viem.\n * @param receiver - Address to receive borrowed tokens (usually user's address)\n * @returns Unsigned transaction parameters for execution with viem wallet\n *\n * @example\n * ```typescript\n * import { buildBorrowTx } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { parseUnits } from \"viem\";\n *\n * // Borrow 100 USDC (6 decimals)\n * const borrowAmount = parseUnits(\"100\", 6);\n *\n * const txParams = buildBorrowTx(\n * \"0x123...\", // Adapter address\n * 2n, // USDC reserve ID\n * borrowAmount,\n * \"0x456...\" // Receiver address\n * );\n *\n * const hash = await walletClient.sendTransaction({\n * to: txParams.to,\n * data: txParams.data,\n * chain: sepolia,\n * });\n * ```\n *\n * @remarks\n * **What happens on-chain:**\n * 1. Checks health factor won't drop below liquidation threshold (1.0)\n * 2. Mints debt tokens to user's proxy contract\n * 3. Transfers borrowed asset to receiver address\n * 4. Updates position debt\n * 5. Emits `Borrowed` event\n *\n * **Possible errors:**\n * - Borrow would make health factor < 1.0\n * - Insufficient collateral\n * - Reserve doesn't exist\n * - Position doesn't exist\n *\n * **Important:** Calculate safe borrow amount using `calculateHealthFactor()` to avoid liquidation.\n */\nexport function buildBorrowTx(\n contractAddress: Address,\n debtReserveId: bigint,\n amount: bigint,\n receiver: Address,\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.BORROW,\n args: [debtReserveId, amount, receiver],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to repay debt on AAVE position.\n *\n * **Requires token approval** - user must approve adapter to spend debt token first.\n * Repays borrowed assets (partial or full repayment supported).\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param borrower - Borrower's address (for self-repay, use connected wallet address)\n * @param debtReserveId - AAVE reserve ID for the debt asset\n * @param amount - Amount to repay in token units. Can repay partial or full debt. For full repay, use `getUserTotalDebt()` to get exact amount.\n * @returns Unsigned transaction parameters for execution with viem wallet\n *\n * @example\n * ```typescript\n * import { buildRepayTx } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * // Build repay transaction (self-repay)\n * const txParams = buildRepayTx(\n * AAVE_ADAPTER,\n * borrowerAddress, // Connected wallet address for self-repay\n * USDC_RESERVE_ID,\n * repayAmount\n * );\n *\n * const hash = await walletClient.sendTransaction({\n * to: txParams.to,\n * data: txParams.data,\n * chain: sepolia,\n * });\n * ```\n *\n * @remarks\n * **What happens on-chain:**\n * 1. Transfers tokens from user to adapter (requires approval)\n * 2. Burns debt tokens from user's proxy\n * 3. Updates position debt\n * 4. Emits `Repaid` event\n *\n * **Possible errors:**\n * - Insufficient token approval\n * - User doesn't have enough tokens\n * - Repay amount exceeds debt\n * - Position doesn't exist\n */\nexport function buildRepayTx(\n contractAddress: Address,\n borrower: Address,\n debtReserveId: bigint,\n amount: bigint,\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.REPAY,\n args: [borrower, debtReserveId, amount],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n","/**\n * Aave Value Conversion Utilities\n *\n * Converts Aave on-chain values to human-readable numbers.\n */\n\nimport {\n AAVE_BASE_CURRENCY_DECIMALS,\n AAVE_BASE_CURRENCY_RAY_DECIMALS,\n WAD_DECIMALS,\n} from \"../constants.js\";\n\n/**\n * Convert Aave base currency value to USD\n *\n * Aave uses 1e26 = $1 USD for collateral values.\n *\n * @param value - Value in Aave base currency (1e26 = $1)\n * @returns Value in USD\n */\nexport function aaveValueToUsd(value: bigint): number {\n return Number(value) / 10 ** AAVE_BASE_CURRENCY_DECIMALS;\n}\n\n/**\n * Convert Aave RAY-scaled base currency value to USD\n *\n * Debt values use higher precision: 1e53 = $1 USD.\n *\n * @param value - Value in RAY-scaled base currency (1e53 = $1)\n * @returns Value in USD\n */\nexport function aaveRayValueToUsd(value: bigint): number {\n return Number(value) / 10 ** AAVE_BASE_CURRENCY_RAY_DECIMALS;\n}\n\n/**\n * Convert Aave WAD value to number\n *\n * WAD is used for health factor and collateral factor (1e18 = 1.0).\n *\n * @param value - Value in WAD (1e18 = 1.0)\n * @returns Decimal number\n */\nexport function wadToNumber(value: bigint): number {\n return Number(value) / 10 ** WAD_DECIMALS;\n}\n","/**\n * Borrow Ratio Utilities\n *\n * Borrow ratio = debt / collateral as a percentage.\n * Shows how much of the collateral is being used for borrowing.\n */\n\n/**\n * Calculate borrow ratio (debt / collateral) as percentage string\n *\n * @param debtUsd - Total debt in USD\n * @param collateralValueUsd - Total collateral value in USD\n * @returns Formatted percentage string (e.g., \"15.7%\")\n */\nexport function calculateBorrowRatio(\n debtUsd: number,\n collateralValueUsd: number,\n): string {\n if (collateralValueUsd <= 0) return \"0%\";\n const ratio = (debtUsd / collateralValueUsd) * 100;\n return `${ratio.toFixed(1)}%`;\n}\n","/**\n * Health Factor Utilities for Aave\n *\n * Health factor is calculated by Aave on-chain using oracle prices.\n * A health factor below 1.0 means the position can be liquidated.\n *\n * Status thresholds:\n * - no_debt: No active debt (null health factor)\n * - danger: < 1.0 (can be liquidated)\n * - warning: < HEALTH_FACTOR_WARNING_THRESHOLD (at risk)\n * - safe: >= HEALTH_FACTOR_WARNING_THRESHOLD (healthy)\n */\n\nimport { BPS_SCALE, HEALTH_FACTOR_WARNING_THRESHOLD } from \"../constants.js\";\n\nexport type HealthFactorStatus = \"safe\" | \"warning\" | \"danger\" | \"no_debt\";\n\n/**\n * Determine health factor status for UI display\n *\n * @param healthFactor - The health factor as a number (null if no debt)\n * @param hasDebt - Whether the position has active debt\n * @returns The status classification\n */\nexport function getHealthFactorStatus(\n healthFactor: number | null,\n hasDebt: boolean,\n): HealthFactorStatus {\n if (!hasDebt) return \"no_debt\";\n if (healthFactor === null) return \"safe\";\n if (healthFactor < 1.0) return \"danger\";\n if (healthFactor < HEALTH_FACTOR_WARNING_THRESHOLD) return \"warning\";\n return \"safe\";\n}\n\n/**\n * Checks if a health factor value represents a healthy position.\n *\n * @param healthFactor - The health factor as a number\n * @returns true if the health factor is >= 1.0 (healthy), false otherwise\n */\nexport function isHealthFactorHealthy(healthFactor: number | null): boolean {\n if (healthFactor === null) {\n return true; // No debt = healthy\n }\n return healthFactor >= 1.0;\n}\n\n/**\n * Get health factor status from a numeric value.\n * Used for UI components that work with Infinity for no-debt scenarios.\n *\n * @param value - Health factor value (Infinity when no debt)\n * @returns The status classification\n */\nexport function getHealthFactorStatusFromValue(\n value: number,\n): HealthFactorStatus {\n const hasDebt = isFinite(value);\n const healthFactor = isFinite(value) ? value : null;\n return getHealthFactorStatus(healthFactor, hasDebt);\n}\n\n/**\n * Calculate health factor for an AAVE position.\n *\n * **Formula:** `HF = (Collateral × Liquidation Threshold) / Total Debt`\n *\n * Health factor determines liquidation risk:\n * - `>= 1.5` - Safe (green)\n * - `1.0 - 1.5` - Warning (amber)\n * - `< 1.0` - Danger, position can be liquidated (red)\n *\n * @param collateralValueUsd - Total collateral value in USD (as number, not bigint)\n * @param totalDebtUsd - Total debt value in USD (as number, not bigint)\n * @param liquidationThresholdBps - Liquidation threshold in basis points (e.g., `8000` = 80%)\n * @returns Health factor value (e.g., `1.5`), or `Infinity` if no debt\n *\n * @example\n * ```typescript\n * import { calculateHealthFactor, HEALTH_FACTOR_WARNING_THRESHOLD } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * // User has $10,000 BTC collateral, $5,000 debt, 80% LT\n * const hf = calculateHealthFactor(10000, 5000, 8000);\n * // Result: 1.6 (safe to borrow more)\n *\n * if (hf < 1.0) {\n * console.error(\"Position can be liquidated!\");\n * } else if (hf < HEALTH_FACTOR_WARNING_THRESHOLD) {\n * console.warn(\"Position at risk, consider repaying\");\n * } else {\n * console.log(\"Position is safe\");\n * }\n * ```\n *\n * @remarks\n * **Before borrowing:**\n * Use this to calculate resulting health factor and ensure it stays above safe threshold.\n *\n * **Unit conversions:**\n * - Convert AAVE base currency (1e26) to USD by dividing by 1e26\n * - Use `aaveValueToUsd()` helper for automatic conversion\n */\nexport function calculateHealthFactor(\n collateralValueUsd: number,\n totalDebtUsd: number,\n liquidationThresholdBps: number,\n): number {\n if (totalDebtUsd <= 0) return Infinity;\n return (\n (collateralValueUsd * (liquidationThresholdBps / BPS_SCALE)) / totalDebtUsd\n );\n}\n","/**\n * Vault Selection Utilities for Aave\n *\n * Provides functions for selecting vaults to match a target collateral amount.\n * Uses a greedy algorithm that prioritizes larger vaults first.\n */\n\nexport interface SelectableVault {\n id: string;\n amount: number;\n}\n\nexport interface VaultSelectionResult {\n /** IDs of selected vaults */\n vaultIds: string[];\n /** Actual total amount from selected vaults */\n actualAmount: number;\n}\n\n/**\n * Select vaults to match the target amount using a greedy algorithm.\n * Sorts vaults by amount descending and picks until target is met.\n *\n * @param vaults - Available vaults to select from\n * @param targetAmount - Target amount to reach\n * @returns Selected vault IDs and actual amount\n */\nexport function selectVaultsForAmount(\n vaults: SelectableVault[],\n targetAmount: number,\n): VaultSelectionResult {\n if (targetAmount <= 0) {\n return { vaultIds: [], actualAmount: 0 };\n }\n\n const sortedVaults = [...vaults].sort((a, b) => b.amount - a.amount);\n\n const selectedIds: string[] = [];\n let selectedAmount = 0;\n\n for (const vault of sortedVaults) {\n if (selectedAmount >= targetAmount) break;\n selectedIds.push(vault.id);\n selectedAmount += vault.amount;\n }\n\n return { vaultIds: selectedIds, actualAmount: selectedAmount };\n}\n\n/**\n * Calculate total amount from a list of vaults\n *\n * @param vaults - Vaults to sum\n * @returns Total amount in BTC\n */\nexport function calculateTotalVaultAmount(vaults: SelectableVault[]): number {\n return vaults.reduce((sum, vault) => sum + vault.amount, 0);\n}\n","/**\n * Cascade Liquidation Simulation\n *\n * Simulates multi-group liquidation cascades for Aave positions backed by\n * indivisible BTC vaults (UTXOs). Each liquidation event seizes a prefix of\n * vaults until the target seizure is covered, then debt is reduced and the\n * cascade continues with remaining vaults.\n *\n * Used by the optimizer to score different vault orderings by how much\n * collateral survives the cascade.\n */\n\n/**\n * Minimal vault shape for cascade simulation.\n * UI layers extend this with display fields (e.g. `name`).\n */\nexport interface CascadeVault {\n id: string;\n btc: number;\n}\n\n/** 1% tolerance for prefix walk coverage — avoids cliff flip at boundary */\nexport const SEIZURE_TOL = 0.01;\n\n/** Circuit breaker for group cascade loop */\nexport const MAX_GROUPS = 20;\n\n/** Minimum debt threshold to continue cascade (avoids infinite loop on dust) */\nexport const MIN_DEBT_THRESHOLD = 0.01;\n\n/**\n * Prefix walk: consume vaults front-to-back until target seizure is covered.\n * Returns the vaults in the first liquidation group.\n */\nexport function getGroup1FromOrder<T extends CascadeVault>(\n order: T[],\n seizedFraction: number,\n seizureTol: number,\n): T[] {\n if (order.length === 0) return [];\n const totalBtc = order.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let prefixSum = 0;\n let i = 0;\n while (i < order.length && prefixSum < coverThreshold) {\n prefixSum += order[i].btc;\n i++;\n }\n return order.slice(0, i);\n}\n\n/**\n * Simulate one liquidation group, returning updated debt and remaining BTC.\n * Handles both safe (non-last) and full (last) liquidation paths.\n */\nfunction simulateOneGroup(\n seizedBtc: number,\n totalBtc: number,\n debt: number,\n isLastGroup: boolean,\n seizedFraction: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { debtAfter: number; btcAfter: number } {\n const liqPenalty = maxLB * CF;\n const pLiq = debt / (totalBtc * CF);\n const targetSeizure = totalBtc * seizedFraction;\n const overSeizureBtc = Math.max(0, seizedBtc - targetSeizure);\n const denominator = THF - liqPenalty;\n const debtToRepay =\n denominator === 0 ? debt : debt * ((THF - expectedHF) / denominator);\n\n let debtAfter: number;\n if (isLastGroup) {\n debtAfter = 0;\n } else {\n const overSeizureVal = (overSeizureBtc * pLiq) / maxLB;\n const fairnessDebtRepay = Math.min(overSeizureVal, debt - debtToRepay);\n debtAfter = Math.max(0, debt - debtToRepay - fairnessDebtRepay);\n }\n return { debtAfter, btcAfter: Math.max(0, totalBtc - seizedBtc) };\n}\n\n/**\n * Simulate full liquidation cascade with debt model.\n *\n * PRIMARY score: sumBtcAfterEvents — sum of BTC remaining after every event.\n * Captures how much collateral survives at each stage.\n * TIEBREAKER: btcAfterG1 — BTC remaining after the first (most likely) event.\n */\nexport function simulateCascade<T extends CascadeVault>(\n order: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { sumBtcAfterEvents: number; btcAfterG1: number } {\n let remaining = [...order];\n let debt = totalDebt;\n const initialTotalBtc = order.reduce((s, v) => s + v.btc, 0);\n let btcAfterG1 = -1;\n let sumBtcAfterEvents = 0;\n let groupCount = 0;\n\n while (\n remaining.length > 0 &&\n debt > MIN_DEBT_THRESHOLD &&\n groupCount < MAX_GROUPS\n ) {\n const totalBtc = remaining.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let prefixSum = 0;\n let i = 0;\n while (i < remaining.length && prefixSum < coverThreshold) {\n prefixSum += remaining[i].btc;\n i++;\n }\n const isLastGroup = i >= remaining.length;\n const { debtAfter } = simulateOneGroup(\n prefixSum,\n totalBtc,\n debt,\n isLastGroup,\n seizedFraction,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n remaining = remaining.slice(i);\n debt = debtAfter;\n const btcNow = totalBtc - prefixSum;\n sumBtcAfterEvents += btcNow;\n if (btcAfterG1 < 0) btcAfterG1 = btcNow;\n groupCount++;\n }\n\n return {\n sumBtcAfterEvents,\n btcAfterG1:\n btcAfterG1 < 0 ? initialTotalBtc : btcAfterG1,\n };\n}\n","/**\n * Optimal Vault Ordering for Liquidation Protection\n *\n * Finds the vault ordering that maximizes collateral surviving a multi-group\n * liquidation cascade. Uses exhaustive bitmask enumeration (2^n for n ≤ 20)\n * to find the minimum-BTC subset covering the target seizure for Group 1,\n * then greedy for subsequent groups.\n *\n * The iterative refinement loop re-runs the optimizer on its own output,\n * converging in ≤3 iterations in practice.\n */\n\nimport { simulateCascade, type CascadeVault } from \"./cascadeSimulation.js\";\n\n/** Convergence threshold for iterative refinement */\nconst EPS = 0.0001;\n\n/** Max refinement iterations for optimizer */\nconst MAX_ITER = 5;\n\n/** Max vaults for exhaustive bitmask search */\nconst MAX_VAULTS_FOR_EXHAUSTIVE = 20;\n\n/**\n * Greedy sub-order: arrange remaining vaults by finding minimum BTC subset\n * covering target for each group, using exhaustive search when feasible.\n */\nfunction greedyOrder<T extends CascadeVault>(\n vaults: T[],\n seizedFraction: number,\n seizureTol: number,\n): T[] {\n const result: T[] = [];\n let remaining = [...vaults];\n\n while (remaining.length > 0) {\n const totalBtc = remaining.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let optSubset: T[] = [...remaining];\n let optSum = totalBtc;\n const m = remaining.length;\n\n if (m <= MAX_VAULTS_FOR_EXHAUSTIVE) {\n for (let mask = 1; mask < 1 << m; mask++) {\n let sum = 0;\n const subset: T[] = [];\n for (let bit = 0; bit < m; bit++) {\n if (mask & (1 << bit)) {\n sum += remaining[bit].btc;\n subset.push(remaining[bit]);\n }\n }\n if (sum >= coverThreshold && sum < optSum) {\n optSum = sum;\n optSubset = subset;\n }\n }\n }\n\n const ids = new Set(optSubset.map((v) => v.id));\n result.push(...[...optSubset].sort((a, b) => b.btc - a.btc));\n remaining = remaining.filter((v) => !ids.has(v.id));\n }\n\n return result;\n}\n\n/**\n * Single-pass optimizer: enumerate all possible Group 1 subsets,\n * use greedy for remaining groups, pick the order that maximizes\n * collateral surviving the cascade.\n */\nfunction computeOptimalOrderSinglePass<T extends CascadeVault>(\n vaults: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { order: T[]; sumBtcAfterEvents: number; btcAfterG1: number } {\n if (vaults.length === 0)\n return { order: [], sumBtcAfterEvents: 0, btcAfterG1: 0 };\n if (vaults.length > MAX_VAULTS_FOR_EXHAUSTIVE) {\n throw new Error(\n `Too many vaults for exhaustive search: ${vaults.length} exceeds maximum of ${MAX_VAULTS_FOR_EXHAUSTIVE}`,\n );\n }\n if (vaults.length === 1) {\n const sim = simulateCascade(\n vaults,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n return { order: [...vaults], ...sim };\n }\n\n const n = vaults.length;\n const totalBtc = vaults.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n\n let bestOrder = [...vaults];\n let bestSum = -Infinity;\n let bestAfterG1 = -Infinity;\n\n for (let mask = 1; mask < 1 << n; mask++) {\n let g1Btc = 0;\n const g1: T[] = [];\n const rest: T[] = [];\n for (let bit = 0; bit < n; bit++) {\n if (mask & (1 << bit)) {\n g1Btc += vaults[bit].btc;\n g1.push(vaults[bit]);\n } else {\n rest.push(vaults[bit]);\n }\n }\n if (g1Btc < coverThreshold) continue;\n\n g1.sort((a, b) => b.btc - a.btc);\n const candidate = [...g1, ...greedyOrder(rest, seizedFraction, seizureTol)];\n const { sumBtcAfterEvents, btcAfterG1 } = simulateCascade(\n candidate,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n\n if (\n sumBtcAfterEvents > bestSum + EPS ||\n (Math.abs(sumBtcAfterEvents - bestSum) <= EPS &&\n btcAfterG1 > bestAfterG1 + EPS)\n ) {\n bestSum = sumBtcAfterEvents;\n bestAfterG1 = btcAfterG1;\n bestOrder = candidate;\n }\n }\n\n return {\n order: bestOrder,\n sumBtcAfterEvents: bestSum,\n btcAfterG1: bestAfterG1,\n };\n}\n\n/**\n * Main optimizer: iterative refinement until stable.\n * Re-running with the improved order lets the next pass find better\n * G1 subsets. Converges in ≤3 iterations in practice.\n */\nexport function computeOptimalOrder<T extends CascadeVault>(\n vaults: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { order: T[]; sumBtcAfterEvents: number; btcAfterG1: number } {\n let result = computeOptimalOrderSinglePass(\n vaults,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n\n for (let i = 0; i < MAX_ITER; i++) {\n const refined = computeOptimalOrderSinglePass(\n result.order,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n const primaryImproves =\n refined.sumBtcAfterEvents > result.sumBtcAfterEvents + EPS;\n const primaryTied =\n Math.abs(refined.sumBtcAfterEvents - result.sumBtcAfterEvents) <= EPS;\n const tiebreakerImproves =\n primaryTied && refined.btcAfterG1 > result.btcAfterG1 + EPS;\n if (!primaryImproves && !tiebreakerImproves) {\n break;\n }\n result = refined;\n }\n\n return result;\n}\n","/**\n * Vault Split Utilities for Aave Liquidation Protection\n *\n * BTC vaults are indivisible UTXOs. During liquidation, the protocol seizes\n * whole vaults as a prefix of the borrower's ordered vault list until the\n * target seizure amount is covered. Splitting deposits into 2 optimally-sized\n * vaults (sacrificial + protected) minimizes over-seizure loss.\n *\n * The sacrificial vault (index 0) is sized to cover the expected target seizure\n * plus a safety margin. The protected vault (index 1) holds the remainder and\n * survives liquidation.\n *\n * Seizure formula (from Aave v4 Section 4.2):\n * ```\n * liq_penalty = LB × CF\n * debt_to_repay = total_debt × (THF - current_HF) / (THF - liq_penalty)\n * target_seizure = debt_to_repay × LB\n * ```\n */\n\nconst MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * Effective dust threshold for HTLC outputs in satoshis.\n *\n * Standard P2TR dust is 330 sats, but HTLC scripts are larger than a standard\n * P2TR key-path spend. A conservative estimate for an HTLC script-path output\n * is ~2000 sats. This is a defense-in-depth check — in practice, minDeposit\n * from the on-chain contract is orders of magnitude larger.\n */\nconst HTLC_EFFECTIVE_DUST_THRESHOLD = 2000n;\n\nexport function assertSafePrecision(value: bigint, name: string): void {\n if (value > MAX_SAFE_BIGINT) {\n throw new RangeError(\n `${name} (${value}) exceeds Number.MAX_SAFE_INTEGER; precision would be lost`,\n );\n }\n}\n\n/**\n * Parameters for computing the optimal vault split.\n */\nexport interface OptimalSplitParams {\n /** Total deposit amount in satoshis */\n totalBtc: bigint;\n /** Collateral factor (e.g. 0.75 for 75%) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05 for 5% bonus) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n /** Safety margin multiplier for the sacrificial vault (e.g. 1.05 for 5% buffer) */\n safetyMargin: number;\n}\n\n/**\n * Result of the optimal vault split computation.\n */\nexport interface OptimalSplitResult {\n /** Sacrificial vault amount in satoshis (index 0, seized first) */\n sacrificialVault: bigint;\n /** Protected vault amount in satoshis (index 1, survives liquidation) */\n protectedVault: bigint;\n /** Fraction of collateral that would be seized (0–1) */\n seizedFraction: number;\n /** Raw target seizure amount in satoshis (before safety margin) */\n targetSeizureBtc: bigint;\n}\n\n/**\n * Parameters for computing the minimum deposit required for a split.\n */\nexport interface MinDepositForSplitParams {\n /** Minimum peg-in amount in satoshis */\n minPegin: bigint;\n /** Seized fraction (0–1), from computeOptimalSplit or computeSeizedFraction */\n seizedFraction: number;\n /** Safety margin multiplier (e.g. 1.05) */\n safetyMargin: number;\n}\n\n/**\n * Parameters for checking if a vault rebalance is needed.\n */\nexport interface RebalanceCheckParams {\n /** Ordered vault amounts in satoshis (index 0 is sacrificial) */\n vaultAmounts: bigint[];\n /** Collateral factor (e.g. 0.75) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n /** Safety margin multiplier (e.g. 1.05) */\n safetyMargin: number;\n}\n\n/**\n * Result of a vault rebalance check.\n */\nexport interface RebalanceCheckResult {\n /** Whether the sacrificial vault needs to be increased */\n needsRebalance: boolean;\n /** How much more the sacrificial vault needs in satoshis (0n if no rebalance needed) */\n deficit: bigint;\n /** Current sacrificial vault coverage in satoshis */\n currentCoverage: bigint;\n /** Required sacrificial vault coverage in satoshis */\n targetCoverage: bigint;\n}\n\n/**\n * Compute the fraction of collateral that would be seized during liquidation,\n * returning both the raw (unclamped) and clamped values.\n *\n * The raw value is useful for detecting unusual protocol parameter combinations\n * (values outside [0, 1] indicate something unexpected).\n *\n * Formula:\n * ```\n * liq_penalty = LB × CF\n * seized_fraction = CF × (THF - expectedHF) / (THF - liq_penalty) × LB / expectedHF\n * ```\n *\n * @param CF - Collateral factor (e.g. 0.75)\n * @param LB - Liquidation bonus (e.g. 1.05)\n * @param THF - Target health factor (e.g. 1.10)\n * @param expectedHF - Expected health factor at liquidation (e.g. 0.95)\n * @returns Both the raw seized fraction and the clamped [0, 1] value\n */\nexport function computeSeizedFractionDetailed(\n CF: number,\n LB: number,\n THF: number,\n expectedHF: number,\n): { seizedFraction: number; seizedFractionRaw: number } {\n // HF ≤ 0 means position is fully underwater — full seizure\n if (expectedHF <= 0) {\n return { seizedFraction: 1, seizedFractionRaw: Infinity };\n }\n\n const liqPenalty = LB * CF;\n\n // If THF <= liq_penalty, full liquidation is inevitable\n if (THF <= liqPenalty) {\n return { seizedFraction: 1, seizedFractionRaw: Infinity };\n }\n\n // Floating-point errors here are ~1e-15, negligible relative to the 5%\n // safety margin applied by callers (computeOptimalSplit, checkRebalanceNeeded).\n const seizedFractionRaw =\n ((CF * (THF - expectedHF)) / (THF - liqPenalty)) * (LB / expectedHF);\n\n return {\n seizedFraction: Math.max(0, Math.min(1, seizedFractionRaw)),\n seizedFractionRaw,\n };\n}\n\n/**\n * Compute the fraction of collateral that would be seized during liquidation.\n *\n * @param CF - Collateral factor (e.g. 0.75)\n * @param LB - Liquidation bonus (e.g. 1.05)\n * @param THF - Target health factor (e.g. 1.10)\n * @param expectedHF - Expected health factor at liquidation (e.g. 0.95)\n * @returns Seized fraction clamped to [0, 1]\n */\nexport function computeSeizedFraction(\n CF: number,\n LB: number,\n THF: number,\n expectedHF: number,\n): number {\n return computeSeizedFractionDetailed(CF, LB, THF, expectedHF).seizedFraction;\n}\n\n/**\n * Compute the optimal split between a sacrificial vault and a protected vault.\n *\n * The sacrificial vault (index 0) is sized to cover the target seizure amount\n * plus a safety margin. The protected vault (index 1) holds the remainder.\n *\n * @param params - Split parameters including total BTC, risk params, and safety margin\n * @returns Split result with vault sizes, seized fraction, and target seizure\n *\n * @example\n * ```typescript\n * import { computeOptimalSplit } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const result = computeOptimalSplit({\n * totalBtc: 1_000_000_000n, // 10 BTC in sats\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * safetyMargin: 1.05,\n * });\n * // result.sacrificialVault ≈ 418_000_000n (4.18 BTC)\n * // result.protectedVault ≈ 582_000_000n (5.82 BTC)\n * ```\n */\nexport function computeOptimalSplit(\n params: OptimalSplitParams,\n): OptimalSplitResult {\n const { totalBtc, CF, LB, THF, expectedHF, safetyMargin } = params;\n\n if (totalBtc <= 0n) {\n return {\n sacrificialVault: 0n,\n protectedVault: 0n,\n seizedFraction: 0,\n targetSeizureBtc: 0n,\n };\n }\n\n assertSafePrecision(totalBtc, \"totalBtc\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n const totalBtcNum = Number(totalBtc);\n const targetSeizureBtc = BigInt(Math.ceil(totalBtcNum * seizedFraction));\n\n const sacrificialRaw = BigInt(\n Math.ceil(totalBtcNum * seizedFraction * safetyMargin),\n );\n const sacrificialVault =\n sacrificialRaw > totalBtc ? totalBtc : sacrificialRaw;\n const protectedVault = totalBtc - sacrificialVault;\n\n // If either vault is non-zero but below the effective dust threshold for\n // HTLC outputs, the split is not viable — return zeroed vaults so the\n // caller treats this as non-splittable. We avoid throwing because this\n // function is called during render (useMemo) and throwing would crash\n // the component instead of showing validation feedback.\n if (\n (sacrificialVault > 0n &&\n sacrificialVault < HTLC_EFFECTIVE_DUST_THRESHOLD) ||\n (protectedVault > 0n && protectedVault < HTLC_EFFECTIVE_DUST_THRESHOLD)\n ) {\n return {\n sacrificialVault: 0n,\n protectedVault: 0n,\n seizedFraction,\n targetSeizureBtc: 0n,\n };\n }\n\n return {\n sacrificialVault,\n protectedVault,\n seizedFraction,\n targetSeizureBtc,\n };\n}\n\n/**\n * Compute the minimum total deposit required for a 2-vault split.\n *\n * Both vaults must be at least `minPegin` satoshis. This function returns\n * the minimum total deposit where both the sacrificial and protected vaults\n * would meet the minimum peg-in requirement.\n *\n * @param params - Parameters including minimum peg-in, seized fraction, and safety margin\n * @returns Minimum total deposit in satoshis. Returns 0n in two cases:\n * - `seizedFraction * safetyMargin >= 1`: split impossible (sacrificial vault would consume entire deposit)\n * - `seizedFraction <= 0`: split not useful (no seizure expected at this health factor)\n *\n * @example\n * ```typescript\n * import { computeMinDepositForSplit } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const minDeposit = computeMinDepositForSplit({\n * minPegin: 50_000n, // 0.0005 BTC\n * seizedFraction: 0.398,\n * safetyMargin: 1.05,\n * });\n * ```\n */\nexport function computeMinDepositForSplit(\n params: MinDepositForSplitParams,\n): bigint {\n const { minPegin, seizedFraction, safetyMargin } = params;\n\n assertSafePrecision(minPegin, \"minPegin\");\n\n const sacrificialShare = seizedFraction * safetyMargin;\n\n // If sacrificial vault would consume the entire deposit, split is not possible\n if (sacrificialShare >= 1) {\n return 0n;\n }\n\n // If seized fraction is effectively zero, split is not useful\n if (sacrificialShare <= 0) {\n return 0n;\n }\n\n // Minimum total so the protected vault (smaller share) >= minPegin\n const protectedShare = 1 - sacrificialShare;\n const minFromProtected = Math.ceil(Number(minPegin) / protectedShare);\n\n // Minimum total so the sacrificial vault >= minPegin\n const minFromSacrificial = Math.ceil(Number(minPegin) / sacrificialShare);\n\n return BigInt(Math.max(minFromProtected, minFromSacrificial));\n}\n\n/**\n * Check if the sacrificial vault (index 0) needs to be increased to cover\n * the current target seizure amount.\n *\n * **Scope:** This function only checks whether the sacrificial vault's sizing\n * is adequate. It does NOT detect whether a split exists — a single vault that\n * exceeds the target coverage returns `needsRebalance: false`. Callers should\n * check `vaultAmounts.length < 2` separately to detect unsplit positions.\n *\n * Used on position page load to detect when parameter changes (THF, CF, LB)\n * have made the current split insufficient.\n *\n * @param params - Current vault amounts and risk parameters\n * @returns Whether rebalance is needed, with deficit details\n *\n * @example\n * ```typescript\n * import { checkRebalanceNeeded } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const result = checkRebalanceNeeded({\n * vaultAmounts: [300_000_000n, 700_000_000n], // 3 BTC sacrificial, 7 BTC protected\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * safetyMargin: 1.05,\n * });\n *\n * if (result.needsRebalance) {\n * console.log(`Sacrificial vault needs ${result.deficit} more sats`);\n * }\n * ```\n */\nexport function checkRebalanceNeeded(\n params: RebalanceCheckParams,\n): RebalanceCheckResult {\n const { vaultAmounts, CF, LB, THF, expectedHF, safetyMargin } = params;\n\n if (vaultAmounts.length === 0) {\n return {\n needsRebalance: false,\n deficit: 0n,\n currentCoverage: 0n,\n targetCoverage: 0n,\n };\n }\n\n const totalBtc = vaultAmounts.reduce((sum, v) => sum + v, 0n);\n assertSafePrecision(totalBtc, \"totalBtc\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n const targetCoverage = BigInt(\n Math.ceil(Number(totalBtc) * seizedFraction * safetyMargin),\n );\n const currentCoverage = vaultAmounts[0];\n\n const deficit =\n targetCoverage > currentCoverage ? targetCoverage - currentCoverage : 0n;\n\n return {\n needsRebalance: deficit > 0n,\n deficit,\n currentCoverage,\n targetCoverage,\n };\n}\n","/**\n * Seizure Simulation Utilities\n *\n * Simulates which vaults would be seized during Aave liquidation.\n * Vaults are seized in prefix order (index 0, 1, 2, ...) until the\n * target seizure amount is covered.\n *\n * Reference: Aave v4 Section 4.2 — liquidation seizes a prefix of the\n * borrower's ordered vault list.\n */\n\nimport { assertSafePrecision, computeSeizedFraction } from \"./vaultSplit.js\";\n\n/**\n * A vault with its on-chain ID and BTC amount, in liquidation-priority order.\n */\nexport interface OrderedVault {\n /** On-chain vault ID (bytes32 hex string) */\n id: string;\n /** Vault amount in satoshis */\n amountSats: bigint;\n}\n\n/**\n * Parameters for simulating prefix seizure.\n */\nexport interface PrefixSeizureParams {\n /** Vaults in their current on-chain order (index 0 is seized first) */\n orderedVaults: OrderedVault[];\n /** Target seizure amount in satoshis */\n targetSeizureSats: bigint;\n}\n\n/**\n * Result of a prefix seizure simulation.\n */\nexport interface PrefixSeizureResult {\n /** Vaults that would be seized (the prefix) */\n seizedVaults: OrderedVault[];\n /** Vaults that survive liquidation */\n protectedVaults: OrderedVault[];\n /** Over-seizure amount in satoshis (total seized - target) */\n overSeizureSats: bigint;\n /** Index where seizure stops (exclusive: vaults[0..cutoffIndex] are seized) */\n cutoffIndex: number;\n /** Total amount seized in satoshis */\n totalSeizedSats: bigint;\n}\n\n/**\n * Parameters for computing target seizure in satoshis.\n */\nexport interface TargetSeizureParams {\n /** Total collateral in satoshis */\n totalCollateralSats: bigint;\n /** Collateral factor (e.g. 0.75) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n}\n\n/**\n * Compute the target seizure amount in satoshis.\n *\n * Uses `computeSeizedFraction` to determine what fraction of total collateral\n * would be seized, then converts to an absolute satoshi amount.\n *\n * @param params - Total collateral and risk parameters\n * @returns Target seizure amount in satoshis (rounded up)\n *\n * @example\n * ```typescript\n * const targetSats = computeTargetSeizureSats({\n * totalCollateralSats: 1_000_000_000n, // 10 BTC\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * });\n * // targetSats ≈ 398_000_000n (3.98 BTC)\n * ```\n */\nexport function computeTargetSeizureSats(\n params: TargetSeizureParams,\n): bigint {\n const { totalCollateralSats, CF, LB, THF, expectedHF } = params;\n\n if (totalCollateralSats <= 0n) {\n return 0n;\n }\n\n assertSafePrecision(totalCollateralSats, \"totalCollateralSats\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n return BigInt(Math.ceil(Number(totalCollateralSats) * seizedFraction));\n}\n\n/**\n * Simulate prefix seizure for a given set of ordered vaults.\n *\n * Walks the ordered vault list, accumulating amounts until the target\n * seizure is covered. Returns which vaults are seized vs protected,\n * the over-seizure amount, and the cutoff index.\n *\n * @param params - Ordered vaults and target seizure amount\n * @returns Seizure simulation result\n * @throws Error if orderedVaults is empty\n * @throws Error if targetSeizureSats is <= 0\n *\n * @example\n * ```typescript\n * const result = simulatePrefixSeizure({\n * orderedVaults: [\n * { id: \"0xabc...\", amountSats: 200_000_000n },\n * { id: \"0xdef...\", amountSats: 300_000_000n },\n * { id: \"0x123...\", amountSats: 500_000_000n },\n * ],\n * targetSeizureSats: 400_000_000n,\n * });\n * // result.seizedVaults = first 2 vaults (200M + 300M = 500M >= 400M)\n * // result.overSeizureSats = 100_000_000n\n * // result.cutoffIndex = 2\n * ```\n */\nexport function simulatePrefixSeizure(\n params: PrefixSeizureParams,\n): PrefixSeizureResult {\n const { orderedVaults, targetSeizureSats } = params;\n\n if (orderedVaults.length === 0) {\n throw new Error(\"orderedVaults must not be empty\");\n }\n\n if (targetSeizureSats <= 0n) {\n throw new Error(\n \"targetSeizureSats must be positive; use computeTargetSeizureSats to derive it\",\n );\n }\n\n let accumulated = 0n;\n let cutoffIndex = orderedVaults.length; // default: all vaults seized\n\n for (let i = 0; i < orderedVaults.length; i++) {\n accumulated += orderedVaults[i].amountSats;\n\n if (accumulated >= targetSeizureSats) {\n cutoffIndex = i + 1;\n break;\n }\n }\n\n const seizedVaults = orderedVaults.slice(0, cutoffIndex);\n const protectedVaults = orderedVaults.slice(cutoffIndex);\n const totalSeizedSats = accumulated;\n const overSeizureSats =\n totalSeizedSats > targetSeizureSats\n ? totalSeizedSats - targetSeizureSats\n : 0n;\n\n return {\n seizedVaults,\n protectedVaults,\n overSeizureSats,\n cutoffIndex,\n totalSeizedSats,\n };\n}\n"],"names":["AAVE_FUNCTION_NAMES","BTC_DECIMALS","USDC_DECIMALS","BPS_TO_PERCENT_DIVISOR","BPS_SCALE","AAVE_BASE_CURRENCY_DECIMALS","AAVE_BASE_CURRENCY_RAY_DECIMALS","WAD_DECIMALS","HEALTH_FACTOR_WARNING_THRESHOLD","MIN_HEALTH_FACTOR_FOR_BORROW","FULL_REPAY_BUFFER_DIVISOR","FULL_REPAY_BUFFER_FRACTION","getPosition","publicClient","contractAddress","user","position","AaveIntegrationAdapterABI","zeroAddress","getPositionSizeParams","result","maxPositionBTC","maxVaultsPerPosition","hasDebtFromPosition","mapPositionResult","getUserAccountData","spokeAddress","userAddress","data","AaveSpokeABI","getUserPosition","reserveId","hasDebt","hasCollateral","getUserTotalDebt","getReserve","getTargetHealthFactor","getDynamicReserveConfig","dynamicConfigKey","buildReorderVaultsTx","permutedVaultIds","encodeFunctionData","buildWithdrawCollateralsTx","vaultIds","buildBorrowTx","debtReserveId","amount","receiver","buildRepayTx","borrower","aaveValueToUsd","value","aaveRayValueToUsd","wadToNumber","calculateBorrowRatio","debtUsd","collateralValueUsd","getHealthFactorStatus","healthFactor","isHealthFactorHealthy","getHealthFactorStatusFromValue","calculateHealthFactor","totalDebtUsd","liquidationThresholdBps","selectVaultsForAmount","vaults","targetAmount","sortedVaults","a","b","selectedIds","selectedAmount","vault","calculateTotalVaultAmount","sum","SEIZURE_TOL","MAX_GROUPS","MIN_DEBT_THRESHOLD","getGroup1FromOrder","order","seizedFraction","seizureTol","coverThreshold","s","v","prefixSum","i","simulateOneGroup","seizedBtc","totalBtc","debt","isLastGroup","CF","THF","maxLB","expectedHF","liqPenalty","pLiq","targetSeizure","overSeizureBtc","denominator","debtToRepay","debtAfter","overSeizureVal","fairnessDebtRepay","simulateCascade","totalDebt","remaining","initialTotalBtc","btcAfterG1","sumBtcAfterEvents","groupCount","btcNow","EPS","MAX_ITER","MAX_VAULTS_FOR_EXHAUSTIVE","greedyOrder","optSubset","optSum","m","mask","subset","bit","ids","computeOptimalOrderSinglePass","sim","n","bestOrder","bestSum","bestAfterG1","g1Btc","g1","rest","candidate","computeOptimalOrder","refined","primaryImproves","tiebreakerImproves","MAX_SAFE_BIGINT","HTLC_EFFECTIVE_DUST_THRESHOLD","assertSafePrecision","name","computeSeizedFractionDetailed","LB","seizedFractionRaw","computeSeizedFraction","computeOptimalSplit","params","safetyMargin","totalBtcNum","targetSeizureBtc","sacrificialRaw","sacrificialVault","protectedVault","computeMinDepositForSplit","minPegin","sacrificialShare","protectedShare","minFromProtected","minFromSacrificial","checkRebalanceNeeded","vaultAmounts","targetCoverage","currentCoverage","deficit","computeTargetSeizureSats","totalCollateralSats","simulatePrefixSeizure","orderedVaults","targetSeizureSats","accumulated","cutoffIndex","seizedVaults","protectedVaults","totalSeizedSats","overSeizureSats"],"mappings":";AAWO,MAAMA,IAAsB;AAAA;AAAA,EAEjC,sBAAsB;AAAA;AAAA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c,IACdC,IAAcH,EAAc;AAEhC,WAASlF,IAAI,GAAGA,IAAIkF,EAAc,QAAQlF;AAGxC,QAFAoF,KAAeF,EAAclF,CAAC,EAAE,YAE5BoF,KAAeD,GAAmB;AACpC,MAAAE,IAAcrF,IAAI;AAClB;AAAA,IACF;AAGF,QAAMsF,IAAeJ,EAAc,MAAM,GAAGG,CAAW,GACjDE,IAAkBL,EAAc,MAAMG,CAAW,GACjDG,IAAkBJ,GAClBK,IACJD,IAAkBL,IACdK,IAAkBL,IAClB;AAEN,SAAO;AAAA,IACL,cAAAG;AAAA,IACA,iBAAAC;AAAA,IACA,iBAAAE;AAAA,IACA,aAAAJ;AAAA,IACA,iBAAAG;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/tbv/integrations/aave/constants.ts","../../../../src/tbv/integrations/aave/clients/query.ts","../../../../src/tbv/integrations/aave/utils/debtUtils.ts","../../../../src/tbv/integrations/aave/clients/spoke.ts","../../../../src/tbv/integrations/aave/clients/transaction.ts","../../../../src/tbv/integrations/aave/utils/aaveConversions.ts","../../../../src/tbv/integrations/aave/utils/borrowRatio.ts","../../../../src/tbv/integrations/aave/utils/healthFactor.ts","../../../../src/tbv/integrations/aave/utils/vaultSelection.ts","../../../../src/tbv/integrations/aave/utils/cascadeSimulation.ts","../../../../src/tbv/integrations/aave/utils/optimalOrder.ts","../../../../src/tbv/integrations/aave/utils/vaultSplit.ts","../../../../src/tbv/integrations/aave/utils/seizureSimulation.ts"],"sourcesContent":["/**\n * Aave Protocol Constants\n *\n * Constants for interacting with Aave v4 protocol.\n * Reference: https://github.com/aave/aave-v4 ISpoke.sol\n */\n\n/**\n * Aave contract function names\n * Centralized constants for contract interactions\n */\nexport const AAVE_FUNCTION_NAMES = {\n /** Withdraw selected vaults from position (partial withdrawal) */\n WITHDRAW_COLLATERALS: \"withdrawCollaterals\",\n /** Borrow from Core Spoke position */\n BORROW: \"borrowFromCorePosition\",\n /** Repay debt to Core Spoke position */\n REPAY: \"repayToCorePosition\",\n /** Reorder vault prefix ordering for liquidation priority */\n REORDER_VAULTS: \"reorderVaults\",\n} as const;\n\n/**\n * BTC token decimals (satoshis)\n * 1 BTC = 100,000,000 satoshis\n */\nexport const BTC_DECIMALS = 8;\n\n/**\n * USDC token decimals\n * Used for debt calculations\n */\nexport const USDC_DECIMALS = 6;\n\n/**\n * Divisor to convert basis points (BPS) to percentage\n *\n * In Aave v4, risk parameters like collateralRisk are stored in BPS\n * where 10000 BPS = 100%.\n *\n * Example: 8000 BPS / 100 = 80%\n *\n * Reference: ISpoke.sol - \"collateralRisk The risk associated with a\n * collateral asset, expressed in BPS\"\n */\nexport const BPS_TO_PERCENT_DIVISOR = 100;\n\n/**\n * Full basis points scale (10000 BPS = 100%)\n *\n * Use this when converting BPS directly to decimal:\n * Example: 8000 BPS / 10000 = 0.80\n */\nexport const BPS_SCALE = 10000;\n\n/**\n * Aave base currency decimals\n * Account data values (collateral, debt) use 1e26 = $1 USD\n *\n * Reference: ISpoke.sol UserAccountData\n */\nexport const AAVE_BASE_CURRENCY_DECIMALS = 26;\n\n/**\n * Aave RAY-scaled base currency decimals\n * Debt values (totalDebtValueRay) use 1e53 = $1 USD\n * (base currency 1e26 scaled by RAY 1e27).\n *\n * Reference: IAaveSpoke.sol UserAccountData.totalDebtValueRay\n */\nexport const AAVE_BASE_CURRENCY_RAY_DECIMALS = 53;\n\n/**\n * WAD decimals (1e18 = 1.0)\n * Used for health factor and collateral factor values\n *\n * Reference: ISpoke.sol - \"healthFactor expressed in WAD. 1e18 represents a health factor of 1.00\"\n */\nexport const WAD_DECIMALS = 18;\n\n/**\n * Health factor warning threshold\n * Positions below this are considered at risk of liquidation\n */\nexport const HEALTH_FACTOR_WARNING_THRESHOLD = 1.5;\n\n/**\n * Minimum health factor allowed for borrowing\n * Prevents users from borrowing if resulting health factor would be below this.\n */\nexport const MIN_HEALTH_FACTOR_FOR_BORROW = 1.2;\n\n/**\n * Buffer for full repayment to account for interest accrual\n * between fetching debt and transaction execution.\n *\n * 0.5% buffer (50 basis points). Sized to absorb hours of execution delay\n * (e.g. Safe-multisig quorum collection) without leaving residual dust.\n * The adapter only pulls what's actually owed; excess approval/balance\n * stays with the user.\n *\n * Users whose wallet balance covers the debt but not the full buffer are\n * routed through the \"max-capped\" repay path instead of `repayFull`, so\n * a larger buffer never blocks a legitimate max-repay.\n */\nexport const FULL_REPAY_BUFFER_DIVISOR = 200n; // 1/200 = 0.5% buffer\n\n/**\n * Same buffer as `FULL_REPAY_BUFFER_DIVISOR`, expressed as a float fraction\n * for UI-side comparisons that operate in `number` rather than `bigint`.\n */\nexport const FULL_REPAY_BUFFER_FRACTION =\n 1 / Number(FULL_REPAY_BUFFER_DIVISOR);\n\n","/**\n * Aave Integration Adapter - Read operations (queries)\n *\n * Only includes functions that provide data NOT available from the indexer.\n * Most position/vault data should be fetched from the GraphQL indexer instead.\n */\n\nimport { type Address, type Hex, type PublicClient, zeroAddress } from \"viem\";\n\nimport type { AaveMarketPosition, PositionSizeParams } from \"../types.js\";\nimport AaveIntegrationAdapterABI from \"./abis/AaveIntegrationAdapter.abi.json\";\n\n/**\n * Get a position by user address.\n *\n * The adapter resolves the user's proxy contract and collateralized vault IDs.\n *\n * NOTE: Prefer using the indexer (fetchAavePositionWithCollaterals) for position data.\n * This function is only needed when you need data not available in the indexer,\n * or when you need to verify on-chain state.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param user - User's Ethereum address\n * @returns Market position data or null if position doesn't exist\n */\nexport async function getPosition(\n publicClient: PublicClient,\n contractAddress: Address,\n user: Address,\n): Promise<AaveMarketPosition | null> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationAdapterABI,\n functionName: \"getPosition\",\n args: [user],\n });\n\n type PositionResult = {\n proxyContract: Address;\n vaultIds: Hex[];\n totalCollateralBTC: bigint;\n };\n\n const position = result as PositionResult;\n\n // Check if position exists (proxyContract should not be zero address)\n if (position.proxyContract === zeroAddress) {\n return null;\n }\n\n return {\n proxyContract: position.proxyContract,\n vaultIds: position.vaultIds,\n totalCollateralBTC: position.totalCollateralBTC,\n };\n}\n\n/**\n * Get position size parameters from the adapter contract.\n *\n * Returns the maximum BTC position size and maximum vaults per position\n * as configured on-chain.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @returns Position size parameters (maxPositionBTC, maxVaultsPerPosition)\n */\nexport async function getPositionSizeParams(\n publicClient: PublicClient,\n contractAddress: Address,\n): Promise<PositionSizeParams> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationAdapterABI,\n functionName: \"getPositionSizeParams\",\n });\n\n const [maxPositionBTC, maxVaultsPerPosition] = result as [bigint, bigint];\n\n return {\n maxPositionBTC,\n maxVaultsPerPosition,\n };\n}\n","/**\n * Aave Debt Utilities\n *\n * Shared utility functions for debt calculations.\n */\n\nimport type { AaveSpokeUserPosition } from \"../types.js\";\n\n/**\n * Check if a position has any debt based on Spoke position data.\n *\n * A position is considered to have debt if any of:\n * - drawnShares > 0 (borrowed principal)\n * - premiumShares > 0 (accrued interest shares)\n *\n * @param position - User position data from Spoke\n * @returns true if the position has any debt\n */\nexport function hasDebtFromPosition(position: AaveSpokeUserPosition): boolean {\n return position.drawnShares > 0n || position.premiumShares > 0n;\n}\n","/**\n * Aave Spoke Client - Read operations\n *\n * Provides read operations for interacting with Aave v4 Spoke contracts.\n * Used to fetch live user position data (debt, collateral) from the Core Spoke.\n *\n * Note: Reserve data should be fetched from the indexer via fetchReserves.ts\n * since it doesn't need to be live and benefits from caching.\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport type {\n AaveSpokeUserAccountData,\n AaveSpokeUserPosition,\n} from \"../types.js\";\nimport { hasDebtFromPosition } from \"../utils/debtUtils.js\";\nimport AaveSpokeABI from \"./abis/AaveSpoke.abi.json\";\n\n/** Account data result type from contract */\ntype AccountDataResult = {\n riskPremium: bigint;\n avgCollateralFactor: bigint;\n healthFactor: bigint;\n totalCollateralValue: bigint;\n totalDebtValueRay: bigint;\n activeCollateralCount: bigint;\n borrowCount: bigint;\n};\n\n/** Position result type from contract */\ntype PositionResult = {\n drawnShares: bigint;\n premiumShares: bigint;\n premiumOffsetRay: bigint;\n suppliedShares: bigint;\n dynamicConfigKey: number;\n};\n\n/**\n * Maps contract result to AaveSpokeUserPosition\n */\nfunction mapPositionResult(result: PositionResult): AaveSpokeUserPosition {\n return {\n drawnShares: result.drawnShares,\n premiumShares: result.premiumShares,\n premiumOffsetRay: result.premiumOffsetRay,\n suppliedShares: result.suppliedShares,\n dynamicConfigKey: result.dynamicConfigKey,\n };\n}\n\n/**\n * Get aggregated user account health data from AAVE spoke.\n *\n * **Live data** - Fetches real-time account health including health factor, total collateral,\n * and total debt across all reserves. Values are calculated on-chain using AAVE oracles\n * and are the authoritative source for liquidation decisions.\n *\n * @param publicClient - Viem public client for reading contracts (from `createPublicClient()`)\n * @param spokeAddress - AAVE Spoke contract address (BTC Vault Core Spoke for vBTC collateral)\n * @param userAddress - User's proxy contract address (NOT user's wallet address)\n * @returns User account data with health metrics, collateral, and debt values\n *\n * @example\n * ```typescript\n * import { getUserAccountData } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { createPublicClient, http } from \"viem\";\n * import { sepolia } from \"viem/chains\";\n *\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: http()\n * });\n *\n * const accountData = await getUserAccountData(\n * publicClient,\n * \"0x123...\", // AAVE Spoke address\n * \"0x456...\" // User's AAVE proxy address (from getPosition)\n * );\n *\n * console.log(\"Health Factor:\", accountData.healthFactor);\n * console.log(\"Collateral (USD):\", accountData.totalCollateralValue);\n * console.log(\"Debt (USD):\", accountData.totalDebtValueRay);\n * ```\n *\n * @remarks\n * **Return values:**\n * - `healthFactor` - WAD format (1e18 = 1.0). Below 1.0 = liquidatable\n * - `totalCollateralValue` - USD value in base currency (1e26 = $1)\n * - `totalDebtValueRay` - USD value in RAY-scaled base currency (1e53 = $1)\n * - `avgCollateralFactor` - Weighted average collateral factor in WAD (1e18 = 100%)\n * - `riskPremium` - Additional risk premium\n *\n * **Use cases:**\n * - Check liquidation risk before borrowing\n * - Calculate safe borrow amount\n * - Monitor position health\n * - Display UI health indicators\n */\nexport async function getUserAccountData(\n publicClient: PublicClient,\n spokeAddress: Address,\n userAddress: Address,\n): Promise<AaveSpokeUserAccountData> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserAccountData\",\n args: [userAddress],\n });\n\n const data = result as AccountDataResult;\n return {\n riskPremium: data.riskPremium,\n avgCollateralFactor: data.avgCollateralFactor,\n healthFactor: data.healthFactor,\n totalCollateralValue: data.totalCollateralValue,\n totalDebtValueRay: data.totalDebtValueRay,\n activeCollateralCount: data.activeCollateralCount,\n borrowCount: data.borrowCount,\n };\n}\n\n/**\n * Get user position from the Spoke\n *\n * This fetches live data from the contract because debt accrues interest\n * and needs to be current for accurate health factor calculations.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns User position data\n */\nexport async function getUserPosition(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<AaveSpokeUserPosition> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserPosition\",\n args: [reserveId, userAddress],\n });\n\n return mapPositionResult(result as PositionResult);\n}\n\n/**\n * Check if a user has any debt in a reserve\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns true if user has debt\n */\nexport async function hasDebt(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<boolean> {\n const position = await getUserPosition(\n publicClient,\n spokeAddress,\n reserveId,\n userAddress,\n );\n return hasDebtFromPosition(position);\n}\n\n/**\n * Check if a user has supplied collateral in a reserve\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Aave Spoke contract address\n * @param reserveId - Reserve ID\n * @param userAddress - User's proxy contract address\n * @returns true if user has supplied collateral\n */\nexport async function hasCollateral(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<boolean> {\n const position = await getUserPosition(\n publicClient,\n spokeAddress,\n reserveId,\n userAddress,\n );\n return position.suppliedShares > 0n;\n}\n\n/**\n * Get user's exact total debt in a reserve (token units, not shares).\n *\n * Returns the precise amount owed including accrued interest. Essential for full repayment.\n * Debt accrues interest every block, so this must be fetched live from the contract.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - AAVE Spoke contract address\n * @param reserveId - Reserve ID for the debt asset (e.g., `2n` for USDC)\n * @param userAddress - User's proxy contract address\n * @returns Total debt amount in token units (e.g., for USDC: `100000000n` = 100 USDC)\n *\n * @example\n * ```typescript\n * import { getUserTotalDebt, FULL_REPAY_BUFFER_DIVISOR } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { formatUnits } from \"viem\";\n *\n * const totalDebt = await getUserTotalDebt(\n * publicClient,\n * AAVE_SPOKE_ADDRESS,\n * 2n, // USDC reserve\n * proxyAddress\n * );\n *\n * // For full repayment, add buffer to account for interest accrual\n * const repayAmount = totalDebt + (totalDebt / FULL_REPAY_BUFFER_DIVISOR);\n *\n * console.log(\"Debt:\", formatUnits(totalDebt, 6), \"USDC\");\n * ```\n *\n * @remarks\n * **Important for full repayment:**\n * - Add `FULL_REPAY_BUFFER_DIVISOR` buffer to account for interest between fetch and tx execution\n * - Contract only takes what's owed; excess stays in wallet\n * - For partial repayment, use any amount less than total debt\n */\nexport async function getUserTotalDebt(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n userAddress: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getUserTotalDebt\",\n args: [reserveId, userAddress],\n });\n\n return result as bigint;\n}\n\n/** Result type from the `getReserve` contract call.\n *\n * Matches the on-chain `Reserve` struct defined in `ITBVAaveSpoke.sol`:\n * struct Reserve {\n * address underlying;\n * address hub;\n * uint16 assetId;\n * uint8 decimals;\n * uint24 collateralRisk;\n * ReserveFlags flags; // uint8 bitmap\n * uint32 dynamicConfigKey;\n * }\n *\n * Note: this is the `Reserve` struct, NOT `ReserveConfig` — the contract\n * exposes both as separate functions and they return different shapes.\n */\ntype ReserveResult = {\n underlying: Address;\n hub: Address;\n assetId: number;\n decimals: number;\n collateralRisk: number;\n flags: number;\n dynamicConfigKey: number;\n};\n\n/**\n * Get reserve data from the Core Spoke contract via the `getReserve` selector.\n *\n * Returns static reserve properties including the `dynamicConfigKey` needed\n * for `getDynamicReserveConfig` calls. Use this as a fallback when reserve\n * data is not available from the GraphQL indexer.\n *\n * Do NOT confuse with the contract's separate `getReserveConfig` function,\n * which returns `{collateralRisk, paused, frozen, borrowable, receiveSharesEnabled}`.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @param reserveId - Reserve ID\n * @returns Reserve data including `dynamicConfigKey`\n */\nexport async function getReserve(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n): Promise<ReserveResult> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getReserve\",\n args: [reserveId],\n });\n return result as ReserveResult;\n}\n\n/** Result type from getLiquidationConfig contract call */\ntype LiquidationConfigResult = {\n targetHealthFactor: bigint;\n healthFactorForMaxBonus: bigint;\n liquidationBonusFactor: bigint;\n};\n\n/** Result type from getDynamicReserveConfig contract call */\ntype DynamicReserveConfigResult = {\n collateralFactor: bigint;\n maxLiquidationBonus: bigint;\n liquidationFee: bigint;\n};\n\n/**\n * Get the target health factor (THF) from the Core Spoke contract.\n *\n * Per-spoke governance parameter. After a liquidation, the protocol targets\n * restoring the position to this health factor.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @returns Target health factor in WAD (1e18 = 1.0). Example: 1.10 = 1_100_000_000_000_000_000n\n */\nexport async function getTargetHealthFactor(\n publicClient: PublicClient,\n spokeAddress: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getLiquidationConfig\",\n });\n const config = result as LiquidationConfigResult;\n return config.targetHealthFactor;\n}\n\n/**\n * Get the dynamic reserve config from the Core Spoke contract.\n *\n * Returns collateral factor, max liquidation bonus, and liquidation fee\n * for a specific reserve and dynamic config key.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param spokeAddress - Core Spoke contract address\n * @param reserveId - Reserve ID (e.g., vBTC reserve ID from indexer config)\n * @param dynamicConfigKey - Dynamic config key (from reserve data)\n * @returns Dynamic reserve config with collateralFactor (BPS), maxLiquidationBonus (BPS), liquidationFee (BPS)\n */\nexport async function getDynamicReserveConfig(\n publicClient: PublicClient,\n spokeAddress: Address,\n reserveId: bigint,\n dynamicConfigKey: number,\n): Promise<DynamicReserveConfigResult> {\n const result = await publicClient.readContract({\n address: spokeAddress,\n abi: AaveSpokeABI,\n functionName: \"getDynamicReserveConfig\",\n args: [reserveId, dynamicConfigKey],\n });\n return result as DynamicReserveConfigResult;\n}\n","/**\n * Aave Integration Adapter - Transaction builders\n *\n * Provides transaction builders for the AaveIntegrationAdapter contract.\n * Only includes Core Spoke operations for regular users (no Arbitrageur operations).\n *\n * These functions return unsigned transaction parameters that can be executed\n * by the vault service using its wallet client and transaction factory.\n */\n\nimport { type Address, type Hex, encodeFunctionData } from \"viem\";\n\nimport { AAVE_FUNCTION_NAMES } from \"../config.js\";\nimport type { TransactionParams } from \"../types.js\";\nimport AaveIntegrationAdapterABI from \"./abis/AaveIntegrationAdapter.abi.json\";\n\n/**\n * Build transaction to reorder vaults for liquidation priority.\n *\n * The permuted array must contain exactly the same vault IDs as the\n * current position, in the desired new order. Vaults are seized in\n * prefix order (index 0 first) during liquidation.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param permutedVaultIds - Vault IDs in desired new order (must be a permutation of current vaults)\n * @returns Unsigned transaction parameters\n */\nexport function buildReorderVaultsTx(\n contractAddress: Address,\n permutedVaultIds: Hex[],\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.REORDER_VAULTS,\n args: [permutedVaultIds],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to withdraw selected vaults from AAVE position.\n *\n * Withdraws specific vaults (partial withdrawal) and redeems them back to the depositor.\n * **Requires zero debt** - position must have no outstanding borrows.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param vaultIds - Array of vault IDs (bytes32) to withdraw\n * @returns Unsigned transaction parameters for execution with viem wallet\n */\nexport function buildWithdrawCollateralsTx(\n contractAddress: Address,\n vaultIds: Hex[],\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.WITHDRAW_COLLATERALS,\n args: [vaultIds],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to borrow assets against vBTC collateral.\n *\n * Borrows stablecoins (e.g., USDC) against your BTC collateral position.\n * Health factor must remain above 1.0 after borrowing, otherwise transaction will revert.\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param debtReserveId - AAVE reserve ID for the debt asset (e.g., `2n` for USDC reserve)\n * @param amount - Amount to borrow in token units with decimals (e.g., for USDC with 6 decimals: `100000000n` = 100 USDC). Use `parseUnits()` from viem.\n * @param receiver - Address to receive borrowed tokens (usually user's address)\n * @returns Unsigned transaction parameters for execution with viem wallet\n *\n * @example\n * ```typescript\n * import { buildBorrowTx } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n * import { parseUnits } from \"viem\";\n *\n * // Borrow 100 USDC (6 decimals)\n * const borrowAmount = parseUnits(\"100\", 6);\n *\n * const txParams = buildBorrowTx(\n * \"0x123...\", // Adapter address\n * 2n, // USDC reserve ID\n * borrowAmount,\n * \"0x456...\" // Receiver address\n * );\n *\n * const hash = await walletClient.sendTransaction({\n * to: txParams.to,\n * data: txParams.data,\n * chain: sepolia,\n * });\n * ```\n *\n * @remarks\n * **What happens on-chain:**\n * 1. Checks health factor won't drop below liquidation threshold (1.0)\n * 2. Mints debt tokens to user's proxy contract\n * 3. Transfers borrowed asset to receiver address\n * 4. Updates position debt\n * 5. Emits `Borrowed` event\n *\n * **Possible errors:**\n * - Borrow would make health factor < 1.0\n * - Insufficient collateral\n * - Reserve doesn't exist\n * - Position doesn't exist\n *\n * **Important:** Calculate safe borrow amount using `calculateHealthFactor()` to avoid liquidation.\n */\nexport function buildBorrowTx(\n contractAddress: Address,\n debtReserveId: bigint,\n amount: bigint,\n receiver: Address,\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.BORROW,\n args: [debtReserveId, amount, receiver],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n/**\n * Build transaction to repay debt on AAVE position.\n *\n * **Requires token approval** - user must approve adapter to spend debt token first.\n * Repays borrowed assets (partial or full repayment supported).\n *\n * @param contractAddress - AaveIntegrationAdapter contract address\n * @param borrower - Borrower's address (for self-repay, use connected wallet address)\n * @param debtReserveId - AAVE reserve ID for the debt asset\n * @param amount - Amount to repay in token units. Can repay partial or full debt. For full repay, use `getUserTotalDebt()` to get exact amount.\n * @returns Unsigned transaction parameters for execution with viem wallet\n *\n * @example\n * ```typescript\n * import { buildRepayTx } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * // Build repay transaction (self-repay)\n * const txParams = buildRepayTx(\n * AAVE_ADAPTER,\n * borrowerAddress, // Connected wallet address for self-repay\n * USDC_RESERVE_ID,\n * repayAmount\n * );\n *\n * const hash = await walletClient.sendTransaction({\n * to: txParams.to,\n * data: txParams.data,\n * chain: sepolia,\n * });\n * ```\n *\n * @remarks\n * **What happens on-chain:**\n * 1. Transfers tokens from user to adapter (requires approval)\n * 2. Burns debt tokens from user's proxy\n * 3. Updates position debt\n * 4. Emits `Repaid` event\n *\n * **Possible errors:**\n * - Insufficient token approval\n * - User doesn't have enough tokens\n * - Repay amount exceeds debt\n * - Position doesn't exist\n */\nexport function buildRepayTx(\n contractAddress: Address,\n borrower: Address,\n debtReserveId: bigint,\n amount: bigint,\n): TransactionParams {\n const data = encodeFunctionData({\n abi: AaveIntegrationAdapterABI,\n functionName: AAVE_FUNCTION_NAMES.REPAY,\n args: [borrower, debtReserveId, amount],\n });\n\n return {\n to: contractAddress,\n data,\n };\n}\n\n","/**\n * Aave Value Conversion Utilities\n *\n * Converts Aave on-chain values to human-readable numbers.\n */\n\nimport {\n AAVE_BASE_CURRENCY_DECIMALS,\n AAVE_BASE_CURRENCY_RAY_DECIMALS,\n WAD_DECIMALS,\n} from \"../constants.js\";\n\n/**\n * Convert Aave base currency value to USD\n *\n * Aave uses 1e26 = $1 USD for collateral values.\n *\n * @param value - Value in Aave base currency (1e26 = $1)\n * @returns Value in USD\n */\nexport function aaveValueToUsd(value: bigint): number {\n return Number(value) / 10 ** AAVE_BASE_CURRENCY_DECIMALS;\n}\n\n/**\n * Convert Aave RAY-scaled base currency value to USD\n *\n * Debt values use higher precision: 1e53 = $1 USD.\n *\n * @param value - Value in RAY-scaled base currency (1e53 = $1)\n * @returns Value in USD\n */\nexport function aaveRayValueToUsd(value: bigint): number {\n return Number(value) / 10 ** AAVE_BASE_CURRENCY_RAY_DECIMALS;\n}\n\n/**\n * Convert Aave WAD value to number\n *\n * WAD is used for health factor and collateral factor (1e18 = 1.0).\n *\n * @param value - Value in WAD (1e18 = 1.0)\n * @returns Decimal number\n */\nexport function wadToNumber(value: bigint): number {\n return Number(value) / 10 ** WAD_DECIMALS;\n}\n","/**\n * Borrow Ratio Utilities\n *\n * Borrow ratio = debt / collateral as a percentage.\n * Shows how much of the collateral is being used for borrowing.\n */\n\n/**\n * Calculate borrow ratio (debt / collateral) as percentage string\n *\n * @param debtUsd - Total debt in USD\n * @param collateralValueUsd - Total collateral value in USD\n * @returns Formatted percentage string (e.g., \"15.7%\")\n */\nexport function calculateBorrowRatio(\n debtUsd: number,\n collateralValueUsd: number,\n): string {\n if (collateralValueUsd <= 0) return \"0%\";\n const ratio = (debtUsd / collateralValueUsd) * 100;\n return `${ratio.toFixed(1)}%`;\n}\n","/**\n * Health Factor Utilities for Aave\n *\n * Health factor is calculated by Aave on-chain using oracle prices.\n * A health factor below 1.0 means the position can be liquidated.\n *\n * Status thresholds:\n * - no_debt: No active debt (null health factor)\n * - danger: < 1.0 (can be liquidated)\n * - warning: < HEALTH_FACTOR_WARNING_THRESHOLD (at risk)\n * - safe: >= HEALTH_FACTOR_WARNING_THRESHOLD (healthy)\n */\n\nimport { BPS_SCALE, HEALTH_FACTOR_WARNING_THRESHOLD } from \"../constants.js\";\n\nexport type HealthFactorStatus = \"safe\" | \"warning\" | \"danger\" | \"no_debt\";\n\n/**\n * Determine health factor status for UI display\n *\n * @param healthFactor - The health factor as a number (null if no debt)\n * @param hasDebt - Whether the position has active debt\n * @returns The status classification\n */\nexport function getHealthFactorStatus(\n healthFactor: number | null,\n hasDebt: boolean,\n): HealthFactorStatus {\n if (!hasDebt) return \"no_debt\";\n if (healthFactor === null) return \"safe\";\n if (healthFactor < 1.0) return \"danger\";\n if (healthFactor < HEALTH_FACTOR_WARNING_THRESHOLD) return \"warning\";\n return \"safe\";\n}\n\n/**\n * Checks if a health factor value represents a healthy position.\n *\n * @param healthFactor - The health factor as a number\n * @returns true if the health factor is >= 1.0 (healthy), false otherwise\n */\nexport function isHealthFactorHealthy(healthFactor: number | null): boolean {\n if (healthFactor === null) {\n return true; // No debt = healthy\n }\n return healthFactor >= 1.0;\n}\n\n/**\n * Get health factor status from a numeric value.\n * Used for UI components that work with Infinity for no-debt scenarios.\n *\n * @param value - Health factor value (Infinity when no debt)\n * @returns The status classification\n */\nexport function getHealthFactorStatusFromValue(\n value: number,\n): HealthFactorStatus {\n const hasDebt = isFinite(value);\n const healthFactor = isFinite(value) ? value : null;\n return getHealthFactorStatus(healthFactor, hasDebt);\n}\n\n/**\n * Calculate health factor for an AAVE position.\n *\n * **Formula:** `HF = (Collateral × Liquidation Threshold) / Total Debt`\n *\n * Health factor determines liquidation risk:\n * - `>= 1.5` - Safe (green)\n * - `1.0 - 1.5` - Warning (amber)\n * - `< 1.0` - Danger, position can be liquidated (red)\n *\n * @param collateralValueUsd - Total collateral value in USD (as number, not bigint)\n * @param totalDebtUsd - Total debt value in USD (as number, not bigint)\n * @param liquidationThresholdBps - Liquidation threshold in basis points (e.g., `8000` = 80%)\n * @returns Health factor value (e.g., `1.5`), or `Infinity` if no debt\n *\n * @example\n * ```typescript\n * import { calculateHealthFactor, HEALTH_FACTOR_WARNING_THRESHOLD } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * // User has $10,000 BTC collateral, $5,000 debt, 80% LT\n * const hf = calculateHealthFactor(10000, 5000, 8000);\n * // Result: 1.6 (safe to borrow more)\n *\n * if (hf < 1.0) {\n * console.error(\"Position can be liquidated!\");\n * } else if (hf < HEALTH_FACTOR_WARNING_THRESHOLD) {\n * console.warn(\"Position at risk, consider repaying\");\n * } else {\n * console.log(\"Position is safe\");\n * }\n * ```\n *\n * @remarks\n * **Before borrowing:**\n * Use this to calculate resulting health factor and ensure it stays above safe threshold.\n *\n * **Unit conversions:**\n * - Convert AAVE base currency (1e26) to USD by dividing by 1e26\n * - Use `aaveValueToUsd()` helper for automatic conversion\n */\nexport function calculateHealthFactor(\n collateralValueUsd: number,\n totalDebtUsd: number,\n liquidationThresholdBps: number,\n): number {\n if (totalDebtUsd <= 0) return Infinity;\n return (\n (collateralValueUsd * (liquidationThresholdBps / BPS_SCALE)) / totalDebtUsd\n );\n}\n","/**\n * Vault Selection Utilities for Aave\n *\n * Provides functions for selecting vaults to match a target collateral amount.\n * Uses a greedy algorithm that prioritizes larger vaults first.\n */\n\nexport interface SelectableVault {\n id: string;\n amount: number;\n}\n\nexport interface VaultSelectionResult {\n /** IDs of selected vaults */\n vaultIds: string[];\n /** Actual total amount from selected vaults */\n actualAmount: number;\n}\n\n/**\n * Select vaults to match the target amount using a greedy algorithm.\n * Sorts vaults by amount descending and picks until target is met.\n *\n * @param vaults - Available vaults to select from\n * @param targetAmount - Target amount to reach\n * @returns Selected vault IDs and actual amount\n */\nexport function selectVaultsForAmount(\n vaults: SelectableVault[],\n targetAmount: number,\n): VaultSelectionResult {\n if (targetAmount <= 0) {\n return { vaultIds: [], actualAmount: 0 };\n }\n\n const sortedVaults = [...vaults].sort((a, b) => b.amount - a.amount);\n\n const selectedIds: string[] = [];\n let selectedAmount = 0;\n\n for (const vault of sortedVaults) {\n if (selectedAmount >= targetAmount) break;\n selectedIds.push(vault.id);\n selectedAmount += vault.amount;\n }\n\n return { vaultIds: selectedIds, actualAmount: selectedAmount };\n}\n\n/**\n * Calculate total amount from a list of vaults\n *\n * @param vaults - Vaults to sum\n * @returns Total amount in BTC\n */\nexport function calculateTotalVaultAmount(vaults: SelectableVault[]): number {\n return vaults.reduce((sum, vault) => sum + vault.amount, 0);\n}\n","/**\n * Cascade Liquidation Simulation\n *\n * Simulates multi-group liquidation cascades for Aave positions backed by\n * indivisible BTC vaults (UTXOs). Each liquidation event seizes a prefix of\n * vaults until the target seizure is covered, then debt is reduced and the\n * cascade continues with remaining vaults.\n *\n * Used by the optimizer to score different vault orderings by how much\n * collateral survives the cascade.\n */\n\n/**\n * Minimal vault shape for cascade simulation.\n * UI layers extend this with display fields (e.g. `name`).\n */\nexport interface CascadeVault {\n id: string;\n btc: number;\n}\n\n/** 1% tolerance for prefix walk coverage — avoids cliff flip at boundary */\nexport const SEIZURE_TOL = 0.01;\n\n/** Circuit breaker for group cascade loop */\nexport const MAX_GROUPS = 20;\n\n/** Minimum debt threshold to continue cascade (avoids infinite loop on dust) */\nexport const MIN_DEBT_THRESHOLD = 0.01;\n\n/**\n * Prefix walk: consume vaults front-to-back until target seizure is covered.\n * Returns the vaults in the first liquidation group.\n */\nexport function getGroup1FromOrder<T extends CascadeVault>(\n order: T[],\n seizedFraction: number,\n seizureTol: number,\n): T[] {\n if (order.length === 0) return [];\n const totalBtc = order.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let prefixSum = 0;\n let i = 0;\n while (i < order.length && prefixSum < coverThreshold) {\n prefixSum += order[i].btc;\n i++;\n }\n return order.slice(0, i);\n}\n\n/**\n * Simulate one liquidation group, returning updated debt and remaining BTC.\n * Handles both safe (non-last) and full (last) liquidation paths.\n */\nfunction simulateOneGroup(\n seizedBtc: number,\n totalBtc: number,\n debt: number,\n isLastGroup: boolean,\n seizedFraction: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { debtAfter: number; btcAfter: number } {\n const liqPenalty = maxLB * CF;\n const pLiq = debt / (totalBtc * CF);\n const targetSeizure = totalBtc * seizedFraction;\n const overSeizureBtc = Math.max(0, seizedBtc - targetSeizure);\n const denominator = THF - liqPenalty;\n const debtToRepay =\n denominator === 0 ? debt : debt * ((THF - expectedHF) / denominator);\n\n let debtAfter: number;\n if (isLastGroup) {\n debtAfter = 0;\n } else {\n const overSeizureVal = (overSeizureBtc * pLiq) / maxLB;\n const fairnessDebtRepay = Math.min(overSeizureVal, debt - debtToRepay);\n debtAfter = Math.max(0, debt - debtToRepay - fairnessDebtRepay);\n }\n return { debtAfter, btcAfter: Math.max(0, totalBtc - seizedBtc) };\n}\n\n/**\n * Simulate full liquidation cascade with debt model.\n *\n * PRIMARY score: sumBtcAfterEvents — sum of BTC remaining after every event.\n * Captures how much collateral survives at each stage.\n * TIEBREAKER: btcAfterG1 — BTC remaining after the first (most likely) event.\n */\nexport function simulateCascade<T extends CascadeVault>(\n order: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { sumBtcAfterEvents: number; btcAfterG1: number } {\n let remaining = [...order];\n let debt = totalDebt;\n const initialTotalBtc = order.reduce((s, v) => s + v.btc, 0);\n let btcAfterG1 = -1;\n let sumBtcAfterEvents = 0;\n let groupCount = 0;\n\n while (\n remaining.length > 0 &&\n debt > MIN_DEBT_THRESHOLD &&\n groupCount < MAX_GROUPS\n ) {\n const totalBtc = remaining.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let prefixSum = 0;\n let i = 0;\n while (i < remaining.length && prefixSum < coverThreshold) {\n prefixSum += remaining[i].btc;\n i++;\n }\n const isLastGroup = i >= remaining.length;\n const { debtAfter } = simulateOneGroup(\n prefixSum,\n totalBtc,\n debt,\n isLastGroup,\n seizedFraction,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n remaining = remaining.slice(i);\n debt = debtAfter;\n const btcNow = totalBtc - prefixSum;\n sumBtcAfterEvents += btcNow;\n if (btcAfterG1 < 0) btcAfterG1 = btcNow;\n groupCount++;\n }\n\n return {\n sumBtcAfterEvents,\n btcAfterG1:\n btcAfterG1 < 0 ? initialTotalBtc : btcAfterG1,\n };\n}\n","/**\n * Optimal Vault Ordering for Liquidation Protection\n *\n * Finds the vault ordering that maximizes collateral surviving a multi-group\n * liquidation cascade. Uses exhaustive bitmask enumeration (2^n for n ≤ 20)\n * to find the minimum-BTC subset covering the target seizure for Group 1,\n * then greedy for subsequent groups.\n *\n * The iterative refinement loop re-runs the optimizer on its own output,\n * converging in ≤3 iterations in practice.\n */\n\nimport { simulateCascade, type CascadeVault } from \"./cascadeSimulation.js\";\n\n/** Convergence threshold for iterative refinement */\nconst EPS = 0.0001;\n\n/** Max refinement iterations for optimizer */\nconst MAX_ITER = 5;\n\n/** Max vaults for exhaustive bitmask search */\nconst MAX_VAULTS_FOR_EXHAUSTIVE = 20;\n\n/**\n * Greedy sub-order: arrange remaining vaults by finding minimum BTC subset\n * covering target for each group, using exhaustive search when feasible.\n */\nfunction greedyOrder<T extends CascadeVault>(\n vaults: T[],\n seizedFraction: number,\n seizureTol: number,\n): T[] {\n const result: T[] = [];\n let remaining = [...vaults];\n\n while (remaining.length > 0) {\n const totalBtc = remaining.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n let optSubset: T[] = [...remaining];\n let optSum = totalBtc;\n const m = remaining.length;\n\n if (m <= MAX_VAULTS_FOR_EXHAUSTIVE) {\n for (let mask = 1; mask < 1 << m; mask++) {\n let sum = 0;\n const subset: T[] = [];\n for (let bit = 0; bit < m; bit++) {\n if (mask & (1 << bit)) {\n sum += remaining[bit].btc;\n subset.push(remaining[bit]);\n }\n }\n if (sum >= coverThreshold && sum < optSum) {\n optSum = sum;\n optSubset = subset;\n }\n }\n }\n\n const ids = new Set(optSubset.map((v) => v.id));\n result.push(...[...optSubset].sort((a, b) => b.btc - a.btc));\n remaining = remaining.filter((v) => !ids.has(v.id));\n }\n\n return result;\n}\n\n/**\n * Single-pass optimizer: enumerate all possible Group 1 subsets,\n * use greedy for remaining groups, pick the order that maximizes\n * collateral surviving the cascade.\n */\nfunction computeOptimalOrderSinglePass<T extends CascadeVault>(\n vaults: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { order: T[]; sumBtcAfterEvents: number; btcAfterG1: number } {\n if (vaults.length === 0)\n return { order: [], sumBtcAfterEvents: 0, btcAfterG1: 0 };\n if (vaults.length > MAX_VAULTS_FOR_EXHAUSTIVE) {\n throw new Error(\n `Too many vaults for exhaustive search: ${vaults.length} exceeds maximum of ${MAX_VAULTS_FOR_EXHAUSTIVE}`,\n );\n }\n if (vaults.length === 1) {\n const sim = simulateCascade(\n vaults,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n return { order: [...vaults], ...sim };\n }\n\n const n = vaults.length;\n const totalBtc = vaults.reduce((s, v) => s + v.btc, 0);\n const coverThreshold = totalBtc * seizedFraction * (1 - seizureTol);\n\n let bestOrder = [...vaults];\n let bestSum = -Infinity;\n let bestAfterG1 = -Infinity;\n\n for (let mask = 1; mask < 1 << n; mask++) {\n let g1Btc = 0;\n const g1: T[] = [];\n const rest: T[] = [];\n for (let bit = 0; bit < n; bit++) {\n if (mask & (1 << bit)) {\n g1Btc += vaults[bit].btc;\n g1.push(vaults[bit]);\n } else {\n rest.push(vaults[bit]);\n }\n }\n if (g1Btc < coverThreshold) continue;\n\n g1.sort((a, b) => b.btc - a.btc);\n const candidate = [...g1, ...greedyOrder(rest, seizedFraction, seizureTol)];\n const { sumBtcAfterEvents, btcAfterG1 } = simulateCascade(\n candidate,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n\n if (\n sumBtcAfterEvents > bestSum + EPS ||\n (Math.abs(sumBtcAfterEvents - bestSum) <= EPS &&\n btcAfterG1 > bestAfterG1 + EPS)\n ) {\n bestSum = sumBtcAfterEvents;\n bestAfterG1 = btcAfterG1;\n bestOrder = candidate;\n }\n }\n\n return {\n order: bestOrder,\n sumBtcAfterEvents: bestSum,\n btcAfterG1: bestAfterG1,\n };\n}\n\n/**\n * Main optimizer: iterative refinement until stable.\n * Re-running with the improved order lets the next pass find better\n * G1 subsets. Converges in ≤3 iterations in practice.\n */\nexport function computeOptimalOrder<T extends CascadeVault>(\n vaults: T[],\n totalDebt: number,\n seizedFraction: number,\n seizureTol: number,\n CF: number,\n THF: number,\n maxLB: number,\n expectedHF: number,\n): { order: T[]; sumBtcAfterEvents: number; btcAfterG1: number } {\n let result = computeOptimalOrderSinglePass(\n vaults,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n\n for (let i = 0; i < MAX_ITER; i++) {\n const refined = computeOptimalOrderSinglePass(\n result.order,\n totalDebt,\n seizedFraction,\n seizureTol,\n CF,\n THF,\n maxLB,\n expectedHF,\n );\n const primaryImproves =\n refined.sumBtcAfterEvents > result.sumBtcAfterEvents + EPS;\n const primaryTied =\n Math.abs(refined.sumBtcAfterEvents - result.sumBtcAfterEvents) <= EPS;\n const tiebreakerImproves =\n primaryTied && refined.btcAfterG1 > result.btcAfterG1 + EPS;\n if (!primaryImproves && !tiebreakerImproves) {\n break;\n }\n result = refined;\n }\n\n return result;\n}\n","/**\n * Vault Split Utilities for Aave Liquidation Protection\n *\n * BTC vaults are indivisible UTXOs. During liquidation, the protocol seizes\n * whole vaults as a prefix of the borrower's ordered vault list until the\n * target seizure amount is covered. Splitting deposits into 2 optimally-sized\n * vaults (sacrificial + protected) minimizes over-seizure loss.\n *\n * The sacrificial vault (index 0) is sized to cover the expected target seizure\n * plus a safety margin. The protected vault (index 1) holds the remainder and\n * survives liquidation.\n *\n * Seizure formula (from Aave v4 Section 4.2):\n * ```\n * liq_penalty = LB × CF\n * debt_to_repay = total_debt × (THF - current_HF) / (THF - liq_penalty)\n * target_seizure = debt_to_repay × LB\n * ```\n */\n\nconst MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * Effective dust threshold for HTLC outputs in satoshis.\n *\n * Standard P2TR dust is 330 sats, but HTLC scripts are larger than a standard\n * P2TR key-path spend. A conservative estimate for an HTLC script-path output\n * is ~2000 sats. This is a defense-in-depth check — in practice, minDeposit\n * from the on-chain contract is orders of magnitude larger.\n */\nconst HTLC_EFFECTIVE_DUST_THRESHOLD = 2000n;\n\nexport function assertSafePrecision(value: bigint, name: string): void {\n if (value > MAX_SAFE_BIGINT) {\n throw new RangeError(\n `${name} (${value}) exceeds Number.MAX_SAFE_INTEGER; precision would be lost`,\n );\n }\n}\n\n/**\n * Parameters for computing the optimal vault split.\n */\nexport interface OptimalSplitParams {\n /** Total deposit amount in satoshis */\n totalBtc: bigint;\n /** Collateral factor (e.g. 0.75 for 75%) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05 for 5% bonus) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n /** Safety margin multiplier for the sacrificial vault (e.g. 1.05 for 5% buffer) */\n safetyMargin: number;\n}\n\n/**\n * Result of the optimal vault split computation.\n */\nexport interface OptimalSplitResult {\n /** Sacrificial vault amount in satoshis (index 0, seized first) */\n sacrificialVault: bigint;\n /** Protected vault amount in satoshis (index 1, survives liquidation) */\n protectedVault: bigint;\n /** Fraction of collateral that would be seized (0–1) */\n seizedFraction: number;\n /** Raw target seizure amount in satoshis (before safety margin) */\n targetSeizureBtc: bigint;\n}\n\n/**\n * Parameters for computing the minimum deposit required for a split.\n */\nexport interface MinDepositForSplitParams {\n /** Minimum peg-in amount in satoshis */\n minPegin: bigint;\n /** Seized fraction (0–1), from computeOptimalSplit or computeSeizedFraction */\n seizedFraction: number;\n /** Safety margin multiplier (e.g. 1.05) */\n safetyMargin: number;\n}\n\n/**\n * Parameters for checking if a vault rebalance is needed.\n */\nexport interface RebalanceCheckParams {\n /** Ordered vault amounts in satoshis (index 0 is sacrificial) */\n vaultAmounts: bigint[];\n /** Collateral factor (e.g. 0.75) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n /** Safety margin multiplier (e.g. 1.05) */\n safetyMargin: number;\n}\n\n/**\n * Result of a vault rebalance check.\n */\nexport interface RebalanceCheckResult {\n /** Whether the sacrificial vault needs to be increased */\n needsRebalance: boolean;\n /** How much more the sacrificial vault needs in satoshis (0n if no rebalance needed) */\n deficit: bigint;\n /** Current sacrificial vault coverage in satoshis */\n currentCoverage: bigint;\n /** Required sacrificial vault coverage in satoshis */\n targetCoverage: bigint;\n}\n\n/**\n * Compute the fraction of collateral that would be seized during liquidation,\n * returning both the raw (unclamped) and clamped values.\n *\n * The raw value is useful for detecting unusual protocol parameter combinations\n * (values outside [0, 1] indicate something unexpected).\n *\n * Formula:\n * ```\n * liq_penalty = LB × CF\n * seized_fraction = CF × (THF - expectedHF) / (THF - liq_penalty) × LB / expectedHF\n * ```\n *\n * @param CF - Collateral factor (e.g. 0.75)\n * @param LB - Liquidation bonus (e.g. 1.05)\n * @param THF - Target health factor (e.g. 1.10)\n * @param expectedHF - Expected health factor at liquidation (e.g. 0.95)\n * @returns Both the raw seized fraction and the clamped [0, 1] value\n */\nexport function computeSeizedFractionDetailed(\n CF: number,\n LB: number,\n THF: number,\n expectedHF: number,\n): { seizedFraction: number; seizedFractionRaw: number } {\n // HF ≤ 0 means position is fully underwater — full seizure\n if (expectedHF <= 0) {\n return { seizedFraction: 1, seizedFractionRaw: Infinity };\n }\n\n const liqPenalty = LB * CF;\n\n // If THF <= liq_penalty, full liquidation is inevitable\n if (THF <= liqPenalty) {\n return { seizedFraction: 1, seizedFractionRaw: Infinity };\n }\n\n // Floating-point errors here are ~1e-15, negligible relative to the 5%\n // safety margin applied by callers (computeOptimalSplit, checkRebalanceNeeded).\n const seizedFractionRaw =\n ((CF * (THF - expectedHF)) / (THF - liqPenalty)) * (LB / expectedHF);\n\n return {\n seizedFraction: Math.max(0, Math.min(1, seizedFractionRaw)),\n seizedFractionRaw,\n };\n}\n\n/**\n * Compute the fraction of collateral that would be seized during liquidation.\n *\n * @param CF - Collateral factor (e.g. 0.75)\n * @param LB - Liquidation bonus (e.g. 1.05)\n * @param THF - Target health factor (e.g. 1.10)\n * @param expectedHF - Expected health factor at liquidation (e.g. 0.95)\n * @returns Seized fraction clamped to [0, 1]\n */\nexport function computeSeizedFraction(\n CF: number,\n LB: number,\n THF: number,\n expectedHF: number,\n): number {\n return computeSeizedFractionDetailed(CF, LB, THF, expectedHF).seizedFraction;\n}\n\n/**\n * Compute the optimal split between a sacrificial vault and a protected vault.\n *\n * The sacrificial vault (index 0) is sized to cover the target seizure amount\n * plus a safety margin. The protected vault (index 1) holds the remainder.\n *\n * @param params - Split parameters including total BTC, risk params, and safety margin\n * @returns Split result with vault sizes, seized fraction, and target seizure\n *\n * @example\n * ```typescript\n * import { computeOptimalSplit } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const result = computeOptimalSplit({\n * totalBtc: 1_000_000_000n, // 10 BTC in sats\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * safetyMargin: 1.05,\n * });\n * // result.sacrificialVault ≈ 418_000_000n (4.18 BTC)\n * // result.protectedVault ≈ 582_000_000n (5.82 BTC)\n * ```\n */\nexport function computeOptimalSplit(\n params: OptimalSplitParams,\n): OptimalSplitResult {\n const { totalBtc, CF, LB, THF, expectedHF, safetyMargin } = params;\n\n if (totalBtc <= 0n) {\n return {\n sacrificialVault: 0n,\n protectedVault: 0n,\n seizedFraction: 0,\n targetSeizureBtc: 0n,\n };\n }\n\n assertSafePrecision(totalBtc, \"totalBtc\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n const totalBtcNum = Number(totalBtc);\n const targetSeizureBtc = BigInt(Math.ceil(totalBtcNum * seizedFraction));\n\n const sacrificialRaw = BigInt(\n Math.ceil(totalBtcNum * seizedFraction * safetyMargin),\n );\n const sacrificialVault =\n sacrificialRaw > totalBtc ? totalBtc : sacrificialRaw;\n const protectedVault = totalBtc - sacrificialVault;\n\n // If either vault is non-zero but below the effective dust threshold for\n // HTLC outputs, the split is not viable — return zeroed vaults so the\n // caller treats this as non-splittable. We avoid throwing because this\n // function is called during render (useMemo) and throwing would crash\n // the component instead of showing validation feedback.\n if (\n (sacrificialVault > 0n &&\n sacrificialVault < HTLC_EFFECTIVE_DUST_THRESHOLD) ||\n (protectedVault > 0n && protectedVault < HTLC_EFFECTIVE_DUST_THRESHOLD)\n ) {\n return {\n sacrificialVault: 0n,\n protectedVault: 0n,\n seizedFraction,\n targetSeizureBtc: 0n,\n };\n }\n\n return {\n sacrificialVault,\n protectedVault,\n seizedFraction,\n targetSeizureBtc,\n };\n}\n\n/**\n * Compute the minimum total deposit required for a 2-vault split.\n *\n * Both vaults must be at least `minPegin` satoshis. This function returns\n * the minimum total deposit where both the sacrificial and protected vaults\n * would meet the minimum peg-in requirement.\n *\n * @param params - Parameters including minimum peg-in, seized fraction, and safety margin\n * @returns Minimum total deposit in satoshis. Returns 0n in two cases:\n * - `seizedFraction * safetyMargin >= 1`: split impossible (sacrificial vault would consume entire deposit)\n * - `seizedFraction <= 0`: split not useful (no seizure expected at this health factor)\n *\n * @example\n * ```typescript\n * import { computeMinDepositForSplit } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const minDeposit = computeMinDepositForSplit({\n * minPegin: 50_000n, // 0.0005 BTC\n * seizedFraction: 0.398,\n * safetyMargin: 1.05,\n * });\n * ```\n */\nexport function computeMinDepositForSplit(\n params: MinDepositForSplitParams,\n): bigint {\n const { minPegin, seizedFraction, safetyMargin } = params;\n\n assertSafePrecision(minPegin, \"minPegin\");\n\n const sacrificialShare = seizedFraction * safetyMargin;\n\n // If sacrificial vault would consume the entire deposit, split is not possible\n if (sacrificialShare >= 1) {\n return 0n;\n }\n\n // If seized fraction is effectively zero, split is not useful\n if (sacrificialShare <= 0) {\n return 0n;\n }\n\n // Minimum total so the protected vault (smaller share) >= minPegin\n const protectedShare = 1 - sacrificialShare;\n const minFromProtected = Math.ceil(Number(minPegin) / protectedShare);\n\n // Minimum total so the sacrificial vault >= minPegin\n const minFromSacrificial = Math.ceil(Number(minPegin) / sacrificialShare);\n\n return BigInt(Math.max(minFromProtected, minFromSacrificial));\n}\n\n/**\n * Check if the sacrificial vault (index 0) needs to be increased to cover\n * the current target seizure amount.\n *\n * **Scope:** This function only checks whether the sacrificial vault's sizing\n * is adequate. It does NOT detect whether a split exists — a single vault that\n * exceeds the target coverage returns `needsRebalance: false`. Callers should\n * check `vaultAmounts.length < 2` separately to detect unsplit positions.\n *\n * Used on position page load to detect when parameter changes (THF, CF, LB)\n * have made the current split insufficient.\n *\n * @param params - Current vault amounts and risk parameters\n * @returns Whether rebalance is needed, with deficit details\n *\n * @example\n * ```typescript\n * import { checkRebalanceNeeded } from \"@babylonlabs-io/ts-sdk/tbv/integrations/aave\";\n *\n * const result = checkRebalanceNeeded({\n * vaultAmounts: [300_000_000n, 700_000_000n], // 3 BTC sacrificial, 7 BTC protected\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * safetyMargin: 1.05,\n * });\n *\n * if (result.needsRebalance) {\n * console.log(`Sacrificial vault needs ${result.deficit} more sats`);\n * }\n * ```\n */\nexport function checkRebalanceNeeded(\n params: RebalanceCheckParams,\n): RebalanceCheckResult {\n const { vaultAmounts, CF, LB, THF, expectedHF, safetyMargin } = params;\n\n if (vaultAmounts.length === 0) {\n return {\n needsRebalance: false,\n deficit: 0n,\n currentCoverage: 0n,\n targetCoverage: 0n,\n };\n }\n\n const totalBtc = vaultAmounts.reduce((sum, v) => sum + v, 0n);\n assertSafePrecision(totalBtc, \"totalBtc\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n const targetCoverage = BigInt(\n Math.ceil(Number(totalBtc) * seizedFraction * safetyMargin),\n );\n const currentCoverage = vaultAmounts[0];\n\n const deficit =\n targetCoverage > currentCoverage ? targetCoverage - currentCoverage : 0n;\n\n return {\n needsRebalance: deficit > 0n,\n deficit,\n currentCoverage,\n targetCoverage,\n };\n}\n","/**\n * Seizure Simulation Utilities\n *\n * Simulates which vaults would be seized during Aave liquidation.\n * Vaults are seized in prefix order (index 0, 1, 2, ...) until the\n * target seizure amount is covered.\n *\n * Reference: Aave v4 Section 4.2 — liquidation seizes a prefix of the\n * borrower's ordered vault list.\n */\n\nimport { assertSafePrecision, computeSeizedFraction } from \"./vaultSplit.js\";\n\n/**\n * A vault with its on-chain ID and BTC amount, in liquidation-priority order.\n */\nexport interface OrderedVault {\n /** On-chain vault ID (bytes32 hex string) */\n id: string;\n /** Vault amount in satoshis */\n amountSats: bigint;\n}\n\n/**\n * Parameters for simulating prefix seizure.\n */\nexport interface PrefixSeizureParams {\n /** Vaults in their current on-chain order (index 0 is seized first) */\n orderedVaults: OrderedVault[];\n /** Target seizure amount in satoshis */\n targetSeizureSats: bigint;\n}\n\n/**\n * Result of a prefix seizure simulation.\n */\nexport interface PrefixSeizureResult {\n /** Vaults that would be seized (the prefix) */\n seizedVaults: OrderedVault[];\n /** Vaults that survive liquidation */\n protectedVaults: OrderedVault[];\n /** Over-seizure amount in satoshis (total seized - target) */\n overSeizureSats: bigint;\n /** Index where seizure stops (exclusive: vaults[0..cutoffIndex] are seized) */\n cutoffIndex: number;\n /** Total amount seized in satoshis */\n totalSeizedSats: bigint;\n}\n\n/**\n * Parameters for computing target seizure in satoshis.\n */\nexport interface TargetSeizureParams {\n /** Total collateral in satoshis */\n totalCollateralSats: bigint;\n /** Collateral factor (e.g. 0.75) */\n CF: number;\n /** Liquidation bonus (e.g. 1.05) */\n LB: number;\n /** Target health factor (e.g. 1.10) */\n THF: number;\n /** Expected health factor at liquidation (e.g. 0.95) */\n expectedHF: number;\n}\n\n/**\n * Compute the target seizure amount in satoshis.\n *\n * Uses `computeSeizedFraction` to determine what fraction of total collateral\n * would be seized, then converts to an absolute satoshi amount.\n *\n * @param params - Total collateral and risk parameters\n * @returns Target seizure amount in satoshis (rounded up)\n *\n * @example\n * ```typescript\n * const targetSats = computeTargetSeizureSats({\n * totalCollateralSats: 1_000_000_000n, // 10 BTC\n * CF: 0.75,\n * LB: 1.05,\n * THF: 1.10,\n * expectedHF: 0.95,\n * });\n * // targetSats ≈ 398_000_000n (3.98 BTC)\n * ```\n */\nexport function computeTargetSeizureSats(\n params: TargetSeizureParams,\n): bigint {\n const { totalCollateralSats, CF, LB, THF, expectedHF } = params;\n\n if (totalCollateralSats <= 0n) {\n return 0n;\n }\n\n assertSafePrecision(totalCollateralSats, \"totalCollateralSats\");\n\n const seizedFraction = computeSeizedFraction(CF, LB, THF, expectedHF);\n\n return BigInt(Math.ceil(Number(totalCollateralSats) * seizedFraction));\n}\n\n/**\n * Simulate prefix seizure for a given set of ordered vaults.\n *\n * Walks the ordered vault list, accumulating amounts until the target\n * seizure is covered. Returns which vaults are seized vs protected,\n * the over-seizure amount, and the cutoff index.\n *\n * @param params - Ordered vaults and target seizure amount\n * @returns Seizure simulation result\n * @throws Error if orderedVaults is empty\n * @throws Error if targetSeizureSats is <= 0\n *\n * @example\n * ```typescript\n * const result = simulatePrefixSeizure({\n * orderedVaults: [\n * { id: \"0xabc...\", amountSats: 200_000_000n },\n * { id: \"0xdef...\", amountSats: 300_000_000n },\n * { id: \"0x123...\", amountSats: 500_000_000n },\n * ],\n * targetSeizureSats: 400_000_000n,\n * });\n * // result.seizedVaults = first 2 vaults (200M + 300M = 500M >= 400M)\n * // result.overSeizureSats = 100_000_000n\n * // result.cutoffIndex = 2\n * ```\n */\nexport function simulatePrefixSeizure(\n params: PrefixSeizureParams,\n): PrefixSeizureResult {\n const { orderedVaults, targetSeizureSats } = params;\n\n if (orderedVaults.length === 0) {\n throw new Error(\"orderedVaults must not be empty\");\n }\n\n if (targetSeizureSats <= 0n) {\n throw new Error(\n \"targetSeizureSats must be positive; use computeTargetSeizureSats to derive it\",\n );\n }\n\n let accumulated = 0n;\n let cutoffIndex = orderedVaults.length; // default: all vaults seized\n\n for (let i = 0; i < orderedVaults.length; i++) {\n accumulated += orderedVaults[i].amountSats;\n\n if (accumulated >= targetSeizureSats) {\n cutoffIndex = i + 1;\n break;\n }\n }\n\n const seizedVaults = orderedVaults.slice(0, cutoffIndex);\n const protectedVaults = orderedVaults.slice(cutoffIndex);\n const totalSeizedSats = accumulated;\n const overSeizureSats =\n totalSeizedSats > targetSeizureSats\n ? totalSeizedSats - targetSeizureSats\n : 0n;\n\n return {\n seizedVaults,\n protectedVaults,\n overSeizureSats,\n cutoffIndex,\n totalSeizedSats,\n };\n}\n"],"names":["AAVE_FUNCTION_NAMES","BTC_DECIMALS","USDC_DECIMALS","BPS_TO_PERCENT_DIVISOR","BPS_SCALE","AAVE_BASE_CURRENCY_DECIMALS","AAVE_BASE_CURRENCY_RAY_DECIMALS","WAD_DECIMALS","HEALTH_FACTOR_WARNING_THRESHOLD","MIN_HEALTH_FACTOR_FOR_BORROW","FULL_REPAY_BUFFER_DIVISOR","FULL_REPAY_BUFFER_FRACTION","getPosition","publicClient","contractAddress","user","position","AaveIntegrationAdapterABI","zeroAddress","getPositionSizeParams","result","maxPositionBTC","maxVaultsPerPosition","hasDebtFromPosition","mapPositionResult","getUserAccountData","spokeAddress","userAddress","data","AaveSpokeABI","getUserPosition","reserveId","hasDebt","hasCollateral","getUserTotalDebt","getReserve","getTargetHealthFactor","getDynamicReserveConfig","dynamicConfigKey","buildReorderVaultsTx","permutedVaultIds","encodeFunctionData","buildWithdrawCollateralsTx","vaultIds","buildBorrowTx","debtReserveId","amount","receiver","buildRepayTx","borrower","aaveValueToUsd","value","aaveRayValueToUsd","wadToNumber","calculateBorrowRatio","debtUsd","collateralValueUsd","getHealthFactorStatus","healthFactor","isHealthFactorHealthy","getHealthFactorStatusFromValue","calculateHealthFactor","totalDebtUsd","liquidationThresholdBps","selectVaultsForAmount","vaults","targetAmount","sortedVaults","a","b","selectedIds","selectedAmount","vault","calculateTotalVaultAmount","sum","SEIZURE_TOL","MAX_GROUPS","MIN_DEBT_THRESHOLD","getGroup1FromOrder","order","seizedFraction","seizureTol","coverThreshold","s","v","prefixSum","i","simulateOneGroup","seizedBtc","totalBtc","debt","isLastGroup","CF","THF","maxLB","expectedHF","liqPenalty","pLiq","targetSeizure","overSeizureBtc","denominator","debtToRepay","debtAfter","overSeizureVal","fairnessDebtRepay","simulateCascade","totalDebt","remaining","initialTotalBtc","btcAfterG1","sumBtcAfterEvents","groupCount","btcNow","EPS","MAX_ITER","MAX_VAULTS_FOR_EXHAUSTIVE","greedyOrder","optSubset","optSum","m","mask","subset","bit","ids","computeOptimalOrderSinglePass","sim","n","bestOrder","bestSum","bestAfterG1","g1Btc","g1","rest","candidate","computeOptimalOrder","refined","primaryImproves","tiebreakerImproves","MAX_SAFE_BIGINT","HTLC_EFFECTIVE_DUST_THRESHOLD","assertSafePrecision","name","computeSeizedFractionDetailed","LB","seizedFractionRaw","computeSeizedFraction","computeOptimalSplit","params","safetyMargin","totalBtcNum","targetSeizureBtc","sacrificialRaw","sacrificialVault","protectedVault","computeMinDepositForSplit","minPegin","sacrificialShare","protectedShare","minFromProtected","minFromSacrificial","checkRebalanceNeeded","vaultAmounts","targetCoverage","currentCoverage","deficit","computeTargetSeizureSats","totalCollateralSats","simulatePrefixSeizure","orderedVaults","targetSeizureSats","accumulated","cutoffIndex","seizedVaults","protectedVaults","totalSeizedSats","overSeizureSats"],"mappings":";AAWO,MAAMA,IAAsB;AAAA;AAAA,EAEjC,sBAAsB;AAAA;AAAA,EAEtB,QAAQ;AAAA;AAAA,EAER,OAAO;AAAA;AAAA,EAEP,gBAAgB;AAClB,GAMaC,IAAe,GAMfC,KAAgB,GAahBC,KAAyB,KAQzBC,IAAY,KAQZC,IAA8B,IAS9BC,IAAkC,IAQlCC,IAAe,IAMfC,IAAkC,KAMlCC,KAA+B,KAe/BC,IAA4B,MAM5BC,KACX,IAAI,OAAOD,CAAyB;ACtFtC,eAAsBE,GACpBC,GACAC,GACAC,GACoC;AAcpC,QAAMC,IAbS,MAAMH,EAAa,aAAa;AAAA,IAC7C,SAASC;AAAA,IACT,KAAKG;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAACF,CAAI;AAAA,EAAA,CACZ;AAWD,SAAIC,EAAS,kBAAkBE,IACtB,OAGF;AAAA,IACL,eAAeF,EAAS;AAAA,IACxB,UAAUA,EAAS;AAAA,IACnB,oBAAoBA,EAAS;AAAA,EAAA;AAEjC;AAYA,eAAsBG,GACpBN,GACAC,GAC6B;AAC7B,QAAMM,IAAS,MAAMP,EAAa,aAAa;AAAA,I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,IACA,iBAAAD;AAAA,IACA,gBAAAD;AAAA,EAAA;AAEJ;ACrSO,SAASG,GACdlB,GACQ;AACR,QAAM,EAAE,qBAAAmB,GAAqB,IAAA1E,GAAI,IAAAmD,GAAI,KAAAlD,GAAK,YAAAE,MAAeoD;AAEzD,MAAImB,KAAuB;AACzB,WAAO;AAGT,EAAA1B,EAAoB0B,GAAqB,qBAAqB;AAE9D,QAAMtF,IAAiBiE,EAAsBrD,GAAImD,GAAIlD,GAAKE,CAAU;AAEpE,SAAO,OAAO,KAAK,KAAK,OAAOuE,CAAmB,IAAItF,CAAc,CAAC;AACvE;AA6BO,SAASuF,GACdpB,GACqB;AACrB,QAAM,EAAE,eAAAqB,GAAe,mBAAAC,EAAA,IAAsBtB;AAE7C,MAAIqB,EAAc,WAAW;AAC3B,UAAM,IAAI,MAAM,iCAAiC;AAGnD,MAAIC,KAAqB;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAIC,IAAc,IACdC,IAAcH,EAAc;AAEhC,WAASlF,IAAI,GAAGA,IAAIkF,EAAc,QAAQlF;AAGxC,QAFAoF,KAAeF,EAAclF,CAAC,EAAE,YAE5BoF,KAAeD,GAAmB;AACpC,MAAAE,IAAcrF,IAAI;AAClB;AAAA,IACF;AAGF,QAAMsF,IAAeJ,EAAc,MAAM,GAAGG,CAAW,GACjDE,IAAkBL,EAAc,MAAMG,CAAW,GACjDG,IAAkBJ,GAClBK,IACJD,IAAkBL,IACdK,IAAkBL,IAClB;AAEN,SAAO;AAAA,IACL,cAAAG;AAAA,IACA,iBAAAC;AAAA,IACA,iBAAAE;AAAA,IACA,aAAAJ;AAAA,IACA,iBAAAG;AAAA,EAAA;AAEJ;"}
|
|
@@ -13,6 +13,12 @@ export interface DepositorStruct {
|
|
|
13
13
|
export interface AaveMarketPosition {
|
|
14
14
|
proxyContract: Address;
|
|
15
15
|
vaultIds: Hex[];
|
|
16
|
+
/**
|
|
17
|
+
* Sum (in satoshis) of all vault amounts collateralised in this position.
|
|
18
|
+
* Mirrors `MarketPosition.totalCollateralBTC` returned by
|
|
19
|
+
* `AaveIntegrationAdapter.getPosition`.
|
|
20
|
+
*/
|
|
21
|
+
totalCollateralBTC: bigint;
|
|
16
22
|
}
|
|
17
23
|
/**
|
|
18
24
|
* User account data from the Spoke
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/tbv/integrations/aave/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,GAAG,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,OAAO,CAAC;IACvB,QAAQ,EAAE,GAAG,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/tbv/integrations/aave/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,GAAG,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,OAAO,CAAC;IACvB,QAAQ,EAAE,GAAG,EAAE,CAAC;IAChB;;;;OAIG;IACH,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,mBAAmB;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,8DAA8D;IAC9D,mBAAmB,EAAE,MAAM,CAAC;IAC5B,yCAAyC;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,8DAA8D;IAC9D,oBAAoB,EAAE,MAAM,CAAC;IAC7B,uEAAuE;IACvE,iBAAiB,EAAE,MAAM,CAAC;IAC1B,2CAA2C;IAC3C,qBAAqB,EAAE,MAAM,CAAC;IAC9B,kCAAkC;IAClC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,wBAAwB;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,gCAAgC;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,sEAAsE;IACtE,gBAAgB,EAAE,MAAM,CAAC;IACzB,iCAAiC;IACjC,cAAc,EAAE,MAAM,CAAC;IACvB,yBAAyB;IACzB,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,+BAA+B;IAC/B,EAAE,EAAE,OAAO,CAAC;IACZ,4BAA4B;IAC5B,IAAI,EAAE,GAAG,CAAC;IACV,8CAA8C;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,sDAAsD;IACtD,cAAc,EAAE,MAAM,CAAC;IACvB,4CAA4C;IAC5C,oBAAoB,EAAE,MAAM,CAAC;CAC9B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var w=Object.defineProperty;var y=(t,e,r)=>e in t?w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var c=(t,e,r)=>y(t,typeof e!="symbol"?e+"":e,r);class d extends Error{constructor(e,r,n="local",s){super(r),this.code=e,this.source=n,this.data=s,this.name="JsonRpcError"}}const _={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},b="2.0",f=3,v=1e3,C=2*1024*1024,g=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),D=new Set([408,429,500,502,503,504]),L=new Set(["vaultProvider_getPeginStatus","vaultProvider_batchGetPeginStatus","vaultProvider_batchGetPegoutStatus","vaultProvider_requestDepositorPresignTransactions"]);function U(t){return L.has(t)}const m="auth_expired";function G(t){if(!(t instanceof d)||t.source!=="wire")return!1;const e=t.data;return e===null||typeof e!="object"?!1:e.kind===m}class B{constructor(e){c(this,"baseUrl");c(this,"timeout");c(this,"headers");c(this,"requestId",0);c(this,"retries");c(this,"retryDelay");c(this,"maxResponseBytes");c(this,"retryableFor");c(this,"tokenProvider");if(this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.headers={"Content-Type":"application/json",...e.headers},this.retries=e.retries??f,this.retryDelay=e.retryDelay??v,this.maxResponseBytes=e.maxResponseBytes??C,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=e.retryableFor??U,this.tokenProvider=e.tokenProvider}async buildHeaders(e){const r={...this.headers};if(this.tokenProvider){const n=await this.tokenProvider.getToken(e);n&&(r.Authorization=`Bearer ${n}`)}return r}async call(e,r,n){try{return await this.callOnce(e,r,n)}catch(s){if(this.tokenProvider&&G(s))return this.tokenProvider.invalidate(),await this.callOnce(e,r,n);throw s}}async callOnce(e,r,n){const s=await this.fetchWithRetry(e,r,n);let o;try{const i=g.has(e)?await s.text():await k(s,this.maxResponseBytes);o=JSON.parse(i)}catch(i){throw i instanceof d?i:new d(_.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(o===null||typeof o!="object"||Array.isArray(o))throw new d(_.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof o}`,"local");const a=o;if("error"in a&&a.error!=null){const i=a.error;throw new d(i.code??_.INVALID_RESPONSE,i.message??"Unknown RPC error","wire",i.data)}if(!("result"in a))throw new d(_.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return a.result}async callRaw(e,r,n){return this.fetchWithRetry(e,r,n)}async fetchWithRetry(e,r,n){const s=++this.requestId,o=this.retryableFor(e)?this.retries:0,i=JSON.stringify({jsonrpc:b,method:e,params:[r],id:s});let u=null;for(let T=0;T<=o;T++){const R=new AbortController,A=setTimeout(()=>R.abort(),this.timeout),l=n?x(n,R.signal):null,p=l?l.signal:R.signal;try{const E=await this.buildHeaders(e),P=await fetch(this.baseUrl,{method:"POST",headers:E,body:i,signal:p});if(clearTimeout(A),l==null||l.cleanup(),!P.ok){if(T<o&&D.has(P.status)){const O=this.retryDelay*Math.pow(2,T);await this.sleep(O,n);continue}throw new Error(`HTTP error: ${P.status} ${P.statusText}`)}return P}catch(E){if(clearTimeout(A),l==null||l.cleanup(),u=E instanceof Error?E:new Error(String(E)),n!=null&&n.aborted)throw new Error("Request aborted");if(E instanceof Error&&E.name==="AbortError"){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(_.TIMEOUT,`Request timeout after ${this.timeout}ms (${o+1} attempts)`,"local")}if(E instanceof TypeError){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(_.NETWORK,`Network error: ${E.message} (${o+1} attempts)`,"local")}throw E}}throw u||new Error("Unknown error after retries")}sleep(e,r){return new Promise((n,s)=>{if(r!=null&&r.aborted){s(new Error("Request aborted"));return}const o=setTimeout(()=>{r==null||r.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o),s(new Error("Request aborted"))};r==null||r.addEventListener("abort",a,{once:!0})})}getBaseUrl(){return this.baseUrl}}function x(t,e){if(t.aborted)return{signal:t,cleanup:()=>{}};if(e.aborted)return{signal:e,cleanup:()=>{}};const r=new AbortController,n=()=>{e.removeEventListener("abort",s),r.abort()},s=()=>{t.removeEventListener("abort",n),r.abort()};t.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",s,{once:!0});const o=()=>{t.removeEventListener("abort",n),e.removeEventListener("abort",s)};return{signal:r.signal,cleanup:o}}async function k(t,e){const r=t.headers.get("content-length");if(r!==null){const i=Number(r);if(Number.isFinite(i)&&i>e)throw S(e)}if(!t.body)return"";const n=t.body.getReader(),s=new TextDecoder;let o=0,a="";try{for(;;){const{done:i,value:u}=await n.read();if(i)break;if(u){if(o+=u.byteLength,o>e)throw await n.cancel(),S(e);a+=s.decode(u,{stream:!0})}}}finally{n.releaseLock()}return a+s.decode()}function S(t){return new d(_.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${t} bytes`,"local")}var I=(t=>(t.PENDING_INGESTION="PendingIngestion",t.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",t.PENDING_BABE_SETUP="PendingBabeSetup",t.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",t.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",t.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",t.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",t.PENDING_ACKS="PendingACKs",t.PENDING_ACTIVATION="PendingActivation",t.ACTIVATED_PENDING_BROADCAST="ActivatedPendingBroadcast",t.ACTIVATED="Activated",t.EXPIRED="Expired",t.INVALID_SIG_IN_CONTRACT="InvalidSigInContract",t.AML_REJECTED="AmlRejected",t.EXPIRED_CLEANED_UP="ExpiredCleanedUp",t.EXPIRED_IN_CLAIM="ExpiredInClaim",t))(I||{});const M=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],V=["PendingACKs","PendingActivation","ActivatedPendingBroadcast","Activated"],h=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...V]),F=new Set(["InvalidSigInContract","AmlRejected","ExpiredCleanedUp","ExpiredInClaim"]),J=new Set([...h,"PendingDepositorSignatures"]),q=50;var N=(t=>(t[t.PEGIN_NOT_FOUND=4001]="PEGIN_NOT_FOUND",t))(N||{});exports.DaemonStatus=I;exports.JSON_RPC_ERROR_CODES=_;exports.JsonRpcClient=B;exports.JsonRpcError=d;exports.POST_WOTS_STATUSES=J;exports.PRE_DEPOSITOR_SIGNATURES_STATES=M;exports.RpcErrorCode=N;exports.VP_BATCH_MAX_SIZE=q;exports.VP_TERMINAL_FAILURE_STATUSES=F;exports.VP_TRANSIENT_STATUSES=h;
|
|
2
|
+
//# sourceMappingURL=types-D2jcXfm7.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-D2jcXfm7.cjs","sources":["../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\n/**\n * Injects bearer tokens into requests for auth-gated methods, and is\n * notified on auth-expired responses so it can invalidate its cache.\n *\n * The `JsonRpcClient` is agnostic to which methods are auth-gated —\n * the provider's `getToken(method)` decides. Returning `null` means\n * \"no auth required for this method\"; the client then sends the\n * request with no `Authorization` header.\n */\nexport interface BearerTokenProvider {\n /**\n * Return the bearer token to inject for `method`, or `null` if the\n * method does not require auth.\n */\n getToken(method: string): Promise<string | null>;\n /**\n * Drop the cached token. Next call to `getToken` must re-acquire.\n * Called by the client on reactive-refresh-trigger responses.\n */\n invalidate(): void;\n}\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Maximum response body size, in bytes, for typed JSON-RPC calls.\n * `callRaw` intentionally returns the unparsed Response and is not capped here.\n * Default: 2 MiB.\n */\n maxResponseBytes?: number;\n /**\n * Predicate that decides which methods retry on transient errors.\n * Default retries only `getPeginStatus`, `batchGetPeginStatus`,\n * `batchGetPegoutStatus`, and `requestDepositorPresignTransactions`.\n * Write methods are not retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. `call`\n * additionally retries once on wire `auth_expired` (invalidate +\n * refetch + retry). `callRaw` skips reactive refresh.\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n// \"wire\" = parsed from a JSON-RPC error envelope; \"local\" = timeout/network/parse failure.\nexport type JsonRpcErrorSource = \"wire\" | \"local\";\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n /** \"wire\" for server-returned envelopes; \"local\" for SDK-side failures. */\n public source: JsonRpcErrorSource = \"local\",\n /** Structured data from the server `error.data` field, if any. */\n public data?: unknown,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n /** SDK client: response body exceeded the configured byte limit */\n RESPONSE_TOO_LARGE: -32701,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Default maximum JSON-RPC response size for typed calls (2 MiB) */\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\n\n/**\n * TODO: Temporary typed-call exceptions for methods that currently return large\n * artifact payloads as JSON-RPC results.\n */\nconst UNCAPPED_TYPED_RESPONSE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatus\",\n \"vaultProvider_batchGetPeginStatus\",\n \"vaultProvider_batchGetPegoutStatus\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * Token-expired marker the server emits in `error.data.kind`. When\n * present on a wire-origin error, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * Kept in sync with btc-vault's auth middleware. Absence of the marker\n * means the server does not support reactive refresh yet; we fall back\n * to proactive-only refresh via `BearerTokenProvider.getToken()` TTL\n * checks.\n */\nconst AUTH_EXPIRED_DATA_KIND = \"auth_expired\";\n\nfunction isAuthExpiredError(error: unknown): boolean {\n if (!(error instanceof JsonRpcError)) return false;\n if (error.source !== \"wire\") return false;\n const data = error.data;\n if (data === null || typeof data !== \"object\") return false;\n const kind = (data as { kind?: unknown }).kind;\n return kind === AUTH_EXPIRED_DATA_KIND;\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private maxResponseBytes: number;\n private retryableFor: (method: string) => boolean;\n private tokenProvider?: BearerTokenProvider;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.maxResponseBytes =\n config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n if (!Number.isFinite(this.maxResponseBytes) || this.maxResponseBytes <= 0) {\n throw new Error(\"maxResponseBytes must be a positive finite number\");\n }\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n this.tokenProvider = config.tokenProvider;\n }\n\n private async buildHeaders(method: string): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...this.headers };\n if (this.tokenProvider) {\n const token = await this.tokenProvider.getToken(method);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n return headers;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * If the request fails with a wire-origin `auth_expired` error and a\n * `tokenProvider` is configured, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n try {\n return await this.callOnce<TParams, TResult>(method, params, signal);\n } catch (error) {\n // The auth-expired retry fires for ALL methods, including mutating\n // ones. This is intentional and safe: the server's auth middleware\n // validates the bearer token BEFORE dispatching to the method\n // handler, so an `auth_expired` error means the handler never ran\n // and no state was mutated. Confirmed against btc-vault at\n // `crates/btc-auth/src/middleware/jsonrpc.rs` — token validation\n // is pre-handler only. The `retryableFor` guard on\n // HTTP-transient-error retries doesn't apply here because that\n // guard is about retrying after a request the server may have\n // started processing; auth_expired is categorically different.\n if (this.tokenProvider && isAuthExpiredError(error)) {\n this.tokenProvider.invalidate();\n return await this.callOnce<TParams, TResult>(method, params, signal);\n }\n throw error;\n }\n }\n\n private async callOnce<TParams, TResult>(\n method: string,\n params: TParams,\n signal: AbortSignal | undefined,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(method, params, signal);\n\n let jsonResponse: unknown;\n try {\n const responseText = UNCAPPED_TYPED_RESPONSE_METHODS.has(method)\n ? await response.text()\n : await readResponseTextWithLimit(response, this.maxResponseBytes);\n jsonResponse = JSON.parse(responseText);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n throw error;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n \"local\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n \"local\",\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as {\n code?: number;\n message?: string;\n data?: unknown;\n };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n \"wire\",\n err.data,\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n \"local\",\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n *\n * Bearer tokens are injected identically to `call`. **Reactive refresh\n * is NOT performed here** — the response body may be unbounded (e.g.\n * claimer-artifact downloads), so the client refuses to parse it to\n * detect auth errors. Callers relying on token-expired retries for\n * large downloads must read the body themselves and re-invoke\n * `callRaw` after `tokenProvider.invalidate()`.\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n // Build headers per-attempt so the token provider can return a\n // freshly-acquired bearer after a prior invalidate() on this\n // request (retry loop path) without plumbing state through.\n const headers = await this.buildHeaders(method);\n\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<string> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedContentLength = Number(contentLength);\n if (\n Number.isFinite(parsedContentLength) &&\n parsedContentLength > maxBytes\n ) {\n throw responseTooLargeError(maxBytes);\n }\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let responseText = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw responseTooLargeError(maxBytes);\n }\n responseText += decoder.decode(value, { stream: true });\n }\n } finally {\n reader.releaseLock();\n }\n\n return responseText + decoder.decode();\n}\n\nfunction responseTooLargeError(maxBytes: number): JsonRpcError {\n return new JsonRpcError(\n JSON_RPC_ERROR_CODES.RESPONSE_TOO_LARGE,\n `JSON-RPC response exceeds maximum size of ${maxBytes} bytes`,\n \"local\",\n );\n}\n","/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation\n * -> ActivatedPendingBroadcast -> Activated\n *\n * Branching / terminal states:\n * - Expired: activation timed out; non-terminal during the grace window\n * (RFC 003) — transitions to ExpiredCleanedUp or ExpiredInClaim.\n * - InvalidSigInContract: terminal — pegin input signature posted on\n * chain failed verification.\n * - AmlRejected: terminal — AML address screening rejected the pegin.\n * - ExpiredCleanedUp: terminal — grace window expired, per-pegin\n * artifacts deleted.\n * - ExpiredInClaim: terminal at the pegin-state-machine level; pegout-side\n * work continues on the pegout_tracking row.\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED_PENDING_BROADCAST = \"ActivatedPendingBroadcast\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n INVALID_SIG_IN_CONTRACT = \"InvalidSigInContract\",\n AML_REJECTED = \"AmlRejected\",\n EXPIRED_CLEANED_UP = \"ExpiredCleanedUp\",\n EXPIRED_IN_CLAIM = \"ExpiredInClaim\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED_PENDING_BROADCAST,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses that represent failure outcomes — polling should\n * stop immediately with an error rather than wait for timeout.\n *\n * Mirrors the failure subset of the server-side terminals\n * (`allowed_transitions()` empty, see\n * `btc-vault/crates/vaultd/src/workers/claimer/mod.rs:230-242`).\n * `Activated` IS terminal on-chain but is the success outcome, so it is\n * intentionally excluded — a caller polling for an earlier state that\n * races straight to `Activated` should treat that as success-via-overshoot,\n * not failure. `Expired` is also excluded — under RFC 003 it is a\n * grace-window interim that transitions to `ExpiredCleanedUp` or\n * `ExpiredInClaim`. Callers that want to stop polling on any expiry\n * should check `status === DaemonStatus.EXPIRED ||\n * VP_TERMINAL_FAILURE_STATUSES.has(status)`.\n */\nexport const VP_TERMINAL_FAILURE_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.INVALID_SIG_IN_CONTRACT,\n DaemonStatus.AML_REJECTED,\n DaemonStatus.EXPIRED_CLEANED_UP,\n DaemonStatus.EXPIRED_IN_CLAIM,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for querying pegin status. Either pegin_txid or vault_id must be provided. */\nexport type GetPeginStatusParams =\n | { pegin_txid: string; vault_id?: never }\n | { vault_id: string; pegin_txid?: never };\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatus`. */\nexport interface GetPeginStatusResponse {\n pegin_txid: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/**\n * Claimer-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ClaimerPegoutStatus.\n */\nexport interface ClaimerPegoutStatus {\n /** Wire string from PegoutStatus enum. */\n status: string;\n failed: boolean;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string;\n /** Unix epoch seconds. */\n created_at: number;\n /** Unix epoch seconds. */\n updated_at: number;\n}\n\n/**\n * Challenger-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ChallengerStatus.\n */\nexport interface ChallengerStatus {\n status: string;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string | null;\n challenge_assert_x_txid: string | null;\n challenge_assert_y_txid: string | null;\n nopayout_txid: string | null;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Pegout status response. Embedded by `batchGetPegoutStatus` per-result\n * envelopes. Mirrors btc-vault `GetPegoutStatusResponse`.\n */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer: ClaimerPegoutStatus | null;\n challengers: ChallengerStatus[];\n}\n\n// ============================================================================\n// Batch Status Types (peginStatus + pegoutStatus)\n// ============================================================================\n\n/** Params for `batchGetPeginStatus`. */\nexport interface BatchGetPeginStatusParams {\n /** Up to MAX_BATCH_SIZE (50) txids per call. */\n pegin_txids: string[];\n}\n\n/** Per-pegin entry in a `batchGetPeginStatus` response. */\nexport interface BatchPeginStatusResult {\n pegin_txid: string;\n result: GetPeginStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPeginStatus`. Results are returned in request order. */\nexport interface BatchGetPeginStatusResponse {\n results: BatchPeginStatusResult[];\n}\n\n/** Params for `batchGetPegoutStatus`. */\nexport interface BatchGetPegoutStatusParams {\n pegin_txids: string[];\n}\n\n/** Per-vault entry in a `batchGetPegoutStatus` response. */\nexport interface BatchPegoutStatusResult {\n pegin_txid: string;\n result: GetPegoutStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPegoutStatus`. Results are returned in request order. */\nexport interface BatchGetPegoutStatusResponse {\n results: BatchPegoutStatusResult[];\n}\n\n/**\n * Maximum number of items per batch call. Mirrors the server-side\n * `MAX_BATCH_SIZE` in btc-vault (`crates/vaultd/src/rpc/server/vault_provider.rs:7`).\n * Callers must chunk requests larger than this.\n */\nexport const VP_BATCH_MAX_SIZE = 50;\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * JSON-RPC error codes returned by the vault provider.\n * Source: btc-vault `crates/vaultd/src/rpc/error.rs::RpcError::error_code`.\n */\nexport enum RpcErrorCode {\n PEGIN_NOT_FOUND = 4001,\n}\n"],"names":["JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","DEFAULT_MAX_RESPONSE_BYTES","UNCAPPED_TYPED_RESPONSE_METHODS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","responseText","readResponseTextWithLimit","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","maxBytes","contentLength","parsedContentLength","responseTooLargeError","reader","decoder","totalBytes","done","value","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_FAILURE_STATUSES","POST_WOTS_STATUSES","VP_BATCH_MAX_SIZE","RpcErrorCode"],"mappings":"iLA4FO,MAAMA,UAAqB,KAAM,CACtC,YACSC,EACPC,EAEOC,EAA6B,QAE7BC,EACP,CACA,MAAMF,CAAO,EAPN,KAAA,KAAAD,EAGA,KAAA,OAAAE,EAEA,KAAA,KAAAC,EAGP,KAAK,KAAO,cACd,CACF,CAEO,MAAMC,EAAuB,CAClC,QAAS,MACT,QAAS,OAET,cAAe,OAEf,kBAAmB,OAEnB,iBAAkB,OAElB,mBAAoB,MACtB,EAGMC,EAAmB,MAGnBC,EAAyB,EAGzBC,EAAyB,IAGzBC,EAA6B,EAAI,KAAO,KAMxCC,MAA2D,IAAI,CACnE,gDACF,CAAC,EAGKC,MAAuD,IAAI,CAC/D,IACA,IACA,IACA,IACA,IACA,GACF,CAAC,EAGKC,MAAqD,IAAI,CAC7D,+BACA,oCACA,qCACA,mDACF,CAAC,EAED,SAASC,EAAoBC,EAAyB,CACpD,OAAOF,EAA0B,IAAIE,CAAM,CAC7C,CAYA,MAAM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