# IonHandlerBase

[Git Source](https://github.com/Ion-Protocol/ion-protocol/blob/88cc595825f1dc2eb738fb93e172a3e8ab7a5c43/src/flash/IonHandlerBase.sol)

The base handler contract for simpler interactions with the `IonPool` core contract. It combines various individual interactions into one compound interaction to facilitate reaching user end-goals in atomic fashion.

*To actually borrow from `IonPool`, a user must submit a "normalized" borrow amount. This contract is designed to be user-intuitive and, thus, allows a user to submit a standard desired borrow amount, which this contract will then convert into to the appropriate "normalized" borrow amount.*

### [State Variables](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#state-variables" id="state-variables"></a>

#### [BASE](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#base" id="base"></a>

```
IERC20 public immutable BASE;
```

#### [WETH](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#weth" id="weth"></a>

```
IWETH9 public immutable WETH;
```

#### [ILK\_INDEX](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#ilk_index" id="ilk_index"></a>

```
uint8 public immutable ILK_INDEX;
```

#### [POOL](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#pool" id="pool"></a>

```
IonPool public immutable POOL;
```

#### [JOIN](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#join" id="join"></a>

```
GemJoin public immutable JOIN;
```

#### [LST\_TOKEN](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#lst_token" id="lst_token"></a>

```
IERC20 public immutable LST_TOKEN;
```

#### [WHITELIST](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#whitelist" id="whitelist"></a>

```
Whitelist public immutable WHITELIST;
```

### [Functions](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#functions" id="functions"></a>

#### [checkDeadline](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#checkdeadline" id="checkdeadline"></a>

Checks if the tx is being executed before the designated deadline for execution.

*This is used to prevent txs that have sat in the mempool for too long from executing at unintended prices.*

```
modifier checkDeadline(uint256 deadline);
```

#### [onlyWhitelistedBorrowers](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#onlywhitelistedborrowers" id="onlywhitelistedborrowers"></a>

Checks if `msg.sender` is on the whitelist.

*This contract will be on the `protocolControlledWhitelist`. As such, it will validate that users are on the whitelist itself and be able to bypass the whitelist check on `IonPool`.*

```
modifier onlyWhitelistedBorrowers(bytes32[] calldata proof);
```

**Parameters**

| Name    | Type        | Description                      |
| ------- | ----------- | -------------------------------- |
| `proof` | `bytes32[]` | to validate the whitelist check. |

#### [constructor](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#constructor" id="constructor"></a>

Creates a new instance of `IonHandlerBase`

```
constructor(uint8 _ilkIndex, IonPool _ionPool, GemJoin _gemJoin, Whitelist _whitelist);
```

**Parameters**

| Name         | Type        | Description                                                    |
| ------------ | ----------- | -------------------------------------------------------------- |
| `_ilkIndex`  | `uint8`     | of the ilk for which this instance is associated with.         |
| `_ionPool`   | `IonPool`   | address of `IonPool` core contract.                            |
| `_gemJoin`   | `GemJoin`   | the `GemJoin` associated with the `ilkIndex` of this contract. |
| `_whitelist` | `Whitelist` | the `Whitelist` module address.                                |

#### [depositAndBorrow](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#depositandborrow" id="depositandborrow"></a>

Combines gem-joining and depositing collateral and then borrowing into one compound action.

```
function depositAndBorrow(
    uint256 amountCollateral,
    uint256 amountToBorrow,
    bytes32[] calldata proof
)
    external
    onlyWhitelistedBorrowers(proof);
```

**Parameters**

| Name               | Type        | Description                                                                                  |
| ------------------ | ----------- | -------------------------------------------------------------------------------------------- |
| `amountCollateral` | `uint256`   | Amount of collateral to deposit. \[WAD]                                                      |
| `amountToBorrow`   | `uint256`   | Amount of WETH to borrow. Due to rounding, true borrow amount might be slightly less. \[WAD] |
| `proof`            | `bytes32[]` | that the user is whitelisted.                                                                |

#### [\_depositAndBorrow](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#depositandborrow" id="depositandborrow"></a>

Handles all logic to gem-join and deposit collateral, followed by a borrow. It is also possible to use this function simply to gem-join and deposit collateral atomically by setting `amountToBorrow` to 0.

```
function _depositAndBorrow(
    address vaultHolder,
    address receiver,
    uint256 amountCollateral,
    uint256 amountToBorrow,
    AmountToBorrow amountToBorrowType
)
    internal;
```

**Parameters**

| Name                 | Type             | Description                                                                                                                                                                                                                                        |
| -------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `vaultHolder`        | `address`        | The user who will be responsible for repaying debt.                                                                                                                                                                                                |
| `receiver`           | `address`        | The user who receives the borrowed funds.                                                                                                                                                                                                          |
| `amountCollateral`   | `uint256`        | to move into vault. \[WAD]                                                                                                                                                                                                                         |
| `amountToBorrow`     | `uint256`        | out of the vault. \[WAD]                                                                                                                                                                                                                           |
| `amountToBorrowType` | `AmountToBorrow` | Whether the `amountToBorrow` is a min or max. This will dictate the rounding direction when converting to normalized amount. If it is a minimum, then the rounding will be rounded up. If it is a maximum, then the rounding will be rounded down. |

#### [repayFullAndWithdraw](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#repayfullandwithdraw" id="repayfullandwithdraw"></a>

Will repay all debt and withdraw desired collateral amount. This function can also simply be used for a full repayment (which may be difficult through a direct tx to the `IonPool`) by setting `collateralToWithdraw` to 0.

*Will repay the debt belonging to `msg.sender`. This function is necessary because with `rate` updating every single block, it may be difficult to repay a full amount if a user uses the total debt from a previous block. If a user ends up repaying all but dust amounts of debt (due to a slight `rate` change), then they repayment will likely fail due to the `dust` parameter.*

```
function repayFullAndWithdraw(uint256 collateralToWithdraw) external;
```

**Parameters**

| Name                   | Type      | Description                 |
| ---------------------- | --------- | --------------------------- |
| `collateralToWithdraw` | `uint256` | in collateral terms. \[WAD] |

#### [\_getFullRepayAmount](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#getfullrepayamount" id="getfullrepayamount"></a>

Helper function to get the repayment amount for all the debt of a `user`.

*This simply emulates the rounding behaviour of the `IonPool` to arrive at an accurate value.*

```
function _getFullRepayAmount(address user) internal view returns (uint256 repayAmount, uint256 normalizedDebt);
```

**Parameters**

| Name   | Type      | Description          |
| ------ | --------- | -------------------- |
| `user` | `address` | Address of the user. |

**Returns**

| Name             | Type      | Description                                                                              |
| ---------------- | --------- | ---------------------------------------------------------------------------------------- |
| `repayAmount`    | `uint256` | Amount of base asset required to repay all debt (this mimics IonPool's behavior). \[WAD] |
| `normalizedDebt` | `uint256` | Total normalized debt held by `user`'s vault. \[WAD]                                     |

#### [repayAndWithdraw](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#repayandwithdraw" id="repayandwithdraw"></a>

Combines repaying debt and then withdrawing and gem-exitting collateral into one compound action. If repaying **all** is the intention, use `repayFullAndWithdraw()` instead to prevent tx revert from dust amounts of debt in vault.

```
function repayAndWithdraw(uint256 debtToRepay, uint256 collateralToWithdraw) external;
```

**Parameters**

| Name                   | Type      | Description                 |
| ---------------------- | --------- | --------------------------- |
| `debtToRepay`          | `uint256` | In ETH terms. \[WAD]        |
| `collateralToWithdraw` | `uint256` | In collateral terms. \[WAD] |

#### [\_repayAndWithdraw](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#repayandwithdraw" id="repayandwithdraw"></a>

Handles all logic to repay debt, followed by a collateral withdrawal and gem-exit. This function can also be used to just withdraw and gem-exit in atomic fashion by setting the `debtToRepay` to 0.

```
function _repayAndWithdraw(
    address vaultHolder,
    address receiver,
    uint256 collateralToWithdraw,
    uint256 debtToRepay
)
    internal;
```

**Parameters**

| Name                   | Type      | Description                                         |
| ---------------------- | --------- | --------------------------------------------------- |
| `vaultHolder`          | `address` | The user whose debt will be repaid.                 |
| `receiver`             | `address` | The user who receives the the withdrawn collateral. |
| `collateralToWithdraw` | `uint256` | to move into vault. \[WAD]                          |
| `debtToRepay`          | `uint256` | out of the vault. \[WAD]                            |

#### [receive](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#receive" id="receive"></a>

ETH cannot be directly sent to this contract.

*To allow unwrapping of WETH into ETH.*

```
receive() external payable;
```

### [Errors](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#errors" id="errors"></a>

#### [CannotSendEthToContract](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#cannotsendethtocontract" id="cannotsendethtocontract"></a>

```
error CannotSendEthToContract();
```

#### [FlashloanRepaymentTooExpensive](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#flashloanrepaymenttooexpensive" id="flashloanrepaymenttooexpensive"></a>

```
error FlashloanRepaymentTooExpensive(uint256 repaymentAmount, uint256 maxRepaymentAmount);
```

#### [TransactionDeadlineReached](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#transactiondeadlinereached" id="transactiondeadlinereached"></a>

```
error TransactionDeadlineReached(uint256 deadline);
```

### [Enums](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#enums" id="enums"></a>

#### [AmountToBorrow](broken://pages/5btX1fOyLU56sGdI4adw) <a href="#amounttoborrow" id="amounttoborrow"></a>

*During conversion from borrow amount -> "normalized" borrow amount," there is division required. In certain scenarios, it may be desirable to round up during division, in others, to round down. This enum allows a developer to indicate the rounding direction by describing the `amountToBorrow`. If it `IS_MIN`, then the final borrowed amount should be larger than `amountToBorrow` (round up), and vice versa for `IS_MAX` (round down).*

```
enum AmountToBorrow {
    IS_MIN,
    IS_MAX
}
```


---

# 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.ionprotocol.io/devs/smart-contract-architecture/flash/ionhandlerbase.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.
