Overview
TheCollateralLogic library computes the total value and threshold-weighted value (TWV) of collateral on credit accounts. It supports efficient collateral checks by allowing calculations to stop once a target TWV is reached.
Key Features
- USD-denominated collateral valuation
- Threshold-weighted value (TWV) calculation for liquidation checks
- Quota-aware collateral calculation
- Early termination when target TWV is reached
- Efficient packing/unpacking of quota and liquidation threshold data
Core Functions
calcCollateral
quotedTokens- Array of quoted tokens on the credit accountquotasPacked- Array of packed (quota, LT) values, same order as tokenscreditAccount- Credit account address to compute collateral forunderlying- Underlying token of the credit managerltUnderlying- Liquidation threshold of the underlying tokentwvUSDTarget- Target TWV to stop calculation (usetype(uint256).maxfor full calculation)convertToUSDFn- Function that converts token amounts to USDpriceOracle- Price oracle address for conversions
totalValueUSD- Total value of all account assets in USDtwvUSD- Total threshold-weighted value in USD
If
twvUSDTarget is specified and reached during calculation, the function stops early and returns partial values. This optimization is useful for efficiently checking if an account has sufficient collateral.calcOneTokenCollateral
creditAccount- Address of the credit accountconvertToUSDFn- Function to convert token amounts to USDpriceOracle- Price oracle addresstoken- Token address to valueliquidationThreshold- LT of the token (in basis points)quotaUSD- Quota limit for this token in USD
valueUSD- Full USD value of the token balanceweightedValueUSD- LT-weighted value, capped by quota:min(valueUSD * LT / 10000, quotaUSD)
The weighted value is the minimum of the LT-weighted value and the quota. This ensures that tokens cannot contribute more to TWV than their allocated quota allows.
Packing Functions
packQuota
quota- Quota value (96 bits)lt- Liquidation threshold (16 bits)
unpackQuota
packedQuota- Packed value containing quota and LT
quota- Quota value (lower 96 bits)lt- Liquidation threshold (upper 16 bits)
Packing format:This efficient packing reduces storage costs and gas usage.
How TWV Works
Threshold-weighted value (TWV) is the effective collateral value used for liquidation checks:- Total Value: Raw USD value of all tokens
- Weighted Value:
value * liquidationThreshold / PERCENTAGE_FACTOR - Quota-Capped:
min(weightedValue, quotaUSD) - TWV: Sum of all quota-capped weighted values
TWV < totalDebt
Usage Example
Optimization: Early Termination
By setting
twvUSDTarget to the debt amount, you can quickly verify if an account is solvent without processing all tokens. This optimization is crucial for gas-efficient health checks.Related Libraries
- CreditLogic - Debt and liquidation calculations
- QuotasLogic - Quota interest management
- Constants - Protocol constants including
PERCENTAGE_FACTOR