# NAVI Protocol Docs Hub

Navi is an one-stop Liquidity Protocol on Sui. It enables users to participate as liquidity providers or borrowers within the Sui Ecosystem. Liquidity providers supply assets to the market, earning passive income through yields, while borrowers have the flexibility to obtain loans for different assets. With its focus on providing essential DeFi infrastructure, Navi aims to be a key player in the rapidly evolving world of DeFi in Sui Ecosystem

The protocol's innovative features, such as Automatic Leverage Vaults and Isolation Mode, enable users to leverage their assets and access novel trading opportunities with minimized risks. Navi's flexibility allows for the integration of various digital assets, while its advanced security features ensure the protection of user funds and the mitigation of systemic risks.

The name "Navi" finds its roots in the Indian language Hindi, meaning "Be Kind to People." This philosophy is reflected in Navi's commitment to fostering mass adoption of DeFi by emphasizing the simplicity and security offered by the Move programming language.


# FAQ

## What is NAVI Protocol?

NAVI is a decentralised non-custodial liquidity market protocol where users can participate as suppliers or borrowers. Suppliers provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an overcollateralised (perpetually) fashion.

## How do I interact with NAVI Protocol?

In order to interact with NAVI protocol, you simply supply your preferred asset and amount. After supplying, you will earn passive income based on the market borrowing demand. Additionally, supplying assets allows you to borrow by using your supplied assets as a collateral. Any interest you earn by supplying funds helps offset the interest rate you accumulate by borrowing.

## What is the cost of using NAVI Protocol?

Interacting with the protocol requires transactions and so transaction fees for Sui Blockchain usage, which depend on the network status and transaction complexity. Sui fees are generally very low, so only a small amount of SUI tokens are needed for interacting with NAVI Protocol.

## Where are the funds stored?

Your funds are allocated in a smart contract. The code of the smart contract is public, open source, formally verified, and audited by third party auditors. You can withdraw your funds from the pool on-demand, and there is no one who is ever in control over your funds.

## What are the risks associated with NAVI Protocol?

The Navi team takes security very seriously and no code will be deployed without extensive reviews, testing, and audits. However there are risks inherent to participating in any Web3 DeFi platform, including:

* Smart contract risk due to unforeseen bugs that are not caught by our stringent security policies.
* Oracle risk due to oracle manipulation.
* Blockchain risk. If the underlying blockchain is somehow compromised, NAVI Protocol cannot protect user funds.

## Why was NAVI Protocol created?

NAVI Protocol was created to build delightful user experiences on the fledgling Sui DeFi ecosystem and take advantage of the desirable features of the Move VM.

## Who is behind NAVI Protocol?

The team behind NAVI Protocol is a seasoned team of founders and builders from the blockchain development space with many collective years of experience building and running protocols across DeFi and Web3 infrastructure.

## Where can I find more info about NAVI Protocol?

Follow us on our socials and subscribe to Discord notifications!

