> For the complete documentation index, see [llms.txt](https://naviprotocol.gitbook.io/navi-protocol-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://naviprotocol.gitbook.io/navi-protocol-docs/~/revisions/U2pBja6jMjj75mDWWNRp/developers-docs/liquidation-mechanics-and-walkthrough.md).

# Liquidation Mechanics & Walkthrough

The health of NAVI Protocol depends on the health of the loans within the system, measured by the Health Factor. When an account’s health factor falls below 1, anyone can call <mark style="color:$primary;">`execute_liquidation`</mark> on the `LendingPool` contract. This repays part of the debt and grants discounted collateral to the liquidator.

This mechanism aligns incentives, encouraging third parties to maintain the protocol’s safety while earning a bonus.

### Ways to Participate in Liquidations

1. Direct Calls: Call <mark style="color:$primary;">`execute_liquidation`</mark> on the LendingPool contract.
2. Automated Bots: Create a system to monitor accounts and liquidate loans automatically.

> Note: Profitable liquidation requires factoring in gas costs. High gas fees can make a liquidation unprofitable. See [*Calculating Profitability vs Gas Cost*](#calculating-profitability-vs-gas-cost) below.

## Prerequisites

When making a <mark style="color:$primary;">`execute_liquidation`</mark> call,  you must:

* Know the account (i.e. the Sui address: `user`) whose health factor is below 1.
* Know the valid debt amount (`debt_to_cover`) and debt asset (`debt`) that can be paid.
  * The close factor is 0.35, which means that only a maximum of 35% of the debt can be liquidated per valid `execute_liquidation`.
  * You can set the `debt_to_cover` to `uint(-1)` and the protocol will proceed with the highest possible liquidation allowed by the close factor.
  * You must already have a sufficient balance of the debt asset, which will be used by the `execute_liquidation` to pay back the debts.
* Know the collateral asset (`collateral`) you are closing. I.e. the collateral asset that the user has 'backing' their outstanding loan that you will partly receive as a 'bonus'.

## 1. Getting accounts to liquidate

Only accounts with health factor < 1 are eligible.

* On-Chain Monitoring:
  * Track protocol events (deposit, repay, borrow, etc.) to maintain an up-to-date local index of user accounts.
  * Call `get_user_account_data` with a user’s address to read their current `health factor`. If the `health_factor` is below 1, then the account can be liquidated.

> *“Users” in NAVI Protocol refers to a single Sui address interacting with the protocol (EOA or contract).*

## 2. Executing the liquidation call

* Calculate the amount of collateral that can be liquidated:

  * Call `get_user_reserve_data` on the LendingPool Lens contract.
  * Maximum liquidation is limited by the close factor (0.35).

    \
    $$debtToCover =  userVariableDebt \* LiquidationCloseFactorPercent$$

* For reserves with `usage_as_collateral_enabled = true`:
  * Use `current_atoken_balance` and `current_liquidation_bonus` to determine the maximum collateral receivable.

    \
    $$maxAmountOfCollateralToLiquidate = (debtAssetPrice \* currentATokenBalance \* liquidationBonus)/ collateralPrice$$

Once you have the account(s) to liquidate, you will need to calculate the amount of collateral that *can* be liquidated:

1. Use `get_user_reserve_data` on the Lending Pool Lens contract with the relevant parameters.
2. Max debt that can be cleared by single liquidation call is given by the current close factor (which is 0.35 currently).\
   For reserves that have `usage_as_collateral_enabled` as `true`, the `current_atoken_balance` and the current [liquidation bonus](/navi-protocol-docs/~/revisions/U2pBja6jMjj75mDWWNRp/protocol-parameters/lending-and-borrowing.md) gives the max amount of collateral that can be liquidated <br>

## 3. Setting up a bot

Depending on your environment, preferred programming tools and languages, your bot should:

* Ensure it has enough (or access to enough) funds when liquidating.
* Calculate the profitability of liquidating loans vs gas costs, taking into account the most lucrative collateral to liquidate.
* Ensure it has access to the latest protocol user data.
* Have the usual fail safes and security you'd expect for any production service.

### Calculating profitability vs gas cost

One way to calculate the profitability is the following:

1. Store and retrieve each collateral's relevant details such as address, decimals used, and liquidation bonus as listed here.
2. Get the user's collateral balance (n`TokenBalance`).
3. Get the asset's price according to the Navi's [oracle contract](notion://www.notion.so/developers/the-core-protocol/price-oracle) (`getAssetPrice()`).
4. The maximum collateral bonus you can receive will be the collateral balance (2) multiplied by the liquidation bonus (1) multiplied by the collateral asset's price in Sui (3). Note that for assets such as USDC, the number of decimals are different from other assets.
5. The maximum cost of your transaction will be your gas price multiplied by the amount of gas used. You should be able to get a good estimation of the gas amount used by calling `estimateGas` via your web3 provider.
6. Your approximate profit will be the value of the collateral bonus (4) minus the cost of your transaction (5).

### **Example Liquidation Scenario**

* A user deposits $100 worth of SUI (70% LTV), and borrows $50 worth of BTC.
  * Supply Balance: $100
  * Borrow Balance: $50
  * Health Factor = 100 \* 0,7 / 50 = 1.4
* wBTC price goes up by 50%
  * Supply Balance: $100
  * Borrow Balance: $75
  * Health Factor = 100 \* 0,7 / 75 = 0,9333

**User is now liquidate-able**

Liquidate positions with a **health factor** below 1.

When the health factor of a position is below 1, liquidators repay part or all of the outstanding borrowed amount on behalf of the borrower, while **receiving a discounted amount of collateral** in return (also known as a liquidation "bonus"). Liquidators can decide if they want to receive an equivalent amount of collateral aTokens, or the underlying asset directly. When the liquidation is completed successfully, the health factor of the position is increased, bringing the health factor above 1.

Liquidators can only close a certain amount of collateral defined by a close factor. Currently the **close factor is 0.35**. In other words, liquidators can only liquidate a maximum of 35% of the amount pending to be repaid in a position. The liquidation discount applies to this amount.

{% hint style="info" %}
*In most scenarios*, profitable liquidators will choose to liquidate as much as they can (50% of the `user` position).

To check a user's health factor, use [`get_user_account_data`](#function-get_user_account_data)
{% endhint %}
