# Borrowing

## Write functions

### depositTokens

{% code title="borrowing.sol" fullWidth="false" %}

```solidity
function depositTokens(
    BorrowDepositParams memory depositParam
) external payable

```

{% endcode %}

{% code title="IBorrowing.sol" %}

```solidity
struct BorrowDepositParams {
    IOptions.StrikePrice strikePercent;
    uint64 strikePrice;
    uint256 volatility;
    AssetName assetName;
    uint256 depositingAmount;
}

enum AssetName {
    DUMMY,
    ETH,
    WeETH,
    rsETH,
    USDa,
    ABOND,
    TUSDT
}
```

{% endcode %}

{% code title="IOptions.sol" %}

```solidity
enum StrikePrice {
    FIVE,
    TEN,
    FIFTEEN,
    TWENTY,
    TWENTY_FIVE
}
```

{% endcode %}

| Param Name       | Type             |                                                           |
| ---------------- | ---------------- | --------------------------------------------------------- |
| strikePercent    | enum StrikePrice | Strike price percentage chosen by user.                   |
| strikePrice      | uint64           | Strike price chosen by user.                              |
| volatility       | uint256          | Collateral volatility.                                    |
| depositingAmount | uint256          | User depositing amount.                                   |
| assetName        | enum AssetName   | Collateral type depositing by user.                       |
| msg.value        | uint256          | Includes user depositing amount with LZ transaction fees. |

After ratio and option fees calculation, half of the collateral is deposited to external protocol. The USDa are minted to the user with option fees deducted. Then it updates the global data by calling LZ's send function.

### withDraw

{% code title="borrowing.sol" %}

```solidity
function withDraw(
    address toAddress,
    uint64 index,
    bytes memory odosAssembledData,
    bytes memory signature
) payable 
```

{% endcode %}

| Param Name        | Type    | Description                                                                 |
| ----------------- | ------- | --------------------------------------------------------------------------- |
| toAddress         | address | Address of the borrower.                                                    |
| index             | uint64  | Index of the borrower's position tries to withdraw.                         |
| odosAssembledData | bytes   | Odos Execution/Assembled data got from Odos API to Swap collateral to USDT. |
| signature         | bytes   | Odos assembled data signed by admin 2.                                      |
| msg.value         | uint256 | LZ transaction fees.                                                        |

Withdraws 50% of the deposited collateral from the protocol after user pays the debt amount. The 50% of the deposited amount is credited to the user with strike price gains and for the remaining they are given with ABOND token which is fungible. Later they can use the ABOND tokens to redeem yields from external protocol and 50% of the deposited collateral.

{% hint style="info" %} <mark style="color:blue;">For collaterals other than ETH, the borrower will get entire deposited amount during withdraw.</mark>
{% endhint %}

{% hint style="info" %} <mark style="color:blue;">When repaying, the Borrowing contract must have  allowance() to spend funds on behalf of msg.sender. This can be done via the standard ERC20 approve() method on the underlying token contract.</mark>
{% endhint %}

### liquidate

{% code title="borrowing.sol" %}

```solidity
function liquidate(
    address user,
    uint64 index,
    IBorrowing.LiquidationType liquidationType
) payable
```

{% endcode %}

{% code title="IBorrowing.sol" %}

```solidity
enum LiquidationType {
    DUMMY,
    ONE,
    TWO,
    THREE
}
```

{% endcode %}

| Param Name      | Type                   | Description                                       |
| --------------- | ---------------------- | ------------------------------------------------- |
| user            | address                | Address of the borrower.                          |
| index           | uint64                 | Index of the borrower's position.                 |
| liquidationType | struct LiquidationType | Defines the type of liquidation needs to be done. |
| msg.value       | uint256                | LZ transaction fees.                              |

{% hint style="info" %} <mark style="color:blue;">There are currently 2 liquidation types present.</mark>

* <mark style="color:blue;">Liquidate by using CDS funds - ONE.</mark>
* <mark style="color:blue;">Liquidate by taking short position in synthetix with 1x leverage - TWO.</mark>
  {% endhint %}

Liquidates the positions whose collateral value becomes 80%.Liquidates the position based on the opted type by admin. Then during withdraw in CDS, the profits and liquidated collaterals are given to the users based on there proportions.

