# Onchain interactions with lending pools

## **Key Concepts**

**Collateral**\
Collateral is an asset that a borrower provides to the lending pool as security for a loan. It ensures that the lender has protection in case the borrower defaults on the loan. In our lending pool, collateral can be supplied in the form of USDT, USDC, DAI, WETH, wstETH, or wBTC. In Liquorice lending pools, the borrower’s collateral cannot be borrowed. Collateral can be withdrawn for as long as withdrawal does not result in the breach of liquidation threshold.&#x20;

**Debt**\
Debt represents the amount of borrowed funds that a borrower owes to the lending pool. This includes both the principal amount borrowed and any accrued interest. Borrowers must repay their debt to avoid liquidation of their collateral.

**LTV**\
The Loan-To-Value ratio is a measure of the borrower’s solvency. It is calculated based on the value of the collateral provided and the amount of debt owed. A higher LTV indicates a higher risk of liquidation for the borrower, while a lower LTV indicates a safer position. Another known measurment of borrower's solvency is health factor which is basically a reversed value of LTV.

## **How to Supply Collateral into the Pool**

To supply collateral into the pool, you can use the `supply` function of the `LendingPool` contract. Here is an example:

```solidity
IERC20(asset).approve(address(lendingPool), amount);
lendingPool.supply(asset, amount, lockedCollateral);
```

* `asset`: The address of the asset you want to supply as collateral.
* `amount`: The amount of the asset you want to supply.
* `lockedCollateral`: A boolean flag indicating whether the collateral is locked. This flag should always be `true` because in Liquorice, only locked collateral is considered when calculating the health factor. Interest is earned on regular deposits but such deposits can be used as collateral to improve health factor

## **How to Repay Debt to the Pool**

To repay debt, you can use the `repay` function of the `LendingPool` contract. Here is an example:

```solidity
IERC20(asset).approve(address(lendingPool), amount);
lendingPool.repay(asset, amount);
```

* `asset`: The address of the asset you want to use to repay the debt.
* `amount`: The amount of the asset you want to repay.

## **How to Determine Maximum Available Borrowing in Each Token**

