@babylonlabs-io/ts-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/PayoutManager-9qwA76_B.cjs +2 -0
  2. package/dist/PayoutManager-9qwA76_B.cjs.map +1 -0
  3. package/dist/{PayoutManager-BVmU4UsM.js → PayoutManager-CvWBwdzd.js} +178 -204
  4. package/dist/PayoutManager-CvWBwdzd.js.map +1 -0
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +72 -70
  7. package/dist/index.js.map +1 -1
  8. package/dist/shared/index.cjs +1 -1
  9. package/dist/shared/index.d.ts +1 -0
  10. package/dist/shared/index.d.ts.map +1 -1
  11. package/dist/shared/index.js +5 -3
  12. package/dist/shared/index.js.map +1 -1
  13. package/dist/shared/wallets/__tests__/signOptions.test.d.ts +2 -0
  14. package/dist/shared/wallets/__tests__/signOptions.test.d.ts.map +1 -0
  15. package/dist/shared/wallets/index.d.ts +1 -0
  16. package/dist/shared/wallets/index.d.ts.map +1 -1
  17. package/dist/shared/wallets/signOptions.d.ts +15 -0
  18. package/dist/shared/wallets/signOptions.d.ts.map +1 -0
  19. package/dist/signOptions-Deg5lCoC.cjs +2 -0
  20. package/dist/signOptions-Deg5lCoC.cjs.map +1 -0
  21. package/dist/signOptions-Drwr3bXB.js +16 -0
  22. package/dist/signOptions-Drwr3bXB.js.map +1 -0
  23. package/dist/tbv/core/index.cjs +1 -1
  24. package/dist/tbv/core/index.js +1 -1
  25. package/dist/tbv/core/managers/PayoutManager.d.ts +1 -1
  26. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  27. package/dist/tbv/core/managers/PeginManager.d.ts +1 -2
  28. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  29. package/dist/tbv/index.cjs +1 -1
  30. package/dist/tbv/index.js +1 -1
  31. package/dist/tbv/integrations/aave/clients/abis/{AaveIntegrationController.abi.json.d.ts → AaveIntegrationAdapter.abi.json.d.ts} +39 -2
  32. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  33. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  34. package/dist/tbv/integrations/aave/clients/query.d.ts +3 -3
  35. package/dist/tbv/integrations/aave/clients/transaction.d.ts +19 -7
  36. package/dist/tbv/integrations/aave/clients/transaction.d.ts.map +1 -1
  37. package/dist/tbv/integrations/aave/constants.d.ts +2 -0
  38. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  39. package/dist/tbv/integrations/aave/index.cjs +1 -1
  40. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  41. package/dist/tbv/integrations/aave/index.d.ts +6 -6
  42. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  43. package/dist/tbv/integrations/aave/index.js +141 -94
  44. package/dist/tbv/integrations/aave/index.js.map +1 -1
  45. package/dist/tbv/integrations/aave/types.d.ts +1 -1
  46. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts +5 -0
  47. package/dist/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.d.ts.map +1 -0
  48. package/dist/tbv/integrations/aave/utils/index.d.ts +2 -0
  49. package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
  50. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts +109 -0
  51. package/dist/tbv/integrations/aave/utils/seizureSimulation.d.ts.map +1 -0
  52. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts +1 -0
  53. package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
  54. package/package.json +3 -3
  55. package/dist/PayoutManager-BVmU4UsM.js.map +0 -1
  56. package/dist/PayoutManager-Ba6cNgHC.cjs +0 -2
  57. package/dist/PayoutManager-Ba6cNgHC.cjs.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/vaultSplit.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} 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 * 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 * 0.01% buffer (1 basis point) - the contract only takes what's owed.\n */\nexport const FULL_REPAY_BUFFER_DIVISOR = 10000n; // 1/10000 = 0.01% buffer\n\n/**\n * Mock Core Spoke parameter: Target Health Factor (THF)\n * Per-spoke governance parameter. After liquidation, the protocol targets\n * restoring the position to this health factor.\n *\n * Stored in WAD format — Aave's fixed-point encoding where 1e18 = 1.0.\n * To convert to a plain number: `Number(value) / 1e18`.\n * 1.10 * 1e18 = 1_100_000_000_000_000_000n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_TARGET_HEALTH_FACTOR_WAD = 1_100_000_000_000_000_000n;\n\n/**\n * Mock Core Spoke parameter: Collateral Factor (CF)\n * Determines what fraction of collateral value counts toward borrowing power.\n *\n * Stored in BPS (basis points) — 1 BPS = 0.01%, so 10000 BPS = 100%.\n * To convert to a decimal: `Number(value) / 10000`.\n * 0.75 (75%) * 10000 = 7500n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_COLLATERAL_FACTOR_BPS = 7500n;\n\n/**\n * Mock Core Spoke parameter: Liquidation Bonus (LB)\n * Bonus multiplier awarded to liquidators. Fixed at 1.05 (5% bonus),\n * min = max (no Dutch auction).\n *\n * Stored in WAD format — Aave's fixed-point encoding where 1e18 = 1.0.\n * To convert to a plain number: `Number(value) / 1e18`.\n * 1.05 * 1e18 = 1_050_000_000_000_000_000n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_LIQUIDATION_BONUS_WAD = 1_050_000_000_000_000_000n;\n","/**\n * Aave Integration Controller - 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 } from \"../types.js\";\nimport AaveIntegrationControllerABI from \"./abis/AaveIntegrationController.abi.json\";\n\n/**\n * Get a position by user address.\n *\n * The controller 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 - AaveIntegrationController 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: AaveIntegrationControllerABI,\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 total collateral for a user's position.\n *\n * @param publicClient - Viem public client for reading contracts\n * @param contractAddress - AaveIntegrationController contract address\n * @param user - User's Ethereum address\n * @returns Total collateral amount in satoshis\n */\nexport async function getPositionCollateral(\n publicClient: PublicClient,\n contractAddress: Address,\n user: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationControllerABI,\n functionName: \"getPositionCollateral\",\n args: [user],\n });\n\n return result as bigint;\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 * - realizedPremiumRay > 0 (realized interest)\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 (\n position.drawnShares > 0n ||\n position.premiumShares > 0n ||\n position.realizedPremiumRay > 0n\n );\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 {\n MOCK_COLLATERAL_FACTOR_BPS,\n MOCK_LIQUIDATION_BONUS_WAD,\n MOCK_TARGET_HEALTH_FACTOR_WAD,\n} from \"../constants.js\";\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 totalDebtValue: bigint;\n activeCollateralCount: bigint;\n borrowedCount: bigint;\n};\n\n/** Position result type from contract */\ntype PositionResult = {\n drawnShares: bigint;\n premiumShares: bigint;\n realizedPremiumRay: 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 realizedPremiumRay: result.realizedPremiumRay,\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.totalDebtValue);\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 * - `totalDebtValue` - USD value in base currency (1e26 = $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 totalDebtValue: data.totalDebtValue,\n activeCollateralCount: data.activeCollateralCount,\n borrowedCount: data.borrowedCount,\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/**\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 (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Target health factor in WAD (1e18 = 1.0). Example: 1.10 = 1_100_000_000_000_000_000n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getTargetHealthFactor(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_TARGET_HEALTH_FACTOR_WAD;\n}\n\n/**\n * Get the collateral factor (CF) from the Core Spoke contract.\n *\n * Determines what fraction of collateral value counts toward borrowing power.\n * Default is 75% (7500 BPS), configurable per spoke.\n *\n * @param _publicClient - Viem public client (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Collateral factor in BPS (10000 = 100%). Example: 0.75 = 7500n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getCollateralFactor(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_COLLATERAL_FACTOR_BPS;\n}\n\n/**\n * Get the liquidation bonus (LB) from the Core Spoke contract.\n *\n * The bonus multiplier awarded to liquidators. Fixed at 1.05 (5% bonus)\n * with min = max (no Dutch auction).\n *\n * @param _publicClient - Viem public client (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Liquidation bonus in WAD (1e18 = 1.0). Example: 1.05 = 1_050_000_000_000_000_000n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getLiquidationBonus(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_LIQUIDATION_BONUS_WAD;\n}\n","/**\n * Aave Integration Controller - Transaction builders\n *\n * Provides transaction builders for the AaveIntegrationController 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 AaveIntegrationControllerABI from \"./abis/AaveIntegrationController.abi.json\";\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 - AaveIntegrationController 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: AaveIntegrationControllerABI,\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 - AaveIntegrationController 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...\", // Controller 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: AaveIntegrationControllerABI,\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 controller to spend debt token first.\n * Repays borrowed assets (partial or full repayment supported).\n *\n * @param contractAddress - AaveIntegrationController 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_CONTROLLER,\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 controller (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: AaveIntegrationControllerABI,\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 { AAVE_BASE_CURRENCY_DECIMALS, WAD_DECIMALS } from \"../constants.js\";\n\n/**\n * Convert Aave base currency value to USD\n *\n * Aave uses 1e26 = $1 USD for collateral and debt 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 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 * Color mapping:\n * - Green (#00E676): safe\n * - Amber (#FFC400): warning\n * - Red (#FF1744): danger\n * - Gray (#5A5A5A): no_debt\n */\n\nimport { BPS_SCALE, HEALTH_FACTOR_WARNING_THRESHOLD } from \"../constants.js\";\n\nexport const HEALTH_FACTOR_COLORS = {\n GREEN: \"#00E676\",\n AMBER: \"#FFC400\",\n RED: \"#FF1744\",\n GRAY: \"#5A5A5A\",\n} as const;\n\nexport type HealthFactorColor =\n (typeof HEALTH_FACTOR_COLORS)[keyof typeof HEALTH_FACTOR_COLORS];\n\n/**\n * Health factor status based on our liquidation threshold\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 * Gets the appropriate color for a health factor status.\n *\n * @param status - The health factor status\n * @returns The color code for the status\n */\nexport function getHealthFactorColor(\n status: HealthFactorStatus,\n): HealthFactorColor {\n switch (status) {\n case \"safe\":\n return HEALTH_FACTOR_COLORS.GREEN;\n case \"warning\":\n return HEALTH_FACTOR_COLORS.AMBER;\n case \"danger\":\n return HEALTH_FACTOR_COLORS.RED;\n case \"no_debt\":\n return HEALTH_FACTOR_COLORS.GRAY;\n }\n}\n\n/**\n * Format health factor number for display\n *\n * @param healthFactor - Health factor number (null if no debt)\n * @returns Formatted string for display\n */\nexport function formatHealthFactor(healthFactor: number | null): string {\n if (healthFactor === null) {\n return \"-\"; // No debt\n }\n return healthFactor.toFixed(2);\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 * 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\nfunction 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 *\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 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 // HF ≤ 0 means position is fully underwater — full seizure\n if (expectedHF <= 0) {\n return 1;\n }\n\n const liqPenalty = LB * CF;\n\n // If THF <= liq_penalty, full liquidation is inevitable\n if (THF <= liqPenalty) {\n return 1;\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 seizedFraction =\n (CF * (THF - expectedHF)) / (THF - liqPenalty) * (LB / expectedHF);\n\n return Math.max(0, Math.min(1, 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 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"],"names":["AAVE_FUNCTION_NAMES","BTC_DECIMALS","USDC_DECIMALS","BPS_TO_PERCENT_DIVISOR","BPS_SCALE","AAVE_BASE_CURRENCY_DECIMALS","WAD_DECIMALS","HEALTH_FACTOR_WARNING_THRESHOLD","MIN_HEALTH_FACTOR_FOR_BORROW","FULL_REPAY_BUFFER_DIVISOR","MOCK_TARGET_HEALTH_FACTOR_WAD","MOCK_COLLATERAL_FACTOR_BPS","MOCK_LIQUIDATION_BONUS_WAD","getPosition","publicClient","contractAddress","user","position","AaveIntegrationControllerABI","zeroAddress","getPositionCollateral","hasDebtFromPosition","mapPositionResult","result","getUserAccountData","spokeAddress","userAddress","data","AaveSpokeABI","getUserPosition","reserveId","hasDebt","hasCollateral","getUserTotalDebt","getTargetHealthFactor","_publicClient","_spokeAddress","getCollateralFactor","getLiquidationBonus","buildWithdrawCollateralsTx","vaultIds","encodeFunctionData","buildBorrowTx","debtReserveId","amount","receiver","buildRepayTx","borrower","aaveValueToUsd","value","wadToNumber","calculateBorrowRatio","debtUsd","collateralValueUsd","HEALTH_FACTOR_COLORS","getHealthFactorStatus","healthFactor","getHealthFactorColor","status","formatHealthFactor","isHealthFactorHealthy","getHealthFactorStatusFromValue","calculateHealthFactor","totalDebtUsd","liquidationThresholdBps","selectVaultsForAmount","vaults","targetAmount","sortedVaults","a","b","selectedIds","selectedAmount","vault","calculateTotalVaultAmount","sum","MAX_SAFE_BIGINT","assertSafePrecision","name","computeSeizedFraction","CF","LB","THF","expectedHF","liqPenalty","seizedFraction","computeOptimalSplit","params","totalBtc","safetyMargin","totalBtcNum","targetSeizureBtc","sacrificialRaw","sacrificialVault","protectedVault","computeMinDepositForSplit","minPegin","sacrificialShare","protectedShare","minFromProtected","minFromSacrificial","checkRebalanceNeeded","vaultAmounts","v","targetCoverage","currentCoverage","deficit"],"mappings":";AAWO,MAAMA,IAAsB;AAAA;AAAA,EAEjC,sBAAsB;AAAA;AAAA,EAEtB,QAAQ;AAAA;AAAA,EAER,OAAO;AACT,GAMaC,IAAe,GAMfC,IAAgB,GAahBC,IAAyB,KAQzBC,IAAY,KAQZC,IAA8B,IAQ9BC,IAAe,IAMfC,IAAkC,KAMlCC,IAA+B,KAO/BC,IAA4B,QAa5BC,IAAgC,sBAYhCC,IAA6B,OAa7BC,IAA6B;AClG1C,eAAsBC,EACpBC,GACAC,GACAC,GACoC;AAapC,QAAMC,IAZS,MAAMH,EAAa,aAAa;AAAA,IAC7C,SAASC;AAAA,IACT,KAAKG;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAACF,CAAI;AAAA,EAAA,CACZ;AAUD,SAAIC,EAAS,kBAAkBE,IACtB,OAGF;AAAA,IACL,eAAeF,EAAS;AAAA,IACxB,UAAUA,EAAS;AAAA,EAAA;AAEvB;AAUA,eAAsBG,EACpBN,GACAC,GACAC,GACiB;AAQjB,SAPe,MAAMF,EAAa,aAAa;AAAA,IAC7C,SAASC;AAAA,IACT,KAAKG;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAACF,CAAI;AAAA,EAAA,CACZ;AAGH;AC1DO,SAASK,EAAoBJ,GAA0C;AAC5E,SACEA,EAAS,cAAc,MACvBA,EAAS,gBAAgB,MACzBA,EAAS,qBAAqB;AAElC;;ACuBA,SAASK,EAAkBC,GAA+C;AACxE,SAA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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/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 * 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 * 0.01% buffer (1 basis point) - the contract only takes what's owed.\n */\nexport const FULL_REPAY_BUFFER_DIVISOR = 10000n; // 1/10000 = 0.01% buffer\n\n/**\n * Mock Core Spoke parameter: Target Health Factor (THF)\n * Per-spoke governance parameter. After liquidation, the protocol targets\n * restoring the position to this health factor.\n *\n * Stored in WAD format — Aave's fixed-point encoding where 1e18 = 1.0.\n * To convert to a plain number: `Number(value) / 1e18`.\n * 1.10 * 1e18 = 1_100_000_000_000_000_000n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_TARGET_HEALTH_FACTOR_WAD = 1_100_000_000_000_000_000n;\n\n/**\n * Mock Core Spoke parameter: Collateral Factor (CF)\n * Determines what fraction of collateral value counts toward borrowing power.\n *\n * Stored in BPS (basis points) — 1 BPS = 0.01%, so 10000 BPS = 100%.\n * To convert to a decimal: `Number(value) / 10000`.\n * 0.75 (75%) * 10000 = 7500n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_COLLATERAL_FACTOR_BPS = 7500n;\n\n/**\n * Mock Core Spoke parameter: Liquidation Bonus (LB)\n * Bonus multiplier awarded to liquidators. Fixed at 1.05 (5% bonus),\n * min = max (no Dutch auction).\n *\n * Stored in WAD format — Aave's fixed-point encoding where 1e18 = 1.0.\n * To convert to a plain number: `Number(value) / 1e18`.\n * 1.05 * 1e18 = 1_050_000_000_000_000_000n\n *\n * TODO: Replace with real contract read when Core Spoke ABI is available\n */\nexport const MOCK_LIQUIDATION_BONUS_WAD = 1_050_000_000_000_000_000n;\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 } 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 total collateral for a user's position.\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 Total collateral amount in satoshis\n */\nexport async function getPositionCollateral(\n publicClient: PublicClient,\n contractAddress: Address,\n user: Address,\n): Promise<bigint> {\n const result = await publicClient.readContract({\n address: contractAddress,\n abi: AaveIntegrationAdapterABI,\n functionName: \"getPositionCollateral\",\n args: [user],\n });\n\n return result as bigint;\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 * - realizedPremiumRay > 0 (realized interest)\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 (\n position.drawnShares > 0n ||\n position.premiumShares > 0n ||\n position.realizedPremiumRay > 0n\n );\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 {\n MOCK_COLLATERAL_FACTOR_BPS,\n MOCK_LIQUIDATION_BONUS_WAD,\n MOCK_TARGET_HEALTH_FACTOR_WAD,\n} from \"../constants.js\";\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 totalDebtValue: bigint;\n activeCollateralCount: bigint;\n borrowedCount: bigint;\n};\n\n/** Position result type from contract */\ntype PositionResult = {\n drawnShares: bigint;\n premiumShares: bigint;\n realizedPremiumRay: 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 realizedPremiumRay: result.realizedPremiumRay,\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.totalDebtValue);\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 * - `totalDebtValue` - USD value in base currency (1e26 = $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 totalDebtValue: data.totalDebtValue,\n activeCollateralCount: data.activeCollateralCount,\n borrowedCount: data.borrowedCount,\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/**\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 (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Target health factor in WAD (1e18 = 1.0). Example: 1.10 = 1_100_000_000_000_000_000n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getTargetHealthFactor(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_TARGET_HEALTH_FACTOR_WAD;\n}\n\n/**\n * Get the collateral factor (CF) from the Core Spoke contract.\n *\n * Determines what fraction of collateral value counts toward borrowing power.\n * Default is 75% (7500 BPS), configurable per spoke.\n *\n * @param _publicClient - Viem public client (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Collateral factor in BPS (10000 = 100%). Example: 0.75 = 7500n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getCollateralFactor(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_COLLATERAL_FACTOR_BPS;\n}\n\n/**\n * Get the liquidation bonus (LB) from the Core Spoke contract.\n *\n * The bonus multiplier awarded to liquidators. Fixed at 1.05 (5% bonus)\n * with min = max (no Dutch auction).\n *\n * @param _publicClient - Viem public client (unused in mock, required for API stability)\n * @param _spokeAddress - Core Spoke contract address (unused in mock, required for API stability)\n * @returns Liquidation bonus in WAD (1e18 = 1.0). Example: 1.05 = 1_050_000_000_000_000_000n\n *\n * TODO: Replace mock with real contract read when Core Spoke ABI is available\n */\nexport async function getLiquidationBonus(\n _publicClient: PublicClient,\n _spokeAddress: Address,\n): Promise<bigint> {\n return MOCK_LIQUIDATION_BONUS_WAD;\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 { AAVE_BASE_CURRENCY_DECIMALS, WAD_DECIMALS } from \"../constants.js\";\n\n/**\n * Convert Aave base currency value to USD\n *\n * Aave uses 1e26 = $1 USD for collateral and debt 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 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 * Color mapping:\n * - Green (#00E676): safe\n * - Amber (#FFC400): warning\n * - Red (#FF1744): danger\n * - Gray (#5A5A5A): no_debt\n */\n\nimport { BPS_SCALE, HEALTH_FACTOR_WARNING_THRESHOLD } from \"../constants.js\";\n\nexport const HEALTH_FACTOR_COLORS = {\n GREEN: \"#00E676\",\n AMBER: \"#FFC400\",\n RED: \"#FF1744\",\n GRAY: \"#5A5A5A\",\n} as const;\n\nexport type HealthFactorColor =\n (typeof HEALTH_FACTOR_COLORS)[keyof typeof HEALTH_FACTOR_COLORS];\n\n/**\n * Health factor status based on our liquidation threshold\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 * Gets the appropriate color for a health factor status.\n *\n * @param status - The health factor status\n * @returns The color code for the status\n */\nexport function getHealthFactorColor(\n status: HealthFactorStatus,\n): HealthFactorColor {\n switch (status) {\n case \"safe\":\n return HEALTH_FACTOR_COLORS.GREEN;\n case \"warning\":\n return HEALTH_FACTOR_COLORS.AMBER;\n case \"danger\":\n return HEALTH_FACTOR_COLORS.RED;\n case \"no_debt\":\n return HEALTH_FACTOR_COLORS.GRAY;\n }\n}\n\n/**\n * Format health factor number for display\n *\n * @param healthFactor - Health factor number (null if no debt)\n * @returns Formatted string for display\n */\nexport function formatHealthFactor(healthFactor: number | null): string {\n if (healthFactor === null) {\n return \"-\"; // No debt\n }\n return healthFactor.toFixed(2);\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 * 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\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 *\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 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 // HF ≤ 0 means position is fully underwater — full seizure\n if (expectedHF <= 0) {\n return 1;\n }\n\n const liqPenalty = LB * CF;\n\n // If THF <= liq_penalty, full liquidation is inevitable\n if (THF <= liqPenalty) {\n return 1;\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 seizedFraction =\n (CF * (THF - expectedHF)) / (THF - liqPenalty) * (LB / expectedHF);\n\n return Math.max(0, Math.min(1, 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 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","WAD_DECIMALS","HEALTH_FACTOR_WARNING_THRESHOLD","MIN_HEALTH_FACTOR_FOR_BORROW","FULL_REPAY_BUFFER_DIVISOR","MOCK_TARGET_HEALTH_FACTOR_WAD","MOCK_COLLATERAL_FACTOR_BPS","MOCK_LIQUIDATION_BONUS_WAD","getPosition","publicClient","contractAddress","user","position","AaveIntegrationAdapterABI","zeroAddress","getPositionCollateral","hasDebtFromPosition","mapPositionResult","result","getUserAccountData","spokeAddress","userAddress","data","AaveSpokeABI","getUserPosition","reserveId","hasDebt","hasCollateral","getUserTotalDebt","getTargetHealthFactor","_publicClient","_spokeAddress","getCollateralFactor","getLiquidationBonus","buildReorderVaultsTx","permutedVaultIds","encodeFunctionData","buildWithdrawCollateralsTx","vaultIds","buildBorrowTx","debtReserveId","amount","receiver","buildRepayTx","borrower","aaveValueToUsd","value","wadToNumber","calculateBorrowRatio","debtUsd","collateralValueUsd","HEALTH_FACTOR_COLORS","getHealthFactorStatus","healthFactor","getHealthFactorColor","status","formatHealthFactor","isHealthFactorHealthy","getHealthFactorStatusFromValue","calculateHealthFactor","totalDebtUsd","liquidationThresholdBps","selectVaultsForAmount","vaults","targetAmount","sortedVaults","a","b","selectedIds","selectedAmount","vault","calculateTotalVaultAmount","sum","MAX_SAFE_BIGINT","assertSafePrecision","name","computeSeizedFraction","CF","LB","THF","expectedHF","liqPenalty","seizedFraction","computeOptimalSplit","params","totalBtc","safetyMargin","totalBtcNum","targetSeizureBtc","sacrificialRaw","sacrificialVault","protectedVault","computeMinDepositForSplit","minPegin","sacrificialShare","protectedShare","minFromProtected","minFromSacrificial","checkRebalanceNeeded","vaultAmounts","v","targetCoverage","currentCoverage","deficit","computeTargetSeizureSats","totalCollateralSats","simulatePrefixSeizure","orderedVaults","targetSeizureSats","accumulated","cutoffIndex","i","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,IAAgB,GAahBC,IAAyB,KAQzBC,IAAY,KAQZC,IAA8B,IAQ9BC,IAAe,IAMfC,IAAkC,KAMlCC,IAA+B,KAO/BC,IAA4B,QAa5BC,IAAgC,sBAYhCC,IAA6B,OAa7BC,IAA6B;ACpG1C,eAAsBC,EACpBC,GACAC,GACAC,GACoC;AAapC,QAAMC,IAZS,MAAMH,EAAa,aAAa;AAAA,IAC7C,SAASC;AAAA,IACT,KAAKG;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAACF,CAAI;AAAA,EAAA,CACZ;AAUD,SAAIC,EAAS,kBAAkBE,IACtB,OAGF;AAAA,IACL,eAAeF,EAAS;AAAA,IACxB,UAAUA,EAAS;AAAA,EAAA;AAEvB;AAUA,eAAsBG,EACpBN,GACAC,GACAC,GACiB;AAQjB,SAPe,MAAMF,EAAa,aAAa;AAAA,IAC7C,SAASC;AAAA,IACT,KAAKG;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAACF,CAAI;AAAA,EAAA,CACZ;AAGH;AC1DO,SAASK,EAAoBJ,GAA0C;AAC5E,SACEA,EAAS,cAAc,MACvBA,EAAS,gBAAgB,MACzBA,EAAS,qBAAqB;AAElC;;ACuBA,SAASK,EAAkBC,GAA+C;AACxE,SAAO;AAAA,IACL,aAAaA,EAAO;AAAA,IACpB,eAAeA,EAAO;AAAA,IACtB,oBAAoBA,EAAO;AAAA,IAC3B,kBAAkBA,EAAO;AAAA,IACzB,gBAAgBA,EAAO;AAAA,IACvB,kBAAkBA,EAAO;AAA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AAAA,EAAA;AAEJ;AChPO,SAASG,GACdpB,GACQ;AACR,QAAM,EAAE,qBAAAqB,GAAqB,IAAA5B,GAAI,IAAAC,GAAI,KAAAC,GAAK,YAAAC,MAAeI;AAEzD,MAAIqB,KAAuB;AACzB,WAAO;AAGT,EAAA/B,EAAoB+B,GAAqB,qBAAqB;AAE9D,QAAMvB,IAAiBN,EAAsBC,GAAIC,GAAIC,GAAKC,CAAU;AAEpE,SAAO,OAAO,KAAK,KAAK,OAAOyB,CAAmB,IAAIvB,CAAc,CAAC;AACvE;AA6BO,SAASwB,GACdtB,GACqB;AACrB,QAAM,EAAE,eAAAuB,GAAe,mBAAAC,EAAA,IAAsBxB;AAE7C,MAAIuB,EAAc,WAAW;AAC3B,UAAM,IAAI,MAAM,iCAAiC;AAGnD,MAAIC,KAAqB;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAIC,IAAc,IACdC,IAAcH,EAAc;AAEhC,WAASI,IAAI,GAAGA,IAAIJ,EAAc,QAAQI;AAGxC,QAFAF,KAAeF,EAAcI,CAAC,EAAE,YAE5BF,KAAeD,GAAmB;AACpC,MAAAE,IAAcC,IAAI;AAClB;AAAA,IACF;AAGF,QAAMC,IAAeL,EAAc,MAAM,GAAGG,CAAW,GACjDG,IAAkBN,EAAc,MAAMG,CAAW,GACjDI,IAAkBL,GAClBM,IACJD,IAAkBN,IACdM,IAAkBN,IAClB;AAEN,SAAO;AAAA,IACL,cAAAI;AAAA,IACA,iBAAAC;AAAA,IACA,iBAAAE;AAAA,IACA,aAAAL;AAAA,IACA,iBAAAI;AAAA,EAAA;AAEJ;"}
