# Liquidation Math How we calculate the *health factor*: $$ {\sum \text{collateral in ETH}_i \times lendFactor_i \over \sum \text{borrow in ETH}_i \times borrowFactor_i} = healthFactor$$ ### Liquidation scenerio ``` Specs: liquidator discount = 1.05e18 == 0.5%. assetA: price: 1 ETH. lendFactor: 0.5e18. borrowFactor: 0. assetB: price: 2 ETH. lendFactor: 0. borrowFactor: 1e18. ``` 1. User provides `1e18` of `assetA` as collateral. 2. User borrows `0.25e18` of `assetB`. Now user's health factor is `1e18`. 3. The price of assetA drops to `0.9e18`. User's health factor becomes `0.9e18` and is now able to be liquidated. --- How do we create a general formula for the liquidator to calculate the optimal `repayAmount` that will leave the user with a health factor of `1.25e18`? $$ {totalCollateral - (x \times ratio \times \text{collateralAsset in ETH} \times lendFactor) \over totalBorrowed - (x \times \text{borrowAsset in ETH} \times borrowFactor)} = 1.25e18 $$ Let: $a = ratio$ $b = \text{borrowAsset in ETH}$ $c = \text{collateralAsset in ETH}$ $d = borrowFactor$ $e = lendFactor$ 1. $$ {totalCollateral - (xace) \over totalBorrowed - (xbd)} = 1.25e18 $$ 2. $$ totalCollateral - (xace) = 1.25e18 \times (totalBorrowed - xbd) $$ 3. $$ (totalCollateral \times 100) - (xace \times 100) = 125e18 \times (totalBorrowed - xbd) $$ 4. $$ (totalCollateral \times 100) - (xace \times 100) = (125e18 \times totalBorrowed) - (125e18 \times xbd) $$ 5. $$ (-xace \times 100) = (125e18 \times totalBorrowed) - (125e18 \times xbd) - (totalCollateral \times 100) $$ 6. $$ (-xace \times 100) + (125e18 \times xbd) = (125e18 \times totalBorrowed) - (totalCollateral \times 100) $$ 7. $$ 25e18x(-4e18eac + 5e18bd) = (125e18 \times totalBorrowed) - (totalCollateral \times 100) $$ **Solution**: $$ x = {(5e18 \times totalBorrowed) - (4e18 \times totalCollateral) \over (5e18 \times \text{borrowAsset in ETH} \times borrowFactor) - (4e18 \times \text{ratio} \times \text{borrowAsset in ETH} \times borrowFactor)} $$