To determine how much you can borrow in each token, use the `getAssetAvailableBorrowAmount` function of the [`PoolData`](https://arbiscan.io/address/0xbf1d10adf5fa4b6cbcff3319f736dba5647b9659#readContract) contract (same contract address exists on all EVM supported chains). Here is an example:

```solidity
uint256 availableBorrowAmount = poolData.getAssetAvailableBorrowAmount(
    lendingPool,
    user,
    asset
);
```

* `lendingPool`: The address of the lending pool from which you wish to borrow.
* `user`: The address of the user, to take into account their existing collateral and debt.
* `asset`: The address of the asset you want to borrow.

## **How to Understand Your Existing Borrowings**

In Liquorice Lending Pools, both collateral and debt are tokenized. When you supply an asset as collateral, you receive collateral tokens representing your collateral position. Similarly, when you borrow an asset, you receive debt tokens representing your debt position. These tokens help track and manage your collateral and debt within the pool.

**Steps to Get Debt Amount for a Specific Asset:**

1. **Debt Tokens**: Your existing borrowings are represented by debt tokens. Each debt token corresponds to a specific borrowed asset. The balance of these debt tokens indicates the amount of debt you owe.
2. **Checking Debt Token Balance**: You can check your debt token balance using the `balanceOf` function of the debt token contract. This balance represents the amount of the borrowed asset you owe, including any accrued interest.
3. **Asset State**: The `LendingPool` contract maintains the state of each asset, including the total borrow amount and the debt token associated with the asset. You can retrieve the asset state using the `getAssetState` function.
4. **Calculating Debt Amount**: The debt amount can be calculated using the exchange rate between debt shares and the total borrow amount. This exchange rate can be obtained using the `getDebtShareToAmountExchangeRate` function from the `PoolData` contract.

Here is an example of how to check your existing borrowings:

```solidity
LendingPool.AssetState memory assetState = lendingPool.getAssetState(WETH);
uint256 debtTokenBalance = IERC20(address(assetState.debtToken)).balanceOf(borrower);
uint256 totalBorrowAmount = assetState.totalBorrowAmount;
uint256 debtShareToAmountExchangeRate = poolData.getDebtShareToAmountExchangeRate(address(lendingPool), WETH);
uint256 debtAmount = debtTokenBalance * debtShareToAmountExchangeRate / 1e18;
```

* `assetState`: The state of the asset you have borrowed.
* `debtTokenBalance`: The balance of your debt tokens.
* `totalBorrowAmount`: The total amount of the asset borrowed from the pool.
* `debtShareToAmountExchangeRate`: The exchange rate between debt shares and the total borrow amount.
* `debtAmount`: The calculated amount of debt you owe.

By following these steps, you can understand your existing borrowings and manage your debt effectively within the lending pool.

## **How to Understand LTV**

For solvency assessment, we use the LTV (Loan-to-Value) ratio. The LTV ratio represents the ratio of the borrowed amount to the value of the collateral.

The `getUserLTV` function from the `LendingPool` contract calculates the current LTV and the liquidation threshold for a given user. Here is an example of how to use this function:

```solidity
(uint256 userLTV, uint256 liquidationThreshold) =
    lendingPool.getUserLTV(userAddress);
```

* `userAddress`: The address of the user whose LTV and liquidation threshold you want to check.
* `userLTV`: The current LTV of the user.
* `liquidationThreshold`: The liquidation threshold for the user.

**Interpreting `userLTV`**:

* **Low LTV**: A low LTV ratio indicates that the borrower has a significant amount of collateral relative to their debt. This is a safer position as it reduces the risk of liquidation.
* **High LTV**: A high LTV ratio indicates that the borrower has a higher amount of debt relative to their collateral. This increases the risk of liquidation if the value of the collateral decreases or if the debt increases due to accrued interest or changes in asset prices.

By using the `getUserLTV` function, borrowers can monitor their health factor and take necessary actions to maintain a safe position within the lending pool.

## **Get Interest Paid on an Asset at Any Moment**

The interest rate for each asset in the lending pool is calculated using the `InterestRateModel` contract. The current interest rate can be obtained using the `getCurrentInterestRate` function.

```solidity
uint256 currentInterestRate = rateModel.getCurrentInterestRate(
    address(lendingPool),
    asset
);
```

* `lendingPool`: The address of the lending pool.
* `asset`: The address of the asset you want to get interest information about.

## Understanding Liquorice tokens

To track liquidity, collateral and debt, Liquorice Protocol operates three share tokens per each asset in the pool:

* Collateral Token - interest bearing LP token
* Locked Collateral Token - non-interest bearing tokens representing non-borrowable collateral
* Debt Token

All three tokens follow ERC20 standard, except Debt tokens are non-transferrable thus all transfer and allowance functions are blocked.

#### Decimals

All share tokens decimals are tied to their underlying token decimals, but for security reasons their decimals are shifted by \_DECIMALS\_OFFSET constant upwards which equals 3. For example USDC decimals is 6, but Liquorice LP USDC has 9 decimals.

The result of decimals() function of share tokens **should be ignored**, it defaults to 18

#### balanceOf

```jsx
function balanceOf(address account) public view virtual override returns (uint256)
```

Returns the amount of tokens owned by account of the user.

#### Underlying balance

To retrieve the amount of underlying ERC20 asset that LP/Collateral/Debt token represents, SharesMath library can be used.

```jsx
function toAmount(uint256 share, uint256 totalAmount, uint256 totalShares) internal pure returns (uint256 result)
```

totalSupply value of the share token should be passed as the totalShares param.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://liquorice.gitbook.io/liquorice-docs/for-market-makers/lending-pools-intro/onchain-interactions-with-lending-pools.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