### redeemYields

```solidity
function redeemYields(address user, uint128 aBondAmount)
```

| Param       | Type    | Description                                  |
| ----------- | ------- | -------------------------------------------- |
| user        | address | Address of the user who is redeeming.        |
| aBondAmount | uint128 | Amount of ABOND tokens user wants to redeem. |

The user provides ABOND tokens to redeem yields from external protocol. Based on the eth backed and cumulative rate of that ABOND token the yield is calculated and given to the user.

{% hint style="info" %} <mark style="color:blue;">When redeeming, the Borrowing contract must have  allowance() to spend funds on behalf of msg.sender. This can be done via the standard ERC20 approve() method on the underlying token contract.</mark>
{% endhint %}

### renewOptions

```solidity
function renewOptions(uint64 index) external payable
```

<table><thead><tr><th>Param</th><th width="235">Type</th><th>Description</th></tr></thead><tbody><tr><td>index</td><td>uint64</td><td>Index of the position to renew.</td></tr></tbody></table>

Renews the 20% downside protection of the borrower position by 30 days by providing USDa tokens.

{% hint style="info" %} <mark style="color:blue;">When renewing, the Borrowing contract must have  allowance() to spend funds on behalf of msg.sender. This can be done via the standard ERC20 approve() method on the underlying token contract.</mark>
{% endhint %}

### calculateRatio

```solidity
function calculateRatio(uint256 amount, uint256 currentEthPrice)
```

| Param Name      | Type    | Description                                     |
| --------------- | ------- | ----------------------------------------------- |
| amount          | uint256 | Collateral amount the user is going to deposit. |
| currentEthPrice | uint256 | Current collateral price.                       |

Calculates the ratio of Collateral value to the total CDS amount in protocol. Updates the total collateral value locked and net CDS amount value based on collateral price changes.

### updateRatePerSecByUSDaPrice

```solidity
function updateRatePerSecByUSDaPrice(uint32 usdaPrice)
```

Updates the interest rate per second based on USDa price. This function can only be called by admin.

### calculateCumulativeRate

```solidity
function calculateCumulativeRate()
```

Calculate the current cumulative rate based on APR and time interval between events.

### Setter Functions

<table data-full-width="false"><thead><tr><th>Function name</th><th>Param Name</th><th>Description</th><th>Param Type</th></tr></thead><tbody><tr><td>setAdmin</td><td>_admin</td><td>Admin who will do core operations.</td><td>address</td></tr><tr><td>setTreasury</td><td>_treasury</td><td>Treasury contract address.</td><td>address</td></tr><tr><td>setOptions</td><td>_options</td><td>Options contract address.</td><td>address</td></tr><tr><td>setBorrowLiquidation</td><td>_borrowLiquidation</td><td>BorrowLiquidation contract address</td><td>address</td></tr><tr><td>setLTV</td><td>_LTV</td><td>LTV ratio.</td><td>uint8</td></tr><tr><td>setAPR</td><td>_ratePerSec</td><td>Interest rate per second based on annual interest.</td><td>uint128</td></tr><tr><td>setBondRatio</td><td>_bondRatio</td><td>ABOND to USDa ratio</td><td>uint64</td></tr></tbody></table>

## Read Functions

### getAbondYields

```solidity
function getAbondYields(address user, uint128 aBondAmount)
```

| Param Name  | Type    | Description                                 |
| ----------- | ------- | ------------------------------------------- |
| user        | address | Address of the user who is redeeming ABOND. |
| aBondAmount | uint128 | Amount of ABONDs to redeem.                 |

Returns the collateral backed for this ABOND, redeemable collateral amount with external protocol interest and USDa amount got from liquidation.

### getUSDValue

```solidity
function getUSDValue(address token)
```

Returns the exchange rate to ETH and USD value of the collateral.

### getLTV

```solidity
function getLTV()
```

### getOptionFeesToPay

```solidity
function getOptionFeesToPay(uint64 index) public view returns (uint256)
```

Returns the option fees the borrower needs to pay to renew the 20% downside protection.


---

# 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://docs.nondollar.life/autonomint/blockchain-docs/core-contracts/borrowing.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.