@@ -8,7 +8,7 @@ export interface DepositorStruct {
8
8
  }
9
9
  /**
10
10
  * Aave position structure from the contract.
11
- * The controller resolves the user's proxy and vaults from their address.
11
+ * The adapter resolves the user's proxy and vaults from their address.
12
12
  */
13
13
  export interface AaveMarketPosition {
14
14
  proxyContract: Address;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Tests for seizure simulation utilities
3
+ */
4
+ export {};
5
+ //# sourceMappingURL=seizureSimulation.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seizureSimulation.test.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/integrations/aave/utils/__tests__/seizureSimulation.test.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -5,6 +5,8 @@ export { HEALTH_FACTOR_COLORS, calculateHealthFactor, formatHealthFactor, getHea
5
5
  export type { HealthFactorColor, HealthFactorStatus } from './healthFactor.js';
6
6
  export { calculateTotalVaultAmount, selectVaultsForAmount, } from './vaultSelection.js';
7
7
  export type { SelectableVault, VaultSelectionResult, } from './vaultSelection.js';
8
+ export { computeTargetSeizureSats, simulatePrefixSeizure, } from './seizureSimulation.js';
9
+ export type { OrderedVault, PrefixSeizureParams, PrefixSeizureResult, TargetSeizureParams, } from './seizureSimulation.js';
8
10
  export { checkRebalanceNeeded, computeMinDepositForSplit, computeOptimalSplit, computeSeizedFraction, } from './vaultSplit.js';
9
11
  export type { MinDepositForSplitParams, OptimalSplitParams, OptimalSplitResult, RebalanceCheckParams, RebalanceCheckResult, } from './vaultSplit.js';
10
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,eAAe,EACf,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,wBAAwB,EACxB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,eAAe,EACf,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,wBAAwB,EACxB,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Seizure Simulation Utilities
3
+ *
4
+ * Simulates which vaults would be seized during Aave liquidation.
5
+ * Vaults are seized in prefix order (index 0, 1, 2, ...) until the
6
+ * target seizure amount is covered.
7
+ *
8
+ * Reference: Aave v4 Section 4.2 — liquidation seizes a prefix of the
9
+ * borrower's ordered vault list.
10
+ */
11
+ /**
12
+ * A vault with its on-chain ID and BTC amount, in liquidation-priority order.
13
+ */
14
+ export interface OrderedVault {
15
+ /** On-chain vault ID (bytes32 hex string) */
16
+ id: string;
17
+ /** Vault amount in satoshis */
18
+ amountSats: bigint;
19
+ }
20
+ /**
21
+ * Parameters for simulating prefix seizure.
22
+ */
23
+ export interface PrefixSeizureParams {
24
+ /** Vaults in their current on-chain order (index 0 is seized first) */
25
+ orderedVaults: OrderedVault[];
26
+ /** Target seizure amount in satoshis */
27
+ targetSeizureSats: bigint;
28
+ }
29
+ /**
30
+ * Result of a prefix seizure simulation.
31
+ */
32
+ export interface PrefixSeizureResult {
33
+ /** Vaults that would be seized (the prefix) */
34
+ seizedVaults: OrderedVault[];
35
+ /** Vaults that survive liquidation */
36
+ protectedVaults: OrderedVault[];
37
+ /** Over-seizure amount in satoshis (total seized - target) */
38
+ overSeizureSats: bigint;
39
+ /** Index where seizure stops (exclusive: vaults[0..cutoffIndex] are seized) */
40
+ cutoffIndex: number;
41
+ /** Total amount seized in satoshis */
42
+ totalSeizedSats: bigint;
43
+ }
44
+ /**
45
+ * Parameters for computing target seizure in satoshis.
46
+ */
47
+ export interface TargetSeizureParams {
48
+ /** Total collateral in satoshis */
49
+ totalCollateralSats: bigint;
50
+ /** Collateral factor (e.g. 0.75) */
51
+ CF: number;
52
+ /** Liquidation bonus (e.g. 1.05) */
53
+ LB: number;
54
+ /** Target health factor (e.g. 1.10) */
55
+ THF: number;
56
+ /** Expected health factor at liquidation (e.g. 0.95) */
57
+ expectedHF: number;
58
+ }
59
+ /**
60
+ * Compute the target seizure amount in satoshis.
61
+ *
62
+ * Uses `computeSeizedFraction` to determine what fraction of total collateral
63
+ * would be seized, then converts to an absolute satoshi amount.
64
+ *
65
+ * @param params - Total collateral and risk parameters
66
+ * @returns Target seizure amount in satoshis (rounded up)
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * const targetSats = computeTargetSeizureSats({
71
+ * totalCollateralSats: 1_000_000_000n, // 10 BTC
72
+ * CF: 0.75,
73
+ * LB: 1.05,
74
+ * THF: 1.10,
75
+ * expectedHF: 0.95,
76
+ * });
77
+ * // targetSats ≈ 398_000_000n (3.98 BTC)
78
+ * ```
79
+ */
80
+ export declare function computeTargetSeizureSats(params: TargetSeizureParams): bigint;
81
+ /**
82
+ * Simulate prefix seizure for a given set of ordered vaults.
83
+ *
84
+ * Walks the ordered vault list, accumulating amounts until the target
85
+ * seizure is covered. Returns which vaults are seized vs protected,
86
+ * the over-seizure amount, and the cutoff index.
87
+ *
88
+ * @param params - Ordered vaults and target seizure amount
89
+ * @returns Seizure simulation result
90
+ * @throws Error if orderedVaults is empty
91
+ * @throws Error if targetSeizureSats is <= 0
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const result = simulatePrefixSeizure({
96
+ * orderedVaults: [
97
+ * { id: "0xabc...", amountSats: 200_000_000n },
98
+ * { id: "0xdef...", amountSats: 300_000_000n },
99
+ * { id: "0x123...", amountSats: 500_000_000n },
100
+ * ],
101
+ * targetSeizureSats: 400_000_000n,
102
+ * });
103
+ * // result.seizedVaults = first 2 vaults (200M + 300M = 500M >= 400M)
104
+ * // result.overSeizureSats = 100_000_000n
105
+ * // result.cutoffIndex = 2
106
+ * ```
107
+ */
108
+ export declare function simulatePrefixSeizure(params: PrefixSeizureParams): PrefixSeizureResult;
109
+ //# sourceMappingURL=seizureSimulation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seizureSimulation.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/seizureSimulation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,6CAA6C;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,+BAA+B;IAC/B,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,uEAAuE;IACvE,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,wCAAwC;IACxC,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,+CAA+C;IAC/C,YAAY,EAAE,YAAY,EAAE,CAAC;IAC7B,sCAAsC;IACtC,eAAe,EAAE,YAAY,EAAE,CAAC;IAChC,8DAA8D;IAC9D,eAAe,EAAE,MAAM,CAAC;IACxB,+EAA+E;IAC/E,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,mCAAmC;IACnC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,mBAAmB,GAC1B,MAAM,CAYR;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,mBAAmB,GAC1B,mBAAmB,CAwCrB"}
@@ -17,6 +17,7 @@
17
17
  * target_seizure = debt_to_repay × LB
18
18
  * ```
19
19
  */
20
+ export declare function assertSafePrecision(value: bigint, name: string): void;
20
21
  /**
21
22
  * Parameters for computing the optimal vault split.
22
23
  */
@@ -1 +1 @@
1
- {"version":3,"file":"vaultSplit.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/vaultSplit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAYH;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,iDAAiD;IACjD,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,mFAAmF;IACnF,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,mEAAmE;IACnE,gBAAgB,EAAE,MAAM,CAAC;IACzB,yEAAyE;IACzE,cAAc,EAAE,MAAM,CAAC;IACvB,wDAAwD;IACxD,cAAc,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,+EAA+E;IAC/E,cAAc,EAAE,MAAM,CAAC;IACvB,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,iEAAiE;IACjE,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,0DAA0D;IAC1D,cAAc,EAAE,OAAO,CAAC;IACxB,wFAAwF;IACxF,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,eAAe,EAAE,MAAM,CAAC;IACxB,sDAAsD;IACtD,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GACjB,MAAM,CAmBR;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,kBAAkB,GACzB,kBAAkB,CAgCpB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,wBAAwB,GAC/B,MAAM,CAyBR;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,oBAAoB,GAC3B,oBAAoB,CA+BtB"}
1
+ {"version":3,"file":"vaultSplit.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/vaultSplit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAMrE;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,iDAAiD;IACjD,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,mFAAmF;IACnF,YAAY,EAAE,MAAM,CAAC;CACtB;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;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,wBAAwB,GAC/B,MAAM,CAyBR;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,oBAAoB,GAC3B,oBAAoB,CA+BtB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonlabs-io/ts-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -62,10 +62,10 @@
62
62
  "license": "ISC",
63
63
  "description": "TypeScript SDK for Babylon protocol integrations",
64
64
  "dependencies": {
65
- "@babylonlabs-io/babylon-tbv-rust-wasm": "0.4.0",
66
65
  "@bitcoin-js/tiny-secp256k1-asmjs": "2.2.3",
67
66
  "bitcoinjs-lib": "6.1.7",
68
- "buffer": "6.0.3"
67
+ "buffer": "6.0.3",
68
+ "@babylonlabs-io/babylon-tbv-rust-wasm": "0.1.0"
69
69
  },
70
70
  "peerDependencies": {
71
71
  "viem": "^2.38.2"