* [Twitter](https://twitter.com/navi_protocol)
* [Telegram](https://t.me/navi_protocol)
* [Discord](https://discord.gg/navi_protocol)
* [GitHub](https://github.com/naviprotocol)


# Borrowing

## Why would I borrow instead of selling my assets?

Selling your assets means closing your position on that particular asset. Hence, if you are long on the asset, you would not be entitled to the potential upside value gain. By borrowing you are able to obtain liquidity (working capital) without selling your assets. Users are mainly borrowing for unexpected expenses, leveraging their holdings or for new investment opportunities.

## How do I borrow?

Before borrowing you need to supply any asset to be used as collateral (check out the [Supplying & Earning FAQ](/navi-protocol-docs-hub/faq/supplying-and-earning) section for more info). After this, simply head to the Borrow section and click on “Borrow” for the asset you want to borrow. Set the amount you need based on your available supplies that would be used as a collateral for the loan. Select either stable or variable rate and confirm your transaction. You can always change your rate afterwards as many times as you want.

## How much I can borrow?

The maximum amount you can borrow depends on the value you have supplied and the available liquidity. For example, you can’t borrow an asset if there is not enough liquidity or if your health factor doesn’t allow you to.

## What asset do I need to repay?

You repay your loan in the same asset you borrowed. For example, if you borrow 1 SUI you will pay back 1 SUI + interest accrued.&#x20;

## How much would I pay in interest?

The interest rate you pay for borrowing assets depends on the borrowing rate which is derived from the supply and demand ratio of the asset. Moreover, the interest rate of a variable rate changes constantly. You can find your current borrowing rate at any time in the Borrowings section of your dashboard.

## What is the health factor?

The health factor is the numeric representation of the safety of your deposited assets against the borrowed assets and its underlying value. The higher the value is, the safer the state of your funds are against a liquidation scenario. If the health factor reaches 1, the liquidation of your deposits will be triggered. A Health Factor below 1 can get liquidated. For a HF=2, the collateral value vs borrow can reduce by 1 out of 2: 50%. The health factor depends on the liquidation threshold of your collateral against the value of your borrowed funds.

## What happens when my health factor is reduced?

Depending on the value fluctuation of your supplies, the health factor will increase or decrease. If your health factor increases, it will improve your borrow position by making the liquidation threshold more unlikely to be reached. In the case that the value of your collateralised assets against the borrowed assets decreases instead, the health factor is also reduced, causing the risk of liquidation to increase.

## When do I need to pay back the loan?

There is no fixed time period to pay back the loan. As long as your position is safe, you can borrow for an undefined period. However, as time passes, the accrued interest will grow making your health factor decrease, which might result in your deposited assets becoming more likely to be liquidated.

## How do I payback the loan?

In order to payback the loan you simply go to the Borrowings section of your dashboard and click on the repay button for the asset you borrowed and want to repay. Select the amount to pay back and confirm the transaction.

## How do I avoid liquidation?

In order to avoid the reduction of your health factor leading to liquidation, you can repay the loan or deposit more assets in order to increase your health factor. Out of these two available options, repaying the loan would increase your health factor more.


# Supplying and Earning

## How do I supply?

Browse to the "Supply" section and click on "Supply" for the asset you want to supply. Select the amount you'd like to supply and submit your transaction. Once the transaction is confirmed, your supply is successfully registered and you begin earning interest.

## How much will I earn?

Depositors receive continuous earnings that evolve with market conditions based on:

* **The interest rate payment on loans** - suppliers share the interests paid by borrowers corresponding to the average borrow rate times the utilisation rate. The higher the utilisation of a reserve the higher the yield for suppliers.

Each asset has its own market of supply and demand with its own APY (Annual Percentage Yield) which evolves with time. You can find the average annual rate over the past 30 days to evaluate the rate evolution, and you can also find more data on the reserve overview of each asset in the home section on the app.

## Is there a minimum or maximum amount to supply?

You can supply any amount you want, there is no minimum or maximum limit.

## How do I withdraw?

To withdraw you need to go to the "Dashboard" section and click on “Withdraw”. Select the amount to withdraw and submit the transaction.&#x20;

You would need to make sure there is enough liquidity (not borrowed) in order to withdraw, if this is not the case you would need to wait for more liquidity from suppliers or borrowers repaying. This is a rare scenario that occurs only if you have a very large position which comprises a large percentage of the pool, or the pool is very highly utlizied, in which case there is an incentive for others to deposit.


# Liquidations

## Introduction

A liquidation is a process that occurs when a borrower's health factor goes below 1 due to their collateral value not properly covering their loan/debt value. This might happen when the collateral decreases in value or the borrowed debt increases in value against each other. This collateral vs loan value ratio is shown in the [health factor](https://docs.aave.com/risk/asset-risk/risk-parameters#health-factor).\
In a liquidation, up to 50% of a borrower's debt is repaid and that value + liquidation fee is taken from the collateral available, so after a liquidation that amount liquidated from your debt is repaid.

## How much is the liquidation penalty?

The liquidation penalty (or bonus for liquidators) depends on the asset used as collateral. You can find every assets' liquidation fee in the [risk parameters section](https://docs.aave.com/risk/asset-risk/risk-parameters).

## Can you give me an example?

Sure! A couple of them here:

**Example 1**&#x20;\
Bob deposits 10 SUI and borrows 5 SUI worth of USDC.&#x20;\
If Bob’s Health Factor drops below 1 his loan will be eligible for liquidation.&#x20;\
A liquidator can repay up to 50% of a single borrowed amount = 2.5 SUI worth of USDC.&#x20;\
In return, the liquidator can claim a single collateral which is SUI (5% bonus). &#x20;\
The liquidator claims 2.5 + 0.125 SUI for repaying 2.5 SUI worth of USDC.

**Example 2**&#x20;\
Bob deposits 5 SUI and 4 SUI worth of WBTC, and borrows 5 SUI worth of USDC&#x20;\
If Bob’s Health Factor drops below 1 his loan will be eligible for liquidation.&#x20;\
A liquidator can repay up to 50% of a single borrowed amount = 2.5 SUI worth of USDC.&#x20;\
In return, the liquidator can claim a single collateral, as the liquidation bonus is higher for WBTC (15%) than SUI (5%) the liquidator chooses to claim WBTC. &#x20;\
The liquidator claims 2.5 + 0.375 SUI worth of YFI for repaying 2.5 SUI worth of USDC.

## How can I avoid getting liquidated?

To avoid liquidation you can raise your health factor by depositing more collateral assets or repaying part of your loan. By default, repayments increase your health factor more than deposits. Also, it's important to monitor your health factor and keep it high to avoid a liquidation. Keeping your health factor over 2, for example, gives you more of a margin to avoid a liquidation.  \
\
You should be mindful of the stablecoin price fluctuations due to market conditions and how it might affect your healthfactor. For example, the market price of USDC 1.00 might not equal exactly USD 1.00, but for example USD 0.95. The price fluctuations of stablecoins, like any assets, affects your healthfactor.&#x20;

## Can I participate in the liquidations ecosystem?

Yes, liquidations are open to anyone, but there is a lot of competition. Normally liquidators develop their own solutions and bots to be the first ones liquidating loans to get the liquidation bonus.&#x20;


# Roadmap

## What is the NAVI Protocol roadmap?

The NAVI Protocol roadmap is broken up into phases, as described below.

### Phase 1 (Q2 2023)

* Launch of liquidity protocol initially supporting SUI, USD stablecoins, wrapped ETH, wrapped BTC.
* NAVI token launch.
* DAO setup and governance functionality available.
* Staking available for NAVI tokens into liquidity protocol.
* Leveraged vault UI launch.

### Phase 2 (Q4 2023)

* Integration with Sui Foundation's Deepbook to utilize deep liquidity and provide users an optimal trading experience.

### Phase 3 (2024)

* Launch of stablecoin on top of money market protocol.


# Glossary

Some terms used throughout the documentation may be unfamiliar to developers. Below we list some common terms that will help with your understanding.

<table><thead><tr><th width="175">Term</th><th>Description</th></tr></thead><tbody><tr><td>APY</td><td><p>Annual Percentage Yield, it is the real rate of return earned on an investment, taking into account the effect of compounding interest.</p><p></p></td></tr><tr><td>Loan To Value (LTV)</td><td>The maximum borrowing power of a specific collateral. If a collateral has a Loan to Value of 75%, for every 1 ETH worth of collateral the user will be able to borrow 0.75 ETH worth of principal currency. The Loan To Value is specified per collateral and expressed in percentage points.</td></tr><tr><td>Liquidation Threshold</td><td>The threshold of a borrow position that will be considered undercollateralized and subject to liquidation. If a collateral has a liquidation threshold of 80%, it means that the loan will be liquidated when the debt value is worth 80% of the collateral value. The liquidation threshold is specified per collateral and expressed in percentage points.</td></tr><tr><td>Liquidation Bonus</td><td>The bonus received by liquidators to incentivise the purchase of specific collateral that has a health factor below 1. The Liquidation Bonus is specified per collateral and expressed in percentage points.</td></tr><tr><td>Health Factor</td><td>Represents the ratio between total collateral multiplied by the liquidation threshold, and the borrowed principal. When the Health Factor goes below 1, the loan is undercollateralized and can be liquidated. Also see <a href="broken://pages/OHTvp8rUcmWU7cBNIbev#function-execute_liquidation"><code>execute_liquidation</code></a>.</td></tr><tr><td>Ray Units</td><td>For internal calculations and to reduce the impact of rounding errors, the protocol uses the concept of Ray Math. A Ray is a unit with 27 decimals of precision. All the rates (liquidity/borrow/utilisation rates) as well as the cumulative indexes and the aTokens exchange rates are expressed in Ray.  Please refer to the following <a href="https://medium.com/dapphub/introducing-ds-math-an-innovative-safe-math-library-d58bc88313da">article</a> for further details about this concept.</td></tr><tr><td>Market</td><td>The address of the underlying asset.</td></tr><tr><td>Lending Pool</td><td>The smart contract with which users interact to perform funding operations</td></tr><tr><td>Funding Operations</td><td>Operations such as <a href="broken://pages/OHTvp8rUcmWU7cBNIbev#function-borrow"><code>borrow</code></a> , <a href="broken://pages/OHTvp8rUcmWU7cBNIbev#function-repay"><code>repay</code></a>, <a href="broken://pages/OHTvp8rUcmWU7cBNIbev#function-withdraw"><code>withdraw</code></a>, <a href="broken://pages/OHTvp8rUcmWU7cBNIbev#function-deposit"><code>deposit</code></a></td></tr><tr><td>Liquidity Rate</td><td>The interest rate currently being earned by the reserve</td></tr><tr><td>Liquidity Index</td><td>The Interest cumulated by the reserve during the time interval since the last updated timestamp</td></tr></tbody></table>


# Tokenomics

## Introduction

The NAVI Protocol is an innovative DeFi ecosystem that begins with a borrowing and lending platform. One of the key features of the NAVI Protocol is its native token, which streamlines user experience and provides a unified incentive structure. In this technical documentation, we will outline the tokenomics and benefits of the NAVI Protocol's native token.

## Tokenomics

The native token serves as both a utility and governance token within the NAVI Protocol ecosystem. Token holders can use the token to access various benefits such as fee discounts, staking rewards, and voting rights.

### Utility & Governance&#x20;

1. **Staking**: Users can stake the native token to receive rewards in the form of interest income from the lending platform. The rewards distribution is proportional to the amount of native tokens staked, incentivizing long-term commitment to the ecosystem.
2. **Governance**: Token holders can participate in the governance of the NAVI Protocol by voting on proposals and updates. The governance process is decentralized, ensuring that the platform's development and future direction are driven by its users.
3. **Fee Collection and Distribution**: The Navi Protocol collects fees from the borrowing and lending platform. A portion of these fees is allocated to stakers, while the remaining fees are distributed to the platform's treasury and other purposes as defined by the platform's design.

### Emissions

In the NAVI Protocol ecosystem, the native token plays a significant role in incentivizing liquidity provision and aligning user interests. An important aspect of this system is token emissions directed towards liquidity providers (LPs) of a particular asset. The mechanism ensures that LPs are rewarded for their contribution to the platform, which in turn encourages more users to participate in the ecosystem.

Here' we'll outline the mechanics by which token holders and stakers can benefit from the usage of the token in both the Perpetual DEX and Borrowing and Lending products.

#### Token Staking, Locking & Gauges, and Fee Discounts

Single-sided staking of the token allows users to receive emissions coming from protocol fees (borrowing), as well as take part in the decision-making of how emissions are directed across the protocol

**Borrowing and Lending**

The NAVI Protocol introduces the concept of vote-escrowed tokens (veNAVI) to enhance the emission allocation mechanism. When users stake their native tokens, they receive veNAVI tokens that grant them voting power to determine the emission distribution for various assets in the liquidity pools. The amount of veNAVI received is proportional to the amount of NAVI tokens locked, as well as the duration of the time period for which those tokens are locked.&#x20;

These veNAVI tokens can be used to vote on "gauges," which are essentially smart contracts that manage the emission rates for each liquidity pool or asset. When users cast their votes using veNAVI tokens on a specific gauge, they influence the allocation of token emissions to that asset or pool. The more veNAVI tokens a gauge has, the higher the emission rate for that particular asset.

This vote-escrowed token mechanism allows users to express their preference for certain assets or liquidity pools while also being rewarded with token emissions for staking their native tokens. The system encourages users to provide liquidity for in-demand assets and ensures fair rewards distribution.

As more users stake the native token and vote for a specific asset or pool using their veNAVI tokens, the emission rate for that particular asset increases. This creates a dynamic system where LPs of popular or in-demand assets receive higher rewards in the form of native tokens, encouraging more users to provide liquidity for those assets.


# Technical Docs

Navi's offering includes a decentralized liquidity protocol. It allows users to lend and borrow cryptocurrency assets without intermediaries, using a shared liquidity pool system.

Navi's liquidity pools are created for each supported asset, and users can deposit their assets into these pools. They receive Navi receipt tokens in return, which represent their share of the pool (i.e. nSUI). These tokens can be used as collateral to borrow other assets from the pool. The collateralization ratio determines the amount that can be borrowed, and it is adjusted dynamically based on supply and demand. More in-depth information can be found in [Technical Reference](broken://pages/5cDE25HF3GtAu5yJCbtW).

Navi has a governance system that allows Navi token holders to vote on proposals and changes to the protocol. This includes setting interest rates, adding new assets to the protocol, and changing the collateralization ratio. Check out the [Tokenomics](https://navi-protocols-organization.gitbook.io/navi-tokenomics/) page for an overview of the Tokenomics.&#x20;

Overall, Navi's architecture provides a decentralized and efficient way for users to lend and borrow assets, without the need for traditional financial intermediaries.

In the following pages, we'll go in depth into how the NAVI liquidity protocol works in all its aspects, from high-level mechanics to granular risk management features we've implemented


# Technical Reference

API references and descriptions of main contracts and infrastructure pieces.


# Liquidation Mechanics & Walkthrough

The health of the NAVI Protocol is dependant on the 'health' of the loans within the system, also known as the 'health factor'. When the 'health factor' of an account's total loans is below 1, anyone can call the [`execute_liquidation`](broken://pages/OHTvp8rUcmWU7cBNIbev#function-execute_liquidation) to the `LendingPool` contract, paying back part of the debt owed and receiving discounted collateral in return.

This incentivises third parties to participate in the health of the overall protocol, by acting in their own interest (to receive the discounted collateral) and as a result, ensure loans are sufficiently collateralised.

There are multiple ways to participate in liquidations:

1. By calling the  [`execute_liquidation`](broken://pages/OHTvp8rUcmWU7cBNIbev#function-execute_liquidation) directly in the LendingPool contract.
2. By creating your own automated bot or system to liquidate loans.

For liquidation calls to be profitable, you must take into account the gas cost involved in liquidating the loan. If a high gas price is used, then the liquidation may be unprofitable for you. See the [Calculating profitability vs gas cost](#calculating-profitability-vs-gas-cost) section for more details.

## Prerequisites

When making a [`execute_liquidation`](broken://pages/OHTvp8rUcmWU7cBNIbev#function-execute_liquidation) 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.5, which means that only a maximum of 50% 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 user accounts that have a health factor below 1 can be liquidated. There are multiple ways you can get the health factor, with most of them involving 'user account data'.

"Users" in the NAVI Protocol refer to a single Sui address that has interacted with the protocol. This can be an externally owned account or contract.

### On-chain

1. To gather user account data from on-chain data, one way would be to monitor emitted events from the protocol and keep an up to date index of user data locally.
   1. Events are emitted each time a user interacts with the protocol (deposit, repay, borrow, etc). See the contract source code for relevant events.
2. When you have the user's address, you can simply call [`get_user_account_data`](broken://pages/OHTvp8rUcmWU7cBNIbev#function-get_user_account_data) to read the user's current `health_factor`. If the `health_factor` is below 1, then the account can be liquidated.

## 2. Executing the liquidation call

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`](broken://pages/eC2ffzyiO7vqHnFwwDeh#function-get_reserve_data) on the [Lending Pool Lens](broken://pages/eC2ffzyiO7vqHnFwwDeh) 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.5 currently).\
   \
   $$debtToCover = (userStableDebt + userVariableDebt) \* LiquidationCloseFactorPercent$$

3. For reserves that have `usage_as_collateral_enabled` as `true`, the `current_atoken_balance` and the current [liquidation bonus](https://docs.aave.com/risk/asset-risk/risk-parameters) gives the max amount of collateral that can be liquidated \
   \
   $$maxAmountOfCollateralToLiquidate = (debtAssetPrice \* currentATokenBalance \* liquidationBonus)/ collateralPrice$$

### Move

TODO

## 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](https://docs.aave.com/risk/asset-risk/risk-parameters).
2. Get the user's collateral balance (n`TokenBalance`).
3. Get the asset's price according to the [Aave'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 ETH (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
* BTC 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.5**. In other words, liquidators can only liquidate a maximum of 50% 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 %}


# Contract Addresses

All of the deployed contract addresses on Sui Testnet and Mainnet.


# API Reference


# Oracles

Here we'll take a look at a core piece of infrastructure of the protocol, the Oracles.

Package Name: `oracle`&#x20;

Source Code: [oracle on GitHub](https://github.com/naviprotocol/protocol-core/tree/mainnet/oracle)

* [`oracle.move`](broken://pages/UQ0iqXTqMI6ebtccjyHd)

## FAQ

<details>

<summary>What are oracles used for?</summary>

Oracles are an on-chain price feed that is used to get the price of any asset into a relative unit. This is important for calculating collateral ratios to determine how much a user can borrow against their collateral, as well as proving that a position is liquidate-able.

</details>

<details>

<summary>What types of oracles can be used?</summary>

An oracle is just an on-chain representation of data, so this can be abstracted into a generic interface. Wrappers will be written for different oracle types including:

* Generic “mock” oracles that return a constant value for testing.
* [Supra](https://data.supraoracles.com/networks) oracles.
* AMM-based TWAP oracles.

</details>

## Smart Contracts

### `NaviOracle`

The NaviOracle is a registry that maps Asset → Oracle Implementation. This is used so that when any of the liquidity protocol code needs to query the price of an asset, it can simply call this contract to get an address of an oracle, then call the given address with a standard interface which implements the oracle.

#### Read Methods

* `price`
  * Returns the price of an asset, in native asset (i.e. SUI).
  * Params
    * `asset_id`: Address of an asset to get a price for.

#### Write Methods

* `set_price_oracle`
  * ONLY allowed to be called by owner (eventually will be DAO).
  * Sets a price oracle for a specific asset.
  * Set to null (0?) to remove an oracle.

### `MockPriceOracle` - ONLY for testing

#### Read Methods

* `price`
  * Returns a hardcoded price for testing.
  * Params
    * `asset_id`: Address of an asset to get a price for.

### `SupraPriceOracle`

#### Read Methods

* `price`
  * Calls Supra oracle for particular asset and returns a price in native asset (i.e. SUI).
  * Params
    * `asset_id`: Address of an asset to get a price for.
  * Implementation
    * Query Supra oracle and get price.
    * (Possibly?) Keep an internal registry of Supra oracles for a given asset.

## Code Sample

`NaviOracle`

```solidity
module oracle::navi_oracle {

    // Part 1: Imports
    use sui::object::{Self, UID};
    use sui::transfer;
    use sui::tx_context::{Self, TxContext};
    use std::vector as vec;

    struct OracleAdmin has key, store { id: UID }

    struct Oracle has store {
        asset: address,
        oracle: address,
    }

    struct Oracles has store {
        oracles: vector<Oracle>
    }

    struct Forge has key, store {
        id: UID,
        swords_created: u64,
    }

    fun init(ctx: &mut TxContext) {
        transfer::public_transfer(OracleAdmin { id: object::new(ctx) }, tx_context::sender(ctx));
    }

    // ======= Admin Functions =======
    public entry fun add_oracle(
        _: &OracleAdmin,
        reg: &mut Oracles,
        asset: address,
        oracle: address,
        _ctx: &mut TxContext
    ) {
        vec::push_back(&mut reg.oracles, Oracle { asset, oracle });
    }

    public entry fun get_price(reg: &mut Oracles, asset: address): u64 {
        let i = 0;
        let price;
        while (i < vec::length(&reg.oracles)) {
            let oracle = vec::borrow(&reg.oracles, i);
            if (oracle.asset == asset) {
                price = oracle.oracle.price();
            };
            i = i + 1;
        };
        price
    }
}
```


# oracle.move


# Core Logic


# calculator.move

Interest and pool rate calculation.

### Public Methods

#### `caculate_utilization(storage: &mut Storage, asset: u8, amount: u256): u256`

Returns the utilisation rate of a pool.

$$
U = B\_a / (C\_a + B\_a)
$$

Where `B` and `C` are the total borrows and total cash of asset `a`

#### `calculate_borrow_rate(storage: &mut Storage, asset: u8, amount: u256): u256`

Get the borrow rate of a pool's asset

#### `calculate_supply_rate(storage: &mut Storage, asset: u8, amount: u256): u256`

Get the supply rate of a pool's asset

#### `calculate_compounded_interest(current_timestamp: u64, last_update_timestamp: u64, rate: u256): u256`

Compound interest calculation implementation

#### `calculate_linear_interest(current_timestamp: u64, last_update_timestamp: u64, rate: u256): u256`

Linear interest calculation implementation


# lending.move

Core lending operation.

## Events

```
struct DepositEvent has copy, drop {
    reserve: u8,
    user: address,
    amount: u64,
}

struct WithdrawEvent has copy, drop {
    reserve: u8,
    user: address,
    to: address,
    amount: u64,
}

struct BorrowEvent has copy, drop {
    reserve: u8,
    user: address,
    amount: u64,
}

struct RepayEvent has copy, drop {
    reserve: u8,
    user: address,
    amount: u64,
}

struct LiquidationCallEvent has copy, drop {
    reserve: u8,
    user: address
}
```

## Public Methods

#### `deposit<CoinType>(clock: &Clock, storage: &mut Storage, pool: &mut Pool, asset: u8, deposit_coin: Coin, amount: u64, ctx: &mut TxContext)`

Deposits `amount` of a `deposit_coin` into the protocol, minting the same `amount` of corresponding tokens to a `pool`

Emits a `DepositEvent`

#### `withdraw<CoinType>(clock: &Clock, oracle: &PriceOracle, storage: &mut Storage, pool: &mut Pool, asset: u8, amount: u64, to: address, ctx: &mut TxContext)`

Withdraws `amount` of the underlying `deposit_coin`, to the `to` account, i.e. redeems the underlying token and burns the tokens in the `pool`.

Emits a `WithdrawEvent`

#### `borrow<CoinType>(clock: &Clock, oracle: &PriceOracle, storage: &mut Storage, pool: &mut Pool, asset: u8, deposit_coin: Coin, amount: u64, ctx: &mut TxContext)`

Borrows `amount` of `deposit_coin` with, sending the `amount` to the `tx_context::sender(ctx)` sender account

Emits a `BorrowEvent`

#### `repay<CoinType>(clock: &Clock, oracle: &PriceOracle, storage: &mut Storage, pool: &mut Pool, asset: u8, repay_coin: Coin, amount: u64, ctx: &mut TxContext)`

Repays a debt `amount` of `repay_coin` for the `tx_context::sender(ctx)` sender account

Emits a `RepayEvent`


# logic.move

Core logic functionally that implements state-mutating functions.

## Read Methods

#### `user_health_factor(storage: &mut Storage, oracle: &PriceOracle, user: address): u256`

#### `user_health_collateral_value(oracle: &PriceOracle, storage: &mut Storage, user: address): u256`

#### `user_health_loan_value(oracle: &PriceOracle, storage: &mut Storage, user: address): u256`

#### `user_loan_value(oracle: &PriceOracle, storage: &mut Storage, asset: u8, user: address): u256`

#### `user_collateral_value(oracle: &PriceOracle, storage: &mut Storage, asset: u8, user: address): u256`

#### `user_collateral_balance(storage: &mut Storage, asset: u8, user: address): u256`

#### `user_loan_balance(storage: &mut Storage, asset: u8, user: address): u256`


# storage.move

## Error Codes

```
STORAGE_CALLER_NOT_OWNER: u64 = 43001
STORAGE_CALLER_NOT_CONFIGURATOR: u64 = 43002
STORAGE_NO_MORE_RESERVES_ALLOWED: u64 = 43003
STORAGE_INVALID_INDEX: u64 = 43004
STORAGE_AMOUNT_NOT_ENOUGH: u64 = 43005
STORAGE_DUPLICATE_RESERVE: u64 = 43006
```

#### `pause(storage: &Storage): bool`

Check if protocol is in `paused` state

#### `get_supply_cap_ceiling(storage: &mut Storage, asset: u8): u256`

Retuns the supply cap of an asset

#### `get_borrow_cap_ceiling_ratio(storage: &mut Storage, asset: u8): u256`

Retuns the borrow cap of an asset

#### `get_total_supply(storage: &mut Storage, asset: u8): (u256, u256)`

Returns the total supplied of an asset

#### `get_index(storage: &mut Storage, asset: u8): (u256, u256)`

Returns the `borrow_index` and the `supply_index` of an asset

#### `get_borrow_rate_factors(storage: &mut Storage, asset: u8): (u256, u256, u256, u256, u256)`

Returns the parameters of the Interest Rate Model of a specific asset, e.g.:

* `base_rate`
* `multiplier`
* `jump_rate_multiplier`
* `reserve_factor`&#x20;
* `optimal_utilization`

For a comprehensive overview of these parameters, refer to [this article](https://ianm.com/posts/2020-12-20-understanding-compound-protocols-interest-rates#interest-rate-spikes)

#### `get_liquidation_factors(storage: &mut Storage, asset: u8): (u256, u256, u256)`

Returns the liquidation parameters of an asset, e.g.:

* `ratio`
* `bonus` i.e. the bonus discount given to the liquidator
* `threshold` i.e. the liquidation threshold below which a position gets liquidated

#### `get_last_update_timestamp(storage: &Storage, asset: u8): u64`

Get the latest timestamp at which the borrow rate was updated

#### `get_current_rate(storage: &mut Storage, asset: u8): (u256, u256)`

Returns the `supply_rate` and `borrow_rate` of an asset

#### `get_user_balance(storage: &mut Storage, asset: u8, user: address): (u256, u256)`

Returns a user's `borrow_balance` and `supply_balance`

#### `get_user_assets(storage: &Storage, user: address): (vector, vector)`

Returns two `vectors` with the user's `collateral` assets and `loans` assets

#### `get_asset_ltv(storage: &Storage, asset: u8): u256`

Returns an `asset`'s LTV

#### `get_coin_type(storage: &Storage, asset: u8): String`

Returns a coin's type


# validation.move

## Error Codes

```
VALIDATION_INVALID_AMOUNT: u64 = 44001
VALIDATION_NO_ACTIVE_RESERVE: u64 = 44002
VALIDATION_RESERVE_FROZEN: u64 = 44003
VALIDATION_MAX_SUPPLY_CAP: u64 = 44004
VALIDATION_MAX_BORROW_CAP: u64 = 44004
VALIDATION_BALANCE_NOT_ENOUGH: u64 = 44005
```

## Read Methods

Validation of user actions

#### `validate_deposit(storage: &mut Storage, asset: u8, amount: u64)`

#### `validate_borrow(storage: &mut Storage, asset: u8, amount: u64)`

#### `validate_repay(_storage: &mut Storage, _asset: u8, amount: u64)`


# Pool

The `pool` is the core contract through which users will interact with the protocol. It allows for all the funding operations.

Package Name: `pool`

Source Code: [pool on GitHub](https://github.com/naviprotocol/protocol-core/tree/mainnet/pool)

* [`pool.move`](broken://pages/lmjHFICFuuPMPzFAXlEI)

## Contract API reference

### Write Methods

#### **`function deposit`**

Deposits `amount` of an `asset` into the protocol, minting the same `amount` of corresponding nTokens

#### **`function withdraw`**

Withdraws `amount` of the underlying `asset`, i.e. redeems the underlying token and burns the aTokens.

{% hint style="info" %}
💡 When withdrawing `to another` address, `msg.sender`should have`nToken` that will be burned by LendingPool .
{% endhint %}

#### **`function borrow`**

Borrows `amount` of `asset` with, sending the `amount` to `msg.sender`

#### **`function repay`**

Repays a debt `amount` of `asset`

#### **`function enable_as_collateral`**

Lets a user sets the `asset` of to be allowed to be used as collateral or not.

#### **`function execute_liquidation`**

What needs to be know:

* The collateral asset
* The debt asset
* User
* The amount of debt that needs to be covered by the liquidator

**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
* BTC 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. Also see our [Liquidations guide](notion://www.notion.so/developers/guides/liquidations).

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.5**. In other words, liquidators can only liquidate a maximum of 50% 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 %}

#### **`function flash_loan`**

See Sui Example flash loan [here](https://github.com/MystenLabs/sui/blob/main/sui_programmability/examples/defi/sources/flash_lender.move).

### View Methods

#### **`function get_market_reserve_data`**

Returns the state of the reserve of a specific market

* Liquidity Index
* Current Supply / Liquidity in Ray
* Current Interest Rate
* Last Update Timestamp
* nToken address
* Underlying address
* Interest Rate Strategy Address

#### **`function get_user_account_data`**

Returns the user account data across all the reserves

* Total Collateral (in Sui)
* Total Debt (in Sui)
* LTV
* Health Factor
* Liquidation Threshold
* Borrowing power left

#### **`function get_market_configuration`**

Returns the configuration of the market

* LTV
* Liquidation Threshold
* Liquidation Bonus
* Reserve Factor
* Borrowing enabled
* Decimals of the market

#### **`function get_market_normalised_income`**

Returns the normalized income per unit of `asset` of a specific market

#### `function get_market_normalised_debt`

Returns the normalized variable debt per unit of `asset` of a specific market

#### **`function paused`**

Returns `true` if the LendingPool is paused.

#### **`function get_market_list`**

Returns the list of markets.

### Error Codes

TODO


# pool.move

## Error Codes

```
POOL_CALLER_NOT_OWNER: u64 = 42001;
```

## Events

```
struct PoolCreate has copy, drop {
    creator: address,
}

struct PoolBalanceRegister has copy, drop {
    sender: address,
    amount: u64,
    new_amount: u64,
    pool: String,
}

struct PoolDeposit has copy, drop {
    sender: address,
    amount: u64,
    pool: String,
}

struct PoolWithdraw has copy, drop {
    sender: address,
    recipient: address,
    amount: u64,
    pool: String,
}

struct PoolOwnerSetting has copy, drop {
    sender: address,
    owner: u256,
    value: bool,
}

struct PoolAdminSetting has copy, drop {
    sender: address,
    admin: u256,
    value: bool,
}
```

## Write Methods

#### `create_pool<CoinType>(ctx: &mut TxContext)`

Creates a new pool for a specific coin type.&#x20;

Emits: `PoolCreate`

## Admin Methods

#### `set_owner(pool_admin_cap: &mut PoolAdminCap, owner: u256, val: bool, ctx: &mut TxContext)`

Sets the owner of a pool

Emits: `PoolOwnerSetting`

#### `set_admin(pool_admin_cap: &mut PoolAdminCap, admin: u256, val: bool, ctx: &mut TxContext)`

Sets the admin of a pool

Emits: `PoolAdminSetting`


# Security Features

In this page, we'll go over some of the tools and features that enable granular risk management of the protocol.

* [Granular Asset Risk Management](/technical/technical-docs/security-features/granular-asset-risk-management)
* [Oracle & Oracle Reliability](/technical/technical-docs/security-features/oracle-pricing)
* [Staying solvent: liquidations mechanics](/technical/technical-docs/security-features/liquidation-mechanics)


# Liquidation Mechanics

Reliable liquidation mechanics are enabled by tight integration with a variety of liquidity partners. We plan on leveraging the centralised liquidity of DeepBook to perform timely liquidations.

Liquidators can purchase under-collateralized assets at a discount on the DEX, providing an incentive to maintain the health and stability of the lending pool. Liquidations are permissionless, thus effectively creating a market for discounted collateral.&#x20;


# Oracle Pricing

The platform utilizes a variety of oracle providers to ensure secure, reliable, and scalable price feeds for all supported assets. These oracles ensure accurate pricing information, which is essential for determining collateral value and enforcing platform security mechanisms.

Considering also our interest in supporting exotic assets, and yield-bearing tokens, we plan as well on integration with a variety of DEXes and develop custom oracles for these assets.&#x20;

The third-party oracles we are currently using are:

* Supra
* Pyth


# Granular Asset Risk Management

### **Supply Limits**

These are limits to how much of the collateral asset can be used in the money market. This parameter is designed to protect the pool against specific, long-tail volatile assets to damage the pool integrity.

For a variety of smaller capitalisation tokens with high fully-diluted valuations that are traded with thin liquidity, having the ability to supply an infinite amount of such token poses structural risks. Were the capitalisation of such token to vary significantly, it is likely that positions backed by such assets could no longer be liquidate-able, posing the risk of bad debt being incurred in the system.

### Debt Ceilings

These are limits on the total borrow amount of a market that is collaterized by another specific asset in the pool. The cap is measured as an amount of the borrowed markets underlying tokens.

Similarly to Supply Limits, debt ceilings enable further granular risk management of certain collateral assets, by making sure that certain tail assets cannot be used to collateralise positions that are too large.&#x20;

### **Asset Blacklisting**

You can blacklist specific collateral assets from borrowing individual borrow assets in a pool. This decreases risk and reflexivity, enabling further isolation modes in pool.&#x20;

For all intents and purposes, this is an extension of the Debt Ceiling: It essentially sets a Debt Ceiling to zero.

### Borrow Limits

The platform enforces borrow limits for each user, calculated as a percentage of their collateral value. Borrow limits ensure users maintain a safe collateralization ratio and protect the lending pool from defaults.


