# Overview

## Tydro Documentation

Tydro is a non-custodial lending protocol for onchain capital markets. Powered by Aave and built on Ink, it enables trustless borrowing, flexible collateral, and seamless coordination across the Ink ecosystem and beyond. Suppliers earn interest by providing liquidity to supported markets. Borrowers access capital by providing collateral that exceeds the borrowed amount.<br>

{% columns %}
{% column %}
[Concepts](/introduction/concepts)
{% endcolumn %}

{% column %}
[Liquidity Protocol](/primitives/liquidity-pool)
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column %}
[Reserve](/primitives/reserve)
{% endcolumn %}

{% column %}
[Oracle](/primitives/oracle)
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column %}
[Flash Loans](/primitives/flash-loans)
{% endcolumn %}

{% column %}
[Smart Contracts](/developers/smart-contracts)
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column %}
[Resources](/resources/risks)
{% endcolumn %}

{% column %}
[FAQs](https://tydro-page.webflow.io/faq)
{% endcolumn %}
{% endcolumns %}

<figure><img src="/files/Auc4SgzTUQ739wmAMI0M" alt=""><figcaption></figcaption></figure>


# Concepts

### Tydro

Basics to know when building on the Tydro<br>

{% columns %}
{% column width="50%" %}
[**Lending Protocol**](/introduction/concepts/lending-protocol)
{% endcolumn %}

{% column %}
[**Supply**](/introduction/concepts/supply)
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column width="50%" %}
[**Borrow**](/introduction/concepts/borrow)
{% endcolumn %}

{% column %}
[**Repay**](/introduction/concepts/repay)
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column width="50%" %}
[**Withdraw**](/introduction/concepts/withdraw)
{% endcolumn %}

{% column %}
[**Liquidations**](/introduction/concepts/liquidations)
{% endcolumn %}
{% endcolumns %}


# Lending Protocol

A lending protocol is a decentralised system of smart contracts that allows users to supply and borrow digital assets. Tydro operates on a collateralised lending model, where users deposit assets into protocol-managed pools to earn interest, and other users borrow from those pools by providing collateral that exceeds the borrowed amount. The protocol is deployed within the Ink ecosystem, ensuring seamless integration with ecosystem-aligned assets and applications

Tydro is non-custodial, meaning users retain full control over their assets. All interactions take place through self-custodial wallets, with supply and borrow actions executed by permissionless smart contracts. These contracts enforce rules such as interest rates, loan-to-value ratios, and liquidation thresholds, providing a transparent and trust-minimised experience.

Liquidity on Tydro flows through Aave-powered pools, leveraging Aave’s battle-tested infrastructure to support efficient and secure lending at scale.

Tydro also includes features such as INK rewards and real-time LTV alerts, and supports ecosystem-aligned assets like USDG, kBTC, and GHO. As part of the broader Ink ecosystem, it provides secure and efficient access to capital through a minimal and composable lending layer


# Supply

<figure><img src="/files/CrtRX190R4MaRsym82Ln" alt=""><figcaption></figcaption></figure>

Supplying tokens to Tydro allows users to earn interest on their digital assets and utilise supplied tokens as collateral. When tokens are supplied, they are transferred to Tydro’s liquidity pools, a system of smart contracts that facilitates overcollateralised borrowing of tokens. In Tydro, supplied tokens automatically accrue interest based on the current market supply rate. As the balance of supplied tokens increases, interest is accrued dynamically, reflecting the current rate allocated to suppliers.

Interest rates for supplied tokens are determined by protocol parameters such as the borrow utilisation rate, which measures the proportion of assets currently borrowed against the total supplied in the pool. These parameters are adjusted through internal configurations that influence incentives across markets, directing capital either towards lenders or borrowers by modifying the effective yield or borrowing cost. As liquidity is supplied, borrowed, repaid, or withdrawn from the pool, the interest rates are updated accordingly.


# Borrow

<figure><img src="/files/aGAxBGIcbBRdYBpdecFg" alt=""><figcaption></figcaption></figure>

Borrowing tokens from Tydro allows users to unlock liquidity by using their supplied tokens as collateral, accessing capital without selling their assets. However, borrowers are exposed to liquidation risk if the value of their collateral drops below the required threshold.

Interest rates are set dynamically based on protocol parameters such as the borrow utilisation rate, which represents the percentage of total supplied liquidity currently borrowed, and internal configurations that direct incentives across markets. These parameters influence the effective rates earned by suppliers and paid by borrowers by adjusting how capital flows between the two sides of the pool. When utilisation increases, borrowing demand rises, causing interest rates to adjust upward to maintain balance and attract additional liquidity.

Each market operates with specific parameters designed to incentivise both borrowers and suppliers. To maintain a healthy ratio and avoid liquidation risk, borrowers should actively monitor their collateral levels. Tools like real-time LTV alerts help ensure borrow positions remain safely overcollateralised as markets move or interest accrues.


# Repay

<figure><img src="/files/BUjPnF0cSzkiMgTV3tzR" alt=""><figcaption></figcaption></figure>

Repaying borrowed tokens in Tydro is an important step in managing active borrow positions. Borrowers can repay using the same tokens they borrowed, or by using aTokens representing the same underlying asset. In supported cases, repayment may also be done using other tokens such as collateral assets through periphery contracts that handle asset conversions automatically. This flexibility makes it easier for borrowers to manage and close their positions when needed.

Repayment improves the health factor of a position by increasing the collateralisation ratio. By reducing the outstanding debt relative to the collateral posted, repayment lowers liquidation risk and may allow borrowers to safely withdraw a portion of their collateral.


# Withdraw

<figure><img src="/files/wjKqxOZ4GJuWIhn97d4C" alt=""><figcaption></figcaption></figure>

Tydro allows suppliers to withdraw their supplied tokens, including accrued interest, as long as there is sufficient unborrowed liquidity in the reserve. The withdrawal amount is limited by the available underlying assets, and that the user’s ability to maintain a sufficient collateral ratio for their borrow position. Periphery contracts with features such as withdraw and switch, allow users to redeem their supplied liquidity in a different token, providing more options for efficient asset management.

When withdrawing with an active borrow position, it’s crucial to maintain a healthy collateralisation ratio to avoid liquidation. Reducing collateral can lower the health factor, increasing the risk of liquidation. To remain safe, after the withdrawal, the account must stay above the liquidation threshold parameters. Therefore, withdrawals require careful management and consideration of the overall borrow positions to avoid liquidation.


# Liquidations

<figure><img src="/files/n2lv8hXXmmKPxarPvBsD" alt=""><figcaption></figcaption></figure>

The health factor is a key metric in Tydro that indicates the safety of a borrow position. It is calculated as:

```
Health Factor = (Total Collateral Value × Liquidation Threshold) / Total Borrow Value
```

A health factor above 1 means the position is safely overcollateralised. If it falls below 1, the position becomes eligible for liquidation.&#x20;

Each asset has its own liquidation threshold, defined through protocol parameters. These parameters determine how much collateral must be maintained for an open loan. For example, the liquidation threshold for most assets will typically be around 75–80% LTV, meaning the loan can reach up to 75–80% of the collateral value before liquidation becomes possible.

For example, if a user supplies $10,000 in ETH with an 80% liquidation threshold and borrows $6,000 in USDG, the health factor would be 1.33.

The health factor changes with market conditions. If the value of the collateral increases, the health factor improves. If it decreases, the health factor drops, increasing liquidation risk. Users can raise their health factor by supplying more collateral or repaying part of their borrow position.

There is no fixed “safe” health factor. What is considered safe depends on the volatility and correlation of the assets. Lower health factors may be acceptable for stable or correlated assets like stablecoins, while more volatile assets require higher buffers.

When a position is liquidated, up to 50% of the borrowed amount can be repaid by a liquidator. In return, the liquidator receives a portion of the collateral along with a liquidation bonus. This process is permissionless, meaning anyone can initiate a liquidation if the conditions are met.

Liquidations are competitive. Liquidators monitor positions closely and aim to execute transactions quickly when a borrower's health factor falls below the threshold.

Tydro includes real-time LTV alerts to help borrowers track their position safety. Monitoring the health factor regularly is essential to avoid liquidation.

### Tools for Managing Health Factor

* Simulate health factor changes: [DeFi Simulator](https://defisim.xyz/)
* Auto-repay borrow position: [DeFi Saver](https://defisaver.com/)

For more information on participating as a liquidator, see the developer guide.


# Liquidity Pool

<figure><img src="/files/ZBP47GquatVI4UIaYckH" alt=""><figcaption></figcaption></figure>

A liquidity pool is a Tydro market instance that enables users to participate as suppliers or borrowers. Parameters such as reserve configurations and collateralisation thresholds define each pool.

Suppliers deposit liquidity into the pool that borrowers can access through overcollateralised positions. In return, suppliers earn interest while borrowers gain access to liquidity, all facilitated through decentralised smart contracts.

Tydro liquidity pools operate across supported blockchain networks. Smart contracts enforce pool parameters and automate borrowing, repayment, and liquidation without intermediaries. This decentralised design enhances the transparency, efficiency, and security of financial interactions within the pool


# Reserve

<figure><img src="/files/cCnbAcDXtKKJT5YLuqMz" alt=""><figcaption></figcaption></figure>

A reserve is an instance of a token within a Tydro liquidity pool. Each reserve is governed by a set of parameters that manage risk and optimise liquidity.&#x20;

### **Key Reserve Parameters**

**Loan-to-Value (LTV)**\
The maximum amount that can be borrowed relative to the value of the collateral. For example, a 75 percent LTV allows borrowing up to 75 percent of the collateral’s value. Assets with zero percent LTV cannot be used as collateral.

**Liquidation Threshold**\
The point at which a position becomes at risk of liquidation. If the value of the collateral falls below this threshold, the position may be liquidated to repay the borrower's debt.

**Borrowing Enabled**\
Specifies whether users can borrow liquidity from this reserve.

**Caps**\
Supply and borrow caps limit the total amount of a token that can be supplied or borrowed from a reserve. These caps help manage liquidity and reduce exposure during volatile market conditions.

**Interest Rate Model**\
Interest rates in Tydro adjust dynamically based on the utilisation of liquidity. As more funds are borrowed, interest rates increase to ensure sufficient liquidity remains available for withdrawals and liquidations. Rates are determined by parameters that define the base rate and how steeply rates rise with utilisation.


# Incentives

<figure><img src="/files/1UTpQ5NZPxQGL3kY02YL" alt=""><figcaption></figcaption></figure>

Incentives within Tydro encourage active participation from both suppliers and borrowers, enhancing liquidity and the overall efficiency of the system. Incentive programs can originate from various sources, including ecosystem-aligned initiatives and external contributors interested in supporting liquidity for specific reserves.

**$INK Rewards**

$INK is the native token of the Ink ecosystem. Users who supply or borrow eligible assets on Tydro earn INK rewards proportional to their activity. Rewards accrue continuously and can be claimed through the Tydro interface.

This incentive model is designed to strengthen market depth, encourage usage, and promote sustained participation in the protocol. It aligns user activity with the long-term health and growth of Tydro markets.

#### Flexibility

Additional incentive programs or changes to reward parameters may be introduced, such as adjusting emission rates, adding new incentivised markets, or launching ecosystem-funded campaigns to support liquidity.


# Oracle

<figure><img src="/files/uoIqe1GZLJqw69f9PXEx" alt=""><figcaption></figcaption></figure>

Each reserve within Tydro is associated with an oracle that reports the market price of the underlying asset. These prices are essential for determining collateral value, borrowing capacity, health factors, and liquidation eligibility.

Tydro uses Chainlink as its price oracle provider. Chainlink is a decentralized oracle network that aggregates market data from a wide set of independent node operators and premium data providers, with reports finalized on-chain. This decentralized model is designed to be resistant to manipulation, downtime, and single points of failure.

### How prices reach the protocol

Each Chainlink price feed publishes updates on-chain when one of two triggers fires:

* **Deviation threshold** — the asset's price has moved by more than a configured percentage since the last update.
* **Heartbeat** — a maximum time has elapsed since the last update.

Together these ensure that on-chain prices stay close to market while bounding update frequency for cost efficiency.

The protocol reads prices through the `TydroOracle` contract, which routes each request to the appropriate Chainlink feed for the asset. The on-chain `TydroOracle` address is listed on the [Addresses page](/resources/addresses).

### Why Chainlink

* **Decentralization** — multiple independent nodes report, aggregated on-chain.
* **Reliability** — deviation thresholds and heartbeats are configured per asset to balance price freshness against gas cost.
* **Track record** — Chainlink secures the majority of value across DeFi lending protocols.

For more information about Chainlink price oracles, see the [Chainlink documentation](https://docs.chain.link/data-feeds).


# Flash Loans

<figure><img src="/files/XdH6q2bMb9H8YCcmTBjC" alt=""><figcaption></figcaption></figure>

Flash Loans let you borrow an asset without posting collateral, provided the borrowed amount plus a fee is returned before the transaction ends. Because everything settles within a single transaction, you may see these referred to as "one-block borrows"\
\
There is no real-world equivalent for flash loans; they rely on how blockchain state is updated within a block. This is an advanced feature intended for developers who are comfortable with the EVM, Solidity, and smart contract patterns.

### Overview

Flash loans allow access to pool liquidity (only for reserves where borrowing is enabled) for the duration of one transaction, as long as either:

* the borrowed amount + fee is returned by the end, or
* a debt position is opened by the end (if permitted).

Tydro exposes two methods:

#### `flashLoan()`

* Borrow from multiple reserves in a single transaction.
* At completion you may \
  1\) repay amount + fee, or\
  2\) open a variable-rate debt position backed by posted collateral or via credit delegation.
* Note: the flash loan fee can be waived for approved `flashBorrowers` (managed by ACLManager).

#### `flashLoanSimple()`

* Borrow from a single reserve for the transaction.
* The fee is not waived and no debt position can be opened at the end.
* Optimized for gas when you only need a basic, single-asset flash loan.

### Execution Flow

Practical mental model for implementation:

1. Request: Your contract calls the Pool and requests a flash loan of specific amount(s) of one or more reserve(s) via `flashLoanSimple()` or `flashLoan()`.
2. Transfer + Callback: After checks, the Pool transfers the requested amounts to your contract and then calls your receiver’s `executeOperation()`.
3. Your Logic: With funds in hand, your contract runs arbitrary logic.
4. Settlement:
   * For `flashLoanSimple()`: before finishing, approve the Pool to pull back amount + fee.
   * For `flashLoan()`: for each reserve, depending on the `interestRateMode` you passed, either\
     a) approve the Pool for amount + fee, or\
     b) ensure sufficient collateral or credit delegation is in place to open a debt position.
5. Atomicity: If the owed amount is not available (insufficient balance, missing approval, or insufficient collateral for debt), the entire transaction reverts.
6. Block scope: Everything above happens within a single transaction (i.e., one block).

### Applications of Flash Loans

Tydro Flash Loans are already used with Tydro for liquidity switch feature. Other examples in the wild (and supported with Tydro) include:

* **Arbitrage**: Arbitrage between assets, without needing to have the principal amount to execute the arbitrage.
* **Liquidations:** Liquidating borrow positions, without having to repay the debt of the positions and using discounted collateral claimed to payoff flashLoan amount + fee.

### Flash loan fee

* The flash loan fee is initialized at **0.05%**. The current value can be queried through `FLASHLOAN_PREMIUM_TOTAL`.
* The total fee paid by borrowers can be shared between LPs and the protocol treasury:
  * Fee to LPs: `FLASHLOAN_PREMIUM_TOTAL - FLASHLOAN_PREMIUM_TO_PROTOCOL`
  * Fee to Protocol: `FLASHLOAN_PREMIUM_TO_PROTOCOL`
* At initialization, `FLASHLOAN_PREMIUM_TO_PROTOCOL` = 0.

### Step by step

#### 1. Setting Up

* Your receiver must implement [`IFlashLoanSimpleReceiver`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/flashloan/interfaces/IFlashLoanSimpleReceiver.sol) or [`IFlashLoanReceiver`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/flashloan/interfaces/IFlashLoanReceiver.sol), including the `executeOperation()` function.
* Because the Pool pulls repayment, your contract must approve the Pool to spend the borrowed amount + premium.

#### 2. Calling flashLoan() or flashLoanSimple()

There are three ways to initiate:

* From an EOA: Send a transaction to the Pool calling `flashLoan()` or `flashLoanSimple()`. See the Pool docs for parameters, and use your receiver address from step 1 as `receiverAddress`.
* From a different contract: Same as above; ensure `receiverAddress` is your receiver from step 1.
* From the same contract: Call the method with `receiverAddress = address(this)`.

> **Security note:** Do **not** keep funds permanently on your receiver / [`FlashLoanReceiverBase`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/flashloan/interfaces/IFlashLoanReceiver.sol). Idle funds can be griefed (e.g., siphoned during forced interactions).

#### 3. Completing the flash loan

**Immediate repayment**

* If you used `flashLoanSimple()` or passed `interestRateMode = 0` for any asset in the `modes` parameter of `flashLoan()`, you must repay immediately.
* Ensure your contract holds amount + premium for each relevant asset. You can compute this from the `amounts`and `premiums` arrays received in `executeOperation()`.
* You do not manually transfer funds back; the Pool pulls repayment when your call returns.

**Incurring a debt**

* If you passed `mode = 1` or `mode = 2` for any asset in `modes`, the `onBehalfOf` address will incur the debt, provided it has previously approved the `msg.sender` to borrow on its behalf.
* You can mix behaviors: some assets repaid immediately, others converted into debt.

### Notes

* Tydro does **not offer a UI** for flash loans. This is a **developer-only feature** available via smart contracts.


# Smart Contracts

Tydro is built on a modular set of smart contracts, all available on [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin).\
Developers can integrate contract addresses directly into Solidity or JavaScript projects using the [<mark style="color:blue;">Tydro Address Book</mark>.](/resources/addresses)

The repository is organized into the following categories:

* Pool
* Configuration
* Logic
* Tokenization
* Helpers
* Misc

### Pool

#### Pool

The [Pool](/developers/smart-contracts/pool) is the central entry point to Tydro. All core user interactions such as supplying, borrowing, and repaying flow through this contract. Ownership of the Pool is tracked by the PoolAddressesProvider, and admin-level actions (like changing parameters) are routed through the PoolConfigurator.

#### L2Pool

The [L2Pool](/developers/smart-contracts/l2-pool) is an optimized version of the Pool contract, designed specifically for rollups.\
It enables gas-efficient interactions by accepting compact, byte-encoded calldata. This reduces transaction costs while maintaining the same functionality as the Pool.

#### PoolConfigurator

The [PoolConfigurator](/developers/smart-contracts/pool-configurator) manages risk parameters and configuration for the Pool. Only addresses with the appropriate permissions, assigned through the ACLManager, can call its write functions.

### Configuration

ACLManager

The [ACLManager](/developers/smart-contracts/aclmanager) is the registry of protocol roles and permissions. It defines and enforces access control across the system.

#### PoolAddressesProvider

The [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) is a registry of various components of the protocol, including the ACLManager and Pool contracts. It has the ability to  update pointers and proxy implementations to support upgrades.

### Logic

[Libraries](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/logic/) that implement the underlying mechanics of protocol operations. These libraries ensure that Pool interactions execute reliably and securely.

### Tokenization

#### aToken

Supplying assets mints [aTokens](/developers/smart-contracts/tokenization) which represent the depositor’s balance and automatically accrue yield. aTokens are burned when assets are withdrawn from the Pool

#### VariableDebtToken

Borrowing at a variable rate issues [VariableDebtTokens](/developers/smart-contracts/tokenization). These non-transferable tokens track a borrower’s position and increase automatically as interest accrues.

### Helpers

#### L2Encoder

The [L2Encoder](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) is a helper contract to encode calldata that is passed to the L2Pool. It is used to optimize calldata size in L2Pool for transaction cost reduction. It is only intended to help generate calldata for users/frontends.

#### TydroProtocolDataProvider

The [TydroProtocolDataProvider](/developers/smart-contracts/view-contracts#view-contracts) and formats data from the Pool, making it easier for applications to access key protocol information.

### Misc

#### TydroOracle

The [TydroOracle](/developers/smart-contracts/oracles#aaveoracle) manages reserve oracles and provides reference prices for assets. It ensures accurate pricing and updates sources as needed.

#### DefaultReserveInterestRateStrategy

The [DefaultReserveInterestRateStrategy](/developers/smart-contracts/interest-rate-strategy) calculates borrowing costs and yields based on the state of each reserve. It defines the parameters and logic used to update interest rates dynamically.

#### PriceOracleSentinel

The [PriceOracleSentinel](/developers/smart-contracts/oracles) safeguards the protocol during oracle disruptions. If a price feed becomes unavailable, it restricts operations until recovery and provides users with a grace period to restore healthy positions.


# Pool

This contract is the main user-facing contract. Most user interactions with Tydro occur via the Pool contract. It exposes the liquidity management methods that can be invoked using either ***Solidity*** or ***Web3*** libraries.

The Pool contract is the main entry point for users in Tydro. Most interactions such as supplying, borrowing, repaying, or managing collateral are executed through this contract. It exposes all core liquidity functions and can be called directly in Solidity or through Web3 libraries.

#### Functions available through Pool

Users can interact with the Pool contract to:

* Supply assets into the protocol
* Withdraw supplied assets
* Borrow against collateral
* Repay borrowed assets
* Enable or disable assets as collateral
* Liquidate undercollateralised positions

The Pool contract is deployed behind a proxy and registered with the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) of each market. Administrative actions are routed through the  [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract referenced in the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider).

The source code is available on [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/Pool.sol).

### Write Methods

#### initialize

```
function initialize(IPoolAddressesProvider provider) external virtual
```

Initializes the Pool.

Function is invoked by the proxy contract when the Pool contract is added to the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) of the market.

Caches the address of the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) in order to reduce gas consumption on subsequent operations.

#### Input Parameters:

| Name     | Type      | Description                              |
| -------- | --------- | ---------------------------------------- |
| provider | `address` | The address of the PoolAddressesProvider |

#### supply

```
function supply(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode
) public virtual override
```

Supplies a certain amount of an asset into the protocol, minting the same amount of corresponding aTokens and transferring them to the onBehalfOf address. For example, if a user supplies 100 USDC and onBehalfOf address is the same as msg.sender, they will get 100 aUSDC in return.

The referralCode is emitted in Supply event and can be for third-party referral integrations. To activate the referral feature and obtain a unique referral code, integrators need to submit a proposal to Tydro.

> ⚠️ **Warning:** When supplying, the `Pool` contract must have `allowance()` to spend funds on behalf of `msg.sender` for at least the amount for the asset being supplied. This can be done via the standard ERC20 `approve()` method on the underlying token contract.

{% hint style="info" %}
Referral supply is currently inactive, you can pass 0 as referralCode. This program may be activated in the future through a Tydro proposal.
{% endhint %}

#### Input Parameters:

| Name         | Type      | Description                                                                                                                                                                                                                                                                                                                |
| ------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset        | `address` | The address of the underlying asset being supplied to the pool                                                                                                                                                                                                                                                             |
| amount       | `uint256` | The amount of asset to be supplied                                                                                                                                                                                                                                                                                         |
| onBehalfOf   | `address` | The address that will receive the corresponding aTokens. This is the only address that will be able to withdraw the asset from the pool. This will be the same as `msg.sender` if the user wants to receive aTokens into their own wallet, or use a different address if the beneficiary of aTokens is a different wallet. |
| referralCode | `uint16`  | Referral supply is currently inactive, you can pass `0`. This code is used to register the integrator originating the operation, for potential rewards. `0` if the action is executed directly by the user, without any middle-men.                                                                                        |

#### supplyWithPermit

```
function supplyWithPermit(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
) public virtual override
```

Supply with transfer approval of the asset to be supplied via permit function. This method removes the need for separate approval tx before supplying asset to the pool. See: <https://eips.ethereum.org/EIPS/eip-2612>.

{% hint style="info" %}
Permit signature must be signed by msg.sender with spender as Pool address.
{% endhint %}

{% hint style="info" %}
Referral program is currently inactive, you can pass 0 as referralCode. This program may be activated in the future through a Tydro proposal.
{% endhint %}

#### Input Parameters:

| Name         | Type      | Description                                                                                                                                                                                                                        |
| ------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset        | `address` | The address of underlying asset being supplied. The same asset as used in permit `v`, `s`, and `r`                                                                                                                                 |
| amount       | `uint256` | The amount of asset to be supplied and signed for approval. The same amount as used in permit `v`, `s`, and `r`                                                                                                                    |
| onBehalfOf   | `address` | The address that will receive the aTokens. This will be the same as `msg.sender` if the user wants to receive aTokens into their own wallet, or use a different address if the beneficiary of aTokens is a different wallet        |
| referralCode | `uint16`  | Referral supply is currently inactive, you can pass `0`. This code is used to register the integrator originating the operation, for potential rewards. `0` if the action is executed directly by the user, without any middle-men |
| deadline     | `uint256` | The unix timestamp up until which the permit signature is valid                                                                                                                                                                    |
| permitV      | `uint8`   | The `v` parameter of the ERC712 permit signature                                                                                                                                                                                   |
| permitR      | `bytes32` | The `r` parameter of the ERC712 permit signature                                                                                                                                                                                   |
| permitS      | `bytes32` | The `s` parameter of the ERC712 permit signature                                                                                                                                                                                   |

#### withdraw

```
function withdraw(address asset, uint256 amount, address to) public virtual override returns (uint256)
```

Withdraws an amount of underlying asset from the reserve, burning the equivalent aTokens owned. For example, if a user has 100 aUSDC and calls withdraw(), they will receive 100 USDC, burning the 100 aUSDC.

If user has any existing debt backed by the underlying token, then the maximum amountavailable to withdraw is the amount that will not leave user's health factor < 1 after withdrawal.

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

{% hint style="info" %}
Reserves with a Loan To Value parameter of 0% must be disabled as collateral (using Pool.setUserUseReserveAsCollateral or by fully withdrawing the supplied balance) before other assets can be withdrawn.
{% endhint %}

#### Input Parameters:

| Name   | Type      | Description                                                                                                                                                                                                                    |
| ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| asset  | `address` | The address of the underlying asset to withdraw, not the aToken                                                                                                                                                                |
| amount | `uint256` | The underlying amount to be withdrawn (the amount supplied), expressed in wei units. Use `type(uint).max` to withdraw the entire aToken balance                                                                                |
| to     | `address` | The address that will receive the underlying `asset`. This will be the same as `msg.sender` if the user wants to receive the tokens into their own wallet, or use a different address if the beneficiary is a different wallet |

#### Return Values:

| Type      | Description                |
| --------- | -------------------------- |
| `uint256` | The final amount withdrawn |

#### borrow

```
function borrow(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode,
    address onBehalfOf
) public virtual override
```

Allows users to borrow a specific amount of the reserve underlying asset, provided the borrower has already supplied enough collateral, or they were given enough allowance by a credit delegator on the corresponding debt token (VariableDebtToken). For example, if a user borrows 100 USDC passing their own address as onBehalfOf, they will receive 100 USDC into their wallet and 100 variable debt tokens.

{% hint style="info" %}
NOTE: If onBehalfOf is not the same as msg.sender, then onBehalfOf must have supplied enough collateral via supply() and have delegated credit to msg.sender via approveDelegation().
{% endhint %}

{% hint style="info" %}
Referral program is currently inactive, you can pass 0 as referralCode. This program may be activated in the future.
{% endhint %}

#### Input Parameters:

| Name             | Type      | Description                                                                                                                                                                                                                        |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset            | `address` | The address of the underlying asset to borrow                                                                                                                                                                                      |
| amount           | `uint256` | The amount to be borrowed, expressed in wei units                                                                                                                                                                                  |
| interestRateMode | `uint256` | Should always be passed a value of `2` (variable rate mode)                                                                                                                                                                        |
| referralCode     | `uint16`  | Referral supply is currently inactive, you can pass `0`. This code is used to register the integrator originating the operation, for potential rewards. `0` if the action is executed directly by the user, without any middle-men |
| onBehalfOf       | `address` | This should be the address of the borrower calling the function if they want to borrow against their own collateral, or the address of the credit delegator if the caller has been given credit delegation allowance               |

repay

```
function repay(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf
) public virtual override returns (uint256)
```

Repays a borrowed amount on a specific reserve, burning the equivalent debt tokens owned. For example, if a user repays 100 USDC, the 100 variable debt tokens owned by the onBehalfOfaddress will be burned.

> ⚠️ **Warning:**  When repaying, the `Pool` contract must have allowance to spend funds on behalf of `msg.sender` for at least the `amount` for the asset you are repaying with. This can be done via the standard ERC20 `approve()` method on the underlying token contract.

#### Input Parameters:

| Name             | Type      | Description                                                                                                                                                                                                                                                                                                   |
| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset            | `address` | The address of the borrowed underlying asset previously borrowed                                                                                                                                                                                                                                              |
| amount           | `uint256` | The amount to repay, expressed in wei units. Use `type(uint256).max` in order to repay the whole debt, ONLY when the repayment is not executed on behalf of a 3rd party. In case of repayments on behalf of another user, it's recommended to send an amount slightly higher than the current borrowed amount |
| interestRateMode | `uint256` | Only available option is `2` (variableRateMode)                                                                                                                                                                                                                                                               |
| onBehalfOf       | `address` | The address of the user who will get their debt reduced/removed. This should be the address of the user calling the function if they want to reduce/remove their own debt, or the address of any other borrower whose debt should be removed                                                                  |

#### repayWithPermit

```
function repayWithPermit(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
) public virtual override returns (uint256)
```

Repay with transfer approval of the borrowed asset to be repaid, done via permit function. This method removes the need for separate approval tx before repaying asset to the pool. See: <https://eips.ethereum.org/EIPS/eip-2612>.

{% hint style="info" %}
Permit signature must be signed by msg.sender with spender value as Pool address.
{% endhint %}

#### Input Parameters:

| Name             | Type      | Description                                                                                                                                                                                                                                  |
| ---------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset            | `address` | The address of the borrowed underlying asset previously borrowed. The same asset as used in permit `v`, `r`, and `s`                                                                                                                         |
| amount           | `uint256` | The amount to repay, expressed in wei units. Use `type(uint256).max` in order to repay the whole debt to pay without leaving aToken dust. The same amount as used in permit `v`,`r`,`s`                                                      |
| interestRateMode | `uint256` | Only available option is `2` (variableRateMode)                                                                                                                                                                                              |
| onBehalfOf       | `address` | The address of the user who will get their debt reduced/removed. This should be the address of the user calling the function if they want to reduce/remove their own debt, or the address of any other borrower whose debt should be removed |
| deadline         | `uint256` | The unix timestamp up until which the permit signature is valid                                                                                                                                                                              |
| permitV          | `uint8`   | The `v` parameter of the ERC712 permit signature                                                                                                                                                                                             |
| permitR          | `bytes32` | The `r` parameter of the ERC712 permit signature                                                                                                                                                                                             |
| permitS          | `bytes32` | The `s` parameter of the ERC712 permit signature                                                                                                                                                                                             |

**Return Values:**

| Type      | Description             |
| --------- | ----------------------- |
| `uint256` | The final amount repaid |

repayWithATokens

```
function repayWithATokens(address asset, uint256 amount, uint256 interestRateMode
) public virtual override returns (uint256)
```

Allows a user to repay a borrowed amount on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. For example, a user repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens. Passing uint256.maxas the amount will clean up any residual aToken dust balance, if the user aToken balance is not enough to cover the whole debt.

#### Input Parameters:

| Name             | Type      | Description                                                                                                                  |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------- |
| asset            | `address` | The address of the borrowed underlying asset previously borrowed                                                             |
| amount           | `uint256` | The amount to repay. Use `type(uint256).max` in order to repay the whole debt for `asset` to pay without leaving aToken dust |
| interestRateMode | `uint256` | Only available option is `2` (variableRateMode)                                                                              |

**Return Values:**

| Type      | Description             |
| --------- | ----------------------- |
| `uint256` | The final amount repaid |

#### setUserUseReserveAsCollateral

```
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) public virtual override
```

Allows suppliers to enable/disable a specific supplied asset as collateral. Sets the <kbd>asset</kbd> of <kbd>msg.sender</kbd> to be used as collateral or not.

{% hint style="info" %}
An asset in Isolation Mode can be enabled to use as collateral only if no other asset is already enabled to use as collateral.
{% endhint %}

{% hint style="info" %}
An asset with LTV parameter of 0% cannot be enabled as collateral.
{% endhint %}

{% hint style="info" %}
The user won’t be able to disable an asset as collateral if they have an outstanding debt position which could be left with the Health Factor < HEALTH\_FACTOR\_LIQUIDATION\_THRESHOLD on disabling the given asset as collateral.
{% endhint %}

**Input Parameters:**

| Name            | Type      | Description                                                                 |
| --------------- | --------- | --------------------------------------------------------------------------- |
| asset           | `address` | The address of the underlying asset supplied                                |
| useAsCollateral | `bool`    | `true` if the user wants to use the supply as collateral, `false` otherwise |

#### liquidationCall

```
function liquidationCall(
    address collateralAsset,
    address debtAsset,
    address user,
    uint256 debtToCover,
    bool receiveAToken
) public virtual override
```

Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1.

When the health factor of a position is below 1, the caller (liquidator) repays the debtToCoveramount of debt of the user getting liquidated. This is part or all of the outstanding borrowed amount on behalf of the borrower. The caller then receives a proportional amount of the collateralAsset (discounted amount of collateral) plus a liquidation bonus to cover market risk.

Liquidators can decide if they want to receive an equivalent amount of collateral aTokens instead of the underlying asset. 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.

* *In most scenarios*, profitable liquidators will choose to liquidate as much as they can (50% of the user position).
* debtToCover parameter can be set to uint(-1) and the protocol will proceed with the highest possible liquidation allowed by the close factor.
* To check a user's health factor, use \[getUserAccountData()].

{% hint style="info" %}
Liquidators must approve() the Pool contract to use debtToCover of the underlying ERC20 of the asset used for the liquidation.
{% endhint %}

**Input Parameters:**

| Name            | Type      | Description                                                                                                                                                            |
| --------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| collateralAsset | `address` | The address of the underlying asset used as collateral, to receive as result of the liquidation                                                                        |
| debtAsset       | `address` | The address of the underlying borrowed asset to be repaid with the liquidation                                                                                         |
| user            | `address` | The address of the borrower getting liquidated                                                                                                                         |
| debtToCover     | `uint256` | The debt amount of borrowed `asset` the liquidator will repay                                                                                                          |
| receiveAToken   | `bool`    | `true` if the liquidator wants to receive the aTokens equivalent of the purchased collateral, `false` if they want to receive the underlying collateral asset directly |

#### flashLoan

```
function flashLoan(
    address receiverAddress,
    address[] calldata assets,
    uint256[] calldata amounts,
    uint256[] calldata interestRateModes,
    address onBehalfOf,
    bytes calldata params,
    uint16 referralCode
) public virtual override
```

Allows users to access liquidity of the pool for a given list of assets within one transaction, as long as the amount taken plus a fee is returned. The receiver must approve the Pool contract for at least the *amount borrowed + fee*, otherwise the transaction will revert.

The flash loan fee is waived for approved FLASH\_BORROWER.

There are security concerns for developers of flashloan receiver contracts that must be taken into consideration. For further details, visit [Flash Loan Developers Guide](/primitives/flash-loans).

{% hint style="info" %}
Referral program is currently inactive, you can pass 0 as referralCode. This program may be activated in the future through a Tydro proposal.
{% endhint %}

**Input Parameters:**

| Name              | Type       | Description                                                                                                                                                                                                                                                                                                                     |
| ----------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| receiverAddress   | address    | The address of the contract receiving the flash-borrowed funds, implementing the IFlashLoanReceiver interface                                                                                                                                                                                                                   |
| assets            | address\[] | The addresses of the assets being flash-borrowed                                                                                                                                                                                                                                                                                |
| amounts           | uint256\[] | The amounts of the assets being flash-borrowed. This needs to contain the same number of entries as assets                                                                                                                                                                                                                      |
| interestRateModes | uint256\[] | The types of the debt position to open if the flash loan is not returned: 0 -> Don't open any debt, the amount + fee must be paid in this case or just revert if the funds can't be transferred from the receiver. 2 -> Open variable rate borrow position for the value of the amount flash-borrowed to the onBehalfOf address |
| onBehalfOf        | address    | The address that will receive the debt if the associated interestRateModes is 1 or 2. onBehalfOf must already have approved sufficient borrow allowance of the associated asset to msg.sender                                                                                                                                   |
| params            | bytes      | Variadic packed params to pass to the receiver as extra information                                                                                                                                                                                                                                                             |
| referralCode      | uint16     | Referral supply is currently inactive, you can pass 0. This code is used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-men                                                                                                  |

#### flashLoanSimple

```
function flashLoanSimple(    address receiverAddress,    address asset,    uint256 amount,    bytes calldata params,    uint16 referralCode) public virtual override
```

Allows users to access liquidity of the pool for a given asset within one transaction, as long as the amount taken plus a fee is returned. The receiver must approve the Pool contract for at least the *amount borrowed + fee*, otherwise the transaction will revert.

This function does not waive the fee for approved FLASH\_BORROWER, nor does it allow for opening a debt position instead of repaying.

There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.

Referral program is currently inactive, you can pass 0 as referralCode. This program may be activated in the future through an Tydro proposal

**Input Parameters:**

| Name            | Type    | Description                                                                                                                                                                                                                    |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| receiverAddress | address | The address of the contract receiving the flash-borrowed funds, implementing the IFlashLoanReceiver interface                                                                                                                  |
| asset           | address | The address of the asset being flash-borrowed                                                                                                                                                                                  |
| amount          | uint256 | The amount of the asset being flash-borrowed                                                                                                                                                                                   |
| params          | bytes   | Variadic packed params to pass to the receiver as extra information                                                                                                                                                            |
| referralCode    | uint16  | Referral supply is currently inactive, you can pass 0. This code is used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-men |

#### mintToTreasury

```
function mintToTreasury(address[] calldata assets) external virtual override
```

Mints the assets accrued through the reserve factor to the treasury in the form of aTokens for the given list of assets.

**Input Parameters:**

| Name   | Type       | Description                                                     |
| ------ | ---------- | --------------------------------------------------------------- |
| assets | address\[] | The list of reserves for which the minting needs to be executed |

#### finalizeTransfer

```
function finalizeTransfer(    address asset,    address from,    address to,    uint256 amount,    uint256 balanceFromBefore,    uint256 balanceToBefore) external virtual override
```

Validates and finalizes an aToken transfer. It is only callable by the overlying aToken of the asset.

**Input Parameters:**

| Name              | Type    | Description                                             |
| ----------------- | ------- | ------------------------------------------------------- |
| asset             | address | The address of the underlying asset of the aToken       |
| from              | address | The user from which the aTokens are transferred         |
| to                | address | The user receiving the aTokens                          |
| amount            | uint256 | The amount being transferred/withdrawn                  |
| balanceFromBefore | uint256 | The aToken balance of the from user before the transfer |
| balanceToBefore   | uint256 | The aToken balance of the to user before the transfer   |

#### setUserEMode

```
function setUserEMode(uint8 categoryId) external virtual override
```

Allows a user to use the protocol in efficiency mode. The category id must be a valid id already defined by *Pool or Risk Admins*.

Will revert if user is borrowing non-compatible asset or if the change will drop the Health Factor < HEALTH\_FACTOR\_LIQUIDATION\_THRESHOLD.

**Input Parameters:**

| Name       | Type  | Description                                                                                                 |
| ---------- | ----- | ----------------------------------------------------------------------------------------------------------- |
| categoryId | uint8 | The eMode category id (0 - 255) defined by Risk or Pool Admins. categoryId set to 0 is a non eMode category |

#### mintUnbacked

```
function mintUnbacked(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode
) external virtual override onlyBridge
```

Allows contracts with BRIDGE role permission to mint an amount of unbacked aTokens to the `onBehalfOf` address.

Only available to the addresses with BRIDGE role. Bridge addresses can be whitelisted by Tydro.

Referral program is currently inactive, you can pass 0 as referralCode. This program may be activated in the future through a Tydro proposal.

**Input Parameters:**

| Name         | Type    | Description                                                                                                                                                                                                                    |
| ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| asset        | address | The address of the underlying asset to mint                                                                                                                                                                                    |
| amount       | uint256 | The amount to mint                                                                                                                                                                                                             |
| onBehalfOf   | address | The address that will receive the aTokens                                                                                                                                                                                      |
| referralCode | uint16  | Referral supply is currently inactive, you can pass 0. This code is used to register the integrator originating the operation, for potential rewards. 0 if the action is executed directly by the user, without any middle-men |

#### backUnbacked

```
function backUnbacked(    address asset,    uint256 amount,    uint256 fee) external virtual override onlyBridge returns (uint256)
```

Allows contracts with BRIDGE role permission to back the current unbacked underlying aTokens with amount and pay fee

Only available to the addresses with BRIDGE role. Bridge addresses can be whitelisted by Tydro.

**Input Parameters:**

| Name   | Type    | Description                                              |
| ------ | ------- | -------------------------------------------------------- |
| asset  | address | The address of the underlying asset to back              |
| amount | uint256 | The amount of asset supplied to back the unbacked tokens |
| fee    | uint256 | The amount paid in fees                                  |

**Return Value:**

| Type    | Description                                                                                                                                                                |
| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| uint256 | The final amount backed, representing the portion of assets that were successfully supplied to back the unbacked aTokens, including any fees that were taken into account. |

#### initReserve

```
function initReserve(    address asset,    address aTokenAddress,    address stableDebtAddress,    address variableDebtAddress,    address interestRateStrategyAddress) external virtual override onlyPoolConfigurator
```

Initializes a reserve, activating it, assigning an aToken and debt tokens and an interest rate strategy.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name                        | Type    | Description                                                                          |
| --------------------------- | ------- | ------------------------------------------------------------------------------------ |
| asset                       | address | The address of the underlying asset of the reserve                                   |
| aTokenAddress               | address | The address of the aToken that will be assigned to the reserve                       |
| stableDebtAddress           | address | The address of the StableDebtToken that will be assigned to the reserve (deprecated) |
| variableDebtAddress         | address | The address of the VariableDebtToken that will be assigned to the reserve            |
| interestRateStrategyAddress | address | The address of the interest rate strategy contract                                   |

#### dropReserve

```
function dropReserve(address asset) external virtual override onlyPoolConfigurator
```

Drop a reserve.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

#### setReserveInterestRateStrategyAddress

```
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external virtual override onlyPoolConfigurator
```

Updates the address of the interest rate strategy contract.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name                | Type    | Description                                        |
| ------------------- | ------- | -------------------------------------------------- |
| asset               | address | The address of the underlying asset of the reserve |
| rateStrategyAddress | address | The address of the interest rate strategy contract |

#### setConfiguration

```
function setConfiguration(address asset, DataTypes.ReserveConfigurationMap calldata configuration) external virtual override onlyPoolConfigurator
```

Sets the configuration bitmap of the reserve as a whole.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name          | Type                              | Description                                        |
| ------------- | --------------------------------- | -------------------------------------------------- |
| asset         | address                           | The address of the underlying asset of the reserve |
| configuration | DataTypes.ReserveConfigurationMap | The new configuration bitmap                       |

The [DataTypes.ReserveConfigurationMap](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L79) struct is composed of the following fields:

| bit     | Description                                                                                   |
| ------- | --------------------------------------------------------------------------------------------- |
| 0-15    | LTV                                                                                           |
| 16-31   | Liquidation threshold                                                                         |
| 32-47   | Liquidation bonus                                                                             |
| 48-55   | Decimals                                                                                      |
| 56      | Reserve is active                                                                             |
| 57      | Reserve is frozen                                                                             |
| 58      | Borrowing is enabled                                                                          |
| 59      | Stable rate borrowing enabled (deprecated)                                                    |
| 60      | Asset is paused                                                                               |
| 61      | Borrowing in isolation mode is enabled                                                        |
| 62      | Siloed borrowing is enabled                                                                   |
| 63      | Flashloaning is enabled                                                                       |
| 64-79   | Reserve factor                                                                                |
| 80-115  | Borrow cap in whole tokens, borrowCap == 0 => no cap                                          |
| 116-151 | Supply cap in whole tokens, supplyCap == 0 => no cap                                          |
| 152-167 | Liquidation protocol fee                                                                      |
| 168-175 | eMode category (deprecated)                                                                   |
| 176-211 | Unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled                   |
| 212-251 | Debt ceiling for isolation mode with (ReserveConfiguration::DEBT\_CEILING\_DECIMALS) decimals |
| 252     | Virtual accounting is enabled                                                                 |
| 253-255 | Unused                                                                                        |

#### updateBridgeProtocolFee

```
function updateBridgeProtocolFee(uint256 protocolFee) external virtual override onlyPoolConfigurator
```

Updates the protocol fee on the bridging.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name        | Type    | Description                                           |
| ----------- | ------- | ----------------------------------------------------- |
| protocolFee | uint256 | The part of the premium sent to the protocol treasury |

#### updateFlashloanPremiums

```
function updateFlashloanPremiums(uint128 flashLoanPremiumTotal, uint128 flashLoanPremiumToProtocol) external virtual override onlyPoolConfigurator
```

Updates flash loan premiums. A flash loan premium consists of two parts:

* A part is sent to aToken holders as extra, one time accumulated interest
* A part is collected by the protocol treasury

The total premium is calculated on the total borrowed amount. The premium to protocol is calculated on the total premium, being a percentage of flashLoanPremiumTotal.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name                       | Type    | Description                                                             |
| -------------------------- | ------- | ----------------------------------------------------------------------- |
| flashLoanPremiumTotal      | uint128 | The total premium, expressed in bps                                     |
| flashLoanPremiumToProtocol | uint128 | The part of the premium sent to the protocol treasury, expressed in bps |

#### configureEModeCategory

```
function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory category) external virtual override onlyPoolConfigurator
```

Configures a new category for the eMode. In eMode, the protocol allows very high borrowing power to borrow assets of the same category. The category 0 is reserved for volatile heterogeneous assets and it's always disabled.

Each eMode category has a custom ltv and liquidation threshold. Each eMode category may or may not have a custom oracle to override the individual assets price oracles.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| id       | uint8                   | The total premium, expressed in bps |
| category | DataTypes.EModeCategory | The configuration of the category   |

The [DataTypes.EModeCategory](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L114) struct is composed of the following fields:

| Name                 | Type    | Description                                             |
| -------------------- | ------- | ------------------------------------------------------- |
| ltv                  | uint16  | The custom Loan to Value for the eMode category         |
| liquidationThreshold | uint16  | The custom liquidation threshold for the eMode category |
| liquidationBonus     | uint16  | The liquidation bonus for the eMode category            |
| collateralBitmap     | uint128 | Bitmap of collateral assets in the category             |
| label                | string  | The custom label describing the eMode category          |
| borrowableBitmap     | uint128 | Bitmap of borrowable assets in the category             |

#### resetIsolationModeTotalDebt

```
function resetIsolationModeTotalDebt(address asset) external virtual override onlyPoolConfigurator
```

Resets the isolation mode total debt of the given asset to zero. It requires the given asset to have a zero debt ceiling.

Only callable by the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract.

**Input Parameters:**

| Name  | Type    | Description                                                             |
| ----- | ------- | ----------------------------------------------------------------------- |
| asset | address | The address of the underlying asset to reset the isolationModeTotalDebt |

#### rescueTokens

```
function rescueTokens(
    address token,
    address to,
    uint256 amount
) external virtual override onlyPoolAdmin
```

Rescue and transfer tokens locked in this contract.

Only available to [POOL\_ADMIN](/developers/smart-contracts/aclmanager) role. The Pool Admin is designated by Tydro.

**Input Parameters:**

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| token  | address | The address of the token        |
| to     | address | The address of the recipient    |
| amount | uint256 | The amount of token to transfer |

#### eliminateReserveDeficit

Covers the deficit of a specified reserve by burning the equivalent aToken amount for assets with virtual accounting enabled or the equivalent amount of underlying for assets with virtual accounting disabled (e.g. GHO). Only callable by address with onlyUmbrella modifier.

```
function eliminateReserveDeficit(address asset, uint256 amount) external;
```

**Input Parameters:**

| Name   | Type    | Description                                                                       |
| ------ | ------- | --------------------------------------------------------------------------------- |
| asset  | address | Underlying token address                                                          |
| amount | uint256 | The amount to be covered, in aToken or underlying on non-virtual accounted assets |

### View Methods

#### getUserAccountData

```
function getUserAccountData(address user) external view virtual override returns (    uint256 totalCollateralBase,    uint256 totalDebtBase,    uint256 availableBorrowsBase,    uint256 currentLiquidationThreshold,    uint256 ltv,    uint256 healthFactor)
```

Returns the user account data across all the reserves.

**Input Parameters:**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| user | address | The address of the user |

**Return Values:**

| Name                        | Type    | Description                                                                      |
| --------------------------- | ------- | -------------------------------------------------------------------------------- |
| totalCollateralBase         | uint256 | The total collateral of the user in the base currency used by the price feed     |
| totalDebtBase               | uint256 | The total debt of the user in the base currency used by the price feed           |
| availableBorrowsBase        | uint256 | The borrowing power left of the user in the base currency used by the price feed |
| currentLiquidationThreshold | uint256 | The liquidation threshold of the user                                            |
| ltv                         | uint256 | The loan to value of the user                                                    |
| healthFactor                | uint256 | The current health factor of the user                                            |

#### getConfiguration

```
function getConfiguration(address asset) external view virtual override returns (DataTypes.ReserveConfigurationMap memory)
```

Returns the configuration of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type                              | Description                      |
| --------------------------------- | -------------------------------- |
| DataTypes.ReserveConfigurationMap | The configuration of the reserve |

The [DataTypes.ReserveConfigurationMap](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L79) struct is composed of the following fields:

| bit     | Description                                                                                   |
| ------- | --------------------------------------------------------------------------------------------- |
| 0-15    | LTV                                                                                           |
| 16-31   | Liquidation threshold                                                                         |
| 32-47   | Liquidation bonus                                                                             |
| 48-55   | Decimals                                                                                      |
| 56      | Reserve is active                                                                             |
| 57      | Reserve is frozen                                                                             |
| 58      | Borrowing is enabled                                                                          |
| 59      | Stable rate borrowing enabled (deprecated)                                                    |
| 60      | Asset is paused                                                                               |
| 61      | Borrowing in isolation mode is enabled                                                        |
| 62      | Siloed borrowing enabled                                                                      |
| 63      | Flashloaning enabled                                                                          |
| 64-79   | Reserve factor                                                                                |
| 80-115  | Borrow cap in whole tokens, borrowCap == 0 => no cap                                          |
| 116-151 | Supply cap in whole tokens, supplyCap == 0 => no cap                                          |
| 152-167 | Liquidation protocol fee                                                                      |
| 168-175 | eMode category (deprecated)                                                                   |
| 176-211 | Unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled                   |
| 212-251 | Debt ceiling for isolation mode with (ReserveConfiguration::DEBT\_CEILING\_DECIMALS) decimals |
| 252     | Virtual accounting is enabled for the reserve                                                 |
| 253-255 | Unused                                                                                        |

#### getUserConfiguration

```
function getUserConfiguration(address user) external view virtual override returns (DataTypes.UserConfigurationMap memory)
```

Returns the configuration of the user across all the reserves.

**Input Parameters:**

| Name | Type    | Description      |
| ---- | ------- | ---------------- |
| user | address | The user address |

**Return Values:**

| Type                           | Description                   |
| ------------------------------ | ----------------------------- |
| DataTypes.UserConfigurationMap | The configuration of the user |

The [DataTypes.UserConfigurationMap](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L105) struct is composed of the following fields:

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">Data</td><td valign="top">uint256</td><td>Bitmap of the users collaterals and borrows. It is divided into pairs of bits, one pair per asset. The first bit indicates if an asset is used as collateral by the user, the second whether an asset is borrowed by the user. The corresponding assets are in the same position as getReservesList(). For example, if the hex value returned is 0x40020, which represents a decimal value of 262176, then in binary it is 1000000000000100000. If we format the binary value into pairs, starting from the right, we get 1 00 00 00 00 00 00 10 00 00. If we start from the right and move left in the above binary pairs, the third pair is 10. Therefore the 1 indicates that third asset from the reserveList is used as collateral, and 0 indicates it has not been borrowed by this user</td></tr></tbody></table>

#### getReserveNormalizedIncome

```
function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256)
```

Returns the ongoing normalized income for the reserve.

A value of 1e27 means there is no income. As time passes, the yield is accrued. A value of 2\*1e27 means for each unit of asset, one unit of income has been accrued.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                     |
| ------- | ------------------------------- |
| uint256 | The reserve's normalized income |

#### getReserveNormalizedVariableDebt

```
function getReserveNormalizedVariableDebt(address asset) external view virtual override returns (uint256)
```

Returns the normalized variable debt per unit of asset.

A value of 1e27 means there is no debt. As time passes, the debt is accrued. A value of 2\*1e27means that for each unit of debt, one unit worth of interest has been accumulated.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                          |
| ------- | ------------------------------------ |
| uint256 | The reserve normalized variable debt |

#### getReservesList

```
function getReservesList() external view virtual override returns (address[] memory)
```

Returns the list of the underlying assets of all the initialized reserves. It does not include dropped reserves.

**Return Values:**

| Type       | Description                                                        |
| ---------- | ------------------------------------------------------------------ |
| address\[] | The addresses of the underlying assets of the initialized reserves |

#### getReserveAddressById

```
function getReserveAddressById(uint16 id) external view returns (address)
```

Returns the address of the underlying asset of a reserve by the reserve id as stored in the [DataTypes.ReserveData](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L42) struct.

**Input Parameters:**

| Name | Type   | Description                                                                                                                                                                                                                   |
| ---- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id   | uint16 | The id of the reserve as stored in the [DataTypes.ReserveData](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L42) struct |

**Return Values:**

| Type    | Description                                   |
| ------- | --------------------------------------------- |
| address | The address of the reserve associated with id |

#### getEModeCategoryData

```
function getEModeCategoryData(uint8 id) external view virtual override returns (DataTypes.EModeCategory memory)
```

Returns the data of an eMode category.

Each eMode category has a custom LTV and liquidation threshold. Each eMode category may or may not have a custom oracle to override the individual assets' price oracles.

**Input Parameters:**

| Name | Type  | Description            |
| ---- | ----- | ---------------------- |
| id   | uint8 | The id of the category |

**Return Values:**

| Type                    | Description                            |
| ----------------------- | -------------------------------------- |
| DataTypes.EModeCategory | The configuration data of the category |

The [DataTypes.EModeCategory](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L114) struct is composed of the following fields:

| Name                 | Type    | Description                                             |
| -------------------- | ------- | ------------------------------------------------------- |
| ltv                  | uint16  | The custom Loan to Value for the eMode category         |
| liquidationThreshold | uint16  | The custom liquidation threshold for the eMode category |
| liquidationBonus     | uint16  | The liquidation bonus for the eMode category            |
| collateralBitmap     | uint128 | Bitmap of collateral assets in the category             |
| label                | string  | The custom label describing the eMode category          |
| borrowableBitmap     | uint128 | Bitmap of borrowable assets in the category             |

#### getReserveData

```
function getReserveData(address asset) external view virtual override returns (DataTypes.ReserveData memory)
```

Returns the state and configuration of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type                  | Description                                     |
| --------------------- | ----------------------------------------------- |
| DataTypes.ReserveData | The state and configuration data of the reserve |

The [DataTypes.ReserveData](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L42) struct is composed of the following fields:

| Name                                 | Type                    | Description                                                                                                                                                                                |
| ------------------------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| configuration                        | ReserveConfigurationMap | Stores the [reserve configuration](https://github.com/aave-dao/aave-v3-origin/blob/3aad8ca184159732e4b3d8c82cd56a8707a106a2/src/core/contracts/protocol/libraries/types/DataTypes.sol#L42) |
| liquidityIndex                       | uint128                 | The yield generated by the reserve during time interval since lastUpdatedTimestamp. Expressed in ray                                                                                       |
| currentLiquidityRate                 | uint128                 | The current supply rate. Expressed in ray                                                                                                                                                  |
| variableBorrowIndex                  | uint128                 | The yield accrued by reserve during time interval since lastUpdatedTimestamp. Expressed in ray                                                                                             |
| currentVariableBorrowRate            | uint128                 | The current variable borrow rate. Expressed in ray                                                                                                                                         |
| \_\_deprecatedStableBorrowRate       | uint128                 | DEPRECATED on v3.2.0                                                                                                                                                                       |
| lastUpdateTimestamp                  | uint40                  | The timestamp of when reserve data was last updated. Used for yield calculation                                                                                                            |
| id                                   | uint16                  | The id of the reserve. It represents the reserve’s position in the list of active reserves                                                                                                 |
| liquidationGracePeriodUntil          | uint40                  | The timestamp until liquidations are not allowed on the reserve. If set to the past, liquidations will be allowed                                                                          |
| aTokenAddress                        | address                 | The address of associated aToken                                                                                                                                                           |
| \_\_deprecatedStableDebtTokenAddress | address                 | DEPRECATED on v3.2.0                                                                                                                                                                       |
| variableDebtTokenAddress             | address                 | The address of associated variable debt token                                                                                                                                              |
| interestRateStrategyAddress          | address                 | The address of interest rate strategy                                                                                                                                                      |
| accruedToTreasury                    | uint128                 | The current treasury balance (scaled)                                                                                                                                                      |
| unbacked                             | uint128                 | The outstanding unbacked aTokens minted through the bridging feature                                                                                                                       |
| isolationModeTotalDebt               | uint128                 | The outstanding debt borrowed against this asset in isolation mode                                                                                                                         |
| virtualUnderlyingBalance             | uint128                 | The virtual balance of the underlying asset for yield calculation purposes                                                                                                                 |

#### getUserEMode

```
function getUserEMode(address user) external view virtual override returns (uint256)
```

Returns eMode the user is using. 0 is a non eMode category.

**Input Parameters:**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| user | address | The address of the user |

**Return Values:**

| Type    | Description  |
| ------- | ------------ |
| uint256 | The eMode id |

#### FLASHLOAN\_PREMIUM\_TOTAL

```
function FLASHLOAN_PREMIUM_TOTAL() public view virtual override returns (uint128)
```

Returns the percent of total flashloan premium paid by the borrower.

A part of this premium is added to reserve's liquidity index i.e. paid to the liquidity provider and the other part is paid to the protocol i.e. accrued to the treasury.

**Return Values:**

| Type    | Description                 |
| ------- | --------------------------- |
| uint128 | The total fee on flashloans |

#### BRIDGE\_PROTOCOL\_FEE

```
function BRIDGE_PROTOCOL_FEE() public view virtual override returns (uint256)
```

Returns the part of the bridge fees sent to protocol.

**Return Values:**

| Type    | Description                                                       |
| ------- | ----------------------------------------------------------------- |
| uint256 | The percentage of available liquidity to borrow, expressed in bps |

#### FLASHLOAN\_PREMIUM\_TO\_PROTOCOL

```
function FLASHLOAN_PREMIUM_TO_PROTOCOL() public view virtual override returns (uint128)
```

Returns the percent of flashloan premium that is accrued to the treasury.

**Return Values:**

| Type    | Description                                                       |
| ------- | ----------------------------------------------------------------- |
| uint128 | The percentage of available liquidity to borrow, expressed in bps |

#### MAX\_NUMBER\_RESERVES

```
function MAX_NUMBER_RESERVES() public view virtual override returns (uint16)
```

Returns the maximum number of reserves supported to be listed in this Pool.

**Return Values:**

| Type   | Description                              |
| ------ | ---------------------------------------- |
| uint16 | The maximum number of reserves supported |

#### getLiquidationGracePeriod

Returns the liquidation grace period of the given asset

```
function getLiquidationGracePeriod(address asset) external view virtual override returns (uint40)
```

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | Underlying token address |

**Return Values:**

| Type    | Description                                          |
| ------- | ---------------------------------------------------- |
| uint256 | Timestamp when the liquidation grace period will end |

#### getReserveDeficit

Returns the current deficit of a reserve.

```
function getReserveDeficit(address asset) external view returns (uint256);
```

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | Underlying token address |

**Return Values:**

| Type    | Description                                                       |
| ------- | ----------------------------------------------------------------- |
| uint256 | Current reserve deficit from undercollateralized borrow positions |

#### getReserveAToken

Returns the aToken address of a reserve.

```
function getReserveAToken(address asset) external view returns (address);
```

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | Underlying token address |

**Return Values:**

| Type    | Description               |
| ------- | ------------------------- |
| address | The address of the AToken |

#### getReserveVariableDebtToken

Returns the variableDebtToken address of a reserve.

```
function getReserveVariableDebtToken(address asset) external view returns (address);
```

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | Underlying token address |

**Return Values:**

| Type    | Description                          |
| ------- | ------------------------------------ |
| address | The address of the VariableDebtToken |

### Pure Methods

#### getRevision

```
function getRevision() internal pure virtual override returns (uint256)
```

Returns the revision number of the contract. Needs to be defined in the inherited class as a constant.

Returns 0x1.

**Return Values:**

| Type    | Description         |
| ------- | ------------------- |
| uint256 | The revision number |


# L2 Pool

On Layer 2 networks, the main cost of transactions comes from calldata. To reduce this cost, Tydro uses a specialised contract on L2 that compresses the calldata of Pool methods.

The L2Pool contract provides the L2-optimised user-facing methods of the protocol. It accepts byte-encoded input arguments and exposes the same liquidity management functions available in the standard Pool contract. Users can interact with L2Pool through Solidity or Web3 libraries. By using compact calldata representations, L2Pool helps lower transaction costs on rollups.

Not all methods are redefined in L2Pool.sol. Functions such as `flashLoan` and `setUserEMode` remain identical to their implementation in the base Pool contract. For those functions, refer to the [Pool](/developers/smart-contracts/pool) documentation.

Because L2 networks use a limited set of supported assets, each asset is assigned an individual 16-bit asset ID, which replaces the standard 160-bit asset address in encoded arguments.

The source code is available on [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/L2Pool.sol).

Tydro also provides an [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract with view methods to encode transaction parameters for the compressed L2Pool functions. This ensures developers can efficiently generate the calldata required for low-cost interactions.

### Methods

#### supply

```
function supply(bytes32 args) external override
```

Calldata efficient wrapper of the supply function on behalf of the caller. Supplies asset into the protocol, minting the same amount of corresponding aTokens, and transferring them to msg.sender.

You can use data returned from encodeSupplyParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

| Name | Type    | Description                                                                                                                                                                                                                                                                                                                                                  |
| ---- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| args | bytes32 | <p>Arguments for the supply function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144-159: uint16 referralCode - used for 3rd party integrations</p> |

#### supplyWithPermit

```
function supplyWithPermit(bytes32 args, bytes32 r, bytes32 s) external override
```

Calldata efficient wrapper of the supplyWithPermit function on behalf of the caller. Supply with transfer approval of supplied asset via permit function. This method removes the need for separate approval transaction before supplying asset to the pool.

You can use data returned from encodeSupplyWithPermitParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the supply function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144-159: uint16 referralCode - used for 3rd party integrations<br>bit 160-191: uint32 shortenedDeadline - shortened deadline from the original uint256<br>bit 192-199: uint8 permitV - the V parameter of ERC712 permit signature</td></tr><tr><td valign="top">r</td><td valign="top">bytes32</td><td>The R parameter of ERC712 permit signature</td></tr><tr><td valign="top">s</td><td valign="top">bytes32</td><td>The S parameter of ERC712 permit signature</td></tr></tbody></table>

#### withdraw

```
function withdraw(bytes32 args) external override returns (uint256)
```

Calldata efficient wrapper of the withdraw function, withdrawing to the caller. Withdraws amount of the underlying asset, i.e. redeems the underlying token and burns the aTokens.

If the user has any existing debt backed by the underlying token, the maximum amount available to withdraw is the amount that will not leave the user with a health factor < 1 after the withdrawal.

You can use data returned from encodeWithdrawParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

| Name | Type    | Description                                                                                                                                                                                                                                                                              |
| ---- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| args | bytes32 | <p>Arguments for the withdraw function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max</p> |

**Return Value:**

| Name   | Type    | Description                                                                                                                                                                                                                                                             |
| ------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| amount | uint256 | The final amount of the underlying asset withdrawn, denominated in the base unit of the asset (e.g., wei for ETH, smallest unit for ERC-20 tokens). This is the amount actually transferred to the caller, accounting for constraints like liquidity and health factor. |

#### borrow

```
function borrow(bytes32 args) external override
```

Calldata efficient wrapper of the borrow function, borrowing on behalf of the caller. Borrows amount of asset with interestRateMode, sending the amount to msg.sender, with the debt being incurred by onBehalfOf.

You can use data returned from encodeBorrowParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the borrow function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144 - 151: uint8 shortenedInterestRateMode<br>bit 152 - 167: uint16 referralCode - used for 3rd party integrations</td></tr></tbody></table>

#### repay

```
function repay(bytes32 args) external override returns (uint256)
```

Calldata efficient wrapper of the repay function, repaying on behalf of the caller. Repays debt of an asset for the given interestRateMode.

You can use data returned from encodeRepayParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the repay function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144 - 151: uint8 shortenedInterestRateMode</td></tr></tbody></table>

**Return Values:**

| Type    | Description             |
| ------- | ----------------------- |
| uint256 | The final amount repaid |

#### repayWithPermit

```
function repayWithPermit(bytes32 args, bytes32 r, bytes32 s) external override returns (uint256)
```

Calldata efficient wrapper of the repayWithPermit function, repaying on behalf of the caller. Repay with transfer approval of borrowed asset via permit function. This method removes the need for separate approval transaction before repaying asset to the pool.

You can use data returned from encodeRepayWithPermitParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.​

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the repayWithPermit function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144 - 151: uint8 shortenedInterestRateMode<br>bit 152-183: uint32 shortenedDeadline - shortened deadline from original uint256<br>bit 184-191: uint8 permitV - the V parameter of ERC712 permit signature</td></tr><tr><td valign="top">r</td><td valign="top">bytes32</td><td>The R parameter of ERC712 permit signature</td></tr><tr><td valign="top">s</td><td valign="top">bytes32</td><td>The S parameter of ERC712 permit signature</td></tr></tbody></table>

**Return Values:**

| Type    | Description             |
| ------- | ----------------------- |
| uint256 | The final amount repaid |

#### repayWithATokens

```
function repayWithATokens(bytes32 args) external override returns (uint256)
```

Calldata efficient wrapper of the repayWithATokens function. Allows user to repay with aTokens of the underlying debt asset without any approvals, for example, Pay DAI debt using aDAI tokens.

You can use data data returned from encodeRepayWithATokensParams() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the repayWithATokens function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16-143: uint128 shortenedAmount - cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 144 - 151: uint8 shortenedInterestRateMode</td></tr></tbody></table>

**Return Values:**

| Type    | Description             |
| ------- | ----------------------- |
| uint256 | The final amount repaid |

#### setUserUseReserveAsCollateral

```
function setUserUseReserveAsCollateral(bytes32 args) external override
```

Calldata efficient wrapper of the setUserUseReserveAsCollateral function. Sets the asset of msg.sender to be used as collateral or not.

You can use data returned from encodeSetUserUseReserveAsCollateral() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.​

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args</td><td valign="top">bytes32</td><td>Arguments for the setUserUseReserveAsCollateral function packed in one bytes32<br>bit 0-15: uint16 assetId - the index of the asset in the reservesList<br>bit 16: 0 => enable useAsCollateral, 1 => disable useAsCollateral</td></tr></tbody></table>

#### liquidationCall

```
function liquidationCall(bytes32 args1, bytes32 args2) external override
```

Calldata efficient wrapper of the liquidationCall function. Liquidate positions with a health factor below 1.

You can use data returned from encodeLiquidationCall() method in [<mark style="color:blue;">L2Encoder</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract to pass to this method.​

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">args1</td><td valign="top">bytes32</td><td>Part of the arguments for the liquidationCall function packed in one bytes32<br>bit 0-15: uint16 collateralAssetId - the index of the collateral asset in the reservesList<br>bit 16-31: uint16 debtAssetId - the index of the debt asset in the reservesList<br>bit 32-191: address of the user being liquidated</td></tr><tr><td valign="top">args2</td><td valign="top">bytes32</td><td>Part of the arguments for the liquidationCall function packed in one bytes32<br>bit 0-127: uint128 shortenedDebtToCover is cast to 256 bits at decode time, if type(uint128).max the value will be expanded to type(uint256).max<br>bit 128: receiveAToken - 0 => receive aToken, 1 => receive underlying asset</td></tr></tbody></table>


# Wrapped Token Gateway

Tydro operates exclusively with ERC-20 [reserve](/primitives/reserve) tokens. To support native gas tokens such as ETH or POL, Tydro provides the WrappedTokenGateway (previously called WETHGateway).

This helper contract allows users to wrap or unwrap gas tokens so they can interact with Pool methods. Through WrappedTokenGateway, users can:

* Supply gas tokens
* Borrow gas tokens
* Repay positions using gas tokens
* Withdraw supplied gas tokens

The smart contract source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/WrappedTokenGatewayV3.sol).

### Write Methods

#### depositETH

```
function depositETH(
    address,
    address onBehalfOf,
    uint16 referralCode
) external payable override
```

Wraps and supplies gas tokens to Tydro. A corresponding amount of the wrapped aTokens are minted to the onBehalfOf address.

The amount of network gas tokens to be supplied is specified in the msg.value field of the transaction.

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">onBehalfOf</td><td valign="top">address</td><td>The address of the user who will receive the aTokens representing the supplied tokens</td></tr><tr><td valign="top">referralCode</td><td valign="top">uint16</td><td>Inactive, can pass 0 as placeholder</td></tr></tbody></table>

#### withdrawETH

```
function withdrawETH(
    address,
    uint256 amount,
    address to
) external override
```

Withdraws amount of the supplied wrapped gas token, unwraps it and transfers to the toaddress. If the amount is uint(-1), the entire balance is withdrawn.

The WrappedTokenGateway contract must have an approved token allowance to spend aWETH on behalf of the user, example:IERC20(aWETHAddress).approve(wrappedTokenGatewayAddress, amount)

**Input Parameters:**

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th></th></tr></thead><tbody><tr><td valign="top">Name</td><td valign="top">Type</td><td>Description</td></tr><tr><td valign="top">amount</td><td valign="top">uint256</td><td>amount of aWETH to withdraw and receive native ETH</td></tr><tr><td valign="top">to</td><td valign="top">address</td><td>The address of the user who will receive native ETH</td></tr></tbody></table>

#### repayETH

```
function repayETH(
    address,
    uint256 amount,
    uint256 rateMode,
    address onBehalfOf
) external payable override
```

Repays a borrow position of onBehalfOf's address for the specified amount (or for the whole amount, if amount of uint256(-1) is passed).

The amount of network gas token to be repaid must also be specified in the msg.value field of the transaction.

**Input Parameters:**

| Name       | Type    | Description                                                               |
| ---------- | ------- | ------------------------------------------------------------------------- |
| amount     | uint256 | The amount to repay, or uint256(-1) if the user wants to repay everything |
| rateMode   | uint256 | Should always be passed a value of 2 (variable rate mode)                 |
| onBehalfOf | address | The address for which msg.sender is repaying                              |

#### borrowETH

```
function borrowETH(
    address,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode
) external override
```

Borrows amount of unwrapped network gas tokens to msg.sender.

The WrappedTokenGateway contract must have an approved [credit delegation](/developers/credit-delegation) to borrow WETH (or corresponding wrapped gas token of the network) on behalf of the the caller, example:IVariableDebtToken(wethAddress).approveDelegation(wrappedTokenGatewayAddress, amount)

**Input Parameters:**

| Name             | Type    | Description                                                                  |
| ---------------- | ------- | ---------------------------------------------------------------------------- |
| amount           | uint256 | The amount of ETH to borrow                                                  |
| interestRateMode | uint256 | Should always be passed a value of 2 (variable rate mode)                    |
| referralCode     | uint16  | Integrators are assigned a referral code and can potentially receive rewards |

#### withdrawETHWithPermit

```
function withdrawETHWithPermit(
    address,
    uint256 amount,
    address to,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
) external override
```

Withdraws amount of the supplied wrapped gas token, unwraps it and transfers to the toaddress. If the amount is uint(-1), the entire balance is withdrawn.

**Input Parameters:**

| Name     | Type    | Description                                            |
| -------- | ------- | ------------------------------------------------------ |
| amount   | uint256 | The amount of aWETH to withdraw and receive native ETH |
| to       | address | The address of the user who will receive native ETH    |
| deadline | uint256 | Timestamp of signature expiration                      |
| permitV  | uint8   | V parameter of ERC712 permit sig                       |
| permitR  | bytes32 | R parameter of ERC712 permit sig                       |
| permitS  | bytes32 | S parameter of ERC712 permit sig                       |

### View Methods

#### getWETHAddress

```
function getWETHAddress() external view returns (address)
```

Get WETH address used by WrappedTokenGatewayV3.

**Return Values:**

| Type    | Description                                    |
| ------- | ---------------------------------------------- |
| address | The WETH address used by WrappedTokenGatewayV3 |


# View Contracts

## View Contracts

Tydro has several view contracts to assist with querying onchain data.

### UiPoolDataProvider

Contract that returns an array of all reserve or user data for a particular market (for example, liquidity, token addresses, rate strategy), used by the [<mark style="color:blue;">Tydro Interface</mark>](https://tydro-page.webflow.io) to display Markets and Dashboard data. \
\
The [Utilities SDK](https://github.com/aave/aave-utilities) includes an interface to make calls to this contract, and functions to format the response for frontend use-cases

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/UiPoolDataProviderV3.sol)<mark style="color:blue;">.</mark>

### View Methods

#### getReservesList

```
function getReservesList(IPoolAddressesProvider provider) public view override returns (address[] memory)
```

Returns the list of initialised reserves in the Pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |

**Return Values:**

| Type       | Description                                  |
| ---------- | -------------------------------------------- |
| address\[] | The list of initialised reserves in the Pool |

#### getReservesData

```
function getReservesData(IPoolAddressesProvider provider) public view override returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory)
```

Returns BaseCurrencyInfo of the Pool and AggregatedReserveData\[] for all the initialised reserves in the Pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |

**Return Values:**

| Type                     | Description                   |
| ------------------------ | ----------------------------- |
| BaseCurrencyInfo         | The base currency information |
| AggregatedReserveData\[] | The aggregated reserve data   |

The BaseCurrencyInfo struct is composed of the following fields:

| Name                              | Type    | Description                                       |
| --------------------------------- | ------- | ------------------------------------------------- |
| marketReferenceCurrencyUnit       | uint256 | Reference aka base currency of the Tydro market   |
| marketReferenceCurrencyPriceInUsd | int256  | Price of reference aka base currency in USD       |
| networkBaseTokenPriceInUsd        | int256  | Price of native token of the network/chain in USD |
| networkBaseTokenPriceDecimals     | uint8   | Decimals of native token of the network/chain     |

The AggregatedReserveData struct is composed of the following fields:

| Name                           | Type    | Description                                                            |
| ------------------------------ | ------- | ---------------------------------------------------------------------- |
| underlyingAsset                | address | The address of the underlying asset of the reserve                     |
| name                           | string  | The name of the underlying reserve asset                               |
| symbol                         | string  | The symbol of the underlying reserve asset                             |
| decimals                       | uint256 | The number of decimals of the reserve                                  |
| baseLTVasCollateral            | uint256 | The ltv of the reserve                                                 |
| reserveLiquidationThreshold    | uint256 | The liquidation threshold of the reserve                               |
| reserveLiquidationBonus        | uint256 | The liquidation bonus of the resurve                                   |
| reserveFactor                  | uint256 | The reserve factor of the reserve                                      |
| usageAsCollateralEnabled       | bool    | true if the asset is enabled to be used as collateral, false otherwise |
| borrowingEnabled               | bool    | true if borrowing is enabled, false otherwise                          |
| isActive                       | bool    | true if reserve is active, false otherwise                             |
| isFrozen                       | bool    | true if reserve is frozen, false otherwise                             |
| BASE DATA                      |         |                                                                        |
| liquidityIndex                 | uint128 | The liquidity index of the reserve                                     |
| variableBorrowIndex            | uint128 | The variable borrow index of the reserve                               |
| liquidityRate                  | uint128 | The liquidity rate of the reserve                                      |
| variableBorrowRate             | uint128 | The variable borrow rate of the reserve                                |
| lastUpdateTimestamp            | uint40  | The timestamp of the last update of the reserve                        |
| aTokenAddress                  | address | The AToken address of the reserve                                      |
| variableDebtTokenAddress       | address | The VariableDebtToken address of the reserve                           |
| interestRateStrategyAddress    | address | The address of the Interest Rate strategy                              |
| availableLiquidity             | uint256 | The liquidity available                                                |
| totalScaledVariableDebt        | uint256 | The total scaled variable debt                                         |
| priceInMarketReferenceCurrency | uint256 | Price of reference aka base currency of Tydro market                   |
| priceOracle                    | address | The address of the price oracle used by the associated market          |
| variableRateSlope1             | uint256 | The variable rate slope                                                |
| variableRateSlope2             | uint256 | The variable rate slope                                                |
| baseVariableBorrowRate         | uint256 | The base variable borrow rate, expressed in ray                        |
| optimalUsageRatio              | uint256 | The optimal usage ratio                                                |
|                                |         |                                                                        |
| V3 ONLY                        |         |                                                                        |
| isPaused                       | bool    | true if the pool is paused, false otherwise                            |
| isSiloedBorrowing              | bool    | true if the asset is siloed for borrowing                              |
| accruedToTreasury              | uint128 | The amount of tokens accrued to treasury that is to be minted          |
| unbacked                       | uint128 | The amount of unbacked aTokens of the reserve                          |
| isolationModeTotalDebt         | uint128 | The outstanding debt borrowed against this asset in isolation mode     |
| flashLoanEnabled               | bool    | true is asset is available to borrow in flash loan transaction         |
| debtCeiling                    | uint256 | The debt ceiling of the reserve                                        |
|                                |         |                                                                        |
| debtCeilingDecimals            | uint256 | The debt ceiling decimals                                              |
| eModeCategoryId                | uint8   | The eMode id of the reserve                                            |
| borrowCap                      | uint256 | The borrow cap of the reserve                                          |
| supplyCap                      | uint256 | The supply cap of the reserve                                          |
| borrowableInIsolation          | bool    | true is asset available to borrow against isolated collateral assets   |
| v3.1                           |         |                                                                        |
| virtualAccActive               | bool    | true if virtual accounting is enabled for a reserve                    |
| virtualUnderlyingBalance       | uint128 | Balance of reserve if virtual accounting is used                       |

#### getUserReservesData

```
function getUserReservesData(IPoolAddressesProvider provider, address user) external view override returns (UserReserveData[] memory, uint8)
```

Returns UserReserveData\[] for all user reserves in the Pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |
| user     | address                | The address of the user                    |

#### UserReserveData

| Type               | Description           |
| ------------------ | --------------------- |
| UserReserveData\[] | The user reserve data |

The [UserReserveData](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/interfaces/IUiPoolDataProviderV3.sol) struct is composed of the following fields:

| Name                           | Type    | Description                                                                                  |
| ------------------------------ | ------- | -------------------------------------------------------------------------------------------- |
| underlyingAsset                | address | The address of the underlying asset supplied/borrowed                                        |
| scaledATokenBalance            | uint256 | The scaled balance of the aToken. scaledBalance = balance/liquidityIndex                     |
| usageAsCollateralEnabledOnUser | bool    | true if the supplied asset is enabled to be used as collateral, false otherwise              |
| scaledVariableDebt             | uint256 | The scaled balance of borrow position: (current balance = scaled balance \* liquidity index) |

#### getEModes

Returns an array of all available E-mode categories in the Pool associated with the [provider](/developers/smart-contracts/pool-addresses-provider).

```
function getEModes(IPoolAddressesProvider provider) external view returns (Emode[] memory)
```

**Input Parameters:**

| Name     | Type                   | Description                                                                     |
| -------- | ---------------------- | ------------------------------------------------------------------------------- |
| provider | IPoolAddressesProvider | The PoolAddressesProvider for the associated Pool to fetch EMode categories for |

**Return Parameters:**

| Name       | Type     | Description                               |
| ---------- | -------- | ----------------------------------------- |
| categories | Emode\[] | The list of E-Modes available in the pool |

**Emode**

The Emode struct is composed of the following fields:

| Name  | Type                    | Description                         |
| ----- | ----------------------- | ----------------------------------- |
| id    | uint8                   | The unique identifier of the E-Mode |
| eMode | DataTypes.EModeCategory | The E-Mode configuration details    |

**DataTypes.EModeCategory**

The EModeCategory struct is composed of the following fields:

| Name                 | Type    | Description                                             |
| -------------------- | ------- | ------------------------------------------------------- |
| ltv                  | uint16  | Loan-to-Value ratio for the E-Mode category             |
| liquidationThreshold | uint16  | The threshold at which liquidation is triggered         |
| liquidationBonus     | uint16  | The bonus applied during liquidation                    |
| collateralBitmap     | uint128 | Bitmap representing eligible collateral for this E-Mode |
| label                | string  | The label describing the E-Mode category                |
| borrowableBitmap     | uint128 | Bitmap representing borrowable assets for this E-Mode   |

### WalletBalanceProvider

Fetches tokens balances for all underlying tokens of Tydro reserves for one user address.

This contract is not used within the Tydro. It is an accessory contract used to reduce the number of calls towards the blockchain from the Tydro backend.

For getting ETH (native chain token) balance use MOCK\_ETH\_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE.

The source code is available on Aave's [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/WalletBalanceProvider.sol).

### View Methods

#### balanceOf

```
function balanceOf(address user, address token) public view returns (uint256)
```

Checks the token balance of a wallet in a token contract. Returns the balance of the token for user (ETH included with MOCK\_ETH\_ADDRESS).

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| user  | address | The address of the user  |
| token | address | The address of the token |

**Return Values:**

| Type    | Description                                                             |
| ------- | ----------------------------------------------------------------------- |
| uint256 | The balance of the token for user. Returns 0 for a non-contract address |

#### batchBalanceOf

```
function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory)
```

Returns balances for a list of users and tokens (ETH included with MOCK\_ETH\_ADDRESS).

**Input Parameters:**

| Name   | Type       | Description        |
| ------ | ---------- | ------------------ |
| users  | address\[] | The list of users  |
| tokens | address\[] | The list of tokens |

**Return Values:**

| Type       | Description                      |
| ---------- | -------------------------------- |
| uint256\[] | A list of balances for each user |

#### getUserWalletBalances

```
function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory)
```

Provides balances of user wallet for all reserves available on the pool.

**Input Parameters:**

| Name     | Type    | Description                 |
| -------- | ------- | --------------------------- |
| provider | address | The address of the provider |
| user     | address | The address of the user     |

**Return Values:**

| Type       | Description                      |
| ---------- | -------------------------------- |
| address\[] | A list of user wallets           |
| uint256\[] | A list of balances for each user |

## UiIncentiveDataProviderV3

Contract that returns an array of all reserve incentives or user claimable rewards within a particular market, used by the Tydro Interface to display incentives data.

The Tydro Utilties SDK includes an interface to make calls to this contract, and functions to format the response for frontend use-cases.&#x20;

The source code is available on Aave's [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/UiIncentiveDataProviderV3.sol).

### View Methods

**getFullReservesIncentiveData**

```
function getFullReservesIncentiveData(IPoolAddressesProvider provider, address user)    external    view    override    returns (AggregatedReserveIncentiveData[] memory, UserReserveIncentiveData[] memory)
```

Returns both AggregatedReserveIncentiveData\[] and UserReserveIncentiveData\[] for the given user for the pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |
| user     | address                | The address of the user                    |

**Return Values:**

| Type                              | Description                           |
| --------------------------------- | ------------------------------------- |
| AggregatedReserveIncentiveData\[] | The aggregated reserve incentive data |
| UserReserveIncentiveData\[]       | The user reserve incentive data       |

The AggregatedReserveIncentiveData struct is composed of the following fields:

| Name            | Type          | Description                                                                                               |
| --------------- | ------------- | --------------------------------------------------------------------------------------------------------- |
| underlyingAsset | address       | Address of the asset supplied/borrowed in Pool                                                            |
| aIncentiveData  | IncentiveData | Details of rewards distributed for supplying to Tydro Pool i.e. rewards for aToken holders                |
| vIncentiveData  | IncentiveData | Details of rewards distributed for variable debt borrowed from Tydro Pool i.e. rewards for vToken holders |

The UserReserveIncentiveData struct is composed of the following fields:

| Name                     | Type              | Description                                                                                             |
| ------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------- |
| underlyingAsset          | address           | Address of the asset supplied/borrowed in Pool                                                          |
| aTokenIncentivesUserData | UserIncentiveData | Details of user rewards received for supplying to Tydro Pool i.e. rewards for aToken                    |
| vTokenIncentivesUserData | UserIncentiveData | Details of user rewards received for borrowing at variable rate from Tydro Pool i.e. rewards for vToken |

**getReservesIncentivesData**

```
function getReservesIncentivesData(IPoolAddressesProvider provider) external view override returns (AggregatedReserveIncentiveData[] memory)
```

Returns AggregatedReserveIncentiveData\[] for the pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |

**Return Values:**

| Type                              | Description                           |
| --------------------------------- | ------------------------------------- |
| AggregatedReserveIncentiveData\[] | The aggregated reserve incentive data |

The AggregatedReserveIncentiveData struct is composed of the following fields:

| Name            | Type          | Description                                                                                               |
| --------------- | ------------- | --------------------------------------------------------------------------------------------------------- |
| underlyingAsset | address       | Address of the asset supplied/borrowed in Pool                                                            |
| aIncentiveData  | IncentiveData | Details of rewards distributed for supplying to Tydro Pool i.e. rewards for aToken holders                |
| vIncentiveData  | IncentiveData | Details of rewards distributed for variable debt borrowed from Tydro Pool i.e. rewards for vToken holders |

**getUserReservesIncentivesData**

```
function getUserReservesIncentivesData(IPoolAddressesProvider provider, address user) external view override returns (UserReserveIncentiveData[] memory)
```

Returns the UserReserveIncentiveData\[] for the given user for the pool associated with the given [provider](/developers/smart-contracts/pool-addresses-provider).

**Input Parameters:**

| Name     | Type                   | Description                                |
| -------- | ---------------------- | ------------------------------------------ |
| provider | IPoolAddressesProvider | The given provider for the associated pool |

**Return Values:**

| Type                        | Description                     |
| --------------------------- | ------------------------------- |
| UserReserveIncentiveData\[] | The user reserve incentive data |

The UserReserveIncentiveData struct is composed of the following fields:

| Name                     | Type              | Description                                                                                             |
| ------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------- |
| underlyingAsset          | address           | Address of the asset supplied/borrowed in Pool                                                          |
| aTokenIncentivesUserData | UserIncentiveData | Details of user rewards received for supplying to Tydro Pool i.e. rewards for aToken                    |
| vTokenIncentivesUserData | UserIncentiveData | Details of user rewards received for borrowing at variable rate from Tydro Pool i.e. rewards for vToken |

### TydroProtocolDataProvider

The TydroProtocolDataProvider is a peripheral contract to collect and pre-process information from the [Pool](/developers/smart-contracts/pool). This contract contains methods for querying token addresses, reserve parameters, and user account information. The methods of the PoolDataProvider are more granular than the UiPoolDataProvider, which queries data for reserve tokens or user balances simultaneously.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/AaveProtocolDataProvider.sol).

### View Methods

#### getAllReservesTokens

```
function getAllReservesTokens() external view returns (TokenData[] memory)
```

Returns a list of the existing reserves in the pool, pairs include the symbol and tokenAddress. Handles MKR and ETH in a different way since they do not have standard symbol functions.

**Return Values:**

| Type         | Description                                          |
| ------------ | ---------------------------------------------------- |
| TokenData\[] | The list of reserves, pairs of symbols and addresses |

The TokenData struct is composed of the following fields:

| Name         | Type    | Description                                 |
| ------------ | ------- | ------------------------------------------- |
| symbol       | string  | The symbol of the underlying reserve asset  |
| tokenAddress | address | The address of the underlying reserve asset |

#### getAllATokens

```
function getAllATokens() external view returns (TokenData[] memory)
```

Returns a list of the existing ATokens in the pool, pairs include the symbol and tokenAddress.

**Return Values:**

| Type         | Description                                         |
| ------------ | --------------------------------------------------- |
| TokenData\[] | The list of ATokens, pairs of symbols and addresses |

The TokenData struct is composed of the following fields:

| Name         | Type    | Description                          |
| ------------ | ------- | ------------------------------------ |
| symbol       | string  | The symbol of aToken of the reserve  |
| tokenAddress | address | The address of aToken of the reserve |

#### getReserveConfigurationData

```
function getReserveConfigurationData(address asset) external view returns (    uint256 decimals,    uint256 ltv,    uint256 liquidationThreshold,    uint256 liquidationBonus,    uint256 reserveFactor,    bool usageAsCollateralEnabled,    bool borrowingEnabled,    bool stableBorrowRateEnabled,    bool isActive,    bool isFrozen)
```

Returns the configuration data of the reserve as described below. Does not return borrow and supply caps, nor pause flag for compatibility.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Name                     | Type    | Description                                                 |
| ------------------------ | ------- | ----------------------------------------------------------- |
| decimals                 | uint256 | The number of decimals of the reserve                       |
| ltv                      | uint256 | The ltv of the reserve                                      |
| liquidationThreshold     | uint256 | The liquidation threshold of the reserve                    |
| liquidationBonus         | uint256 | The liquidation bonus of the reserve                        |
| reserveFactor            | uint256 | The reserve factor of the reserve                           |
| usageAsCollateralEnabled | bool    | true if the usage as collateral is enabled, false otherwise |
| borrowingEnabled         | bool    | true if borrowing is enabled, false otherwise               |
| stableBorrowRateEnabled  | bool    | Always false (deprecated)                                   |
| isActive                 | bool    | true if reserve is active, false otherwise                  |
| isFrozen                 | bool    | true if reserve is frozen, false otherwise                  |

#### getReserveCaps

```
function getReserveCaps(address asset) external view returns (uint256 borrowCap, uint256 supplyCap)
```

Returns the caps parameters of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

#### Return Values:

| Name      | Type    | Description                   |
| --------- | ------- | ----------------------------- |
| borrowCap | uint256 | The borrow cap of the reserve |
| supplyCap | uint256 | The supply cap of the reserve |

#### getPaused

```
function getPaused(address asset) external view returns (bool isPaused)
```

Returns true if the pool isPaused.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Name     | Type | Description                                 |
| -------- | ---- | ------------------------------------------- |
| isPaused | bool | true if the pool is paused, false otherwise |

#### getSiloedBorrowing

```
function getSiloedBorrowing(address asset) external view override returns (bool)
```

Returns the siloed borrowing flag. It returns true if the asset is <mark style="color:blue;">siloed for borrowing.</mark>

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type | Description                               |
| ---- | ----------------------------------------- |
| bool | true if the asset is siloed for borrowing |

#### getLiquidationProtocolFee

```
function getLiquidationProtocolFee(address asset) external view override returns (uint256)
```

Returns the protocol fee on the liquidation bonus.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                     |
| ------- | ------------------------------- |
| uint256 | The protocol fee on liquidation |

#### getUnbackedMintCap

```
function getUnbackedMintCap(address asset) external view override returns (uint256)
```

Returns the unbacked mint cap of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                          |
| ------- | ------------------------------------ |
| uint256 | The unbacked mint cap of the reserve |

#### getDebtCeiling

```
function getDebtCeiling(address asset) external view override returns (uint256)
```

Returns the debt ceiling of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                     |
| ------- | ------------------------------- |
| uint256 | The debt ceiling of the reserve |

#### getReserveData

```
function getReserveData(address asset) external view override returns (    uint256 unbacked,    uint256 accruedToTreasuryScaled,    uint256 totalAToken,    uint256 totalStableDebt,    uint256 totalVariableDebt,    uint256 liquidityRate,    uint256 variableBorrowRate,    uint256 stableBorrowRate,    uint256 averageStableBorrowRate,    uint256 liquidityIndex,    uint256 variableBorrowIndex,    uint40 lastUpdateTimestamp)
```

Returns the reserve data.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Name                    | Type    | Description                                                          |
| ----------------------- | ------- | -------------------------------------------------------------------- |
| unbacked                | uint256 | The amount of unbacked aTokens of the reserve                        |
| accruedToTreasuryScaled | uint256 | The scaled amount of tokens accrued to treasury that is to be minted |
| totalAToken             | uint256 | The total supply of the aToken                                       |
| totalStableDebt         | uint256 | The total stable debt of the reserve (deprecated)                    |
| totalVariableDebt       | uint256 | The total variable debt of the reserve                               |
| liquidityRate           | uint256 | The liquidity rate of the reserve                                    |
| variableBorrowRate      | uint256 | The variable borrow rate of the reserve                              |
| stableBorrowRate        | uint256 | The stable borrow rate of the reserve (deprecated)                   |
| averageStableBorrowRate | uint256 | The average stable borrow rate of the reserve (deprecated)           |
| liquidityIndex          | uint256 | The liquidity index of the reserve                                   |
| variableBorrowIndex     | uint256 | The variable borrow index of the reserve                             |
| lastUpdateTimestamp     | uint40  | The timestamp of the last update of the reserve                      |

#### getATokenTotalSupply

```
function getATokenTotalSupply(address asset) external view override returns (uint256)
```

Returns the total supply of aTokens for a given asset.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                    |
| ------- | ------------------------------ |
| uint256 | The total supply of the aToken |

#### getTotalDebt

```
function getTotalDebt(address asset) external view override returns (uint256)
```

Returns the total debt for a given asset.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                    |
| ------- | ------------------------------ |
| uint256 | The total borrows for an asset |

#### getUserReserveData

```
function getUserReserveData(address asset, address user) external view returns (    uint256 currentATokenBalance,    uint256 currentStableDebt,    uint256 currentVariableDebt,    uint256 principalStableDebt,    uint256 scaledVariableDebt,    uint256 stableBorrowRate,    uint256 liquidityRate,    uint40 stableRateLastUpdated,    bool usageAsCollateralEnabled)
```

Returns the following user reserve data.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |
| user  | address | The address of the user                            |

**Return Values:**

| Name                     | Type    | Description                                                           |
| ------------------------ | ------- | --------------------------------------------------------------------- |
| currentATokenBalance     | uint256 | The current AToken balance of the user                                |
| currentStableDebt        | uint256 | The current stable debt of the user (deprecated)                      |
| currentVariableDebt      | uint256 | The current variable debt of the user                                 |
| principalStableDebt      | uint256 | The principal stable debt of the user (deprecated)                    |
| scaledVariableDebt       | uint256 | The scaled variable debt of the user                                  |
| stableBorrowRate         | uint256 | The stable borrow rate of the user (deprecated)                       |
| liquidityRate            | uint256 | The liquidity rate of the reserve                                     |
| stableRateLastUpdated    | uint40  | The timestamp of the last update of the user stable rate (deprecated) |
| usageAsCollateralEnabled | bool    | true if the user is using the asset as collateral, else false         |

#### getReserveTokensAddresses

```
function getReserveTokensAddresses(address asset) external view override returns (    address aTokenAddress,    address stableDebtTokenAddress,    address variableDebtTokenAddress)
```

Returns the addresses of the aToken, stableDebtToken and variableDebtToken of the reserve.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Name                     | Type    | Description                                             |
| ------------------------ | ------- | ------------------------------------------------------- |
| aTokenAddress            | address | The AToken address of the reserve                       |
| stableDebtTokenAddress   | address | The StableDebtToken address of the reserve (deprecated) |
| variableDebtTokenAddress | address | The VariableDebtToken address of the reserve            |

#### getInterestRateStrategyAddress

```
function getInterestRateStrategyAddress(address asset) external view override returns (address irStrategyAddress)
```

Returns the address of the Interest Rate strategy.

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Name              | Type    | Description                               |
| ----------------- | ------- | ----------------------------------------- |
| irStrategyAddress | address | The address of the Interest Rate strategy |

#### getReserveDeficit

```
function getReserveDeficit(address asset) external view override returns (uint256)
```

**Input Parameters:**

| Name  | Type    | Description                                        |
| ----- | ------- | -------------------------------------------------- |
| asset | address | The address of the underlying asset of the reserve |

**Return Values:**

| Type    | Description                                                       |
| ------- | ----------------------------------------------------------------- |
| uint256 | Current reserve deficit from undercollateralized borrow positions |

### Pure Methods

**getDebtCeilingDecimals**

```
function getDebtCeilingDecimals() external pure override returns (uint256)
```

Returns the debt ceiling decimals.

**Return Values:**

| Type    | Description               |
| ------- | ------------------------- |
| uint256 | The debt ceiling decimals |

### LiquidationDataProvider

This contract is a utility for fetching and pre-processing liquidation-related parameters for a given user. It aggregates data from the underlying Pool and Price Oracle to determine a user’s position, collateral, borrow details, and liquidation limits according to the protocol parameters.

The source code is available on [<mark style="color:blue;">GitHub</mark>](https://github.com/bgd-labs/aave-v3-origin/blob/1f4df52c1be2633b720b3638a299d74b3d5dcbb7/src/contracts/helpers/LiquidationDataProvider.sol).

### View Methods

#### getUserPositionFullInfo

```
getUserPositionFullInfo(address user) public view override returns (UserPositionFullInfo memory)
```

Returns aggregated position information for a user including total collateral, total debt, available borrows, current liquidation threshold, loan-to-value (LTV), and health factor. All values are denominated in the base currency.

**Input Parameters:**

| Name | Type    | Description                                       |
| ---- | ------- | ------------------------------------------------- |
| user | address | The address of the user whose position is queried |

**Return Values:**

| Name                 | Type   | Description                                     |
| -------------------- | ------ | ----------------------------------------------- |
| UserPositionFullInfo | struct | The aggregated position information of the user |

The UserPositionFullInfo struct is composed of the following fields:

| Name                           | Type    | Description                          |
| ------------------------------ | ------- | ------------------------------------ |
| totalCollateralInBaseCurrency  | uint256 | Total collateral in base currency    |
| totalDebtInBaseCurrency        | uint256 | Total debt in base currency          |
| availableBorrowsInBaseCurrency | uint256 | Available borrows in base currency   |
| currentLiquidationThreshold    | uint256 | Current liquidation threshold        |
| ltv                            | uint256 | Loan-to-value ratio                  |
| healthFactor                   | uint256 | Health factor of the user’s position |

#### getCollateralFullInfo

```
getCollateralFullInfo(address user, address collateralAsset) external view override returns (CollateralFullInfo memory)
```

Returns detailed information regarding a user’s collateral for a given asset. The returned struct includes the asset’s unit (based on decimals), its current price (via the Price Oracle), the associated aToken address, the raw collateral balance, and its equivalent value in the base currency.

**Input Parameters:**

| Name            | Type    | Description                                                  |
| --------------- | ------- | ------------------------------------------------------------ |
| user            | address | The address of the user                                      |
| collateralAsset | address | The address of the collateral asset to fetch information for |

**Return Values:**

| Name               | Type   | Description                                             |
| ------------------ | ------ | ------------------------------------------------------- |
| CollateralFullInfo | struct | Detailed collateral information for the specified asset |

The CollateralFullInfo struct is composed of the following fields:

| Name                            | Type    | Description                                         |
| ------------------------------- | ------- | --------------------------------------------------- |
| assetUnit                       | uint256 | The unit value of the asset (10^decimals)           |
| price                           | uint256 | Current price of the asset from the Price Oracle    |
| aToken                          | address | Address of the aToken associated with the asset     |
| collateralBalance               | uint256 | The raw collateral balance of the user              |
| collateralBalanceInBaseCurrency | uint256 | Collateral balance denominated in the base currency |

#### getDebtFullInfo&#x20;

```
getDebtFullInfo(address user, address debtAsset) external view override returns (DebtFullInfo memory)
```

Returns detailed information regarding a user’s debt for a given asset. The returned struct includes the asset’s unit, current price, the associated variable debt token address, the debt balance, and its equivalent value in the base currency.

**Input Parameters:**

| Name      | Type    | Description                                            |
| --------- | ------- | ------------------------------------------------------ |
| user      | address | The address of the user                                |
| debtAsset | address | The address of the debt asset to fetch information for |

**Return Values:**

| Name         | Type   | Description                                       |
| ------------ | ------ | ------------------------------------------------- |
| DebtFullInfo | struct | Detailed debt information for the specified asset |

The DebtFullInfo struct is composed of the following fields:

| Name                      | Type    | Description                                                  |
| ------------------------- | ------- | ------------------------------------------------------------ |
| assetUnit                 | uint256 | The unit value of the asset (10^decimals)                    |
| price                     | uint256 | Current price of the asset from the Price Oracle             |
| variableDebtToken         | address | Address of the variable debt token associated with the asset |
| debtBalance               | uint256 | The raw debt balance of the user                             |
| debtBalanceInBaseCurrency | uint256 | Debt balance denominated in the base currency                |

#### getLiquidationInfo (without custom debt amount)

```
getLiquidationInfo(address user, address collateralAsset, address debtAsset) public view override returns (LiquidationInfo memory)
```

A convenience function that returns liquidation parameters for a user using the maximum possible debt liquidation amount. Internally, it calls the overloaded version with debtLiquidationAmount set to the maximum (type(uint256).max).

**Input Parameters:**

| Name            | Type    | Description                         |
| --------------- | ------- | ----------------------------------- |
| user            | address | The address of the user             |
| collateralAsset | address | The address of the collateral asset |
| debtAsset       | address | The address of the debt asset       |

**Return Values:**

| Name            | Type   | Description                                                        |
| --------------- | ------ | ------------------------------------------------------------------ |
| LiquidationInfo | struct | Detailed liquidation information for the specified user and assets |

The LiquidationInfo struct is composed of the following fields:

| Name                          | Type    | Description                                                          |
| ----------------------------- | ------- | -------------------------------------------------------------------- |
| userInfo                      | struct  | Aggregated position details of the user (UserPositionFullInfo above) |
| collateralInfo                | struct  | Detailed collateral information (CollateralFullInfo above)           |
| debtInfo                      | struct  | Detailed debt information (DebtFullInfo above)                       |
| maxCollateralToLiquidate      | uint256 | Maximum collateral that can be liquidated                            |
| maxDebtToLiquidate            | uint256 | Maximum debt that can be liquidated                                  |
| liquidationProtocolFee        | uint256 | Protocol fee applied on the liquidation bonus                        |
| amountToPassToLiquidationCall | uint256 | Adjusted debt amount for the liquidation call                        |

#### getLiquidationInfo (with custom debt liquidation amount)

```
getLiquidationInfo(address user, address collateralAsset, address debtAsset, uint256 debtLiquidationAmount) public view override returns (LiquidationInfo memory)
```

Returns comprehensive liquidation parameters for a user given a specific collateral asset and debt asset, considering a custom maximum debt liquidation amount. The function aggregates the user’s position, collateral and debt details, checks if liquidation conditions are met, and computes the optimal amounts for liquidation—including any applicable protocol fees.

**Input Parameters:**

| Name                  | Type    | Description                                                                            |
| --------------------- | ------- | -------------------------------------------------------------------------------------- |
| user                  | address | The address of the user                                                                |
| collateralAsset       | address | The address of the collateral asset to be liquidated                                   |
| debtAsset             | address | The address of the debt asset to be repaid                                             |
| debtLiquidationAmount | uint256 | The maximum debt amount that can be liquidated (if lower than the user’s debt balance) |

**Return Values:**

| Name            | Type   | Description                                                        |
| --------------- | ------ | ------------------------------------------------------------------ |
| LiquidationInfo | struct | Detailed liquidation information for the specified user and assets |

The LiquidationInfo struct is composed of the following fields:

| Name                          | Type    | Description                                                          |
| ----------------------------- | ------- | -------------------------------------------------------------------- |
| userInfo                      | struct  | Aggregated position details of the user (UserPositionFullInfo above) |
| collateralInfo                | struct  | Detailed collateral information (CollateralFullInfo above)           |
| debtInfo                      | struct  | Detailed debt information (DebtFullInfo above)                       |
| maxCollateralToLiquidate      | uint256 | Maximum collateral that can be liquidated                            |
| maxDebtToLiquidate            | uint256 | Maximum debt that can be liquidated                                  |
| liquidationProtocolFee        | uint256 | Protocol fee applied on the liquidation bonus                        |
| amountToPassToLiquidationCall | uint256 | Adjusted debt amount for the liquidation call                        |


# Incentives

The [UiIncentiveDataProvider](/developers/smart-contracts/view-contracts) contract provides methods to query all active incentive emissions and the claimable user incentives for a specific Tydro market. This contract is primarily used by frontends to display incentive information for suppliers and borrowers.

## RewardsController

* Rewards accrue automatically for users holding incentivised ERC-20 assets. No staking or locking is required.
* Users can claim all rewards in a single transaction or claim individual rewards with more granularity.
* On every transfer, incentivised assets call the `handleAction` method to account for updated reward balances.

Key properties:

The RewardsController is the main rewards contract where users interact to claim rewards from their Tydro positions. It is designed as an abstract template that can be extended to create distributor contracts for ERC-20 rewards.

The source code is available on [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/rewards/RewardsController.sol).

### Write Methods

#### initialize

```
function initialize(address) external initializer
```

Initialize RewardsController instance.

**Input Parameters:**

| Type    | Description                                                                        |
| ------- | ---------------------------------------------------------------------------------- |
| address | Unused but required due to being initialized by PoolAddressProvider.\_updateImpl() |

#### configureAssets

```
function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external override onlyEmissionManager
```

Configure assets to incentivize with an emission of rewards per second until the end of distribution.

**Input Parameters:**

| Name   | Type                                   | Description                                             |
| ------ | -------------------------------------- | ------------------------------------------------------- |
| config | RewardsDataTypes.RewardsConfigInput\[] | The emission per second following rewards unit decimals |

The [<mark style="color:blue;">RewardsDataTypes.RewardsConfigInput</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/rewards/libraries/RewardsDataTypes.sol) struct is composed of the following fields:

| Name              | Type                | Description                                                                                                                                                   |
| ----------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| emissionPerSecond | uint88              | The emission per second following rewards unit decimals                                                                                                       |
| totalSupply       | uint256             | The total supply of the asset to incentivize                                                                                                                  |
| distributionEnd   | uint32              | The end of the distribution of the incentives for an asset                                                                                                    |
| asset             | address             | The asset address to incentivize                                                                                                                              |
| reward            | address             | The reward token address                                                                                                                                      |
| transferStrategy  | ITransferStrategy   | The TransferStrategy address with the install hook and claim logic                                                                                            |
| rewardOracle      | IEACAggregatorProxy | The Price Oracle of a reward to visualize the incentives at the UI frontend. Must follow Chainlink Aggregator IEACAggregatorProxy interface to be compatible. |

#### setTransferStrategy

```
function setTransferStrategy(address reward, ITransferStrategyBase transferStrategy) external onlyEmissionManager
```

Sets a TransferStrategy logic contract that determines the logic of the rewards transfer.

**Input Parameters:**

| Name             | Type    | Description                                        |
| ---------------- | ------- | -------------------------------------------------- |
| reward           | address | The address of the reward token                    |
| transferStrategy | address | The address of the TransferStrategy logic contract |

#### setRewardOracle

```
function setRewardOracle(address reward, IEACAggregatorProxy rewardOracle) external onlyEmissionManager
```

Sets an Aave Oracle contract to enforce rewards with a source of value.

At the moment of reward configuration, the Incentives Controller performs a check to see if the reward asset oracle is compatible with IEACAggregator proxy. This check is enforced for integrators to show incentives at the current Aave UI without needing to set up an external price registry.

**Input Parameters:**

| Name         | Type                | Description                                                                    |
| ------------ | ------------------- | ------------------------------------------------------------------------------ |
| reward       | address             | The address of the reward to set the price aggregator                          |
| rewardOracle | IEACAggregatorProxy | The address of price aggregator that follows the IEACAggregatorProxy interface |

#### handleAction

```
function handleAction(address user, uint256 totalSupply, uint256 userBalance) external override
```

Called by the corresponding asset on transfer hook to update the rewards distribution of a user.

**Input Parameters:**

| Name        | Type    | Description                   |
| ----------- | ------- | ----------------------------- |
| user        | address | The address of the user       |
| totalSupply | uint256 | The user balance of the asset |
| userBalance | uint256 | The total supply of the asset |

#### claimRewards

```
function claimRewards(    address[] calldata assets,    uint256 amount,    address to,    address reward) external override returns (uint256)
```

Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards. Rewards are received by the to address.

**Input Parameters:**

| Name   | Type       | Description                                                                                                   |
| ------ | ---------- | ------------------------------------------------------------------------------------------------------------- |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards. Pass a/s/vToken addresses         |
| amount | uint256    | The amount of rewards to claim, expressed in wei. Pass MAX\_UINT to claim the entire unclaimed reward balance |
| to     | address    | The address that will be receiving the rewards                                                                |
| reward | address    | The address of the reward token (e.g., stkAAVE)                                                               |

**Return Values:**

| Type    | Description                                           |
| ------- | ----------------------------------------------------- |
| uint256 | The amount of rewards claimed for one specific reward |

The msg.sender must be an authorized claimer set using the setClaimer() method

#### claimRewardsOnBehalf

```
function claimAllRewardsOnBehalf(
    address[] calldata assets,
    address user,
    address to
) external override onlyAuthorizedClaimers(msg.sender, user) returns (address[] memory rewardsList, uint256[] memory claimedAmounts)
```

Claims rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards of the assets passed by the first argument. The caller must be whitelisted via the <kbd>allowClaimOnBehalf</kbd> function by the EmissionManager role held by Tydro. Rewards are received by the Press <kbd>to</kbd> address. address.

**Input Parameters:**

| Name   | Type       | Description                                                                                                   |
| ------ | ---------- | ------------------------------------------------------------------------------------------------------------- |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards. Pass a/s/vToken addresses         |
| amount | uint256    | The amount of rewards to claim, expressed in wei. Pass MAX\_UINT to claim the entire unclaimed reward balance |
| user   | address    | The address to check and claim rewards                                                                        |
| to     | address    | The address that will be receiving the rewards                                                                |
| reward | address    | The address of the reward token being claimed (e.g., stkAAVE)                                                 |

**Return Values:**

| Type    | Description                   |
| ------- | ----------------------------- |
| uint256 | The amount of rewards claimed |

#### claimRewardsToSelf

```
function claimRewardsToSelf(address[] calldata assets, uint256 amount, address reward) external override returns (uint256)
```

Claims reward for msg.sender, on all the assets of the pool, accumulating the pending rewards passed by the first input parameter. Rewards are received by msg.sender.

**Input Parameters:**

| Name   | Type       | Description                                                                                                   |
| ------ | ---------- | ------------------------------------------------------------------------------------------------------------- |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards. Pass a/s/vToken addresses         |
| amount | uint256    | The amount of rewards to claim, expressed in wei. Pass MAX\_UINT to claim the entire unclaimed reward balance |
| reward | address    | The address of the reward token                                                                               |

**Return Values:**

| Type    | Description                                           |
| ------- | ----------------------------------------------------- |
| uint256 | The amount of rewards claimed for one specific reward |

#### claimAllRewards

```
function claimAllRewards(address[] calldata assets, address to) external override returns (address[] memory rewardsList, uint256[] memory claimedAmounts)
```

Claims all rewards for a user to the desired address, on all the assets of the pool, accumulating the pending rewards passed by the first input parameter. Rewards are received by the toaddress.

**Input Parameters:**

| Name   | Type       | Description                                                                                                        |
| ------ | ---------- | ------------------------------------------------------------------------------------------------------------------ |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards (aToken or variableDebtToken addresses) |
| to     | address    | The address that will be receiving the rewards                                                                     |

**Return Values:**

| Name           | Type       | Description                                                                                   |
| -------------- | ---------- | --------------------------------------------------------------------------------------------- |
| rewardsList    | address\[] | The list of addresses of the reward tokens                                                    |
| claimedAmounts | uint256\[] | The list that contains the claimed amount per reward, following the same order as rewardsList |

#### claimAllRewardsOnBehalf

```
function claimAllRewardsOnBehalf(    address[] calldata assets,    address user,    address to) external override onlyAuthorizedClaimers(msg.sender, user) returns (address[] memory rewardsList, uint256[] memory claimedAmounts)
```

Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards passed by the first input parameter. The caller must be whitelisted via the allowClaimOnBehalf function by the EmissionManager role held by Tydro. Rewards are received by the to address.

**Input Parameters:**

| Name   | Type       | Description                                                                                           |
| ------ | ---------- | ----------------------------------------------------------------------------------------------------- |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards. Pass a/s/vToken addresses |
| user   | address    | The address to check and claim rewards                                                                |
| to     | address    | The address that will be receiving the rewards                                                        |

**Return Values:**

| Name           | Type       | Description                                                                                   |
| -------------- | ---------- | --------------------------------------------------------------------------------------------- |
| rewardsList    | address\[] | The list of addresses of the reward tokens                                                    |
| claimedAmounts | uint256\[] | The list that contains the claimed amount per reward, following the same order as rewardsList |

#### claimAllRewardsToSelf

```
function claimAllRewardsToSelf(address[] calldata assets) external override returns (address[] memory rewardsList, uint256[] memory claimedAmounts)
```

Claims all rewards accrued by msg.sender, on all assets of the pool, accumulating the pending rewards by the first input parameter. Rewards are received by msg.sender.

**Input Parameters:**

| Name   | Type       | Description                                                                                           |
| ------ | ---------- | ----------------------------------------------------------------------------------------------------- |
| assets | address\[] | The list of assets to check eligible distributions before claiming rewards. Pass a/s/vToken addresses |

**Return Values:**

| Name           | Type       | Description                                                                                   |
| -------------- | ---------- | --------------------------------------------------------------------------------------------- |
| rewardsList    | address\[] | The list of addresses of the reward tokens                                                    |
| claimedAmounts | uint256\[] | The list that contains the claimed amount per reward, following the same order as rewardsList |

#### setClaimer

```
function setClaimer(address user, address caller) external override onlyEmissionManager
```

Whitelists an address to claim rewards on behalf of another address. Can only be called by the EmissionManager help by Tydro

**Input Parameters:**

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| user   | address | The address of the user    |
| caller | address | The address of the claimer |

### View Methods

#### getClaimer

```
function getClaimer(address user) external view override returns (address)
```

Returns the whitelisted claimer for a certain address. It returns the 0x0 address if it is not set.

**Input Parameters:**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| user | address | The address of the user |

**Return Values:**

| Type    | Description         |
| ------- | ------------------- |
| address | The claimer address |

#### getRewardOracle

```
function getRewardOracle(address reward) external view override returns (address)
```

Get the price aggregator oracle address.

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| reward | address | The address of the reward token |

**Return Values:**

| Type    | Description                      |
| ------- | -------------------------------- |
| address | The address of the reward oracle |

#### getTransferStrategy

```
function getTransferStrategy(address reward) external view override returns (address)
```

Returns the Transfer Strategy implementation contract address being used for a reward address.

| Name   | Type    | Description               |
| ------ | ------- | ------------------------- |
| reward | address | The address of the reward |

**Return Values:**

| Type    | Description                                  |
| ------- | -------------------------------------------- |
| address | The address of the TransferStrategy contract |

### Pure Methods

```
function getRevision() internal pure override returns (uint256)
```

Returns the revision of the implementation contract.

**Return Values:**

| Type    | Description                  |
| ------- | ---------------------------- |
| uint256 | The current revision version |


# Tokenization

### AToken

aTokens are tokens minted when assets are supplied to a Tydro market and burned when assets are withdrawn. They represent both the amount of crypto assets supplied and the yield earned on those assets.

* The value of an aToken is pegged 1:1 to the underlying asset.
* aTokens can be stored, transferred, or traded like standard ERC-20 tokens.
* Yield is distributed directly to aToken holders by continuously increasing their wallet balance.

The aToken contract is the interest-bearing token implementation for Tydro. It inherits from [<mark style="color:blue;">ScaledBalanceTokenBase</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/ScaledBalanceTokenBase.sol) and [<mark style="color:blue;">EIP712Base</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/EIP712Base.sol) token contracts.

All standard ERC-20 methods are implemented, including:

* `balanceOf`
* `transfer`
* `transferFrom`
* `approve`
* `totalSupply`

The `balanceOf` function always returns the most up-to-date user balance, combining both the principal supplied and the yield earned.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/AToken.sol).

### Write Methods

#### initialize

```
function initialize(
    IPool initializingPool,
    address treasury,
    address underlyingAsset,
    IAaveIncentivesController incentivesController,
    uint8 aTokenDecimals,
    string calldata aTokenName,
    string calldata aTokenSymbol,
    bytes calldata params
) public virtual
```

Called when aToken instance is initialized.

**Input Parameters:**

| Name                 | Type                      | Description                                               |
| -------------------- | ------------------------- | --------------------------------------------------------- |
| initializingPool     | IPool                     | The address of the associated pool                        |
| treasury             | address                   | The address of the treasury                               |
| underlyingAsset      | address                   | The address of the underlying asset                       |
| incentivesController | IAaveIncentivesController | The address of the incentives controller for this aToken  |
| aTokenDecimals       | uint8                     | The decimals of the underlying asset                      |
| aTokenName           | string                    | The name of the aToken                                    |
| aTokenSymbol         | string                    | The symbol of the aToken                                  |
| params               | bytes                     | A set of encoded parameters for additional initialization |

#### mint

```
function mint(
    address caller,
    address onBehalfOf,
    uint256 amount,
    uint256 index
) external virtual override onlyPool returns (bool)
```

Mints amount aTokens to user.

**Input Parameters:**

| Name       | Type    | Description                                                  |
| ---------- | ------- | ------------------------------------------------------------ |
| caller     | address | The address performing the mint                              |
| onBehalfOf | address | The address of the user that will receive the minted aTokens |
| amount     | uint256 | The amount of tokens getting minted                          |
| index      | uint256 | The next liquidity index of the reserve                      |

**Return Values:**

| Type | Description                                        |
| ---- | -------------------------------------------------- |
| bool | true if the the previous balance of the user was 0 |

#### burn

```
function burn(
    address from,
    address receiverOfUnderlying,
    uint256 amount,
    uint256 index
) external virtual override onlyPool
```

In some instances, the mint event could be emitted from a burn transaction if the amount to burn is less than the interest that the user accrued.

**Input Parameters:**

| Name                 | Type    | Description                                        |
| -------------------- | ------- | -------------------------------------------------- |
| from                 | address | The address from which the aTokens will be burned  |
| receiverOfUnderlying | address | The address that will receive the underlying asset |
| amount               | uint256 | The amount of tokens that will be burned           |
| index                | uint256 | The next liquidity index of the reserve            |

#### mintToTreasury

```
function mintToTreasury(uint256 amount, uint256 index) external override onlyPool
```

Mints aTokens to the reserve treasury.

**Input Parameters:**

| Name   | Type    | Description                                        |
| ------ | ------- | -------------------------------------------------- |
| amount | uint256 | The amount of tokens getting minted                |
| index  | uint256 | The address that will receive the underlying asset |

#### transferOnLiquidation

```
function transferOnLiquidation(
    address from,
    address to,
    uint256 value
) virtual override onlyPool
```

Transfers aTokens in the event of a borrow being liquidated, in case the liquidator reclaims the aToken.

**Input Parameters:**

| Name  | Type    | Description                                                  |
| ----- | ------- | ------------------------------------------------------------ |
| from  | address | The address getting liquidated, current owner of the aTokens |
| to    | address | The recipient of aTokens                                     |
| value | uint256 | The amount of tokens getting transferred                     |

#### transferUnderlyingTo

```
function transferUnderlyingTo(address target, uint256 amount) external virtual override onlyPool
```

Transfers the underlying asset to target.

Used by the [Pool](/developers/smart-contracts/pool) to transfer assets in borrow(), withdraw() and flashLoan().

**Input Parameters:**

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| user   | address | The recipient of the underlying |
| amount | uint256 | The amount getting transferred  |

#### handleRepayment

```
function handleRepayment(address user, address onBehalfOf, uint256 amount) external virtual override onlyPool
```

Handles the underlying received by the aToken after the transfer has been completed.

The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying to receive LM rewards. In that case, handleRepayment() would perform the staking of the underlying asset.

**Input Parameters:**

| Name       | Type      | Description                                         |
| ---------- | --------- | --------------------------------------------------- |
| user       | address   | The user executing the repayment                    |
| onBehalfOf | address\` | The address for which the borrow position is repaid |
| amount     | uint256   | The amount getting repaid                           |

#### permit

```
function permit(
    address owner,
    address spender,
    uint256 value,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
) external override
```

Allows a user to permit another account (or contract) to use their funds using a signed message. This enables gas-less transactions and single approval/transfer transactions. Allow passing a signed message to approve spending.

Implements the permit function as for EIP-2612.

**Input Parameters:**

| Name     | Type    | Description                                                       |
| -------- | ------- | ----------------------------------------------------------------- |
| owner    | address | The owner of the funds                                            |
| spender  | address | The spender of the funds                                          |
| value    | uint256 | The amount the spender is permitted to spend                      |
| deadline | uint256 | The deadline timestamp, use type(uint256).max for max/no deadline |
| v        | uint8   | The V signature parameter                                         |
| r        | bytes32 | The R signature parameter                                         |
| s        | bytes32 | The S signature parameter                                         |

Example of signing and utilizing permit:

```
import { signTypedData_v4 } from "eth-sig-util";
import { fromRpcSig } from "ethereumjs-util";
// ... other imports
import aTokenAbi from "./aTokenAbi.json";
// ... setup your web3 provider
const aTokenAddress = "ATOKEN_ADDRESS";
const aTokenContract = new web3.eth.Contract(aTokenAbi, aTokenAddress);
const privateKey = "YOUR_PRIVATE_KEY_WITHOUT_0x";
const chainId = 1;
const owner = "OWNER_ADDRESS";
const spender = "SPENDER_ADDRESS";
const value = 100; // Amount the spender is permitted
const nonce = 1; // The next valid nonce, use `_nonces()`
const deadline = 1600093162;
const permitParams = {
  types: {
    EIP712Domain: [
      { name: "name", type: "string" },
      { name: "version", type: "string" },
      { name: "chainId", type: "uint256" },
      { name: "verifyingContract", type: "address" },
    ],
    Permit: [
      { name: "owner", type: "address" },
      { name: "spender", type: "address" },
      { name: "value", type: "uint256" },
      { name: "nonce", type: "uint256" },
      { name: "deadline", type: "uint256" },
    ],
  },
  primaryType: "Permit",
  domain: {
    name: "aTOKEN_NAME",
    version: "1",
    chainId: chainId,
    verifyingContract: aTokenAddress,
  },
  message: {
    owner,
    spender,
    value,
    nonce,
    deadline,
  },
};
const signature = signTypedData_v4(Buffer.from(privateKey, "hex"), {
  data: permitParams,
});
// The signature can now be used to execute the transaction
const { v, r, s } = fromRpcSig(signature);
await aTokenContract.methods
  .permit({
    owner,
    spender,
    value,
    deadline,
    v,
    r,
    s,
  })
  .send()
  .catch((e) => {
    throw Error(`Error permitting: ${e.message}`);
  });
```

#### rescueTokens

```
function rescueTokens(
    address token,
    address to,
    uint256 amount
) external override onlyPoolAdmin
```

Rescue and transfer tokens locked in this contract. Only callable by [POOL\_ADMIN](/developers/smart-contracts/aclmanager).

**Input Parameters:**

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| token  | address | The address of the token        |
| to     | address | The address of the recipient    |
| amount | uint256 | The amount of token to transfer |

### View Methods

#### balanceOf

```
function balanceOf(address user)
    public
    view
    virtual
    override(IncentivizedERC20, IERC20)
    returns (uint256)
```

Returns the amount of tokens owned by user.

Overrides the base function.

**Input Parameters:**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| user | address | The address of the user |

**Return Values:**

| Type    | Description                        |
| ------- | ---------------------------------- |
| uint256 | The amount of tokens owned by user |

#### totalSupply

```
function totalSupply() public view virtual override(IncentivizedERC20, IERC20 returns (uint256)
```

Returns the amount of tokens in existence.

Overrides the base function.

**Return Values:**

| Type    | Description                       |
| ------- | --------------------------------- |
| uint256 | The amount of tokens in existence |

#### RESERVE\_TREASURY\_ADDRESS

```
function RESERVE_TREASURY_ADDRESS() external view override returns (address)
```

Returns the address of the Tydro treasury, controlled by Tydro, receiving the fees on this aToken.

**Return Values:**

| Type    | Description                      |
| ------- | -------------------------------- |
| address | The address of the Aave treasury |

#### UNDERLYING\_ASSET\_ADDRESS

```
function UNDERLYING_ASSET_ADDRESS() external view override returns (address)
```

Returns the address of the underlying reserve asset of this aToken (E.g. WETH for aWETH).

**Return Values:**

| Type    | Description                         |
| ------- | ----------------------------------- |
| address | The address of the underlying asset |

#### DOMAIN\_SEPARATOR

```
function DOMAIN_SEPARATOR() public view override(IAToken, EIP712Base) returns (bytes32)
```

Get the domain separator for the token at the current chain.

Return cached value if chainId matches cache, otherwise recomputes separator.

Overrides the base function to fully implement IAToken.

**Return Values:**

| Type    | Description                                        |
| ------- | -------------------------------------------------- |
| bytes32 | The domain separator of the token at current chain |

#### nonces

```
function nonces(address owner) public view override(IAToken, EIP712Base) returns (uint256)
```

Returns the nonce value for address specified as parameter. This is the nonce used when calling permit().

Overrides the base function to fully implement IAToken.

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| owner | address | The address of the owner |

**Return Values:**

| Type    | Description            |
| ------- | ---------------------- |
| uint256 | The nonce of the owner |

Example:

```
const token = new Contract(aTokenAddress, aToken.abi, provider);
await token.nonces(user);
```

### Pure Methods

#### getRevision

```
function getRevision() internal pure virtual override returns (uint256)
```

Returns the revision number of the contract. Needs to be defined in the inherited class as a constant.

Returns 0x1.

**Return Values:**

| Type    | Description         |
| ------- | ------------------- |
| uint256 | The revision number |

## StaticATokenFactory

The StataTokenFactory is a factory and registry contract that manages all deployed StataToken instances for a specified Aave pool. It allows deploying new StataToken instances on demand and validates that there is only one StataToken instance per underlying asset. This contract maintains a mapping between underlying assets and their corresponding StataTokenaddresses.

StataTokens are ERC-4626 compliant tokens that wrap Aave's aTokens to provide a non-rebasing yield accrual mechanism.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>.](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/StataTokenFactory.sol)

### Write Methods

#### initialize

```
function initialize() external initializer
```

Initializes the StataTokenFactory contract. This function is part of the Initializable pattern and is required to initialize the contract after deployment. In this implementation, it does not perform any actions.

#### createStataTokens

```
function createStataTokens(address[] memory underlyings) external returns (address[] memory)
```

Creates new StataToken instances for the given underlying assets if they do not already exist. For each provided underlying asset, the function checks if a StataToken already exists. If it does, the existing StataToken address is returned. If not, it deploys a new StataToken for that underlying asset, registers it, and returns the new address.

**Input Parameters:**

| Name        | Type       | Description                            |
| ----------- | ---------- | -------------------------------------- |
| underlyings | address\[] | An array of underlying asset addresses |

**Return Values:**

| Type       | Description                                                                      |
| ---------- | -------------------------------------------------------------------------------- |
| address\[] | An array of StataToken addresses corresponding to the provided underlying assets |

**Emits:**

* StataTokenCreated(address indexed stataToken, address indexed underlying) event for each new StataToken created.

**Reverts:**

* NotListedUnderlying(address underlying) if the underlying asset is not listed in the Aave pool.

### View Methods

#### getStataTokens

```
function getStataTokens() external view returns (address[] memory)
```

Returns all StataToken instances deployed via this factory.

**Return Values:**

| Type       | Description                                   |
| ---------- | --------------------------------------------- |
| address\[] | An array of all StataToken contract addresses |

#### getStataToken

```
function getStataToken(address underlying) external view returns (address)
```

Returns the StataToken address for a given underlying asset.

**Input Parameters:**

| Name       | Type    | Description                         |
| ---------- | ------- | ----------------------------------- |
| underlying | address | The address of the underlying asset |

**Return Values:**

| Type    | Description                                                                  |
| ------- | ---------------------------------------------------------------------------- |
| address | The address of the corresponding StataToken; returns address(0) if not found |

#### POOL

```
function POOL() external view returns (IPool)
```

Returns the address of the Aave pool associated with this factory.

**Return Values:**

| Type  | Description                             |
| ----- | --------------------------------------- |
| IPool | The address of the associated Aave pool |

#### PROXY\_ADMIN

```
function PROXY_ADMIN() external view returns (address)
```

Returns the address of the proxy admin used for the StataToken proxies.

**Return Values:**

| Type    | Description                    |
| ------- | ------------------------------ |
| address | The address of the proxy admin |

#### TRANSPARENT\_PROXY\_FACTORY

```
function TRANSPARENT_PROXY_FACTORY() external view returns (ITransparentProxyFactory)
```

Returns the address of the transparent proxy factory used for creating new StataToken proxies.

**Return Values:**

| Type                     | Description                                  |
| ------------------------ | -------------------------------------------- |
| ITransparentProxyFactory | The address of the transparent proxy factory |

#### STATA\_TOKEN\_IMPL

```
function STATA_TOKEN_IMPL() external view returns (address)
```

Returns the address of the StataToken implementation used when deploying new StataTokeninstances.

**Return Values:**

| Type    | Description                                  |
| ------- | -------------------------------------------- |
| address | The address of the StataToken implementation |

## VariableDebtToken

Implements a variable debt token to track the borrowing positions of users at variable rate mode.

transfer and approve functionalities are disabled as variable debt tokens are non-transferable.

The vToken value is pegged 1:1 to the value of underlying borrowed asset and represents the current total amount owed to the protocol i.e. principal debt + interest accrued.

The VariableDebtToken contract inherits the [<mark style="color:blue;">DebtTokenBase</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/DebtTokenBase.sol) and [<mark style="color:blue;">ScaledBalanceTokenBase</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/ScaledBalanceTokenBase.sol) token contracts.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/VariableDebtToken.sol).

### Write Methods

#### initialize

```
function initialize(
    IPool initializingPool,
    address underlyingAsset,
    IAaveIncentivesController incentivesController,
    uint8 debtTokenDecimals,
    string memory debtTokenName,
    string memory debtTokenSymbol,
    bytes calldata params
) external virtual
```

Called when variableDebtToken instance is initialised.

**Input Parameters:**

| Name                 | Type                      | Description                                                              |
| -------------------- | ------------------------- | ------------------------------------------------------------------------ |
| initializingPool     | IPool                     | The pool contract that is initializing this contract                     |
| underlyingAsset      | address                   | The address of the underlying asset of this aToken (E.g. WETH for aWETH) |
| incentivesController | IAaveIncentivesController | The smart contract managing potential incentives distribution            |
| debtTokenDecimals    | uint8                     | The decimals of the variableDebtToken, same as the underlying asset's    |
| debtTokenName        | string                    | The name of the variable debt token                                      |
| debtTokenSymbol      | string                    | The symbol of the variable debt token                                    |
| params               | bytes                     | A set of encoded parameters for additional initialization                |

#### mint

```
function mint(
    address user,
    address onBehalfOf,
    uint256 amount,
    uint256 index
) external virtual override onlyPool returns (bool, uint256)
```

Mints the variable debt token to the onBehalfOf address.

**Input Parameters:**

| Name       | Type    | Description                                                                                                                    |
| ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
| user       | address | The address receiving the borrowed underlying, being the delegatee in case of credit delegate, or same as onBehalfOf otherwise |
| onBehalfOf | address | The address receiving the variable debt tokens                                                                                 |
| amount     | uint256 | The amount of variable debt tokens to mint                                                                                     |
| index      | uint256 | The variable debt index of the reserve                                                                                         |

**Return Values:**

| Type    | Description                                                    |
| ------- | -------------------------------------------------------------- |
| bool    | true if the previous balance of the user is 0, false otherwise |
| uint256 | The scaled total debt of the reserve                           |

#### burn

```
function burn(
    address from,
    uint256 amount,
    uint256 index
) external virtual override onlyPool returns (uint256)
```

Burns user variable debt.

In some instances, a burn transaction will emit a mint event if the amount to burn is less than the interest that the user accrued.

**Input Parameters:**

| Name   | Type    | Description                                    |
| ------ | ------- | ---------------------------------------------- |
| from   | address | The address from which the debt will be burned |
| amount | uint256 | The amount of debt tokens that will be burned  |
| index  | uint256 | The variable debt index of the reserve         |

**Return Values:**

| Type    | Description                          |
| ------- | ------------------------------------ |
| uint256 | The scaled total debt of the reserve |

### View Methods

#### UNDERLYING\_ASSET\_ADDRESS

```
function UNDERLYING_ASSET_ADDRESS() external view override returns (address)
```

Returns the address of the underlying asset of this variableDebtToken (e.g. WETH for variableDebtWETH)

**Return Values:**

| Type    | Description                         |
| ------- | ----------------------------------- |
| address | The address of the underlying asset |

#### balanceOf

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

Returns the amount of tokens owned by account - the most up to date accumulated debt (principal + interest) of the user.

Standard ERC20 function.

**Input Parameters:**

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| account | address | The balance of this address |

**Return Values:**

| Type    | Description                           |
| ------- | ------------------------------------- |
| uint256 | The amount of tokens owned by account |

#### totalSupply

```
function totalSupply() public view virtual override returns (uint256)
```

Returns the amount of tokens in existence - the most up to date total debt accrued by all protocol users for that specific variable rate of debt token.

Standard ERC20 function.

**Return Values:**

| Type    | Description                       |
| ------- | --------------------------------- |
| uint256 | The amount of tokens in existence |

### Pure Methods

#### getRevision

```
function getRevision() internal pure virtual override returns (uint256)
```

Returns the revision number of the contract. Needs to be defined in the inherited class as a constant.

Returns 0x1.

**Return Values:**

| Type    | Description         |
| ------- | ------------------- |
| uint256 | The revision number |

### NOT SUPPORTED OPERATIONS

Being non-transferrable, the variable debt token does not implement any of the standard ERC20 functions for transfer and allowance.

The following functions below will revert with the error code 80, OPERATION\_NOT\_SUPPORTED: transfer, allowance, approve, transferFrom, increaseAllowance, decreaseAllowance.


# Interest Rate Strategy

This contract implements the calculation of interest rates based on the state of each reserve. The model follows a **two-slope structure**:

* One slope applies when utilisation is below the `OPTIMAL_USAGE_RATIO`.
* A steeper slope applies once utilisation rises above the optimal point, up to 100%.

Each Tydro market deploys its own instance of the interest rate strategy contract, as it caches the [`PoolAddressesProvider`](/developers/smart-contracts/pool-addresses-provider) and cannot be shared across markets

The source code is available on [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/DefaultReserveInterestRateStrategyV2.sol).

### View Methods

#### getVariableRateSlope1

```
function getVariableRateSlope1(address reserve) external view returns (uint256)
```

Returns the variable rate slope below the optimal usage ratio for the specified reserve. This is the variable rate when the usage ratio is between 0 and OPTIMAL\_USAGE\_RATIO.

**Input Parameters:**

| Name    | Type    | Description                |
| ------- | ------- | -------------------------- |
| reserve | address | The address of the reserve |

**Return Values:**

| Type    | Description             |
| ------- | ----------------------- |
| uint256 | The variable rate slope |

#### getVariableRateSlope2

```
function getVariableRateSlope2(address reserve) external view returns (uint256)
```

Returns the variable rate slope above the optimal usage ratio for the specified reserve. This is the variable rate when the usage ratio is greater than OPTIMAL\_USAGE\_RATIO.

**Input Parameters:**

| Name    | Type    | Description                |
| ------- | ------- | -------------------------- |
| reserve | address | The address of the reserve |

**Return Values:**

| Type    | Description             |
| ------- | ----------------------- |
| uint256 | The variable rate slope |

#### getBaseVariableBorrowRate

```
function getBaseVariableBorrowRate(address reserve) external view override returns (uint256)
```

Returns the base variable borrow rate for the specified reserve.

**Input Parameters:**

| Name    | Type    | Description                |
| ------- | ------- | -------------------------- |
| reserve | address | The address of the reserve |

**Return Values:**

| Type    | Description                                     |
| ------- | ----------------------------------------------- |
| uint256 | The base variable borrow rate, expressed in ray |

#### getMaxVariableBorrowRate

```
function getMaxVariableBorrowRate(address reserve) external view override returns (uint256)
```

Returns the maximum variable borrow rate for the specified reserve.

**Input Parameters:**

| Name    | Type    | Description                |
| ------- | ------- | -------------------------- |
| reserve | address | The address of the reserve |

**Return Values:**

| Type    | Description                                        |
| ------- | -------------------------------------------------- |
| uint256 | The maximum variable borrow rate, expressed in ray |

#### calculateInterestRates

```
function calculateInterestRates(    DataTypes.CalculateInterestRatesParams memory params) external view override returns (uint256, uint256)
```

Calculates the interest rates depending on the reserve's state and configurations. This function returns only two values: the liquidity rate and the variable borrow rate.

**Input Parameters:**

| Name   | Type                                   | Description                                       |
| ------ | -------------------------------------- | ------------------------------------------------- |
| params | DataTypes.CalculateInterestRatesParams | The parameters needed to calculate interest rates |

The DataTypes.CalculateInterestRatesParams struct is composed of the following fields:

| Name                     | Type    | Description                                                                 |
| ------------------------ | ------- | --------------------------------------------------------------------------- |
| unbacked                 | uint256 | The amount of unbacked tokens                                               |
| liquidityAdded           | uint256 | The liquidity added during the operation                                    |
| liquidityTaken           | uint256 | The liquidity taken during the operation                                    |
| totalDebt                | uint256 | The total borrowed from the reserve                                         |
| reserveFactor            | uint256 | The reserve portion of the interest that goes to the treasury of the market |
| reserve                  | address | The address of the reserve                                                  |
| usingVirtualBalance      | bool    | Flag to indicate if the virtual balance is being used                       |
| virtualUnderlyingBalance | uint256 | The virtual balance of underlying asset used for mintable assets            |

**Return Values:**

| Name               | Type    | Description                                |
| ------------------ | ------- | ------------------------------------------ |
| liquidityRate      | uint256 | The liquidity rate, expressed in ray       |
| variableBorrowRate | uint256 | The variable borrow rate, expressed in ray |


# ACLManager

The ACLManager (Access Control List Manager) is the registry of roles and permissions within Tydro. It ensures that sensitive operations are restricted to authorised addresses and that responsibilities are clearly separated across different roles.

Tydro implements an access control list to segregate powers and/or benefits that can be allocated to different entities on the protocol. The ACL\_MANAGER contract is managed by the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) contract.

ACLManager keeps track of the individual roles and its holders, and allows a *Role Admin* to manage roles. *Role Admin* is itself a role that is managed by the DEFAULT\_ADMIN\_ROLE.

The DEFAULT\_ADMIN\_ROLE is held by the [ACL\_ADMIN](#acl_admin), and should be initialized in the [PoolAddressesProvider](/developers/smart-contracts/pool-addresses-provider) beforehand.

### Roles

Below we outline the responsibilities/powers of the roles and the specific methods that are only accessible to the holders of these roles.

The [FLASH\_BORROWER](/developers/smart-contracts/aclmanager#flash_borrower) and [BRIDGE](/developers/smart-contracts/aclmanager#bridge) roles have few direct responsibilities and can primarily access specific features of the protocol, while ADMIN roles have the power and responsibility to handle risk or configuration parameters.

#### FLASH\_BORROWER

Holders of this role will have the premium on flash loans waived (this does not include the simple flash loan).

**Methods Accessible:**

[**Pool**](/developers/smart-contracts/pool):

**Methods Accessible:**

[**Pool**](/developers/smart-contracts/pool):

* [mintUnbacked()](/developers/smart-contracts/pool#mintunbacked)
* [backUnbacked()](/developers/smart-contracts/pool#backunbacked)

#### ASSET\_LISTING\_ADMIN

Holders of this role can:

* Update asset oracle sources and the fallback oracle.
* Add new assets to the Tydro market.

**Methods Accessible:**

[TydroOracles:](/developers/smart-contracts/oracles)

* [setAssetSources()](/developers/smart-contracts/oracles#setassetsources)
* [setFallbackOracle()](/developers/smart-contracts/oracles#setfallbackoracle)

[**PoolConfigurator**](/developers/smart-contracts/pool-configurator):

* [initReserves()](/developers/smart-contracts/pool-configurator#initreserves)

#### RISK\_ADMIN

Holders of this role can:

* Update the grace period of Oracle Sentinels.
* Update reserve parameters such as reserve factor, caps, E-Mode category, borrowing enabled, freeze/unfreeze, LTV, liquidation threshold, liquidation bonus (cannot pause/unpause or activate/deactivate a reserve).
* Create new and update existing E-Mode categories (not category 0).
* Update unbacked mint cap and liquidation protocol fee.

**Methods Accessible:**

[**PoolConfigurator**](/developers/smart-contracts/pool-configurator):

* [setReserveBorrowing()](/developers/smart-contracts/pool-configurator#setreserveborrowing)
* [configureReserveAsCollateral()](/developers/smart-contracts/pool-configurator#configurereserveascollateral)
* [setReserveFreeze()](/developers/smart-contracts/pool-configurator#setreservefreeze)
* [setBorrowableInIsolation()](/developers/smart-contracts/pool-configurator#setborrowableinisolation)
* [setReserveFactor()](/developers/smart-contracts/pool-configurator#setreservefactor)
* [setDebtCeiling()](/developers/smart-contracts/pool-configurator#setdebtceiling)
* [setSiloedBorrowing()](/developers/smart-contracts/pool-configurator#setsiloedborrowing)
* [setBorrowCap()](/developers/smart-contracts/pool-configurator#setborrowcap)
* [setSupplyCap()](/developers/smart-contracts/pool-configurator#setsupplycap)
* [setLiquidationProtocolFee()](/developers/smart-contracts/pool-configurator#setliquidationprotocolfee)
* [setEModeCategory()](/developers/smart-contracts/pool-configurator#setemodecategory)
* [setAssetCollateralInEMode()](/developers/smart-contracts/pool-configurator#setassetcollateralinemode)
* [setUnbackedMintCap()](/developers/smart-contracts/pool-configurator#setunbackedmintcap)
* [setReserveInterestRateStrategyAddress()](/developers/smart-contracts/pool-configurator#setreserveinterestratestrategyaddress)
* [setReserveInterestRateData()](/developers/smart-contracts/pool-configurator#setreserveinterestratedata)
* [disableLiquidationGracePeriod()](/developers/smart-contracts/pool-configurator#disableliquidationgraceperiod)
* [setReserveFlashLoaning()](/developers/smart-contracts/pool-configurator#setreserveflashloaning)

[**PriceOracleSentinel**](/developers/smart-contracts/oracles):

* [setGracePeriod()](/developers/smart-contracts/oracles#setgraceperiod)

#### ACL\_ADMIN

Holders of this role manage the role admins in the ACLManager. The DEFAULT\_ADMIN\_ROLE is held by the ACL\_ADMIN, and should be initialized in the PoolAddressesProvider beforehand.

**Methods Accessible:**

[**ACLManager**](/developers/smart-contracts/aclmanager):

* [setRoleAdmin()](/developers/smart-contracts/aclmanager#setroleadmin)
* [addPoolAdmin()](/developers/smart-contracts/aclmanager#addpooladmin)
* [removePoolAdmin()](/developers/smart-contracts/aclmanager#removepooladmin)
* [addEmergencyAdmin()](/developers/smart-contracts/aclmanager#addemergencyadmin)
* [removeEmergencyAdmin()](/developers/smart-contracts/aclmanager#removeemergencyadmin)
* [addRiskAdmin()](/developers/smart-contracts/aclmanager#addriskadmin)
* [removeRiskAdmin()](/developers/smart-contracts/aclmanager#removeriskadmin)
* [addFlashBorrower()](/developers/smart-contracts/aclmanager#addflashborrower)
* [removeFlashBorrower()](/developers/smart-contracts/aclmanager#removeflashborrower)
* [addBridge()](/developers/smart-contracts/aclmanager#addbridge)
* [removeBridge()](/developers/smart-contracts/aclmanager#removebridge)
* [addAssetListingAdmin()](/developers/smart-contracts/aclmanager#addassetlistingadmin)
* [removeAssetListingAdmin()](/developers/smart-contracts/aclmanager#removeassetlistingadmin)

#### EMERGENCY\_ADMIN

Holders of this role can pause and unpause the pool or an individual reserve.

**Methods Accessible:**

[**PoolConfigurator**](/developers/smart-contracts/pool-configurator):

* [setReservePause()](/developers/smart-contracts/pool-configurator#setreservepause)
* [setPoolPause()](/developers/smart-contracts/pool-configurator#setpoolpause)
* [setReserveActive()](/developers/smart-contracts/pool-configurator#setreserveactive)
* [setReserveFreeze()](/developers/smart-contracts/pool-configurator#setreservefreeze)

#### POOL\_ADMIN

Holders of this role can update token implementations, drop, (un)pause and (de)activate reserves, update premiums along with everything the [ASSET\_LISTING\_ADMIN](/developers/smart-contracts/aclmanager#asset_listing_admin) and [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) can do.

The [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role is governed by the Guardians multisig.

**Methods Accessible:**

All methods accessible to ASSET\_LISTING\_ADMIN.

All methods accessible to RISK\_ADMIN.

[**AToken**](/developers/smart-contracts/tokenization):

* [rescueTokens()](/developers/smart-contracts/tokenization#rescuetokens)

[**Pool**](/developers/smart-contracts/pool):

* [rescueTokens()](/developers/smart-contracts/pool#rescuetokens)

[**PoolConfigurator**](/developers/smart-contracts/pool-configurator):

* [dropReserve()](/developers/smart-contracts/pool-configurator#dropreserve)
* [updateAToken()](/developers/smart-contracts/pool-configurator#updateatoken)
* [updateVariableDebtToken()](/developers/smart-contracts/pool-configurator#updatevariabledebttoken)
* [setReserveActive()](/developers/smart-contracts/pool-configurator#setreserveactive)
* [updateBridgeProtocolFee()](/developers/smart-contracts/pool-configurator#updatebridgeprotocolfee)
* [updateFlashloanPremiumTotal()](/developers/smart-contracts/pool-configurator#updateflashloanpremiumtotal)
* [updateFlashloanPremiumToProtocol()](/developers/smart-contracts/pool-configurator#updateflashloanpremiumtoprotocol)
* [setAssetBorrowableInEMode()](/developers/smart-contracts/pool-configurator#setassetborrowableinemode)
* [setReserveInterestRateData()](/developers/smart-contracts/pool-configurator#setreserveinterestratedata)
* [setReserveInterestRateStrategyAddress()](/developers/smart-contracts/pool-configurator#setreserveinterestratestrategyaddress)

[**PriceOracleSentinel**](/developers/smart-contracts/oracles):

* [setSequencerOracle()](/developers/smart-contracts/oracles#setsequenceroracle)

### Write Methods

#### setRoleAdmin

```
function setRoleAdmin(bytes32 role, bytes32 adminRole) external override onlyRole(DEFAULT_ADMIN_ROLE)
```

Sets the role as admin of a specific role. By default, the adminRole for all roles is [DEFAULT\_ADMIN\_ROLE](/developers/smart-contracts/aclmanager#acl_admin).

This method can only be called by an address with [DEFAULT\_ADMIN\_ROLE](/developers/smart-contracts/aclmanager#acl_admin).

**Input Parameters:**

| Name      | Type    | Description                                                                                                                                                                   |
| --------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| role      | bytes32 | The role to be managed by the admin role - keccak256 hash of one of the following: POOL\_ADMIN, EMERGENCY\_ADMIN, RISK\_ADMIN, FLASH\_BORROWER, BRIDGE, ASSET\_LISTING\_ADMIN |
| adminRole | bytes32 | The admin role. 0x00 is reserved for the DEFAULT\_ADMIN\_ROLE                                                                                                                 |

#### addPoolAdmin

```
function addPoolAdmin(address admin) external override
```

Adds a new admin as *Pool Admin*. The address is added to the list of members with the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#acl_admin) role. Holders of this role can update token implementations, drop, (un)pause and (de)activate reserves, update premiums and do everything the [ASSET\_LISTING\_ADMIN](/developers/smart-contracts/aclmanager#asset_listing_admin) and [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) can do.

This method can only be called by the *Role Admin*, specified by Tydro, responsible for managing the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                            |
| ----- | ------- | ------------------------------------------------------ |
| admin | address | The address which will be granted the POOL\_ADMIN role |

#### removePoolAdmin

```
function removePoolAdmin(address admin) external override
```

Removes an admin as *Pool Admin*. The given address is removed from the list of members with the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role.

This method can only be called by the *Role Admin*, specified by Tydro, responsible for managing the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                                            |
| ----- | ------- | ---------------------------------------------------------------------- |
| admin | address | The address for which the POOL\_ADMIN role permissions will be removed |

#### addEmergencyAdmin

```
function addEmergencyAdmin(address admin) external override
```

Adds a new admin as an *Emergency Admin*. The address is added to the list of members with the [EMERGENCY\_ADMIN](/developers/smart-contracts/aclmanager#emergency_admin) role. Holders of this role can pause and unpause the pool or an individual reserve.

This method can only be called by the *Role Admin*, specified by Tydro, responsible for managing the [EMERGENCY\_ADMIN](/developers/smart-contracts/aclmanager#emergency_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                                 |
| ----- | ------- | ----------------------------------------------------------- |
| admin | address | The address which will be granted the EMERGENCY\_ADMIN role |

#### removeEmergencyAdmin

```
function removeEmergencyAdmin(address admin) external override
```

Removes an admin as *Emergency Admin*. The given address is removed from the list of members with the [EMERGENCY\_ADMIN](/developers/smart-contracts/aclmanager#emergency_admin) role.

This method can only be called by the *Role Admin*, specified by Tydro, responsible for managing the [EMERGENCY\_ADMIN](/developers/smart-contracts/aclmanager#emergency_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                                                 |
| ----- | ------- | --------------------------------------------------------------------------- |
| admin | address | The address for which the EMERGENCY\_ADMIN role permissions will be removed |

#### addRiskAdmin

```
function addRiskAdmin(address admin) external override
```

Adds a new admin as a *Risk Admin*. The address is added to the list of members with the [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) role. Holders of this role can update grace period of Oracle Sentinels, reserve params, unbacked mint cap, liquidation fee and eMode categories.

**Input Parameters:**

| Name  | Type    | Description                                            |
| ----- | ------- | ------------------------------------------------------ |
| admin | address | The address which will be granted the RISK\_ADMIN role |

#### removeRiskAdmin

```
function removeRiskAdmin(address admin) external override
```

Removes an admin as *Risk Admin*. The given address is removed from the list of members with the [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                                            |
| ----- | ------- | ---------------------------------------------------------------------- |
| admin | address | The address for which the RISK\_ADMIN role permissions will be removed |

#### addFlashBorrower

```
function addFlashBorrower(address borrower) external override
```

Adds a new borrower address as *Flash Borrower*. The address is added to the list of members with the [FLASH\_BORROWER](/developers/smart-contracts/aclmanager#flash_borrower) role. Holders of this role do not pay premium for flash loan (does not apply to flashLoanSimple).

**Input Parameters:**

| Name     | Type    | Description                                                |
| -------- | ------- | ---------------------------------------------------------- |
| borrower | address | The address which will be granted the FLASH\_BORROWER role |

#### removeFlashBorrower

```
function removeFlashBorrower(address borrower) external override
```

Removes an admin as *Flash Borrower*. The given borrower address is removed from the list of members with the [FLASH\_BORROWER](/developers/smart-contracts/aclmanager#flash_borrower) role.

**Input Parameters:**

| Name     | Type    | Description                                                                |
| -------- | ------- | -------------------------------------------------------------------------- |
| borrower | address | The address for which the FLASH\_BORROWER role permissions will be removed |

**Input Parameters:**

| Name   | Type    | Description                                   |
| ------ | ------- | --------------------------------------------- |
| bridge | address | The address which will be granted BRIDGE role |

#### addAssetListingAdmin

```
function addAssetListingAdmin(address admin) external override
```

Adds a new admin as *Asset Listing Admin*. The address is added to the list of members with the [ASSET\_LISTING\_ADMIN](/developers/smart-contracts/aclmanager#asset_listing_admin) role. Holder of this role can update oracles and add new assets to the Aave market.

**Input Parameters:**

| Name  | Type    | Description                                                  |
| ----- | ------- | ------------------------------------------------------------ |
| admin | address | The address which will be granted ASSET\_LISTING\_ADMIN role |

#### removeAssetListingAdmin

```
function removeAssetListingAdmin(address admin) external override
```

Removes an admin as *Asset Listing Admin*. The given address is removed from the list of members with the [ASSET\_LISTING\_ADMIN](/developers/smart-contracts/aclmanager#asset_listing_admin) role.

**Input Parameters:**

| Name  | Type    | Description                                                                  |
| ----- | ------- | ---------------------------------------------------------------------------- |
| admin | address | The address for which ASSET\_LISTING\_ADMIN role permissions will be removed |

### View Methods

#### isPoolAdmin

```
function isPoolAdmin(address admin) external view override returns (bool)
```

Returns true if the address has the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role, false otherwise.

**Input Parameters:**

| Name  | Type    | Description          |
| ----- | ------- | -------------------- |
| admin | address | The address to check |

**Return Values:**

| Type | Description                                               |
| ---- | --------------------------------------------------------- |
| bool | true if the given address is POOL\_ADMIN, false otherwise |

#### isEmergencyAdmin

```
function isEmergencyAdmin(address admin) external view override returns (bool)
```

Returns true if the address has the [EMERGENCY\_ADMIN](/developers/smart-contracts/aclmanager#emergency_admin) role, false otherwise.

**Input Parameters:**

| Name  | Type    | Description          |
| ----- | ------- | -------------------- |
| admin | address | The address to check |

**Return Values:**

| Type | Description                                                    |
| ---- | -------------------------------------------------------------- |
| bool | true if the given address is EMERGENCY\_ADMIN, false otherwise |

#### isRiskAdmin

```
function isRiskAdmin(address admin) external view override returns (bool)
```

Returns true if the address has the [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) role, false otherwise.

**Input Parameters:**

| Name  | Type    | Description          |
| ----- | ------- | -------------------- |
| admin | address | The address to check |

**Return Values:**

| Type | Description                                               |
| ---- | --------------------------------------------------------- |
| bool | true if the given address is RISK\_ADMIN, false otherwise |

#### isFlashBorrower

```
function isFlashBorrower(address borrower) external view override returns (bool)
```

Returns true if the address has the [FLASH\_BORROWER](/developers/smart-contracts/aclmanager#flash_borrower) role, false otherwise.

**Input Parameters:**

| Name     | Type    | Description          |
| -------- | ------- | -------------------- |
| borrower | address | The address to check |

**Return Values:**

| Type | Description                                                   |
| ---- | ------------------------------------------------------------- |
| bool | true if the given address is FLASH\_BORROWER, false otherwise |

#### isBridge

```
function isBridge(address bridge) external view override returns (bool)
```

Returns true if the address has [BRIDGE](/developers/smart-contracts/aclmanager#isbridge) role, false otherwise.

**Input Parameters:**

| Name   | Type    | Description          |
| ------ | ------- | -------------------- |
| bridge | address | The address to check |

**Return Values:**

| Type | Description                                          |
| ---- | ---------------------------------------------------- |
| bool | true if the given address is BRIDGE, false otherwise |

#### isAssetListingAdmin

```
function isAssetListingAdmin(address admin) external view override returns (bool)
```

Returns true if the address has the [ASSET\_LISTING\_ADMIN](/developers/smart-contracts/aclmanager#asset_listing_admin) role, false otherwise.

**Input Parameters:**

| Name  | Type    | Description          |
| ----- | ------- | -------------------- |
| admin | address | The address to check |

**Return Values:**

| Type | Description                                                         |
| ---- | ------------------------------------------------------------------- |
| bool | true if the given address is ASSET\_LISTING\_ADMIN, false otherwise |


# Oracles

Contract to get asset prices and manage price sources.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/AaveOracle.sol).

{% hint style="info" %}
This contract is owned by Tydro
{% endhint %}

### Write Methods

#### setAssetSources

```
function setAssetSources(address[] calldata assets, address[] calldata sources) external override onlyAssetListingOrPoolAdmins
```

Sets the price sources for given list of assets.

This method can only be called by a POOL\_ADMIN or ASSET\_LISTING\_ADMIN. Please look at the [ACLManager](/developers/smart-contracts/aclmanager) contract for further details on system roles.

**Input Parameters:**

| Name    | Type       | Description                                                                                |
| ------- | ---------- | ------------------------------------------------------------------------------------------ |
| assets  | address\[] | The addresses of the assets for which source is being set                                  |
| sources | address\[] | The address of the source of each asset. Length of assets and sources array should be same |

#### setFallbackOracle

```
function setFallbackOracle(address fallbackOracle) external override onlyAssetListingOrPoolAdmins
```

Sets/updates the fallbackOracle.

This method can only be called by a POOL\_ADMIN or ASSET\_LISTING\_ADMIN. Please look at the [ACLManager](/developers/smart-contracts/aclmanager) contract for further details on system roles.

**Input Parameters:**

| Name           | Type    | Description                        |
| -------------- | ------- | ---------------------------------- |
| fallbackOracle | address | The address of the fallback oracle |

### View Methods

#### getAssetPrice

```
function getAssetPrice(address asset) public view override returns (uint256)
```

Returns the price of the supported asset in [<mark style="color:blue;">BASE\_CURRENCY</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/interfaces/IPriceOracleGetter.sol) of the Tydro market in wei.

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | The address of the asset |

**Return Values:**

| Type    | Description                                                         |
| ------- | ------------------------------------------------------------------- |
| uint256 | The price of the asset in BASE\_CURRENCY of the Tydro market in wei |

#### getAssetsPrices

```
function getAssetsPrices(address[] calldata assets) external view override returns (uint256[] memory)
```

Returns a list of prices from a list of the supported assets addresses in [<mark style="color:blue;">BASE\_CURRENCY</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/interfaces/IPriceOracleGetter.sol) of the Tydro market. All prices are in wei.

**Input Parameters:**

| Name   | Type       | Description                                                   |
| ------ | ---------- | ------------------------------------------------------------- |
| assets | address\[] | The list of assets addresses for which price is being queried |

**Return Values:**

| Type       | Description                                                                 |
| ---------- | --------------------------------------------------------------------------- |
| uint256\[] | The prices of the given assets in BASE\_CURRENCY of the Tydro market in wei |

#### getSourceOfAsset

```
function getSourceOfAsset(address asset) external view override returns (address)
```

Returns the address of the price source for an asset address.

**Input Parameters:**

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| asset | address | The address of the asset |

**Return Values:**

| Type    | Description               |
| ------- | ------------------------- |
| address | The address of the source |

#### getFallbackOracle

```
function getFallbackOracle() external view returns (address)
```

Returns the address of the fallback oracle.

**Return Values:**

| Type    | Description                        |
| ------- | ---------------------------------- |
| address | The address of the fallback oracle |

## PriceOracleSentinel

The PriceOracleSentinel contract validates if the operations are allowed depending on the PriceOracle health.

This feature introduces a grace period for liquidations and disables borrowing under specific circumstances.

This feature has been specifically designed for L2s to handle eventual downtime of the sequencer (but can be extended to handle other cases, even on L1s, in the future).

Once the PriceOracle gets up after an outage or downtime, users can make their positions healthy during a grace period. The PriceOracle is considered healthy once its completely up and the grace period has passed.

The source code is available on [<mark style="color:blue;">Github</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/PriceOracleSentinel.sol).

### Write Methods

#### setSequencerOracle

```
function setSequencerOracle(address newSequencerOracle) external onlyPoolAdmin
```

Updates the address of the sequencer oracle.

This method can only be called by PoolAdmin.

This method can only be called by the *Role Admin*, responsible for managing the [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) role.

**Input Parameters:**

| Name               | Type    | Description                                       |
| ------------------ | ------- | ------------------------------------------------- |
| newSequencerOracle | address | The address of the new Sequencer Oracle to be set |

#### setGracePeriod

```
function setGracePeriod(uint256 newGracePeriod) public onlyRiskOrPoolAdmins
```

Updates the duration of the grace period.

Can only be called by PoolAdmin or RiskAdmin.

**Input Parameters:**

| Name           | Type    | Description                                 |
| -------------- | ------- | ------------------------------------------- |
| newGracePeriod | uint256 | The duration of new grace period in seconds |

### View Methods

#### isBorrowAllowed

```
function isBorrowAllowed() external view override returns (bool)
```

Returns true if the borrow operation is allowed. The operation is not allowed when PriceOracleis down or the grace period has not passed.

**Return Values:**

| Type | Description                                                                                                          |
| ---- | -------------------------------------------------------------------------------------------------------------------- |
| bool | Returns true if the borrow operation is allowed (the PriceOracle is up and grace period has passed), false otherwise |

#### isLiquidationAllowed

```
function isLiquidationAllowed() external view override returns (bool)
```

Returns true if the liquidation operation is allowed. The operation is not allowed when PriceOracle is down or the grace period has not passed.

**Return Values:**

| Type | Description                                                                                                               |
| ---- | ------------------------------------------------------------------------------------------------------------------------- |
| bool | Returns true if the liquidation operation is allowed (the PriceOracle is up and grace period has passed), false otherwise |

#### getSequencerOracle

```
function getSequencerOracle() external view returns (address)
```

Returns the SequencerOracle.

**Return Values:**

| Type    | Description                                  |
| ------- | -------------------------------------------- |
| address | The address of the sequencer oracle contract |

#### getGracePeriod

```
function getGracePeriod() external view returns (uint256)
```

Returns the grace period.

**Return Values:**

| Type    | Description                                 |
| ------- | ------------------------------------------- |
| uint256 | The duration of the grace period in seconds |


# Pool Addresses Provider

The PoolAddressesProvider is the central registry of addresses for Tydro. It stores the addresses of all core modules and permissioned roles within a specific market. The PoolAddressesProvider also works as the admin of proxy contracts and can update their implementations when needed. For example:

* Updating the address of the [ACLManager](/developers/smart-contracts/aclmanager)
* Updating the implementation of the [Pool](/developers/smart-contracts/pool)

This contract defines the initial holder of the  [DEFAULT\_ADMIN\_ROLE](/developers/smart-contracts/aclmanager#acl_admin), which is immutable once set.

When interacting with the Pool, it is recommended to always fetch the address directly from the PoolAddressesProvider to ensure the correct implementation is used.

The source code is available on Aave's [<mark style="color:blue;">GitHub</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/configuration/PoolAddressesProvider.sol).

### Write Methods

#### setMarketId

```
function setMarketId(string memory newMarketId) external override onlyOwner
```

Updates the identifier of the Aave market by associating an id with a specific PoolAddressesProvider. This can be used to create an on-chain registry of pool addresses providers to identify and validate multiple Aave markets.

**Input Parameters:**

| Name        | Type   | Description              |
| ----------- | ------ | ------------------------ |
| newMarketId | string | The new id of the market |

#### setAddress

```
function setAddress(bytes32 id, address newAddress) external override onlyOwner
```

Sets the address of the protocol contract stored at the given id, replacing the address saved in the addresses map.

For example, utils.keccak256(utils.toUtf8Bytes("INCENTIVES\_CONTROLLER")), is set to the address of INCENTIVES\_CONTROLLER.

Use this function carefully, as it will do a hard replacement of the current address in the addresses map.

**Input Parameters:**

| Name       | Type    | Description                                              |
| ---------- | ------- | -------------------------------------------------------- |
| id         | bytes32 | keccak256 hash of UTF8Bytes string representing contract |
| newAddress | address | The new address to be set corresponding to the id        |

#### setAddressAsProxy

```
function setAddressAsProxy(bytes32 id, address newImplementationAddress) external override onlyOwner
```

Updates the implementation address of a proxy contract with a specified id.

If there is no proxy registered, it will instantiate one and set the implementation as the newImplementationAddress.

Use this function carefully, only for ids that do not have an explicit setter function in order to avoid unexpected consequences.

**Input Parameters:**

| Name                     | Type    | Description                                                           |
| ------------------------ | ------- | --------------------------------------------------------------------- |
| id                       | bytes32 | The id of the proxy contract                                          |
| newImplementationAddress | address | The address of new implementation contract corresponding to the proxy |

#### setPoolImpl

```
function setPoolImpl(address newPoolImpl) external override onlyOwner
```

Updates the implementation of the [Pool](/developers/smart-contracts/pool) contract, or creates a proxy.

**Input Parameters:**

| Name        | Type    | Description                                     |
| ----------- | ------- | ----------------------------------------------- |
| newPoolImpl | address | The address of new Pool implementation contract |

#### setPoolConfiguratorImpl

```
function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external override onlyOwner
```

Updates the implementation of the [PoolConfigurator](/developers/smart-contracts/pool-configurator) contract, or creates a proxy.

**Input Parameters:**

| Name                    | Type    | Description                                                 |
| ----------------------- | ------- | ----------------------------------------------------------- |
| newPoolConfiguratorImpl | address | The address of new PoolConfigurator implementation contract |

#### setPriceOracle

```
function setPriceOracle(address newPriceOracle) external override onlyOwner
```

Updates the address of the price oracle.

**Input Parameters:**

| Name           | Type    | Description                     |
| -------------- | ------- | ------------------------------- |
| newPriceOracle | address | The address of new price oracle |

#### setACLManager

```
function setACLManager(address newAclManager) external override onlyOwner
```

Updates the address of the Access Control List Manager.

**Input Parameters:**

| Name          | Type    | Description                       |
| ------------- | ------- | --------------------------------- |
| newAclManager | address | The address of the new ACLManager |

#### setACLAdmin

```
function setACLAdmin(address newAclAdmin) external override onlyOwner
```

Updates the address of the Access Control List Admin.

**Input Parameters:**

| Name        | Type    | Description                 |
| ----------- | ------- | --------------------------- |
| newAclAdmin | address | The address of new ACLAdmin |

#### setPriceOracleSentinel

```
function setPriceOracleSentinel(address newPriceOracleSentinel) external override onlyOwner
```

Updates the address of the price oracle sentinel.

**Input Parameters:**

| Name                   | Type    | Description                            |
| ---------------------- | ------- | -------------------------------------- |
| newPriceOracleSentinel | address | The address of new PriceOracleSentinel |

#### setPoolDataProvider

```
function setPoolDataProvider(address newDataProvider) external override onlyOwner
```

Updates the address of the data provider.

**Input Parameters:**

| Name            | Type    | Description                     |
| --------------- | ------- | ------------------------------- |
| newDataProvider | address | The address of new DataProvider |

### View Methods

#### getMarketId

```
function getMarketId() external view override returns (string memory)
```

Returns the market id of the associated Tydro market.

**Return Values:**

| Type   | Description                              |
| ------ | ---------------------------------------- |
| string | A string representation of the market id |

#### getAddress

```
function getAddress(bytes32 id) public view override returns (address)
```

Returns the address of protocol contract stored at the given id. The returned address might be an EOA or a contract, which may be proxied. It will return ZERO if there is no registered address with the given id.

**Input Parameters:**

| Name | Type    | Description                                                 |
| ---- | ------- | ----------------------------------------------------------- |
| id   | bytes32 | The id. For example, the Protocol Data Provider uses id 0x1 |

**Return Values:**

| Type    | Description                               |
| ------- | ----------------------------------------- |
| address | The address associated with the id passed |

**Example:**

```
// Get address of incentive controllerimport { utils } from "@ethers/lib/utils";
const id = utils.keccak256(utils.toUtf8Bytes("INCENTIVES_CONTROLLER"));const address = poolAddressProvider.getAddress(id);
```

#### getPool

```
function getPool() external view override returns (address)
```

Returns the address of the latest Pool proxy contract.

**Return Values:**

| Type    | Description                              |
| ------- | ---------------------------------------- |
| address | The address of the associated Pool proxy |

#### getPoolConfigurator

```
function getPoolConfigurator() external view override returns (address)
```

Returns the address of the PoolConfigurator proxy. Used for configuration methods, like init reserves or update token implementation etc, of the market.

**Return Values:**

| Type    | Description                        |
| ------- | ---------------------------------- |
| address | The PoolConfigurator proxy address |

#### getPriceOracle

```
function getPriceOracle() external view override returns (address)
```

Returns the address of the Price Oracle used by the market.

**Return Values:**

| Type    | Description                                                   |
| ------- | ------------------------------------------------------------- |
| address | The address of the price oracle used by the associated market |

#### getACLManager

```
function getACLManager() external view override returns (address)
```

Returns the address of the Access Control List Manager (ACLManager) that manages the system role of the market.

**Return Values:**

| Type    | Description                                                                             |
| ------- | --------------------------------------------------------------------------------------- |
| address | The address of the ACLManger contract managing the system role of the associated market |

#### getACLAdmin

```
function getACLAdmin() external view override returns (address)
```

Returns the address of the Access Control List Admin (ACLAdmin) of the market which holds the DEFAULT\_ADMIN\_ROLE in ACLManager.

**Return Values:**

| Type    | Description                                                           |
| ------- | --------------------------------------------------------------------- |
| address | The address of the Access Control List admin of the associated market |

#### getPriceOracleSentinel

```
function getPriceOracleSentinel() external view override returns (address)
```

Returns the address of the price oracle sentinel.

**Return Values:**

<table data-header-hidden><thead><tr><th></th><th></th><th data-hidden></th></tr></thead><tbody><tr><td>Type</td><td>Description</td><td></td></tr><tr><td>address</td><td>The address of the PriceOracleSentinel of the associated market</td><td></td></tr></tbody></table>

#### getPoolDataProvider

```
function getPoolDataProvider() external view override returns (address)
```

Returns the address of latest pool data provider.

**Return Values:**

| Type    | Description                                                    |
| ------- | -------------------------------------------------------------- |
| address | The address of the pool data provider of the associated market |


# Pool Configurator

The PoolConfigurator contract contains the configuration methods for Tydro. These methods control how reserves and markets are set up and maintained.

The write methods exposed by PoolConfigurator are restricted to specific permissioned roles, which are managed by the [ACLManager](/developers/smart-contracts/aclmanager)

The source code is available on [Aave's Github](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/PoolConfigurator.sol)

### Write Methods

### Only Asset Listing Or Pool Admins Methods

#### initReserves

```
function initReserves(ConfiguratorInputTypes.InitReserveInput[] calldata input) external override onlyAssetListingOrPoolAdmins
```

Initialzes multiple reserves using the array of initialization parameters as input.

**Input Parameters:**

| Name  | Type                                       | Description                            |
| ----- | ------------------------------------------ | -------------------------------------- |
| input | ConfiguratorInputTypes.InitReserveInput\[] | The array of initialization parameters |

The [<mark style="color:blue;">ConfiguratorInputTypes.InitReserveInput\[\]</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/types/ConfiguratorInputTypes.sol) struct is composed of the following fields:

| Name                        | Type    | Description                                                         |
| --------------------------- | ------- | ------------------------------------------------------------------- |
| aTokenImpl                  | address | The address of the aToken contract implementation                   |
| variableDebtTokenImpl       | address | The address of the variable debt token contract                     |
| useVirtualBalance           | bool    | true if reserve is utilising virtual balance accounting             |
| interestRateStrategyAddress | address | The address of the interest rate strategy contract for this reserve |
| underlyingAsset             | address | The address of the underlying asset                                 |
| treasury                    | address | The address of the treasury                                         |
| incentivesController        | address | The address of the incentives controller for this aToken            |
| aTokenName                  | string  | The name of the aToken                                              |
| aTokenSymbol                | string  | The symbol of the aToken                                            |
| variableDebtTokenName       | string  | The name of the variable debt token                                 |
| variableDebtTokenSymbol     | string  | The symbol of the variable debt token                               |
| params                      | bytes   | A set of encoded parameters for additional initialization           |
| interestRateData            | bytes   | Encoded interest rate strategy data                                 |

### Only Emergency Admin Methods

#### setPoolPause

```
function setPoolPause(bool paused) external override onlyEmergencyOrPoolAdmin
```

Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions are suspended.

**Input Parameters:**

| Name   | Type | Description                                              |
| ------ | ---- | -------------------------------------------------------- |
| paused | bool | true if the protocol needs to be paused, otherwise false |

### Only Emergency Or Pool Admin Methods

#### setReservePause

```
function setReservePause(address asset, bool paused) public override onlyEmergencyOrPoolAdmin
```

Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, liquidate, atoken transfers).

**Input Parameters:**

| Name   | Type    | Description                                                 |
| ------ | ------- | ----------------------------------------------------------- |
| asset  | address | The address of the underlying asset of the reserve          |
| paused | bool    | true if pausing the reserve, false if unpausing the reserve |

### Only Pool Admin Methods

#### dropReserve

```
function dropReserve(address asset) external override onlyPoolAdmin
```

Drops a reserve entirely.

**Input Parameters:**

| Name  | Type    | Description                        |
| ----- | ------- | ---------------------------------- |
| asset | address | The address of the reserve to drop |

#### updateAToken

```
function updateAToken(ConfiguratorInputTypes.UpdateATokenInput calldata input) external override onlyPoolAdmin
```

Updates the aToken implementation for the reserve. Takes the aToken update parameters as input.

**Input Parameters:**

| Name  | Type                                     | Description                  |
| ----- | ---------------------------------------- | ---------------------------- |
| input | ConfiguratorInputTypes.UpdateATokenInput | The aToken update parameters |

The [ConfiguratorInputTypes.UpdateATokenInput](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/types/ConfiguratorInputTypes.sol) struct is composed of the following fields:

| Name                 | Type    | Description                                               |
| -------------------- | ------- | --------------------------------------------------------- |
| asset                | address | The address of the underlying asset of the reserve        |
| treasury             | address | The address of the treasury                               |
| incentivesController | address | The address of the incentives controller for this aToken  |
| name                 | string  | The name of the aToken                                    |
| symbol               | string  | The symbol of the aToken                                  |
| implementation       | address | The new aToken implementation                             |
| params               | bytes   | A set of encoded parameters for additional initialization |

#### updateVariableDebtToken

```
function updateVariableDebtToken(ConfiguratorInputTypes.UpdateDebtTokenInput calldata input) external override onlyPoolAdmin
```

**Input Parameters:**

| Name  | Type                                        | Description                             |
| ----- | ------------------------------------------- | --------------------------------------- |
| input | ConfiguratorInputTypes.UpdateDebtTokenInput | The variableDebtToken update parameters |

The [<mark style="color:blue;">ConfiguratorInputTypes.UpdateDebtTokenInput</mark>](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/types/ConfiguratorInputTypes.sol) struct is composed of the following fields:

| Name                 | Type    | Description                                                         |
| -------------------- | ------- | ------------------------------------------------------------------- |
| asset                | address | The address of the underlying asset of the reserve                  |
| incentivesController | address | The address of the incentives controller for this variableDebtToken |
| name                 | string  | The name of the variableDebtToken                                   |
| symbol               | string  | The symbol of the variableDebtToken                                 |
| implementation       | address | The new variableDebtToken implementation                            |
| params               | bytes   | A set of encoded parameters for additional initialization           |

#### setReserveActive

```
function setReserveActive(address asset, bool active) external override onlyPoolAdmin
```

Activate or deactivate a reserve.

**Input Parameters:**

| Name   | Type    | Description                                             |
| ------ | ------- | ------------------------------------------------------- |
| asset  | address | The address of the underlying asset of the reserve      |
| active | bool    | true if the reserve needs to be active, false otherwise |

#### updateBridgeProtocolFee

```
function updateBridgeProtocolFee(uint256 newBridgeProtocolFee) external override onlyPoolAdmin
```

Updates the bridge fee collected by the protocol reserves.

**Input Parameters:**

| Name                 | Type    | Description                                                         |
| -------------------- | ------- | ------------------------------------------------------------------- |
| newBridgeProtocolFee | uint256 | The part of the fee sent to the protocol treasury, expressed in bps |

#### setReserveFlashLoaning

```
function setReserveFlashLoaning(address asset, bool enabled) external override onlyRiskOrPoolAdmins
```

Enables or disables flash loans for a reserve.

**Input Parameters:**

| Name    | Type    | Description                      |
| ------- | ------- | -------------------------------- |
| asset   | address | Address of the reserve asset     |
| enabled | bool    | true to enable, false to disable |

#### updateFlashloanPremiumTotal

```
function updateFlashloanPremiumTotal(uint128 newFlashloanPremiumTotal) external override onlyPoolAdmin
```

Updates the total flash loan premium. The premium is calculated on the total amount borrowed, and is expressed in bps.

The total flash loan premium consists of two parts:

* A part is sent to aToken holders as extra balance, and
* A part is collected by the protocol reserves.

**Input Parameters:**

| Name                     | Type    | Description                 |
| ------------------------ | ------- | --------------------------- |
| newFlashloanPremiumTotal | uint128 | The total flashloan premium |

#### updateFlashloanPremiumToProtocol

```
function updateFlashloanPremiumToProtocol(uint128 newFlashloanPremiumToProtocol) external override onlyPoolAdmin
```

Updates the flash loan premium collected by protocol reserves. The premium to protocol is calculated on the total flashloan premium, and is expressed in bps.

**Input Parameters:**

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| newFlashloanPremiumToProtocol | uint128 | The part of the flashloan premium sent to the protocol treasury |

### Only Risk Or Pool Admins Methods

#### setReserveBorrowing

```
function setReserveBorrowing(address asset, bool enabled) external override onlyRiskOrPoolAdmins
```

**Input Parameters:**

| Name    | Type    | Description                                            |
| ------- | ------- | ------------------------------------------------------ |
| asset   | address | The address of the underlying asset of the reserve     |
| enabled | bool    | true if borrowing needs to be enabled, false otherwise |

#### configureReserveAsCollateral

```
function configureReserveAsCollateral(
    address asset,
    uint256 ltv,
    uint256 liquidationThreshold,
    uint256 liquidationBonus
) external override onlyRiskOrPoolAdmins
```

Configures the reserve collateralization parameters. All the values are expressed in bps. A value of 10000 results in 100.00%. The liquidationBonus is always above 100%. A value of 105% means the liquidator will receive a 5% bonus.

**Input Parameters:**

| Name                 | Type    | Description                                                                                        |
| -------------------- | ------- | -------------------------------------------------------------------------------------------------- |
| asset                | address | The address of the underlying asset of the reserve                                                 |
| ltv                  | uint256 | The loan to value of the asset when used as collateral                                             |
| liquidationThreshold | uint256 | The threshold at which loans using this asset as collateral will be considered undercollateralized |
| liquidationBonus     | uint256 | The bonus liquidators receive to liquidate this asset                                              |

#### setReserveFreeze

```
function setReserveFreeze(address asset, bool freeze) external override onlyRiskOrPoolAdmins
```

Freeze or unfreeze a reserve. A frozen reserve doesn't allow any new supply or borrow but allows repayments, liquidations, rate rebalances and withdrawals.

**Input Parameters:**

| Name   | Type    | Description                                             |
| ------ | ------- | ------------------------------------------------------- |
| asset  | address | The address of the underlying asset of the reserve      |
| freeze | bool    | true if the reserve needs to be frozen, false otherwise |

#### setBorrowableInIsolation

```
function setBorrowableInIsolation(address asset, bool borrowable) external override onlyRiskOrPoolAdmins
```

Sets the borrowable in isolation flag for the reserve. When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed amount will be accumulated in the isolated collateral's total debt exposure. Only assets of the same family (e.g. USD stablecoins) should be borrowable in isolation mode to keep consistency in the debt ceiling calculations.

**Input Parameters:**

| Name       | Type    | Description                                                          |
| ---------- | ------- | -------------------------------------------------------------------- |
| asset      | address | The address of the underlying asset of the reserve                   |
| borrowable | bool    | true if the asset should be borrowable in isolation, false otherwise |

#### setReserveFactor

```
function setReserveFactor(address asset, uint256 newReserveFactor) external override onlyRiskOrPoolAdmins
```

Updates the reserve factor of a reserve.

**Input Parameters:**

| Name             | Type    | Description                                        |
| ---------------- | ------- | -------------------------------------------------- |
| asset            | address | The address of the underlying asset of the reserve |
| newReserveFactor | uint256 | The new reserve factor of the reserve              |

#### setDebtCeiling

```
function setDebtCeiling(address asset, uint256 newDebtCeiling) external override onlyRiskOrPoolAdmins
```

Sets the debt ceiling for an asset.

**Input Parameters:**

| Name           | Type    | Description                                        |
| -------------- | ------- | -------------------------------------------------- |
| asset          | address | The address of the underlying asset of the reserve |
| newDebtCeiling | uint256 | The new debt ceiling                               |

#### setSiloedBorrowing

```
function setSiloedBorrowing(address asset, bool newSiloed) external override onlyRiskOrPoolAdmins
```

Sets siloed borrowing for an asset

**Input Parameters:**

| Name      | Type    | Description                                                                         |
| --------- | ------- | ----------------------------------------------------------------------------------- |
| asset     | address | The address of the underlying asset of the reserve                                  |
| newSiloed | bool    | The new siloed borrowing state - enable or disable siloed borrowing for the reserve |

#### setBorrowCap

```
function setBorrowCap(address asset, uint256 newBorrowCap) external override onlyRiskOrPoolAdmins
```

Updates the borrow cap of a reserve. Allows [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) and [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) to add/update cap on the total borrow that can be borrowed from the reserve. Once the borrow cap is reached, no more borrow positions for the given reserve asset can be initiated.

**Input Parameters:**

| Name         | Type    | Description                                                                                         |
| ------------ | ------- | --------------------------------------------------------------------------------------------------- |
| asset        | address | The address of the underlying asset of the reserve                                                  |
| newBorrowCap | uint256 | The new borrow cap of the reserve in whole tokens. A borrow cap of 0 signifies that there is no cap |

#### setSupplyCap

```
function setSupplyCap(address asset, uint256 newSupplyCap) external override onlyRiskOrPoolAdmins
```

Updates the supply cap of a reserve. Allows [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) and [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) to add/update liquidity supply cap on the reserve. Once the supply cap is reached, no more liquidity for the given reserve asset can be supplied to the pool.

**Input Parameters:**

| Name         | Type    | Description                                                                                         |
| ------------ | ------- | --------------------------------------------------------------------------------------------------- |
| asset        | address | The address of the underlying asset of the reserve                                                  |
| newSupplyCap | uint256 | The new supply cap of the reserve in whole tokens. A supply cap of 0 signifies that there is no cap |

#### disableLiquidationGracePeriod

```
function disableLiquidationGracePeriod(address asset) external override onlyEmergencyOrPoolAdmin
```

Disables the liquidation grace period for a reserve.

**Input Parameters**

| Name  | Type    | Description                  |
| ----- | ------- | ---------------------------- |
| asset | address | Address of the reserve asset |

#### setLiquidationProtocolFee

```
function setLiquidationProtocolFee(address asset, uint256 newFee) external override onlyRiskOrPoolAdmins
```

Updates the liquidation protocol fee of reserve.

**Input Parameters:**

| Name   | Type    | Description                                                       |
| ------ | ------- | ----------------------------------------------------------------- |
| asset  | address | The address of the underlying asset of the reserve                |
| newFee | uint256 | The new liquidation protocol fee of the reserve, expressed in bps |

#### setEModeCategory

```
function setEModeCategory(
    uint8 categoryId,
    uint16 ltv,
    uint16 liquidationThreshold,
    uint16 liquidationBonus,
    string calldata label
) external override onlyRiskOrPoolAdmins
```

Adds a new efficiency mode (eMode) category. Allows [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) and [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) to configure existing or add new eModeCategory

If zero is provided as oracle address, the default asset oracles will be used to compute the overall debt and overcollateralization of the users using this category. The new ltv and liquidation threshold must be greater than the base ltvs and liquidation thresholds of all assets within the eMode category.

**Input Parameters:**

| Name                 | Type   | Description                                                                                                                   |
| -------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| categoryId           | uint8  | The id of the category to be configured. categoryId ≠ 0. NOTE: category 0 is reserved for the default category i.e. non-eMode |
| ltv                  | uint16 | The loan to value for the associated eMode category. It must be less than or equal to the liquidationThreshold                |
| liquidationThreshold | uint16 | The liquidation threshold associated with the category                                                                        |
| liquidationBonus     | uint16 | The liquidation bonus associated with the category                                                                            |
| label                | string | A custom label identifying the category                                                                                       |

#### setAssetCollateralInEMode

```
function setAssetCollateralInEMode(address asset, uint8 categoryId, bool allowed) external override onlyRiskOrPoolAdmins
```

Assign collateral status to an asset for a particular efficiency mode (eMode) category. Allows [RISK\_ADMIN](/developers/smart-contracts/aclmanager#risk_admin) and [POOL\_ADMIN](/developers/smart-contracts/aclmanager#pool_admin) to configure eModeCategory of an asset.

**Input Parameters:**

| Name       | Type    | Description                                                     |
| ---------- | ------- | --------------------------------------------------------------- |
| asset      | address | The address of the underlying asset of the reserve              |
| categoryId | uint8   | eMode category id to set asset collateral status for            |
| allowed    | bool    | true if asset is enabled as collateral in designated categoryId |

#### setAssetBorrowableInEMode

```
function setAssetBorrowableInEMode(address asset, uint8 categoryId, bool borrowable) external override onlyRiskOrPoolAdmins
```

Configures if an asset can be borrowed in a specific eMode category.

**Input Parameters:**

| Name       | Type    | Description                      |
| ---------- | ------- | -------------------------------- |
| asset      | address | Address of the reserve asset     |
| categoryId | uint8   | eMode category ID                |
| borrowable | bool    | true to enable, false to disable |

#### setUnbackedMintCap

```
function setUnbackedMintCap(address asset, uint256 newUnbackedMintCap) external override onlyRiskOrPoolAdmins
```

Updates the unbacked mint cap of reserve.

**Input Parameters:**

| Name               | Type    | Description                                        |
| ------------------ | ------- | -------------------------------------------------- |
| asset              | address | The address of the underlying asset of the reserve |
| newUnbackedMintCap | uint256 | The new unbacked mint cap of the reserve           |

#### setReserveInterestRateData

```
function setReserveInterestRateData(address asset, bytes calldata rateData) external onlyRiskOrPoolAdmins
```

Sets custom interest rate parameters for a reserve.

**Input Parameters:**

| Name     | Type    | Description                      |
| -------- | ------- | -------------------------------- |
| asset    | address | Address of the reserve asset     |
| rateData | bytes   | Encodes rate strategy parameters |

#### setReserveInterestRateStrategyAddress

```
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress, bytes calldata rateData) external override onlyRiskOrPoolAdmins
```

Sets the interest rate strategy of a reserve.

**Input Parameters:**

| Name                | Type    | Description                                        |
| ------------------- | ------- | -------------------------------------------------- |
| asset               | address | The address of the underlying asset of the reserve |
| rateStrategyAddress | address | The address of the interest strategy contract      |
| rateData            | bytes   | Encoded interst rate strategy data                 |

### Pure Methods

#### getRevision

```
function getRevision() internal pure virtual override returns (uint256)
```

Returns the revision number of the contract. Needs to be defined in the inherited class as a constant.

Returns 0x1.

**Return Values:**

| Type    | Description         |
| ------- | ------------------- |
| uint256 | The revision number |


# Vaults

## ATokenVault

The ATokenVault contract is an ERC-4626 compliant yield-bearing vault designed for Aave V3. It allows users to supply and withdraw ERC-20 tokens supported by Aave V3, automatically managing asset supply and withdrawal within the Aave Protocol. This vault also enables managers to collect a fee on the yield generated.

The smart contract source code is available on <mark style="color:blue;">GitHub</mark>.

### Write Methods

#### initialize

```
function initialize(    address owner,    uint256 initialFee,    string memory shareName,    string memory shareSymbol,    uint256 initialLockDeposit) external initializer
```

Initializes the vault, setting its initial parameters and initializing inherited contracts. An initial non-zero deposit (in underlying tokens) is required to prevent frontrunning attacks. It does not initialize the OwnableUpgradeable contract to avoid setting the proxy admin as the owner.

**Input Parameters:**

| Name               | Type    | Description                                                                                                                                    |   |
| ------------------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | - |
| owner              | address | The address to set as the owner of the vault.                                                                                                  |   |
| initialFee         | uint256 | The initial fee to set, expressed in wad, where (1 \times 10^18) is 100%.                                                                      |   |
| shareName          | string  | The name to set for the vault's shares.                                                                                                        |   |
| shareSymbol        | string  | The symbol to set for the vault's shares.                                                                                                      |   |
| initialLockDeposit | uint256 | The initial amount of underlying assets to deposit. This must be a non-zero, non-trivial amount, depending on the underlying asset's decimals. |   |

#### deposit

```
function deposit(uint256 assets, address receiver) public override returns (uint256)
```

Deposits assets (underlying tokens) into the vault and mints a corresponding amount of vault shares to the receiver.

**Input Parameters:**

| Name     | Type    | Description                                       |   |
| -------- | ------- | ------------------------------------------------- | - |
| assets   | uint256 | The amount of underlying assets to deposit.       |   |
| receiver | address | The address to which vault shares will be minted. |   |

**Return Values:**

| Type    | Description                        |   |
| ------- | ---------------------------------- | - |
| uint256 | The amount of vault shares minted. |   |

#### depositATokens

```
function depositATokens(uint256 assets, address receiver) public override returns (uint256)
```

Deposits assets (aTokens) directly into the vault and mints a corresponding amount of vault shares to the receiver.

**Input Parameters:**

| Name     | Type    | Description                                       |   |
| -------- | ------- | ------------------------------------------------- | - |
| assets   | uint256 | The amount of aTokens to deposit.                 |   |
| receiver | address | The address to which vault shares will be minted. |   |

**Return Values:**

| Type    | Description                        |   |
| ------- | ---------------------------------- | - |
| uint256 | The amount of vault shares minted. |   |

#### depositWithSig

```
function depositWithSig(    uint256 assets,    address receiver,    address depositor,    EIP712Signature calldata sig) public override returns (uint256)
```

Deposits assets (underlying tokens) into the vault on behalf of a depositor, authenticated by an EIP-712 signature. Vault shares are minted to the receiver.

**Input Parameters:**

| Name      | Type            | Description                                                                                    |   |
| --------- | --------------- | ---------------------------------------------------------------------------------------------- | - |
| assets    | uint256         | The amount of underlying assets to deposit.                                                    |   |
| receiver  | address         | The address to which vault shares will be minted.                                              |   |
| depositor | address         | The address of the actual depositor, whose signature is provided.                              |   |
| sig       | EIP712Signature | The EIP-712 signature for the deposit transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                        |   |
| ------- | ---------------------------------- | - |
| uint256 | The amount of vault shares minted. |   |

#### depositATokensWithSig

```
function depositATokensWithSig(    uint256 assets,    address receiver,    address depositor,    EIP712Signature calldata sig) public override returns (uint256)
```

Deposits assets (aTokens) directly into the vault on behalf of a depositor, authenticated by an EIP-712 signature. Vault shares are minted to the receiver.

**Input Parameters:**

| Name      | Type            | Description                                                                                    |   |
| --------- | --------------- | ---------------------------------------------------------------------------------------------- | - |
| assets    | uint256         | The amount of aTokens to deposit.                                                              |   |
| receiver  | address         | The address to which vault shares will be minted.                                              |   |
| depositor | address         | The address of the actual depositor, whose signature is provided.                              |   |
| sig       | EIP712Signature | The EIP-712 signature for the deposit transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                        |   |
| ------- | ---------------------------------- | - |
| uint256 | The amount of vault shares minted. |   |

#### mint

```
function mint(uint256 shares, address receiver) public override returns (uint256)
```

Mints an exact amount of shares (vault shares) to the receiver by depositing the calculated amount of underlying assets.

**Input Parameters:**

| Name     | Type    | Description                                       |   |
| -------- | ------- | ------------------------------------------------- | - |
| shares   | uint256 | The exact amount of vault shares to mint.         |   |
| receiver | address | The address to which vault shares will be minted. |   |

**Return Values:**

| Type    | Description                                                            |   |
| ------- | ---------------------------------------------------------------------- | - |
| uint256 | The amount of underlying assets required to mint the specified shares. |   |

#### mintWithATokens

```
function mintWithATokens(uint256 shares, address receiver) public override returns (uint256)
```

Mints an exact amount of shares (vault shares) to the receiver by depositing the calculated amount of aTokens.

**Input Parameters:**

| Name     | Type    | Description                                       |   |
| -------- | ------- | ------------------------------------------------- | - |
| shares   | uint256 | The exact amount of vault shares to mint.         |   |
| receiver | address | The address to which vault shares will be minted. |   |

**Return Values:**

| Type    | Description                                                  |   |
| ------- | ------------------------------------------------------------ | - |
| uint256 | The amount of aTokens required to mint the specified shares. |   |

#### mintWithSig

```
function mintWithSig(    uint256 shares,    address receiver,    address depositor,    EIP712Signature calldata sig) public override returns (uint256)
```

Mints an exact amount of shares (vault shares) to the receiver on behalf of a depositor, authenticated by an EIP-712 signature, by depositing the calculated amount of underlying assets.

**Input Parameters:**

| Name      | Type            | Description                                                                                 |   |
| --------- | --------------- | ------------------------------------------------------------------------------------------- | - |
| shares    | uint256         | The exact amount of vault shares to mint.                                                   |   |
| receiver  | address         | The address to which vault shares will be minted.                                           |   |
| depositor | address         | The address of the actual depositor, whose signature is provided.                           |   |
| sig       | EIP712Signature | The EIP-712 signature for the mint transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                                            |   |
| ------- | ---------------------------------------------------------------------- | - |
| uint256 | The amount of underlying assets required to mint the specified shares. |   |

#### mintWithATokensWithSig

```
function mintWithATokensWithSig(    uint256 shares,    address receiver,    address depositor,    EIP712Signature calldata sig) public override returns (uint256)
```

Mints an exact amount of shares (vault shares) to the receiver on behalf of a depositor, authenticated by an EIP-712 signature, by depositing the calculated amount of aTokens.

**Input Parameters:**

| Name      | Type            | Description                                                                                 |   |
| --------- | --------------- | ------------------------------------------------------------------------------------------- | - |
| shares    | uint256         | The exact amount of vault shares to mint.                                                   |   |
| receiver  | address         | The address to which vault shares will be minted.                                           |   |
| depositor | address         | The address of the actual depositor, whose signature is provided.                           |   |
| sig       | EIP712Signature | The EIP-712 signature for the mint transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                                  |   |
| ------- | ------------------------------------------------------------ | - |
| uint256 | The amount of aTokens required to mint the specified shares. |   |

#### withdraw

```
function withdraw(    uint256 assets,    address receiver,    address owner) public override returns (uint256)
```

Withdraws assets (underlying tokens) from the vault and sends them to the receiver. The corresponding vault shares are burned from the owner.

**Input Parameters:**

| Name     | Type    | Description                                              |   |
| -------- | ------- | -------------------------------------------------------- | - |
| assets   | uint256 | The amount of underlying assets to withdraw.             |   |
| receiver | address | The address to which the underlying assets will be sent. |   |
| owner    | address | The address from which vault shares will be burned.      |   |

**Return Values:**

| Type    | Description                                           |   |
| ------- | ----------------------------------------------------- | - |
| uint256 | The amount of vault shares burned for the withdrawal. |   |

#### withdrawATokens

```
function withdrawATokens(uint256 assets, address receiver, address owner) public override returns (uint256)
```

Withdraws assets (aTokens) directly from the vault and sends them to the receiver. The corresponding vault shares are burned from the owner.

**Input Parameters:**

| Name     | Type    | Description                                         |   |
| -------- | ------- | --------------------------------------------------- | - |
| assets   | uint256 | The amount of aTokens to withdraw.                  |   |
| receiver | address | The address to which the aTokens will be sent.      |   |
| owner    | address | The address from which vault shares will be burned. |   |

**Return Values:**

| Type    | Description                                           |   |
| ------- | ----------------------------------------------------- | - |
| uint256 | The amount of vault shares burned for the withdrawal. |   |

#### withdrawWithSig

```
function withdrawWithSig(    uint256 assets,    address receiver,    address owner,    EIP712Signature calldata sig) public override returns (uint256)
```

Withdraws assets (underlying tokens) from the vault and sends them to the receiver. The corresponding vault shares are burned from the owner, authenticated by an EIP-712 signature.

**Input Parameters:**

| Name     | Type            | Description                                                                                       |   |
| -------- | --------------- | ------------------------------------------------------------------------------------------------- | - |
| assets   | uint256         | The amount of underlying assets to withdraw.                                                      |   |
| receiver | address         | The address to which the underlying assets will be sent.                                          |   |
| owner    | address         | The address from which vault shares will be burned. This address must be the signatory.           |   |
| sig      | EIP712Signature | The EIP-712 signature for the withdrawal transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                           |   |
| ------- | ----------------------------------------------------- | - |
| uint256 | The amount of vault shares burned for the withdrawal. |   |

#### withdrawATokensWithSig

```
function withdrawATokensWithSig(    uint256 assets,    address receiver,    address owner,    EIP712Signature calldata sig) public override returns (uint256)
```

Withdraws assets (aTokens) directly from the vault and sends them to the receiver. The corresponding vault shares are burned from the owner, authenticated by an EIP-712 signature.

**Input Parameters:**

| Name     | Type            | Description                                                                                       |   |
| -------- | --------------- | ------------------------------------------------------------------------------------------------- | - |
| assets   | uint256         | The amount of aTokens to withdraw.                                                                |   |
| receiver | address         | The address to which the aTokens will be sent.                                                    |   |
| owner    | address         | The address from which vault shares will be burned. This address must be the signatory.           |   |
| sig      | EIP712Signature | The EIP-712 signature for the withdrawal transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                           |   |
| ------- | ----------------------------------------------------- | - |
| uint256 | The amount of vault shares burned for the withdrawal. |   |

#### redeem

```
function redeem(    uint256 shares,    address receiver,    address owner) public override returns (uint256)
```

Redeems shares (vault shares) for the underlying assets, which are sent to the receiver. The shares are burned from the owner.

**Input Parameters:**

| Name     | Type    | Description                                              |   |
| -------- | ------- | -------------------------------------------------------- | - |
| shares   | uint256 | The amount of vault shares to redeem.                    |   |
| receiver | address | The address to which the underlying assets will be sent. |   |
| owner    | address | The address from which vault shares will be burned.      |   |

**Return Values:**

| Type    | Description                                              |   |
| ------- | -------------------------------------------------------- | - |
| uint256 | The amount of underlying assets received for the shares. |   |

#### redeemAsATokens

```
function redeemAsATokens(uint256 shares, address receiver, address owner) public override returns (uint256)
```

Redeems shares (vault shares) for aTokens, which are sent to the receiver. The shares are burned from the owner.

**Input Parameters:**

| Name     | Type    | Description                                         |   |
| -------- | ------- | --------------------------------------------------- | - |
| shares   | uint256 | The amount of vault shares to redeem.               |   |
| receiver | address | The address to which the aTokens will be sent.      |   |
| owner    | address | The address from which vault shares will be burned. |   |

**Return Values:**

| Type    | Description                                    |   |
| ------- | ---------------------------------------------- | - |
| uint256 | The amount of aTokens received for the shares. |   |

#### redeemWithSig

```
function redeemWithSig(    uint256 shares,    address receiver,    address owner,    EIP712Signature calldata sig) public override returns (uint256)
```

Redeems shares (vault shares) for the underlying assets, which are sent to the receiver. The shares are burned from the owner, authenticated by an EIP-712 signature.

**Input Parameters:**

| Name     | Type            | Description                                                                                       |   |
| -------- | --------------- | ------------------------------------------------------------------------------------------------- | - |
| shares   | uint256         | The amount of vault shares to redeem.                                                             |   |
| receiver | address         | The address to which the underlying assets will be sent.                                          |   |
| owner    | address         | The address from which vault shares will be burned. This address must be the signatory.           |   |
| sig      | EIP712Signature | The EIP-712 signature for the redemption transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                              |   |
| ------- | -------------------------------------------------------- | - |
| uint256 | The amount of underlying assets received for the shares. |   |

#### redeemWithATokensWithSig

```
function redeemWithATokensWithSig(    uint256 shares,    address receiver,    address owner,    EIP712Signature calldata sig) public override returns (uint256)
```

Redeems shares (vault shares) for aTokens, which are sent to the receiver. The shares are burned from the owner, authenticated by an EIP-712 signature.

**Input Parameters:**

| Name     | Type            | Description                                                                                       |   |
| -------- | --------------- | ------------------------------------------------------------------------------------------------- | - |
| shares   | uint256         | The amount of vault shares to redeem.                                                             |   |
| receiver | address         | The address to which the aTokens will be sent.                                                    |   |
| owner    | address         | The address from which vault shares will be burned. This address must be the signatory.           |   |
| sig      | EIP712Signature | The EIP-712 signature for the redemption transaction, including v, r, s parameters, and deadline. |   |

**Return Values:**

| Type    | Description                                    |   |
| ------- | ---------------------------------------------- | - |
| uint256 | The amount of aTokens received for the shares. |   |

#### setFee

```
function setFee(uint256 newFee) public override onlyOwner
```

Sets a new fee percentage for the vault. This function can only be called by the vault owner. Accrues current yield before updating the fee.

**Input Parameters:**

| Name   | Type    | Description                                                           |   |
| ------ | ------- | --------------------------------------------------------------------- | - |
| newFee | uint256 | The new fee to set, expressed in wad, where (1 \times 10^18) is 100%. |   |

#### withdrawFees

```
function withdrawFees(address to, uint256 amount) public override onlyOwner
```

Withdraws amount of accumulated fees (in aTokens) to the specified to address. This function can only be called by the vault owner. Accrues current yield before withdrawing fees.

**Input Parameters:**

| Name   | Type    | Description                                           |   |
| ------ | ------- | ----------------------------------------------------- | - |
| to     | address | The address to which the collected fees will be sent. |   |
| amount | uint256 | The amount of fees to withdraw.                       |   |

#### claimRewards

```
function claimRewards(address to) public override onlyOwner
```

Claims any pending rewards accumulated by the vault and sends them to the specified toaddress. This function can only be called by the vault owner.

**Input Parameters:**

| Name | Type    | Description                                            |   |
| ---- | ------- | ------------------------------------------------------ | - |
| to   | address | The address to which the claimed rewards will be sent. |   |

#### emergencyRescue

```
function emergencyRescue(    address token,    address to,    uint256 amount) public override onlyOwner
```

Allows the vault owner to rescue an arbitrary amount of an ERC-20 token that was mistakenly sent to the vault, transferring it to the to address. This function cannot be used to rescue the AToken that the vault is designed to hold.

**Input Parameters:**

| Name   | Type    | Description                                                              |   |
| ------ | ------- | ------------------------------------------------------------------------ | - |
| token  | address | The address of the ERC-20 token to rescue. Cannot be the vault's AToken. |   |
| to     | address | The address to which the rescued tokens will be sent.                    |   |
| amount | uint256 | The amount of tokens to rescue.                                          |   |

### View Methods

#### maxDeposit

```
function maxDeposit(address) public view override returns (uint256)
```

Returns the maximum amount of underlying assets that can be deposited into the vault. This is determined by the Aave protocol's supply cap and the current supplied amount.

**Input Parameters:**

| Name | Type    | Description                                         |   |
| ---- | ------- | --------------------------------------------------- | - |
| -    | address | Placeholder for receiver (not used in computation). |   |

**Return Values:**

| Type    | Description                                                    |   |
| ------- | -------------------------------------------------------------- | - |
| uint256 | The maximum amount of underlying assets that can be deposited. |   |

#### maxMint

```
function maxMint(address) public view override returns (uint256)
```

Returns the maximum amount of vault shares that can be minted. This is derived from the maximum suppliable assets converted to shares.

**Input Parameters:**

| Name | Type    | Description                                         |   |
| ---- | ------- | --------------------------------------------------- | - |
| -    | address | Placeholder for receiver (not used in computation). |   |

**Return Values:**

| Type    | Description                                            |   |
| ------- | ------------------------------------------------------ | - |
| uint256 | The maximum amount of vault shares that can be minted. |   |

#### maxWithdraw

```
function maxWithdraw(address owner) public view override returns (uint256)
```

Returns the maximum amount of underlying assets that can be withdrawn by a specific owner. This is limited by the vault's balance and Aave's available liquidity.

**Input Parameters:**

| Name  | Type    | Description                                                               |   |
| ----- | ------- | ------------------------------------------------------------------------- | - |
| owner | address | The address of the share owner whose maximum withdrawal is being queried. |   |

**Return Values:**

| Type    | Description                                                    |   |
| ------- | -------------------------------------------------------------- | - |
| uint256 | The maximum amount of underlying assets that can be withdrawn. |   |

#### maxRedeem

```
function maxRedeem(address owner) public view override returns (uint256)
```

Returns the maximum amount of vault shares that can be redeemed by a specific owner. This is limited by the vault's balance and Aave's available liquidity.

**Input Parameters:**

| Name  | Type    | Description                                                               |   |
| ----- | ------- | ------------------------------------------------------------------------- | - |
| owner | address | The address of the share owner whose maximum redemption is being queried. |   |

**Return Values:**

| Type    | Description                                              |   |
| ------- | -------------------------------------------------------- | - |
| uint256 | The maximum amount of vault shares that can be redeemed. |   |

#### previewDeposit

```
function previewDeposit(uint256 assets) public view override returns (uint256)
```

Provides a preview of the amount of vault shares that would be minted for a given assetsdeposit.

**Input Parameters:**

| Name   | Type    | Description                                             |   |
| ------ | ------- | ------------------------------------------------------- | - |
| assets | uint256 | The amount of underlying assets to preview deposit for. |   |

**Return Values:**

| Type    | Description                                        |   |
| ------- | -------------------------------------------------- | - |
| uint256 | The amount of vault shares that would be received. |   |

#### previewMint

```
function previewMint(uint256 shares) public view override returns (uint256)
```

Provides a preview of the amount of underlying assets that would be required to mint a given shares amount of vault shares.

**Input Parameters:**

| Name   | Type    | Description                                     |   |
| ------ | ------- | ----------------------------------------------- | - |
| shares | uint256 | The amount of vault shares to preview mint for. |   |

**Return Values:**

| Type    | Description                                             |   |
| ------- | ------------------------------------------------------- | - |
| uint256 | The amount of underlying assets that would be required. |   |

#### previewWithdraw

```
function previewWithdraw(uint256 assets) public view override returns (uint256)
```

Provides a preview of the amount of vault shares that would be burned for a given assetswithdrawal.

**Input Parameters:**

| Name   | Type    | Description                                                |   |
| ------ | ------- | ---------------------------------------------------------- | - |
| assets | uint256 | The amount of underlying assets to preview withdrawal for. |   |

**Return Values:**

| Type    | Description                                      |   |
| ------- | ------------------------------------------------ | - |
| uint256 | The amount of vault shares that would be burned. |   |

#### previewRedeem

```
function previewRedeem(uint256 shares) public view override returns (uint256)
```

Provides a preview of the amount of underlying assets that would be received for a given shares redemption.

**Input Parameters:**

| Name   | Type    | Description                                       |   |
| ------ | ------- | ------------------------------------------------- | - |
| shares | uint256 | The amount of vault shares to preview redeem for. |   |

**Return Values:**

| Type    | Description                                             |   |
| ------- | ------------------------------------------------------- | - |
| uint256 | The amount of underlying assets that would be received. |   |

#### domainSeparator

```
function domainSeparator() public view override returns (bytes32)
```

Returns the EIP-712 domain separator for this contract.

**Return Values:**

| Type    | Description                   |   |
| ------- | ----------------------------- | - |
| bytes32 | The EIP-712 domain separator. |   |

#### totalAssets

```
function totalAssets() public view override returns (uint256)
```

Reports the total assets managed by the vault, net of fees, for vault share logic.

**Return Values:**

| Type    | Description                                                 |   |
| ------- | ----------------------------------------------------------- | - |
| uint256 | The total amount of assets held by the vault (net of fees). |   |

#### getClaimableFees

```
function getClaimableFees() public view override returns (uint256)
```

Calculates and returns the total amount of fees that are currently claimable by the vault manager.

**Return Values:**

| Type    | Description                                   |   |
| ------- | --------------------------------------------- | - |
| uint256 | The total amount of fees that can be claimed. |   |

#### getSigNonce

```
function getSigNonce(address signer) public view override returns (uint256)
```

Returns the current nonce for a given signer address, used for EIP-712 signatures to prevent replay attacks.

**Input Parameters:**

| Name   | Type    | Description                                                 |   |
| ------ | ------- | ----------------------------------------------------------- | - |
| signer | address | The address whose EIP-712 signature nonce is being queried. |   |

**Return Values:**

| Type    | Description                                 |   |
| ------- | ------------------------------------------- | - |
| uint256 | The current nonce for the specified signer. |   |

#### getLastVaultBalance

```
function getLastVaultBalance() public view override returns (uint256)
```

Returns the last recorded balance of the vault's AToken. This value is updated when yield is accrued.

**Return Values:**

| Type    | Description                                             |   |
| ------- | ------------------------------------------------------- | - |
| uint256 | The last recorded balance of ATokens held by the vault. |   |

#### getFee

```
function getFee() public view override returns (uint256)
```

Returns the current fee percentage set for the vault.

**Return Values:**

| Type    | Description                                                        |   |
| ------- | ------------------------------------------------------------------ | - |
| uint256 | The current fee, expressed in wad, where (1 \times 10^18) is 100%. |   |


# Swap Features

The [Aave Labs interface](https://app.aave.com/) integrates multiple features integrating token swaps detailed below.

### Swap Tokens

The *Swap Tokens* feature enables users to swap between tokens using [ParaSwap](https://app.paraswap.io/) or [CoW Swap](https://swap.cow.fi/)as the swap provider, depending on network availability. Tokens traded using CoW Swap will incur a fee depending on token pair. A discounted fee of 15bps is applied to swaps between correlated assets (e.g. ETH/wstETH), for all other swaps a fee of 25bps is applied — the list of correlated assets is reviewed and updated periodically:

* **Stablecoin asset group**: USDC, USDT, DAI, GHO, EURC, USDbC, USDe, USDS, sUSDe, RLUSD, PYUSD, LUSD, sDAI, crvUSD, USD₮0, USDC.e, EURe, xDAI, wxDAI
* **ETH correlated asset group**: weETH, ETH, WETH, wstETH, cbETH, ezETH, wrsETH, osETH, rETH, ETHx
* **BTC correlated asset group**: cbBTC, WBTC, LBTC, tBTC, eBTC

### Swap Adapter Contracts

The swap adapter contracts integrate Aave's Flash Loans and the [ParaSwap](https://app.paraswap.io/) DEX aggregator to facilitate advanced actions such as repaying borrow positions using collateral, swapping collateral assets, swapping borrow positions, and withdrawing and swapping assets. They allow users to perform complex operations in a single transaction, leveraging the liquidity of the Aave protocol and the atomic swapping capabilities of decentralized exchanges.

The table below outlines swap feature availability across V3 markets on the [Aave Labs interface](https://app.aave.com/):

| Market           | Token Swap | Repay With Collateral | Collateral Swap | Debt Swap | Withdraw & Swap |   |
| ---------------- | ---------- | --------------------- | --------------- | --------- | --------------- | - |
| Ethereum Core    |            |                       |                 |           |                 |   |
| Ethereum Prime   |            |                       |                 |           |                 |   |
| Ethereum EtherFi |            |                       |                 |           |                 |   |
| Arbitrum         |            |                       |                 |           |                 |   |
| Avalanche        |            |                       |                 |           |                 |   |
| Base             |            |                       |                 |           |                 |   |
| BNB              |            |                       |                 |           |                 |   |
| Optimism         |            |                       |                 |           |                 |   |
| Polygon          |            |                       |                 |           |                 |   |
| Gnosis           |            |                       |                 |           |                 |   |
| Metis            |            |                       |                 |           |                 |   |
| Scroll           |            |                       |                 |           |                 |   |
| ZKsync           |            |                       |                 |           |                 |   |
| Sonic            |            |                       |                 |           |                 |   |
| Celo             |            |                       |                 |           |                 |   |
| Soneium          |            |                       |                 |           |                 |   |

### Repay With Collateral

The ParaSwapRepayAdapter contract enables users to repay their borrow positions on Aave using their supplied collateral directly, without the need to unwind their positions or provide additional liquidity. It leverages Aave's Flash Loans and the ParaSwap DEX aggregator to swap the user's collateral for the borrowed asset and repay the borrow position in a single atomic transaction.

By using this adapter, users can efficiently manage their positions and reduce their borrow positions using their existing collateral, saving on transaction costs and avoiding manual steps.

The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/extensions/paraswap-adapters/ParaSwapRepayAdapter.sol).

Reference Integration: [useCollateralRepaySwap.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useCollateralRepaySwap.tsx)

#### Write Methods

**executeOperation**

```
function executeOperation(    address asset,    uint256 amount,    uint256 premium,    address initiator,    bytes calldata params) external override nonReentrant returns (bool)
```

Uses the received funds from the flash loan to repay a borrow position on the protocol on behalf of the user. Then, pulls the collateral from the user and swaps it to the debt asset to repay the flash loan.

The user should give this contract allowance to pull the aTokens in order to withdraw the underlying asset, swap it, and repay the flash loan.

Supports only one asset on the flash loan.

The params parameter should be the ABI-encoded values of the following:

* IERC20Detailed debtAsset — The address of the borrow position asset
* uint256 debtRepayAmount — The amount of the borrow position to be repaid
* uint256 buyAllBalanceOffset — Offset in the ParaSwap calldata if swapping all balance
* uint256 rateMode — The rate mode of the borrow position to be repaid
* bytes paraswapData — Data for the ParaSwap Adapter
* PermitSignature permitSignature — Struct containing the permit signature, set to zeroes if not used

**Input Parameters:**

| Name      | Type    | Description                                                       |   |
| --------- | ------- | ----------------------------------------------------------------- | - |
| asset     | address | The address of the flash-borrowed asset                           |   |
| amount    | uint256 | The amount of the flash-borrowed asset                            |   |
| premium   | uint256 | The fee of the flash-borrowed asset                               |   |
| initiator | address | The address of the flash loan initiator                           |   |
| params    | bytes   | The byte-encoded parameters passed when initiating the flash loan |   |

**Return Values:**

| Type | Description                                                      |   |
| ---- | ---------------------------------------------------------------- | - |
| bool | True if the execution of the operation succeeds, false otherwise |   |

**swapAndRepay**

```
function swapAndRepay(    IERC20Detailed collateralAsset,    IERC20Detailed debtAsset,    uint256 collateralAmount,    uint256 debtRepayAmount,    uint256 debtRateMode,    uint256 buyAllBalanceOffset,    bytes calldata paraswapData,    PermitSignature calldata permitSignature) external nonReentrant
```

Swaps the user's collateral for the debt asset and then repays the borrow position on the protocol on behalf of the user without using flash loans. This method can be used when the temporary transfer of the collateral asset to this contract does not affect the user's position.

The user should give this contract allowance to pull the aTokens in order to withdraw the underlying asset.

**Input Parameters:**

| Name                | Type            | Description                                                                         |   |
| ------------------- | --------------- | ----------------------------------------------------------------------------------- | - |
| collateralAsset     | IERC20Detailed  | The address of the collateral asset to be swapped                                   |   |
| debtAsset           | IERC20Detailed  | The address of the debt asset                                                       |   |
| collateralAmount    | uint256         | The maximum amount of the collateral to be swapped                                  |   |
| debtRepayAmount     | uint256         | The amount of the borrow position to be repaid, or maximum amount when repaying all |   |
| debtRateMode        | uint256         | The rate mode of the borrow position to be repaid                                   |   |
| buyAllBalanceOffset | uint256         | Offset in the ParaSwap calldata if swapping all balance, otherwise 0                |   |
| paraswapData        | bytes           | Data for the ParaSwap Adapter                                                       |   |
| permitSignature     | PermitSignature | Struct containing the permit signature, set to zeroes if not used                   |   |

**PermitSignature Struct**

```
struct PermitSignature {    uint256 deadline;    uint8 v;    bytes32 r;    bytes32 s;}
```

**Members:**

| Name     | Type    | Description                                     |   |
| -------- | ------- | ----------------------------------------------- | - |
| deadline | uint256 | The deadline timestamp for the permit signature |   |
| v        | uint8   | The V parameter of the ECDSA signature          |   |
| r        | bytes32 | The R parameter of the ECDSA signature          |   |
| s        | bytes32 | The S parameter of the ECDSA signature          |   |

***

### Collateral Swap

The ParaSwapLiquiditySwapAdapter contract allows users to swap their supplied collateral from one asset to another in a single transaction using Aave's Flash Loans and the ParaSwap DEX aggregator.

This adapter enables users to rebalance their collateral positions without needing to withdraw and re-supply assets manually. By leveraging flash loans, the user can swap their existing collateral to a new asset and supply it back into the Aave protocol in a single transaction.

The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/extensions/paraswap-adapters/ParaSwapLiquiditySwapAdapter.sol).

Reference Integration: [useCollateralSwap.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useCollateralSwap.tsx)

#### Write Methods

**executeOperation**

```
function executeOperation(    address asset,    uint256 amount,    uint256 premium,    address initiator,    bytes calldata params) external override nonReentrant returns (bool)
```

Swaps the received amount from the flash loan into the specified asset. The received funds from the swap are then supplied into the protocol on behalf of the user.

The user should give this contract allowance to pull the aTokens in order to withdraw the underlying asset and repay the flash loan.

The params parameter should be the ABI-encoded values of the following:

* IERC20Detailed assetToSwapTo — The address of the underlying asset to be swapped to and supplied
* uint256 minAmountToReceive — The minimum amount to be received from the swap
* uint256 swapAllBalanceOffset — Offset in the Augustus calldata if swapping all balance, otherwise 0
* bytes swapCalldata — Calldata for ParaSwap's Augustus Swapper contract
* IParaSwapAugustus augustus — Address of ParaSwap's Augustus Swapper contract
* PermitSignature permitParams — Struct containing the permit signature, set to zeroes if not used

**Input Parameters:**

| Name      | Type    | Description                                                       |   |
| --------- | ------- | ----------------------------------------------------------------- | - |
| asset     | address | The address of the flash-borrowed asset                           |   |
| amount    | uint256 | The amount of the flash-borrowed asset                            |   |
| premium   | uint256 | The fee of the flash-borrowed asset                               |   |
| initiator | address | The address of the flash loan initiator                           |   |
| params    | bytes   | The byte-encoded parameters passed when initiating the flash loan |   |

**Return Values:**

| Type | Description                                                      |   |
| ---- | ---------------------------------------------------------------- | - |
| bool | True if the execution of the operation succeeds, false otherwise |   |

**swapAndDeposit**

```
function swapAndDeposit(    IERC20Detailed assetToSwapFrom,    IERC20Detailed assetToSwapTo,    uint256 amountToSwap,    uint256 minAmountToReceive,    uint256 swapAllBalanceOffset,    bytes calldata swapCalldata,    IParaSwapAugustus augustus,    PermitSignature calldata permitParams) external nonReentrant
```

Swaps an amount of an asset to another and supplies the new asset amount on behalf of the user without using a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract does not affect the user's position.

The user should give this contract allowance to pull the aTokens in order to withdraw the underlying asset and perform the swap.

**Input Parameters:**

| Name                 | Type              | Description                                                       |   |
| -------------------- | ----------------- | ----------------------------------------------------------------- | - |
| assetToSwapFrom      | IERC20Detailed    | The address of the underlying asset to be swapped from            |   |
| assetToSwapTo        | IERC20Detailed    | The address of the underlying asset to be swapped to and supplied |   |
| amountToSwap         | uint256           | Amount to be swapped, or maximum amount when swapping all balance |   |
| minAmountToReceive   | uint256           | Minimum amount to be received from the swap                       |   |
| swapAllBalanceOffset | uint256           | Offset in Augustus calldata if swapping all balance, otherwise 0  |   |
| swapCalldata         | bytes             | Calldata for ParaSwap's Augustus Swapper contract                 |   |
| augustus             | IParaSwapAugustus | Address of ParaSwap's Augustus Swapper contract                   |   |
| permitParams         | PermitSignature   | Struct containing the permit signature, set to zeroes if not used |   |

***

### Borrow Position Swap

The ParaSwapDebtSwapAdapter contracts allow users to swap their borrow positions from one asset to another. They leverage Aave's Flash Loans and the ParaSwap DEX aggregator to perform the swap in a single atomic transaction.

There are two versions of the adapter:

* **ParaSwapDebtSwapAdapterV3**: The standard version that supports swapping any borrow position asset.
  * Source Code: [GitHub](https://github.com/bgd-labs/aave-debt-swap/blob/main/src/contracts/ParaSwapDebtSwapAdapterV3.sol)
  * Reference Integration: [useDebtSwitch.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useDebtSwitch.tsx)
* **ParaSwapDebtSwapAdapterV3GHO**: A specialized version that supports GHO, where GHO can be flash minted via the ERC-3156 interface.
  * Source Code: [GitHub](https://github.com/bgd-labs/aave-debt-swap/blob/main/src/contracts/ParaSwapDebtSwapAdapterV3GHO.sol)
  * Reference Integration: [useDebtSwitch.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useDebtSwitch.tsx)

#### ParaSwapDebtSwapAdapterV3

The ParaSwapDebtSwapAdapterV3 contract allows users to swap their borrow positions from one asset to another, enabling borrow position refinancing on the Aave protocol.

This adapter leverages Aave's Flash Loans and the ParaSwap DEX aggregator to perform the borrow position swap in a single transaction.

**Write Methods**

**executeOperation**

```
function executeOperation(    address[] calldata assets,    uint256[] calldata amounts,    uint256[] calldata,    address initiator,    bytes calldata params) external returns (bool)
```

Performs the borrow position swap operation using the received funds from the flash loan.

Performs the swap and repay operation using the borrowed funds from the flash loan, and then re-borrows the new borrow position asset to maintain the overall borrow position.

The params parameter should be the ABI-encoded values required for the operation, such as:

* The addresses of the borrow position assets involved
* The rate modes of the borrow positions
* ParaSwap swap data
* Any necessary permit signatures

**Input Parameters:**

| Name      | Type       | Description                                                       |   |
| --------- | ---------- | ----------------------------------------------------------------- | - |
| assets    | address\[] | The addresses of the assets being borrowed in the flash loan      |   |
| amounts   | uint256\[] | The amounts of the assets being borrowed                          |   |
| premiums  | uint256\[] | The fees for the flash loans                                      |   |
| initiator | address    | The address of the flash loan initiator                           |   |
| params    | bytes      | Arbitrary data containing the parameters needed for the operation |   |

**Return Values:**

| Type | Description                                                      |   |
| ---- | ---------------------------------------------------------------- | - |
| bool | True if the execution of the operation succeeds, false otherwise |   |

#### ParaSwapDebtSwapAdapterV3GHO

The ParaSwapDebtSwapAdapterV3GHO contract is a specialized version of the borrow position swap adapter that supports GHO, allowing users to swap their borrow positions involving GHO. It utilizes the ERC-3156 flash mint interface for GHO.

Performs the swap and repay operation using the borrowed funds from the flash loan, and then re-borrows the borrow position asset to maintain the overall borrow position.

**Write Methods**

**onFlashLoan**

```
function onFlashLoan(    address initiator,    address token,    uint256 amount,    uint256 fee,    bytes calldata data) external override returns (bytes32)
```

This is the ERC-3156 Flash Loan callback function that gets called when the contract receives a flash loan (in this case, flash mint) from the GHO Flash Minter.

**Input Parameters:**

| Name      | Type    | Description                                                       |   |
| --------- | ------- | ----------------------------------------------------------------- | - |
| initiator | address | The initiator of the flash loan                                   |   |
| token     | address | The address of the token being borrowed                           |   |
| amount    | uint256 | The amount of tokens being borrowed                               |   |
| fee       | uint256 | The fee for the flash loan                                        |   |
| data      | bytes   | Arbitrary data containing the parameters needed for the operation |   |

**Return Values:**

| Type    | Description                                                         |   |
| ------- | ------------------------------------------------------------------- | - |
| bytes32 | The keccak256 hash of the string 'ERC3156FlashBorrower.onFlashLoan' |   |

***

### Withdraw & Swap

The ParaSwapWithdrawSwapAdapter contract allows users to withdraw their supplied assets from Aave and swap them to another asset in a single transaction using the ParaSwap DEX aggregator.

This adapter enables users to efficiently exit positions and swap their assets without having to perform multiple transactions, reducing gas costs and simplifying the user experience.

The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/extensions/paraswap-adapters/ParaSwapWithdrawSwapAdapter.sol).

Reference Integration: [WithdrawAndSwitchActions.tsx](https://github.com/aave/interface/blob/main/src/components/transactions/Withdraw/WithdrawAndSwitchActions.tsx)

#### Write Methods

**withdrawAndSwap**

```
function withdrawAndSwap(    IERC20Detailed assetToSwapFrom,    IERC20Detailed assetToSwapTo,    uint256 amountToSwap,    uint256 minAmountToReceive,    uint256 swapAllBalanceOffset,    bytes calldata swapCalldata,    IParaSwapAugustus augustus,    PermitSignature calldata permitParams) external nonReentrant
```

Swaps an amount of an asset to another after a withdrawal and transfers the new asset to the user. The user should give this contract allowance to pull the aTokens in order to withdraw the underlying asset and perform the swap.

**Input Parameters:**

| Name                 | Type              | Description                                                       |   |
| -------------------- | ----------------- | ----------------------------------------------------------------- | - |
| assetToSwapFrom      | IERC20Detailed    | The address of the underlying asset to be swapped from            |   |
| assetToSwapTo        | IERC20Detailed    | The address of the underlying asset to be swapped to              |   |
| amountToSwap         | uint256           | Amount to be swapped, or maximum amount when swapping all balance |   |
| minAmountToReceive   | uint256           | Minimum amount to be received from the swap                       |   |
| swapAllBalanceOffset | uint256           | Offset in Augustus calldata if swapping all balance, otherwise 0  |   |
| swapCalldata         | bytes             | Calldata for ParaSwap's Augustus Swapper contract                 |   |
| augustus             | IParaSwapAugustus | Address of ParaSwap's Augustus Swapper contract                   |   |
| permitParams         | PermitSignature   | Struct containing the permit signature, set to zeroes if not used |   |

**executeOperation**

Note that in this contract, the executeOperation method is overridden but simply reverts with NOT\_SUPPORTED, so it's not intended to be used.


# Credit Delegation

<figure><img src="/files/NgFxnIN3mcnguAdtnJBD" alt=""><figcaption></figcaption></figure>

Credit delegation allows a supplier to contribute liquidity to Tydro to earn interest, and delegate their borrowing power (i.e. their credit) to another address.\
The enforcement of the borrow position and its terms are agreed upon between the supplier (delegator) and the borrower (delegatee), which can happen either off-chain (via legal agreements) or on-chain (via smart contracts).

This enables:

* The delegator to earn extra yield on top of their base lending yield
* The delegatee to access uncollateralized liquidity

Borrowing by a delegatee must be consistent with the delegator’s eMode category. For example, if a delegator is in the STABLECOINS eMode:

* Delegatee can only borrow assets within the STABLECOINS category
* If a delegatee attempts to borrow a non-STABLECOIN asset (e.g. WETH), the transaction will revert

Additionally, the delegatee cannot cause liquidation of the delegator. If a delegated borrow causes the delegator’s Health Factor to drop below the liquidation threshold, the transaction will fail.

### Approving the delegation

The approveDelegation or delegationWithSig function on the [VariableDebtToken](/developers/smart-contracts/tokenization#variabledebttoken) contract must be called by the supplier (delegator), approving the borrower (delegatee) a certain amount.

This is done for each debt token that needs to be delegated.

The delegator does not need to already have supplied funds in the protocol to approveDelegation. However, **before** the delegatee executes borrow, there must be sufficient collateral supplied by delegator in the protocol.

### Borrowing the credit

The borrower (delegatee) calls the borrow function on the [Pool](/developers/smart-contracts/pool), using the supplier's (delegator's) address in final parameter onBehalfOf.

The borrower's available credit is reduced by the borrowed amount.

### Repaying the credit

Anyone can repay the borrow position *OnBehalf* of the user, by calling one of the following [Pool](/developers/smart-contracts/pool) functions - repay or repayWithPermit. The supplier (aka creditor) can also use the repayWithATokens function to repay a borrow position with their *aTokens* of the underlying asset in the same pool.


# Testing & Debugging

This guide explains how to test and debug Tydro integrations effectively.

### Testing

There are two main ways to test with Tydro:

1. Using a **testnet**
2. Creating **fork networks**

### Testnet

Tydro is available on the Sepolia testnet. You can connect to the Sepolia market through the Tydro app by enabling testnet mode in the top-right corner.

To get started:

1. Open the Sepolia test market in the Tydro app.
2. Use the Faucet tab to claim test tokens available in the market.
3. Supply those tokens into the protocol.
4. Try operations such as borrowing, repaying, and withdrawing to confirm functionality.

#### Fork Networks

A fork network replicates the state of a live chain, letting you test in a controlled sandbox that mirrors mainnet conditions. This is useful for scenarios that depend on deployed contracts or existing liquidity.

Popular tools for forking include:

* Tenderly: transaction simulations, debugging, and dashboards
* Foundry: modular toolkit for smart contract development
* Hardhat: local Ethereum development environment

On a fork, you can fund your account by impersonating an address that holds tokens (findable via block explorers) and transferring assets.

**Connecting a Fork to the UI**

The Tydro app can also connect directly to a forked network. This requires setting specific variables through the browser console. See the integration guide for full instructions.

**Debugging**

When working with Tydro contracts, you may hit errors or failed transactions. This section covers error codes, debugging tools, and common issues.

#### Error Codes

Tydro uses dedicated error codes to explain why a transaction reverted. Each protocol version defines them in its own `Errors.sol` file.

* Tydro V3 Error Codes: `Errors.sol`
* Tydro V2 Error Codes: `Errors.sol`

Understanding these codes is essential for resolving failures.

#### Debugging Tools

* Tenderly: Simulate transactions by providing `to`, `from`, `data`, and `value`. Step through execution, see error codes, and review stack traces.
* Hardhat: Run a local chain, fork mainnet, log from Solidity, and inspect detailed stack traces.
* Foundry: Portable toolkit with `forge` for testing/debugging contracts and simulating transactions.

**Understanding “Gas Estimation Failed”**

This error means the transaction would revert if executed. To debug:

1. Collect the transaction’s `to`, `from`, `data`, and `value`.
2. Simulate the call using Tenderly, Hardhat, or Foundry.
3. Identify the specific error code or exception.
4. Trace the call stack to pinpoint the issue.

### Common Errors

#### Pool Interactions

* Token Approval: Before supplying or repaying, you must approve the Tydro Pool to transfer your ERC-20 tokens. Call `approve()` on the token contract with the Pool as spender.
* Insufficient Collateral: Borrowing requires enough collateral at or above the required Loan-to-Value (LTV). Supply additional assets or check your ratios.
* Borrow Cap Reached: If an asset’s borrow cap is maxed out, no new borrows are possible until positions are repaid or more liquidity is supplied.

#### Loan To Value = 0% (LTV0)

If a reserve’s LTV is set to 0%, the asset behaves differently:

* It does not contribute to borrowing power.
* It cannot be enabled as collateral.
* If received via transfer, it won’t auto-enable as collateral.
* To withdraw other assets, you must first disable LTV0 assets as collateral (via `Pool.setUserUseReserveAsCollateral`) or fully withdraw them.

#### WrappedTokenGateway

When dealing with ETH in Tydro, the WrappedTokenGateway handles wrapping/unwrapping ETH into WETH.\
Common issues include:

* Not sending ETH along with a deposit transaction
* Calling the wrong function for wrapping/unwrapping

Check the WrappedTokenGateway docs for full usage and potential revert cases.


# Agent MCP (New)

### Background

Use Tydro's MCP with any AI agent to query live rates, check positions, and execute onchain actions like supply, borrow, repay, and withdraw.

### Installation

```
npm install
npm run build
```

### Configuration

```
# Required: network (mainnet only for now)
export TYDRO_NETWORK=mainnet

# Optional: only needed for write operations (supply/borrow/repay/withdraw)
export PRIVATE_KEY=0x...
```

### Usage with Claude Desktop

```
{
  "mcpServers": {
    "tydro": {
      "command": "node",
      "args": ["/path/to/tydro-mcp/build/index.js"],
      "env": {
        "TYDRO_NETWORK": "mainnet",
        "PRIVATE_KEY": "0x..."
      }
    }
  }
}
```

### Tools

#### `get_reserve_data`

Get supply/borrow APYs, liquidity, and utilization for any reserve.

```
{ "asset": "WETH" }
{ "asset": "kBTC" }
{ "asset": "USDT0" }
```

#### `get_user_account`

Get overall health factor, collateral, debt, and borrow capacity.

```
{ "address": "0x..." }
```

#### `get_user_reserve`

Get a user's position for a specific asset (supplied, borrowed, collateral status).

```
{ "asset": "USDT0", "address": "0x..." }
```

#### `supply`

Deposit assets to earn interest. Auto-approves if needed.

```
{ "asset": "USDT0", "amount": "1000" }
{ "asset": "WETH",  "amount": "0.5"  }
```

#### `borrow`

Borrow against collateral. Variable rate only (stable rate deprecated in Aave V3).

```
{ "asset": "USDT0", "amount": "500" }
```

#### `repay`

Repay borrowed assets. Use `"max"` to repay full debt including accrued interest.

```
{ "asset": "USDT0", "amount": "500"  }
{ "asset": "WETH",  "amount": "max"  }
```

#### `withdraw`

Withdraw supplied assets. Use `"max"` to withdraw full aToken balance.

```
{ "asset": "USDT0", "amount": "max" }
```

### Notes

* **Read-only tools** (`get_reserve_data`, `get_user_account`, `get_user_reserve`) work without `PRIVATE_KEY`
* **Write tools** (`supply`, `borrow`, `repay`, `withdraw`) require `PRIVATE_KEY`
* Approvals are checked before sending — no redundant approval transactions
* Max repay/withdraw uses `type(uint256).max` — Aave caps at actual balance/debt
* Health factor warnings trigger below 1.5 (liquidation threshold is 1.0)


# GHO 🟡

<figure><img src="/files/NgFxnIN3mcnguAdtnJBD" alt=""><figcaption></figcaption></figure>

GHO (pronounced "go") is a decentralised, over-collateralised stablecoin that is fully backed, transparent, and native to the Aave Protocol. Designed to maintain a value pegged to the U.S. dollar, GHO is minted by users on demand, subject to mint cap limitations set by Aave's governance. Its stability is maintained through market efficiencies and over-collateralisation mechanisms inherent in the Aave Protocol.

GHO is an ERC-20 token deployed on Ethereum that operates through a facilitator model. Facilitators are contracts approved by Aave Governance with the ability to mint and burn GHO, each subject to a governance-defined mint cap. This model allows for flexibility in expanding GHO's functionality while maintaining decentralized control over the supply.

### GHO Token

The GHO Token contract includes specific roles for managing facilitators and their minting capacities:

* **FACILITATOR\_MANAGER\_ROLE**: This role is responsible for adding and removing facilitators.
* **BUCKET\_MANAGER\_ROLE**: This role is responsible for setting the bucketCapacity for existing facilitators.

Each facilitator is represented by a Facilitator struct, which contains:

* **label**: A string identifier for the facilitator.
* **bucketCapacity**: The maximum amount of GHO a facilitator can mint.
* **bucketLevel**: The current amount of GHO minted by the facilitator.

#### transfer

The simplest method for transferring ERC-20 tokens is transfer which can be used to send tokens to any address without a prior token approval. The limitation of transfer is that it must be executed directly by the token holder, so it cannot be used within a smart contract function call to retrieve funds from a user (EOA).

#### transferFrom

To transfer tokens within a smart contract function, transferFrom is the method that is used. The transferFrom function requires the sender to have approved the spender address for at least the transfer amount. There are two methods which can be used to perform the approval:

#### approve

The standard ERC-20 approve requires an on-chain transaction from the token holder to a approve a specified spender and amount.

#### permit

EIP-2612 permit is a type of token approval which requires two components:

* A signed approval message from the token holder which encodes: owner, spender, amount, nonce, deadline, DOMAIN\_SEPARATOR
* An on-chain permit transaction which can be executed from any address

The advantages to using permit in place of approve are that the gas cost of the transaction can be paid for by an address other than the token owner, and can reduce the number of transactions by batching the permit call with another action, an example of this is [supplyWithPermit](https://github.com/aave-dao/aave-v3-origin/blob/ec33f4fcc5546710c0faca5208af1775c761ac9c/src/contracts/protocol/pool/Pool.sol#L154) from Aave Protocol V3.

### Facilitators

Facilitators are contract addresses approved by Aave Governance with the FACILITATOR\_MANAGER\_ROLE and BUCKET\_MANAGER\_ROLE, giving them the ability to mint and burn GHO tokens. Each facilitator operates under a specific bucketCapacity, controlling the maximum amount of GHO they can generate. Facilitators play a crucial role in maintaining GHO's stability and integrating it across various platforms and use cases.

#### GHO Token Functions for Facilitators

Facilitators interact with the GHO token using the following functions:

* **mint(address account, uint256 amount)**: Allows a facilitator to mint amount of GHO tokens to the account. The amount must be greater than 0, and the new bucketLevel (current bucketLevel + amount) must not exceed the facilitator's bucketCapacity. This function updates the facilitator's bucketLevel.
* **burn(uint256 amount)**: Allows a facilitator to burn amount of GHO tokens from their own balance. The amount must be greater than 0, and the facilitator's bucketLevel is decreased by the burned amount.

#### Facilitator Management Functions

The GHO token contract also provides functions for managing facilitators:

* **addFacilitator(address facilitatorAddress, string calldata facilitatorLabel, uint128 bucketCapacity)**: Callable by an address with the FACILITATOR\_MANAGER\_ROLE, this function adds a new facilitator with a specified label and bucketCapacity. A facilitator cannot be added if it already exists or if the label is empty.
* **removeFacilitator(address facilitatorAddress)**: Callable by an address with the FACILITATOR\_MANAGER\_ROLE, this function removes an existing facilitator. A facilitator can only be removed if its bucketLevel is 0.
* **setFacilitatorBucketCapacity(address facilitator, uint128 newCapacity)**: Callable by an address with the BUCKET\_MANAGER\_ROLE, this function updates the bucketCapacity of an existing facilitator.

#### Facilitator Query Functions

Information about facilitators can be retrieved using:

* **getFacilitatorsList()**: Returns a list of all registered facilitator addresses.
* **getFacilitator(address facilitator)**: Returns the Facilitator struct details (label, bucketCapacity, bucketLevel) for a given facilitator address.
* **getFacilitatorBucket(address facilitator)**: Returns the bucketCapacity and bucketLevel of a specific facilitator.

#### Aave V3 Ethereum Market

The Aave V3 Ethereum Market serves as a primary facilitator for GHO. Users can mint GHO by supplying approved collateral assets into the Aave Protocol and borrowing GHO against them. This process follows standard over-collateralisation practices, ensuring the protocol's security and the stablecoin's reliability.

Interacting with GHO via the Aave Pool Facilitator is very similar to interacting with a typical Aave reserve asset with two key differences:

* GHO is minted, not supplied, therefore interest rate and available liquidity calculations are based on custom interest rate strategy and facilitator caps respectively

Below are the technical guides for all GHO actions along with their contract references.

**Minting**

Minting occurs through the borrow function of the Aave V3 Ethereum market. To mint GHO, the process is nearly identical to borrowing any other reserve. To mint, an address must have sufficient collateral which is performed by approving and then calling supply on the Aave Pool with an eligible collateral asset. Once an address has sufficient collateral, it is able to borrow up to a maximum collateral factor determined by its collateral asset composition.

Since GHO is created and not borrowed from suppliers, GHO is not subject to restrictions on available liquidity, and instead, the Facilitator cap and collateralization requirements define the limits to which GHO can be minted as calculated below.

availableFacilitatorCap = ghoReserveData.aaveFacilitatorButcketMaxCapacity - ghoReserveData.aaveFacilitatorBucketLevel

See [core functions](https://aave.com/docs/developers/smart-contracts/pool) for more information on integrating Aave borrow functionality.

**Repay**

GHO is repaid just like any other asset, by approving the Pool contract to spend GHO tokens (by approval transaction or signed permit and repayWithPermit).

See [core functions](https://aave.com/docs/developers/smart-contracts/pool) for more information on integrating Aave repay functionality.

#### Liquidation

When an address has a GHO borrow position, they are eligible to be liquidated under the same conditions as any other collateralized address. If the health factor of a GHO borrow falls below one, which occurs when the sum of borrow value exceeds the weighted average of liquidation thresholds of collateral assets, then any address is eligible to make a liquidationCall on the Pool contract.

The liquidationCall repays up to 100% of the GHO borrow position in exchange for an equivalent USD valuation of the collateral plus a liquidation bonus.

#### Flash Mint

Since GHO is not borrowed like a typical Aave reserve, a separate Facilitator is used in place to replicate the flashloan functionality of the Aave Pool.

The FlashMinter Facilitator has a separate minting cap from the Aave Pool. Since all FlashMint transactions are returned in a single transaction, no GHO is ever minted against this Facilitator and the cap is applied to each transaction.

FlashMint is useful for a variety of applications such as liquidations, debt switches, and peg arbitrage. The GhoFlashMinter smart contract implements the following functions:

```
function maxFlashLoan(address token) external view override returns (uint256)
```

```
function getFee() external view override returns (uint256)
```

```
function flashLoan(    IERC3156FlashBorrower receiver,    address token,    uint256 amount,    bytes calldata data) external override returns (bool)
```

See the developers [flash loan guide](https://aave.com/docs/developers/flash-loans) for more information on developing flash loan integrations.

#### Stability Module

A Peg Stability Module (PSM) is a contract that enables the conversion of two tokens at a predetermined ratio. The GHO Stability Module (GSM) leverages the benefits of existing PSM models while innovating upon them in several ways to help further maintain GHO’s peg. The GSM is designed to facilitate conversions between GHO and governance-approved tokens, underpinned by a suite of features designed for flexible operations and risk management.

**GSMRegistry**

The GSMRegistry is a smart contract that stores a list of all GSM instances. This contract is owned by the Aave Governance Short Executor.

**GSM**

Each token pairing in the stability module has a GSM or GSM4626 contract instance that acts as the GHO facilitator and entry-point for buy and sell functionality.

The GSM4626 contract is a special instance of the GSM that supports ERC-4626 tokenized vault shares as the exogenous token.

The parameters and periphery contracts that dictate module operations are detailed below:

**Price Strategy**

The GSM introduces a flexible Price Strategy framework, enabling the module to adapt its pricing mechanism based on market conditions or strategic objectives. This system supports both fixed and dynamic pricing strategies, allowing for adjustments in response to real-time market data or predetermined conditions. The initial implementation focuses on a fixed 1:1 pricing strategy for simplicity and stability, with provisions for future adaptation to dynamic strategies as dictated by Aave governance.

**Fee Strategy**

Each GSM instance has a FeeStrategy contract that determines a percentage fee for buy and sell conversions that is allocated to the Aave DAO treasury.

**Exposure Cap**

The exposure cap is a parameter determined by Aave Governance that sets the maximum amount of an exogenous token the stability module can hold.

**Conversion Freezes and Oracle Price Bounds**

In case the price of the exogenous token deviates from a determined ratio, the freeze role can be utilized by the Aave DAO or assigned to an entity (autonomous agents or contracts) to respond and halt conversions.

An implementation of the freeze role is the OracleSwapFreezer contract. This contract utilizes Chainlink oracles and price bounds determined by Aave Governence to freeze/unfreeze based on oracle conditions.

**Last Resort Liquidations**

In case of a rapid increase in risk in an exogenous token, the GSM features Last Resort Liquidations to liquidate the exogenous token. This contract role allows in the worst-case scenarios for the Aave DAO to pause GSM functionality and liquidate the underlying balance of exogenous tokens.

#### Cross-Chain

All GHO tokens are originated on Ethereum mainnet. GHO is made available to access on other networks using an infrastructure of cross-chain messaging.

The Chainlink CCIP protocol has been approved by Aave Governance as the messaging bridge to facilitate the transfer of GHO between networks.

GHO is transferred by between networks by initiating a lock (Ethereum mainnet) or burn (other networks) action on the source network, and a release (Ethereum mainnet) or mint (other networks) action occurs on the destination chain after the cross-chain message has been validated.

The GHOCCIPTokenPoolEthereum contract facilitates the locking and burning of GHO on Ethereum and other chains, enabling GHO's presence across multiple DeFi ecosystems.

\*\* GHO Token Deployments\*\*:

* [Ethereum Mainnet](https://etherscan.io/address/0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f)
* [Arbitrum](https://arbiscan.io/address/0x7dfF72693f6A4149b17e7C6314655f6A9F7c8B33)
* [Base](https://basescan.org/address/0x6Bb7a212910682DCFdbd5BCBb3e28FB4E8da10Ee)
* [Avalanche](https://snowtrace.io/address/0xfc421aD3C883Bf9E7C4f42dE845C4e4405799e73)
* [Gnosis](https://gnosisscan.io/address/0xfc421aD3C883Bf9E7C4f42dE845C4e4405799e73)

**GHO CCIP Subgraph**:

* [CCIP Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/E11p8T4Ff1DHZbwSUC527hkUb5innVMdTuP6A2s1xtm1?view=Query\&chain=arbitrum-one)
* [CCIP Arbitrum Subgraph](https://thegraph.com/explorer/subgraphs/GPpZfiGoDChLsiWoMG5fxXdRNEYrsVDrKJ39moGcbz6i?view=Query\&chain=arbitrum-one)
* [CCIP Base Subgraph](https://thegraph.com/explorer/subgraphs/7WRSEgg43s2CqpymK2wkHrhQjn4v5fEnufonwRkkokbM?view=Query\&chain=arbitrum-one)
* [CCIP Avalanche Subgraph](https://thegraph.com/explorer/subgraphs/7WRSEgg43s2CqpymK2wkHrhQjn4v5fEnufonwRkkokbM?view=Query\&chain=arbitrum-one)
* [CCIP Gnosis Subgraph](https://thegraph.com/explorer/subgraphs/CFjU1G9iUtFDqEBTzSePRiPjghjUzQeFX5C67DGSK2Ao?view=Query\&chain=arbitrum-one)

### GHO Liquidity Committee

The GHO Liquidity Committee (GLC) was created in October 2023 to focus solely on the liquidity of the GHO stablecoin. The committee was formed through a [governance proposal](https://governance-v2.aave.com/governance/proposal/343/) and consisted of a small team. After a successful initial 3-month period, it was [integrated](https://governance-v2.aave.com/governance/proposal/407/) into the Aave Liquidity Committee (ALC).

The ALC's main responsibilities regarding GHO include:

* Providing analytics and modelling of the liquidity strategy
* Liaising with teams that support the protocols hosting GHO liquidity
* Leading and coordinating the committee's weekly activities
* Providing critical feedback and helping refine the strategy
* Verifying and signing transactions

The ALC's performance measures and liquidity targets for GHO can be found on the [GHO Analytics platform](https://aave.tokenlogic.xyz/liquidity-committee) provided by TokenLogic.

More information regarding the role of the GHO Liquidity Committee can be found in [Aave's Governance forum](https://governance.aave.com/t/temp-check-treasury-management-create-and-fund-gho-liquidity-committee/14800).

### GHO Stewards

GHO Stewards is an additional entity created in April 2024 to more flexibly manage GHO market parameters, enabling GHO to be scaled per prevailing market conditions. The source code for GHO Steward contracts can be found on [GitHub](https://github.com/aave/gho-core/tree/main/src/contracts/misc).

The GHO Stewards determine if and how much to adjust the following, subject to pre-defined and Governance accepted thresholds:

* GHO Borrow Cap
* GHO Borrow Rate
* GSM Exposure Cap
* GSM Bucket Capacity
* GSM Price Strategy
* GSM Fee Strategy
* GSM Price Range (Freeze, Unfreeze)

With many liquidity pools being created and rewards distributed across them, it is important that the DAO can swiftly increase the GHO Borrow Cap to mitigate GHO trading above $1. The GHO Stewards can swiftly increase the GHO Borrow Cap to mitigate GHO trading above the peg. The GHO Stewards can increase the GHO Borrow Cap to a threshold of 50M units to a total borrow cap of 100M.

The Borrow Rate must be adjusted gradually to enable the ecosystem to expand safely. If the trailing 30-day average price of GHO stays outside a $0.995 - $1.005 price range, the GHO Stewards are able to adjust the Borrow Rate no more than 500bps per 2-day period, up to a maximum 25% APR.

GHO Stewards consist of members from Growth (ACI), Risk (ChaosLabs), and Finance (TokenLogic + karpatkey) Service Providers and utilise a 3 of 4 multi-sig.

### Deployed Contracts

#### Ethereum Mainnet

| Contract                  | Address                                                                                                               |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| GhoToken                  | [0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f](https://etherscan.io/address/0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f) |
| GhoCCIPTokenPoolEthereum  | [0x06179f7C1be40863405f374E7f5F8806c728660A](https://etherscan.io/address/0x06179f7C1be40863405f374E7f5F8806c728660A) |
| GhoFlashMinter            | [0xb639D208Bcf0589D54FaC24E655C79EC529762B8](https://etherscan.io/address/0xb639D208Bcf0589D54FaC24E655C79EC529762B8) |
| GhoLiquidityComittee      | [0xA1c93D2687f7014Aaf588c764E3Ce80aF016229b](https://etherscan.io/address/0xA1c93D2687f7014Aaf588c764E3Ce80aF016229b) |
| GhoGsmSteward             | [0xD1E856a947CdF56b4f000ee29d34F5808E0A6848](https://etherscan.io/address/0xD1E856a947CdF56b4f000ee29d34F5808E0A6848) |
| GSMRegistry               | [0x167527DB01325408696326e3580cd8e55D99Dc1A](https://etherscan.io/address/0x167527DB01325408696326e3580cd8e55D99Dc1A) |
| GSMUSDC                   | [0xFeeb6FE430B7523fEF2a38327241eE7153779535](https://etherscan.io/address/0xFeeb6FE430B7523fEF2a38327241eE7153779535) |
| GSMUSDT                   | [0x535b2f7C20B9C83d70e519cf9991578eF9816B7B](https://etherscan.io/address/0x535b2f7C20B9C83d70e519cf9991578eF9816B7B) |
| GSMUSDCFixedFeeStrategy   | [0xD4478A76aCeA81D3768A0ACB6e38f25eEB6Eb1B5](https://etherscan.io/address/0xD4478A76aCeA81D3768A0ACB6e38f25eEB6Eb1B5) |
| GSMUSDTFixedFeeStrategy   | [0xD4478A76aCeA81D3768A0ACB6e38f25eEB6Eb1B5](https://etherscan.io/address/0xD4478A76aCeA81D3768A0ACB6e38f25eEB6Eb1B5) |
| GSMUSDCFixedPriceStrategy | [0x430BEdcA5DfA6f94d1205Cb33AB4f008D0d9942a](https://etherscan.io/address/0x430BEdcA5DfA6f94d1205Cb33AB4f008D0d9942a) |
| GSMUSDTFixedPriceStrategy | [0x4c707764cbFB4FFa078e169e6b8A6AdbE7526a2c](https://etherscan.io/address/0x4c707764cbFB4FFa078e169e6b8A6AdbE7526a2c) |
| GSMUSDCOracleSwapFreezer  | [0xef6beCa8D9543eC007bceA835aF768B58F730C1f](https://etherscan.io/address/0xef6beCa8D9543eC007bceA835aF768B58F730C1f) |
| GSMUSDTOracleSwapFreezer  | [0x71381e6718b37C12155CB961Ca3D374A8BfFa0e5](https://etherscan.io/address/0x71381e6718b37C12155CB961Ca3D374A8BfFa0e5) |
| GHO\_AAVE\_CORE\_STEWARD  | [0x98217A06721Ebf727f2C8d9aD7718ec28b7aAe34](https://etherscan.io/address/0x98217A06721Ebf727f2C8d9aD7718ec28b7aAe34) |
| GHO\_BUCKET\_STEWARD      | [0x46Aa1063e5265b43663E81329333B47c517A5409](https://etherscan.io/address/0x46Aa1063e5265b43663E81329333B47c517A5409) |
| GHO\_CCIP\_STEWARD        | [0xC5BcC58BE6172769ca1a78B8A45752E3C5059c39](https://etherscan.io/address/0xC5BcC58BE6172769ca1a78B8A45752E3C5059c39) |
| RISK\_COUNCIL             | [0x8513e6F37dBc52De87b166980Fa3F50639694B60](https://etherscan.io/address/0x8513e6F37dBc52De87b166980Fa3F50639694B60) |

#### Arbitrum

| Contract           | Address                                                                                                              |
| ------------------ | -------------------------------------------------------------------------------------------------------------------- |
| GHOToken           | [0x7dfF72693f6A4149b17e7C6314655f6A9F7c8B33](https://arbiscan.io/address/0x7dfF72693f6A4149b17e7C6314655f6A9F7c8B33) |
| GHOCCIPTokenPool   | [0xB94Ab28c6869466a46a42abA834ca2B3cECCA5eB](https://arbiscan.io/address/0xB94Ab28c6869466a46a42abA834ca2B3cECCA5eB) |
| GHOAaveCoreSteward | [0xd2D586f849620ef042FE3aF52eAa10e9b78bf7De](https://arbiscan.io/address/0xd2D586f849620ef042FE3aF52eAa10e9b78bf7De) |
| GHOBucketSteward   | [0xa9afaE6A53E90f9E4CE0717162DF5Bc3d9aBe7B2](https://arbiscan.io/address/0xa9afaE6A53E90f9E4CE0717162DF5Bc3d9aBe7B2) |
| GHOCCIPSteward     | [0xCd5ab470AaC5c13e1063ee700503f3346b7C90Db](https://arbiscan.io/address/0xCd5ab470AaC5c13e1063ee700503f3346b7C90Db) |

#### Base

| Contract           | Address                                                                                                               |
| ------------------ | --------------------------------------------------------------------------------------------------------------------- |
| GHOToken           | [0x6Bb7a212910682DCFdbd5BCBb3e28FB4E8da10Ee](https://basescan.org/address/0x6Bb7a212910682DCFdbd5BCBb3e28FB4E8da10Ee) |
| GHOCCIPTokenPool   | [0x98217A06721Ebf727f2C8d9aD7718ec28b7aAe34](https://basescan.org/address/0x98217A06721Ebf727f2C8d9aD7718ec28b7aAe34) |
| GHOAaveCoreSteward | [0xC5BcC58BE6172769ca1a78B8A45752E3C5059c39](https://basescan.org/address/0xC5BcC58BE6172769ca1a78B8A45752E3C5059c39) |
| GHOBucketSteward   | [0x3c47237479e7569653eF9beC4a7Cd2ee3F78b396](https://basescan.org/address/0x3c47237479e7569653eF9beC4a7Cd2ee3F78b396) |
| GHOCCIPSteward     | [0xB94Ab28c6869466a46a42abA834ca2B3cECCA5eB](https://basescan.org/address/0xB94Ab28c6869466a46a42abA834ca2B3cECCA5eB) |

#### Sepolia (Testnet)

| Contract                 | Address                                                                                                                       |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| GhoToken                 | [0xc4bF5CbDaBE595361438F8c6a187bDc330539c60](https://sepolia.etherscan.io/address/0xc4bF5CbDaBE595361438F8c6a187bDc330539c60) |
| GhoATokenImpl            | [0xD4BDb51fB96996CA24a5C49E7b57f94a1850Fa30](https://sepolia.etherscan.io/address/0xD4BDb51fB96996CA24a5C49E7b57f94a1850Fa30) |
| GhoDiscountRateStrategy  | [0x19cdecE64EDE475ba0EB114ff4E319d64Ef8ECCf](https://sepolia.etherscan.io/address/0x19cdecE64EDE475ba0EB114ff4E319d64Ef8ECCf) |
| GhoInterestRateStrategy  | [0x521247B4d0a51E71DE580dA2cBF99EB40a44b3Bf](https://sepolia.etherscan.io/address/0x521247B4d0a51E71DE580dA2cBF99EB40a44b3Bf) |
| GhoOracle                | [0x00f7fecFAEbEd9499e1f3f9d04E755a21E5fc47C](https://sepolia.etherscan.io/address/0x00f7fecFAEbEd9499e1f3f9d04E755a21E5fc47C) |
| GhoStableDebtTokenImpl   | [0x2aa7819F2e88aF4cfF8FD0869ABdB97E336101Ee](https://sepolia.etherscan.io/address/0x2aa7819F2e88aF4cfF8FD0869ABdB97E336101Ee) |
| GhoVariableDebtTokenImpl | [0xd4FEA5bD40cE7d0f7b269678541fF0a95FCb4b68](https://sepolia.etherscan.io/address/0xd4FEA5bD40cE7d0f7b269678541fF0a95FCb4b68) |
| GhoFlashMinter           | [0xB5d0ef1548D9C70d3E7a96cA67A2d7EbC5b1173E](https://sepolia.etherscan.io/address/0xB5d0ef1548D9C70d3E7a96cA67A2d7EbC5b1173E) |
| UiGhoDataProvider        | [0x69B9843A16a6E9933125EBD97659BA3CCbE2Ef8A](https://sepolia.etherscan.io/address/0x69B9843A16a6E9933125EBD97659BA3CCbE2Ef8A) |


# Savings GHO (sGHO) 🟡

Savings GHO (sGHO) is the Aave Protocol's native savings mechanism for the GHO stablecoin, [deployed](https://etherscan.io/address/0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d) on Ethereum mainnet. sGHO allows GHO holders to supply their tokens to a smart contract and receive sGHO that accumulates rewards paid in GHO. This mechanism has no cooldowns to redeem sGHO for GHO, no slashing risk, and no rehypothecation of supplied funds. All rewards for sGHO holders are distributed through the [Merit program](https://apps.aavechan.com/merit/ethereum-sgho).

### Deposit

To start earning rewards by depositing GHO into sGHO, follow these steps.

First, prepare the execution plan for the deposit operation.

* React
* TypeScript
* GraphQL

Use the useSavingsGhoDeposit hook to create the execution plan for depositing GHO to sGHO.

**Deposit GHO**

```
import { useWalletClient } from "wagmi";import { useSavingsGhoDeposit, bigDecimal, evmAddress } from "@aave/react";
// …
const { data: walletClient } = useWalletClient();
const [deposit, depositing] = useSavingsGhoDeposit();
const execute = async () => {  const result = await deposit({    amount: {      value: bigDecimal(1000), // 1000 GHO    },    depositor: evmAddress(walletClient!.account.address),  });
  // …};
```

#### 2. Process the Execution Plan

Then, handle the execution plan.

* React
* TypeScript
* GraphQL

Use the useSendTransaction hook for the [wallet library of your choice](https://aave.com/docs/getting-started/react#integrations-send-aave-transactions) to send the transactions in the execution plan.

**Viem**

```
import { useWalletClient } from "wagmi";import { errAsync, useSavingsGhoDeposit } from "@aave/react";import { useSendTransaction } from "@aave/react/viem";
// …
const { data: walletClient } = useWalletClient();
const [deposit, depositing] = useSavingsGhoDeposit();const [sendTransaction, sending] = useSendTransaction(walletClient);
// …
const loading = depositing.loading || sending.loading;const error = depositing.error || sending.error;
// …
const execute = async () => {  const result = await deposit({    // …  }).andThen((plan) => {    switch (plan.__typename) {      case "TransactionRequest":        // Single transaction execution        return sendTransaction(plan);
      case "ApprovalRequired":        // Approval + transaction sequence        return sendTransaction(plan.approval).andThen(() =>          sendTransaction(plan.originalTransaction)        );
      case "InsufficientBalanceError":        return errAsync(          new Error(`Insufficient balance: ${plan.required.value} required.`)        );    }  });
  if (result.isErr()) {    console.error("Deposit failed:", result.error);  } else {    console.log("Deposit successful with hash:", result.value);  }};
```

### Balance

Retrieve the balance of a user's sGHO.

* React
* TypeScript
* GraphQL

Use the useSavingsGhoBalance hook to fetch the balance of a user's sGHO.

* **Loading State**
* **React Suspense**

```
const { data, loading, error } = useSavingsGhoBalance({  user: EvmAddress,});
```

Fetch the balance of a user's sGHO.

**sGHO Balance**

```
import { useSavingsGhoBalance, evmAddress } from "@aave/react";
// …
const { data, loading, error } = useSavingsGhoBalance({  user: EvmAddress,});
if (loading) {  return <p>Loading sGHO balance...</p>;}
if (error) {  return <p>Error: {error.message}</p>;}
// data: TokenAmount
```

### Withdraw

Withdraw sGHO to GHO instantly with no cooldown period. You can still claim any previous rewards.

Follow these steps to withdraw sGHO to GHO:

#### 1. Prepare the Execution Plan

First, prepare the execution plan for the withdrawal operation.

* React
* TypeScript
* GraphQL

Use the useSavingsGhoWithdraw hook to create the execution plan for withdrawing sGHO to GHO.

**Withdraw GHO**

```
import { useWalletClient } from "wagmi";import { useSavingsGhoWithdraw, bigDecimal, evmAddress } from "@aave/react";
// …
const { data: walletClient } = useWalletClient();
const [withdraw, withdrawing] = useSavingsGhoWithdraw();
const execute = async () => {  const result = await withdraw({    amount: {      value: bigDecimal(1000), // 1000 sGHO    },    sharesOwner: evmAddress(walletClient!.account.address),    // recipient: evmAddress("0x1234…"), if different from sharesOwner  });
  // …};
```

#### 2. Process the Execution Plan

Finally, handle the execution plan.

* React
* TypeScript
* GraphQL

Use the useSendTransaction hook for the [wallet library of your choice](https://aave.com/docs/getting-started/react#integrations-send-aave-transactions) to send the transaction.

**Viem**

```
import { useWalletClient } from "wagmi";import {  useSavingsGhoWithdraw,  bigDecimal,  evmAddress,  errAsync,} from "@aave/react";import { useSendTransaction } from "@aave/react/viem";
// …
const { data: walletClient } = useWalletClient();
const [withdraw, withdrawing] = useSavingsGhoWithdraw();const [sendTransaction, sending] = useSendTransaction(walletClient);
const loading = withdrawing.loading || sending.loading;const error = withdrawing.error || sending.error;
// …
const execute = async () => {  const result = await withdraw({    amount: {      value: bigDecimal(1000), // 1000 sGHO    },    sharesOwner: evmAddress(walletClient!.account.address),    // recipient: evmAddress("0x1234…"), if different from sharesOwner  }).andThen((plan) => {    switch (plan.__typename) {      case "TransactionRequest":        // Single transaction execution        return sendTransaction(plan);
      case "ApprovalRequired":        // Approval + transaction sequence        return sendTransaction(plan.approval).andThen(() =>          sendTransaction(plan.originalTransaction)        );
      case "InsufficientBalanceError":        return errAsync(          new Error(            `Insufficient balance to withdraw: ${plan.required.value} is the maximum withdrawal allowed.`          )        );    }  });
  if (loading) {    return <p>Withdrawing sGHO to GHO...</p>;  }
  if (error) {    return <p>Error: {error.message}</p>;  }};
```

***

### Claiming Incentives

Users who deposit into sGHO become eligible for rewards distributed through [Merkl](https://app.merkl.xyz/).

These rewards are not automatically added to the sGHO balance, they must be claimed separately.

Users can claim rewards in two ways:

* Through the [ACI Merit UI](https://apps.aavechan.com/merit/ethereum-sgho) for a simple interface to view and claim rewards
* Using the SDK

Follow these steps to claim rewards using the SDK:

#### 1. Fetch the Claimable Rewards

First, determine if a user has claimable rewards.

* React
* TypeScript
* GraphQL

Use the useUserMeritRewards hook to fetch the user's sGHO claimable rewards and the transaction to claim them.

* **Loading State**
* **React Suspense**

```
const { data, loading, error } = useUserMeritRewards({  user: EvmAddress,  chainId: ChainId,});
```

Fetch the user's claimable rewards and the transaction to claim them.

**sGHO Rewards**

```
import { useUserMeritRewards, evmAddress, chainId } from "@aave/react";
// …
const sGHO_ADDRESS = evmAddress("0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d");
const { data, loading, error } = useUserMeritRewards({  user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"),  chainId: chainId(1),  filter: {    tokens: [sGHO_ADDRESS],  },});
if (loading) {  return <p>Loading claimable rewards...</p>;}
if (error) {  return <p>Error: {error.message}</p>;}
// data: UserMeritRewards | null
```

If data is null, the user has no sGHO claimable rewards.

#### 2. Claim Rewards

Finally, if the user has claimable rewards, they can claim them by sending the transaction.

* React
* TypeScript
* GraphQL

Use the useSendTransaction hook for the [wallet library of your choice](https://aave.com/docs/getting-started/react#integrations-send-aave-transactions) to send the transactions in the execution plan.

**Viem**

```
import { useWalletClient } from "wagmi";import { useUserMeritRewards } from "@aave/react";import { useSendTransaction } from "@aave/react/viem";
// …
const { data: walletClient } = useWalletClient();const { data } = useUserMeritRewards({  // …  suspense: true,});
const [sendTransaction, sending] = useSendTransaction(walletClient);
// …
const execute = async () => {  if (data !== null) {    const result = await sendTransaction(data.transaction);
    if (result.isErr()) {      console.error(result.error.message);    } else {      console.log("sGHO claim rewards successful with hash:", result.value);    }  }};
```

For more details, see the GHO Savings Upgrade [forum post](https://governance.aave.com/t/arfc-gho-savings-upgrade/21680).


# Umbrella

Aave Umbrella is a modular, onchain risk management system that automates bad debt coverage for Aave v3 pools. It enables users to stake wrapped aTokens or GHO, and earn protocol rewards.

### System Overview

Umbrella is built from three main contract types:

* **UmbrellaCore:** Orchestrates deficit monitoring, slashing, and asset coverage for each Aave v3 pool.
* **StakeToken:** ERC4626 Vault per asset and network that handles staking, cooldown, slashing, and integrates with the rewards controller.
* **RewardsController:** Manages multi-token rewards, emission curves, and user reward accounting.
* **UmbrellaBatchHelper**: Periphery contract enabling multiple actions to be batched into a single transaction.

### Staking

To participate, users deposit supported assets (wrapped aTokens or GHO) into the appropriate StakeToken contract. This action mints shares representing their position. The StakeToken uses an exchange rate that starts at 1:1 and only decreases if slashing occurs.

Staking can be performed with a standard ERC20 approve and deposit, or with EIP-2612 permit signature using depositWithPermit. Users may also set a cooldown operator to manage their cooldowns.

```
IERC20 underlying = IERC20(stakeToken.asset());underlying.approve(address(stakeToken), amount);stakeToken.deposit(amount, msg.sender);
```

### Unstaking

To withdraw, users must first activate a cooldown by calling cooldown(). The cooldown period is 20 days (configurable by governance), followed by a 2-day unstake window. During cooldown, rewards continue to accrue and funds remain slashable. Only one cooldown record is allowed per user at a time. If a user transfers shares after activating cooldown, the amount available for withdrawal is reduced. Depositing more after cooldown does not affect the cooldowned amount.

After the cooldown period, users can withdraw within the unstake window using redeem or withdraw. If the window is missed, the cooldown must be restarted. Withdrawals are always subject to the current exchange rate, which may have changed due to slashing.

```
stakeToken.cooldown();// ...wait for cooldown period...stakeToken.redeem(shares, msg.sender, msg.sender);
```

### Slashing

Slashing is triggered automatically by UmbrellaCore when a deficit in the corresponding Aave pool exceeds the configured offset. Slashing reduces total assets in the StakeToken, lowering the value of all shares. The contract enforces a minimum assets floor to prevent full depletion. Only UmbrellaCore (the owner) can call slash, and slashed assets are sent to the Aave Collector for deficit coverage.

```
function slash(uint256 amount) external onlyOwner;
```

### Rewards

Rewards are managed by the RewardsController, which supports up to 8 reward tokens per StakeToken. Emission rates are governed by a piecewise linear curve, targeting optimal liquidity. Below the target liquidity, rewards are boosted to attract stakers; at target, emission is maximized; above target, emission tapers off to discourage over-staking. Governance sets up new assets and rewards, while a Rewards Admin can adjust emission rates and distribution end times.

Users can claim all available rewards for their assets at any time, or authorize a claimer to do so on their behalf.

```
rewardsController.claimAllRewards([address(stakeToken)], msg.sender);
```

To claim a specific reward:

```
rewardsController.claimRewards(    [address(stakeToken)],    amount,    msg.sender,    rewardToken);
```

To set a claimer:

```
rewardsController.setClaimer(user, claimer);
```

### Deployed Contracts

| Name                                                | Address                                                                                                               |   |
| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | - |
| **UMBRELLA**                                        | [0xD400fc38ED4732893174325693a63C30ee3881a8](https://etherscan.io/address/0xD400fc38ED4732893174325693a63C30ee3881a8) |   |
| **UMBRELLA\_IMPL**                                  | [0x929e21D24D3f2A529621AdC248D227012B72646d](https://etherscan.io/address/0x929e21D24D3f2A529621AdC248D227012B72646d) |   |
| **UMBRELLA\_STAKE\_TOKEN\_IMPL**                    | [0x75e8aC0c063B6966E2A9954adEdf39BdE9370197](https://etherscan.io/address/0x75e8aC0c063B6966E2A9954adEdf39BdE9370197) |   |
| **UMBRELLA\_REWARDS\_CONTROLLER**                   | [0x4655Ce3D625a63d30bA704087E52B4C31E38188B](https://etherscan.io/address/0x4655Ce3D625a63d30bA704087E52B4C31E38188B) |   |
| **UMBRELLA\_REWARDS\_CONTROLLER\_IMPL**             | [0x85C3371044e49782DbE3dC23de1D77a078aFb5d0](https://etherscan.io/address/0x85C3371044e49782DbE3dC23de1D77a078aFb5d0) |   |
| **PERMISSIONED\_PAYLOADS\_CONTROLLER**              | [0xF86F77F7531B3374274E3f725E0A81D60bC4bB67](https://etherscan.io/address/0xF86F77F7531B3374274E3f725E0A81D60bC4bB67) |   |
| **PERMISSIONED\_PAYLOADS\_CONTROLLER\_EXECUTOR**    | [0x2759de67aD133C747C9f41d56F1b8A343cE679a1](https://etherscan.io/address/0x2759de67aD133C747C9f41d56F1b8A343cE679a1) |   |
| **UMBRELLA\_BATCH\_HELPER**                         | [0xCe6Ced23118EDEb23054E06118a702797b13fc2F](https://etherscan.io/address/0xCe6Ced23118EDEb23054E06118a702797b13fc2F) |   |
| **UMBRELLA\_CONFIG\_ENGINE**                        | [0x3f3EfAeba02bbA78BA7E89Dc6Ec503C8fe5fd5a4](https://etherscan.io/address/0x3f3EfAeba02bbA78BA7E89Dc6Ec503C8fe5fd5a4) |   |
| **DATA\_AGGREGATION\_HELPER**                       | [0xcc8FD820B1b9C5EBACA8615927f2fFc1f74B9dB3](https://etherscan.io/address/0xcc8FD820B1b9C5EBACA8615927f2fFc1f74B9dB3) |   |
| **DEFICIT\_OFFSET\_CLINIC\_STEWARD**                | [0x6c1DC85f2aE71C3DAcd6E44Bb57DEeF61b540a5A](https://etherscan.io/address/0x6c1DC85f2aE71C3DAcd6E44Bb57DEeF61b540a5A) |   |
| **AAVE**                                            | [0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9](https://etherscan.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9) |   |
| **AAVE\_ORACLE**                                    | [0x547a514d5e3769680Ce22B2361c10Ea13619e8a9](https://etherscan.io/address/0x547a514d5e3769680Ce22B2361c10Ea13619e8a9) |   |
| **STK\_AAVE**                                       | [0x4da27a545c0c5B758a6BA100e3a049001de870f5](https://etherscan.io/address/0x4da27a545c0c5B758a6BA100e3a049001de870f5) |   |
| **GHO**                                             | [0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f](https://etherscan.io/address/0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f) |   |
| **GHO\_ORACLE**                                     | [0x3f12643d3f6f874d39c2a4c9f2cd6f2dbac877fc](https://etherscan.io/address/0x3f12643d3f6f874d39c2a4c9f2cd6f2dbac877fc) |   |
| **STK\_GHO**                                        | [0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d](https://etherscan.io/address/0x1a88Df1cFe15Af22B3c4c783D4e6F7F9e0C1885d) |   |
| **STK\_AAVE\_WSTETH\_BALANCER\_POOL\_V2**           | [0x9eDA81C21C273a82BE9Bbc19B6A6182212068101](https://etherscan.io/address/0x9eDA81C21C273a82BE9Bbc19B6A6182212068101) |   |
| **STK\_AAVE\_WSTETH\_BALANCER\_POOL\_V2\_ORACLE**   | [0xADf86b537eF08591c2777E144322E8b0Ca7E82a7](https://etherscan.io/address/0xADf86b537eF08591c2777E144322E8b0Ca7E82a7) |   |
| **STK\_AAVE\_WSTETH\_BALANCER\_POOL\_V2\_MIGRATOR** | [0xecD4bd3121F9FD604ffaC631bF6d41ec12f1fafb](https://etherscan.io/address/0xecD4bd3121F9FD604ffaC631bF6d41ec12f1fafb) |   |
| **STK\_AAVE\_ETH\_BALANCER\_POOL\_V1** (deprecated) | [0xa1116930326D21fB917d5A27F1E9943A9595fb47](https://etherscan.io/address/0xa1116930326D21fB917d5A27F1E9943A9595fb47) |   |
| **STK\_AAVE\_ETH\_BALANCER\_POOL\_V1** (deprecated) | [0x209Ad99bd808221293d03827B86cC544bcA0023b](https://etherscan.io/address/0x209Ad99bd808221293d03827B86cC544bcA0023b) |   |

### Resources

* [Smart Contracts](https://github.com/aave-dao/aave-umbrella)
* [Frontend Implemenation](https://github.com/aave-dao/aave-umbrella-ui)

\ <br>


# Tydro Vaults

Tydro Vaults are ERC-4626 compliant yield-bearing vaults that allow users to supply and withdraw ERC-20 tokens supported by Aave V3. Vaults manage the supply and withdrawal of assets in the Aave Protocol while enabling vault managers to take a fee on the yield earned.

To deploy a vault, clone and deploy from the [Aave Vault contract repository](https://github.com/aave/aave-vault/).

### Aave ERC-4626 Vaults

#### Overview

Aave Vaults follow the [ERC-4626 Tokenized Vault Standard](https://eips.ethereum.org/EIPS/eip-4626), which standardizes the interface for yield-bearing vaults. This standard simplifies integration with various applications and aggregators while improving interoperability across the DeFi ecosystem.

Each vault allows depositors to:

* Deposit supported tokens (assets) and receive vault shares in return
* Redeem vault shares for the underlying assets plus accrued yield
* Automatically earn yield from Aave V3 markets without direct interaction with the protocol

#### Architecture

Aave Vaults consist of three key components:

1. **ERC-4626 Interface**: Standardized methods for deposit, withdrawal, and accounting of assets.
2. **Yield Strategy**: Manages deposits into Aave V3 markets and handles yield accrual.
3. **Fee Management**: Enables vault managers to collect a percentage of the yield generated.

When a user deposits an asset into a vault:

* The vault mints proportional vault shares (ERC-20 tokens) to the user
* The vault deposits the underlying assets into the corresponding Aave V3 market
* The vault receives aTokens from Aave, which automatically accrue yield
* Yield is reflected in the increasing value of vault shares over time

#### Fee Structure

Vault managers can set a fee percentage on the yield generated by the vault. This fee structure includes:

* **Performance Fee**: A percentage of the yield earned that goes to the vault manager
* **Max Fee**: A maximum limit on the performance fee that can be charged
* **Fee Recipient**: The address that receives the collected fees

Fees are collected when yield is realized through:

* User withdrawals or redemptions
* Explicit fee collection by the vault manager

The fee is only applied to the yield portion of the assets and not to the principal amount deposited by users.

#### Interacting with Vaults

Vaults implement the standard ERC-4626 interface with methods such as:

* deposit(uint256 assets, address receiver): Deposit assets and receive vault shares
* withdraw(uint256 assets, address receiver, address owner): Withdraw assets by burning vault shares
* mint(uint256 shares, address receiver): Mint exact amount of shares by depositing assets
* redeem(uint256 shares, address receiver, address owner): Redeem shares for underlying assets

Additionally, vaults provide view functions to check:

* totalAssets(): Total assets managed by the vault
* convertToShares(uint256 assets): Convert asset amount to vault shares
* convertToAssets(uint256 shares): Convert vault shares to asset amount
* previewDeposit(uint256 assets): Preview shares received for a deposit
* previewWithdraw(uint256 assets): Preview shares needed for a withdrawal

For a detailed contract reference, see [here](https://aave.com/docs/smart-contracts/vaults).

#### Benefits for Users

* **Simplified Yield**: Earn yield from Aave V3 without managing multiple transactions
* **Gas Efficiency**: Lower gas costs compared to direct protocol interactions
* **Standard Interface**: Easier integration with other DeFi protocols and applications
* **Composability**: Vault shares can be used in other DeFi applications

#### Benefits for Vault Managers

* **Yield Capture**: Earn fees on yield generated by user deposits
* **Customization**: Configure fee parameters to suit different strategies
* **Standardization**: Leverage the ERC-4626 standard for broader integration


# Risks

<figure><img src="/files/pYvFtnilNLIzphQQ73gN" alt=""><figcaption></figcaption></figure>

Tydro offers non-custodial access to onchain liquidity but, like any DeFi system, it carries certain risks. Robust risk management measures, including smart contract audits and security frameworks, are in place to help mitigate them. Below is an overview of key risks and mitigation efforts.

### **Smart Contract Risk**

Tydro’s lending engine is powered entirely by decentralised smart contracts. All actions including supplying, borrowing, and liquidation are executed through permissionless contracts, which reduces custodial risk. These contracts undergo audits and security reviews, but no system is entirely free from potential bugs or vulnerabilities. Users should remain aware of the risks involved when interacting with smart contracts.

### **Oracle Risk**

Tydro relies on external oracles for price feeds and data, including redemption ratios for liquid staking tokens. If an oracle fails or is compromised, it could lead to incorrect asset valuations. To mitigate this, Tydro uses decentralised oracle networks such as Chainlink, which are designed to deliver tamper-resistant and reliable data.

### **Collateral Risk**

The value and liquidity of assets used as collateral can fluctuate. A significant drop in collateral value may result in undercollateralisation or liquidation. To manage this, each asset listed on Tydro is configured with loan-to-value ratios and liquidation thresholds that reflect current market conditions.

### Network / Bridge Risk

Tydro is deployed across multiple blockchains. While the protocol does not depend on cross-chain bridges to move liquidity, multichain deployment increases exposure to network-specific risks such as congestion, downtime, or chain vulnerabilities. These risks are assessed before expanding to new networks.

For additional information on Tydro risk management, see <mark style="color:blue;">Security & Audits.</mark>


# Addresses

<table><thead><tr><th width="285">Name</th><th width="456">Address</th></tr></thead><tbody><tr><td>TydroProtocolDataProvider</td><td>0x96086C25d13943C80Ff9a19791a40Df6aFC08328</td></tr><tr><td>ACLAdmin</td><td>0x1dF462e2712496373A347f8ad10802a5E95f053D</td></tr><tr><td>ACLManager</td><td>0x86E2938daE289763D4e09a7e42c5cCcA62Cf9809</td></tr><tr><td>Collector</td><td>0x9138E2cAdFEB23AFFdc0419F2912CaB8F135dba9</td></tr><tr><td>ConfigEngine</td><td>0xea9989569Cf2D860597b4d649c9A963c15ab84fa</td></tr><tr><td>ATokenInstance</td><td>0xd8247C7926841337E8adf9fD9E87026992C45062</td></tr><tr><td>DefaultIncentivesController</td><td>0xD93e3Ae8f69D04d484d1652Ca569d4b0522414DF</td></tr><tr><td>VariableDebtToken</td><td>0x294daB91f3539f5a74Ed995a59235eE62A14A345</td></tr><tr><td>Dustbin</td><td>0xb50881a9e7Ca0d1c08A59f4da1dE2f3D75B1E34E</td></tr><tr><td>EmissionManager</td><td>0x9CbcEf2c44cF28ff2aa36Bff7BaB315398209A79</td></tr><tr><td>L2Encoder </td><td>0x988B5d3863bdEE83339Be41cD31344Dfd9FD197c</td></tr><tr><td>TydroOracle</td><td>0x4758213271BFdC72224A7a8742dC865fC97756e1</td></tr><tr><td>Pool</td><td>0x2816cf15F6d2A220E789aA011D5EE4eB6c47FEbA</td></tr><tr><td>PoolAddressesProvider</td><td>0x4172E6aAEC070ACB31aaCE343A58c93E4C70f44D</td></tr><tr><td>PoolAddressesProviderRegistry</td><td>0x501B4c19dd9C2e06E94dA7b6D5Ed4ddA013EC741</td></tr><tr><td>PoolConfigurator</td><td>0x4f221e5c0B7103f7e3291E10097de6D9e3BfC02d</td></tr><tr><td>PoolConfiguratorInstance</td><td>0xe892E40C92c2E4D281Be59b2E6300F271d824E75</td></tr><tr><td>L2PoolInstance</td><td>0x2aB3580a805fB10CbAd567212C70e26C1B6769eC</td></tr><tr><td>StataFactory</td><td>0x5362dBb1e601abF3a4c14c22ffEdA64042E5eAA3</td></tr><tr><td>UIIncentiveDataProvider</td><td>0x25Ec457d1778b0E5316e7f38f3c22baF413F1A8C</td></tr><tr><td>UIPoolDataProvider</td><td>0x39bc1bfDa2130d6Bb6DBEfd366939b4c7aa7C697</td></tr><tr><td>WalletBalanceProvider</td><td>0xB1532b76D054c9F9E61b25c4d91f69B4133E4671</td></tr><tr><td>WETHGateway</td><td>0xDe090EfCD6ef4b86792e2D84E55a5fa8d49D25D2</td></tr><tr><td>BorrowLogic</td><td>0xFeD9871528E713B5038c4c44BbE7a315f56cAdc6</td></tr><tr><td>EModeLogic</td><td>0xD1bddC05A3BB5A7907d82A1b4F1E21dBCE69c3d5</td></tr><tr><td>FlashLoanLogic</td><td>0x5e84CEe2afb7B37d2AB14722C39A7c1C26F5B0BB</td></tr><tr><td>LiquidationLogic</td><td>0x36Ae486289bB807C3C79A1427b9c3D934294ef43</td></tr><tr><td>PoolLogic</td><td>0xE51B69e5722Bf547866A4d7Bc190c6e81b626806</td></tr><tr><td>SupplyLogic</td><td>0x034Fd14b9Ae6bB066a1F9f85A55e990b0b25c168</td></tr></tbody></table>


# Risk Parameters

| **Parameter**            | **KBTC** | **USDG**   | **USDT0**   | **WETH** |
| ------------------------ | -------- | ---------- | ----------- | -------- |
| Isolation Mode           | No       | No         | No          | No       |
| Borrowable               | Yes      | Yes        | Yes         | Yes      |
| Collateral Enabled       | Yes      | No         | Yes         | Yes      |
| Supply Cap               | 1,500    | 50,000,000 | 250,000,000 | 40,000   |
| Borrow Cap               | 200      | 40,000,000 | 220,000,000 | 10,000   |
| Debt Ceiling             | -        | -          | -           | -        |
| LTV                      | 72%      | -          | 75%         | 80%      |
| LT                       | 77%      | -          | 78%         | 83%      |
| Liquidation Bonus        | 7.5%     | -          | 4.5%        | 7.5%     |
| Liquidation Protocol Fee | 10%      | -          | 10%         | 10%      |
| Variable Base            | 0%       | 0%         | 0%          | 0%       |
| Variable Slope1          | 4.0%     | 5.5%       | 5.5%        | 2.7%     |
| Variable Slope2          | 80%      | 50%        | 40%         | 40%      |
| Uoptimal                 | 45%      | 80%        | 90%         | 90%      |
| Reserve Factor           | 50%      | 10%        | 10%         | 15%      |


# Code Licensing

Tydro, a fork of the Aave Protocol operates on decentralized blockchain networks, with smart contracts that are self-executing and publicly auditable. These smart contracts and peripheral interfaces are licensed to define and regulate the use of the underlying code. The code exists across multiple GitHub repositories, and below are examples of some key licenses that apply to different Aave components:

* **Aave v3.3 Smart Contracts**: Business Source License 1.1 permits non-commercial use and modification, restricting competitive use for four years, with a transition to the MIT License on March 6, 2027​. ([GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/LICENSE))
* **Aave v3.2 Smart Contracts**: Business Source License 1.1 permits non-commercial use and modification, restricting competitive use for four years, with a transition to the MIT License on March 6, 2027​. ([GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/LICENSE))
* **GHO Stablecoin**: MIT License grants free and unrestricted rights to use, copy, modify, and distribute the software, provided the original copyright notice and license are included. The software is provided "as is," with no warranties or liabilities for any issues arising from its use. ([GitHub](https://github.com/aave/gho-core/blob/main/LICENSE))
* **Aave v2 Smart Contracts**: GNU Affero General Public License ([GitHub](https://github.com/aave/protocol-v2/blob/master/LICENSE.md))
* **Aave v1 Smart Contracts**: GNU Affero General Public License ([GitHub](https://github.com/aave/aave-protocol/blob/master/LICENSE.md))
* **Aave Labs Interface**: All Rights Reserved. ([GitHub](https://github.com/aave/interface/blob/main/LICENSE.md))


# Bridge to INK

To participate in the Tydro ecosystem, users may need to transfer assets from other blockchains into Ink. This is achieved through cross-chain bridges, which are independent protocols that enable tokens to move between networks. Bridging allows users to bring liquidity securely into Ink while maintaining compatibility with Tydro and other Ink-based applications.

The Ink protocol does not operate a native bridge. All bridging is managed by third-party services that have added support for the Ink network.

Bridges use different mechanisms to move liquidity. Some rely on liquidity pools and relayers, while others use lock and mint or burn and redeem models. Each approach carries its own trade-offs in terms of speed, cost, security, and trust. Users should select the provider that best matches their needs.

Here are some of the ways you can bridge assets into Ink:

#### Bungee Exchange <a href="#bungee-exchange" id="bungee-exchange"></a>

Bungee is an aggregator of multiple bridges, providing a simple and unified interface for transferring assets to INK. It automatically routes your transfer through the most efficient bridge, minimizing cost and time.

Best For: Users who want to bridge quickly and cheaply without manually selecting routes or understanding underlying protocols.

Bridge to INK: [Bungee Bridge](https://www.bungee.exchange/?fromChainId=10\&fromTokenAddress=0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\&toChainId=57073\&toTokenAddress=0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee)​

#### Superbridge <a href="#superbridge" id="superbridge"></a>

Superbridge focuses on simplicity and user experience, offering a streamlined interface for bridging ETH and other assets to INK. It abstracts the technical details while maintaining reliability and minimal slippage.

Best For:Users bridging ETH or native assets who want a clean UX and little slippage.

Bridge to INK: [Superbridge](https://superbridge.app/optimism)​

#### USDT0 Native Transfer <a href="#usdt0-native-transfer" id="usdt0-native-transfer"></a>

USDT0 is a native stablecoin transfer mechanism designed for direct movement of USDT between supported Superchain networks and INK. It eliminates traditional bridging complexity by using canonical token contracts on each network, ensuring instant settlement and no wrapping or synthetic assets.

Best For: Users who want to bridge stablecoins such as USDT or USDT0 into INK quickly, securely, and without conversion risk.

Bridge to INK: [USDT0 Site](https://usdt0.to/transfer?source=ethereum\&destination=ink)​

#### Eco Bridge <a href="#eco-bridge" id="eco-bridge"></a>

Eco focuses on simplicity and user experience. It provides a straightforward interface for moving assets into Ink without exposing much of the underlying complexity.

Eco is often the best choice for users who want to bridge stablecoins only.

Bridge to INK: [Eco Portal](https://portal.eco.com/)​

#### Across <a href="#across" id="across"></a>

Across is optimised for speed and low cost, particularly when transferring from Ethereum mainnet and Layer 2 networks. It relies on a relayer network that fronts liquidity to deliver funds quickly, with settlement finalised on the source chain later.

Across is well-suited for users who want fast transfers from rollups with minimal fees

Bridge to INK: [Across Bridge ](https://app.across.to/bridge?)

#### Aave (GHO Bridge) <a href="#eco-bridge" id="eco-bridge"></a>

Aave is a leading DeFi protocol for lending and borrowing crypto assets. It also launched GHO, a decentralized stablecoin that users can mint by supplying collateral. GHO is available across multiple networks and supports native bridging via Aave’s cross-chain system.

Best For: Purchasing or minting GHO and bridging it from Ethereum, Base, or Arbitrum to INK.

Supported Assets: GHO

Bridge to INK: [Aave Markets](https://app.aave.com/markets/)

## **Bridge Comparison Table**

| **Bridge**      | **Best For**                                                              | **Supported Assets**  | **Approx. Fee**              | **Link**                                                                                          |
| --------------- | ------------------------------------------------------------------------- | --------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------- |
| **Bungee**      | Cheapest, fastest option across multiple bridges                          | ETH, USDT0, USDC, GHO | Varies (auto-routed)         | [Bungee Bridge](https://www.notion.so/Updated-Bridge-Doc-29759f6be93380b19c2cc71e83bfe0dc?pvs=21) |
| **Superbridge** | Bridging ETH from Ethereum mainnet with zero fees                         | ETH, others           | ETH: **Free**; Others: 0.05% | [Superbridge](https://www.notion.so/Updated-Bridge-Doc-29759f6be93380b19c2cc71e83bfe0dc?pvs=21)   |
| **USDT0**       | Simple & safe USDT bridging with no wrapping                              | USDT / USDT0          | \~**0.1**                    | [USDT0 Site](https://usdt0.to/transfer?source=ethereum\&destination=ink)                          |
| **Across**      | Fast ETH transfers from Layer 2s                                          | ETH                   | Varies by network            | [Across Bridge](https://www.notion.so/Updated-Bridge-Doc-29759f6be93380b19c2cc71e83bfe0dc?pvs=21) |
| **Aave**        | \*\*Aave (GHO)\*\*Purchasing or minting **GHO** and bridging it to INKGHO | GHO                   | Varies by network            | [Aave Markets](https://app.aave.com/markets/)                                                     |

#### **Tip: A Simple Way to Get Started**

One of the smoothest ways to get major assets into Ink and start using Tydro is:

1. Bridge USDT to INK using [USDT0](https://usdt0.to/transfer?source=ethereum\&destination=ink)
2. Then, swap USDT0 for other tokens on [Velodrome (DEX)](https://velodrome.finance/swap)

This route minimizes steps and lets you access key assets on Ink with less friction.


# Web3

Web3 is the next evolution of the internet, where people have ownership and control over their data, digital identity, and online relationships. Together, these elements form what is often called social capital.

In Web2, companies like Amazon, Google, and Meta store user data on private servers and monetise it by selling to advertisers. While this model created free and easy-to-use applications, it also led to issues such as privacy loss, data manipulation, and limited opportunities for users to benefit directly from their activity.

Web3 addresses these challenges by using blockchain technology, which is designed around user ownership. People can monetise their data on their own terms, move their profiles and assets across platforms, and interact on a more equal footing with applications. The result is a more open and balanced internet, where users have both a stake and a voice.

## Blockchain

A blockchain is a decentralised, distributed ledger that records and verifies transactions across a network of computers. Unlike traditional databases controlled by central authorities, a blockchain is maintained collectively by its participants (nodes), each of which stores a complete copy of the ledger.

Transactions are grouped into units called blocks. Once validated by the network through consensus, a block is added sequentially to the chain. Each block references the one before it, creating a chronological record that is tamper-resistant and transparent. Altering past data would require rewriting all subsequent blocks with majority approval, making the system highly secure.

## Smart Contracts

Smart contracts are programs that automatically execute predefined actions when conditions are met, such as transferring tokens or updating balances. They eliminate the need for intermediaries, making transactions faster, cheaper, and less prone to error or manipulation.

Smart contracts run on decentralised networks like Ethereum, where their code is executed deterministically by all nodes. This guarantees that contracts run exactly as written, providing both transparency and immutability. As a result, smart contracts are a foundation for decentralised applications in areas like finance, identity, and governance.

## DeFi

DeFi uses blockchains and smart contracts to provide financial services without centralised intermediaries such as banks or brokers. The goal is to create a system that is open, transparent, and accessible to anyone with an internet connection.

In DeFi, transactions are validated by decentralised networks instead of middlemen. This reduces costs, lowers barriers to entry, and increases efficiency. DeFi applications first grew on Ethereum and now extend to Layer 2 networks like Arbitrum, Optimism, and zkSync, offering faster and cheaper transactions.

## Stablecoins

Stablecoins are digital assets designed to maintain a stable value relative to a reference asset, usually a fiat currency like the US dollar. They are widely used for payments, remittances, trading, and as safe havens during volatility.

Common use cases:

* Remittances: Faster, cheaper cross-border transfers.
* DeFi: Used for supplying, borrowing, and yield strategies.
* Hedging: Moving out of volatile assets without converting to fiat.
* Payments: Merchants can accept them without price risk.

Types of stablecoins:

* Fiat-collateralised: Backed 1:1 by reserves of fiat (e.g., USDT, USDC).
* Decentralised: Issued and managed by smart contracts using on-chain collateral (e.g., GHO).
* Algorithmic: Maintain their peg through supply adjustments like minting and burning.

Stablecoins serve as a bridge between traditional finance and decentralised systems, enabling predictable value transfer inside Web3.


# Glossary

| Term                  | Description                                                                                                                                                                                                             |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| aTokens               | Interest-bearing tokens received by users when they supply assets to Tydro. aTokens represent the user’s share of the liquidity pool and accrue interest in real time.                                                  |
| APY                   | Annual Percentage Yield, which is the yield or interest earned over a year including compounding. This differs from APR, which does not account for compounding.                                                        |
| Borrow Cap            | A limit on the maximum amount of a specific asset that can be borrowed from the protocol. Borrow caps help manage exposure and reduce systemic risk.                                                                    |
| Collateral            | An asset supplied to Tydro to secure a borrowing position. The collateral value must exceed the borrowed amount to ensure solvency.                                                                                     |
| Cooldown Period       | A mandatory waiting period that users must observe before unstaking their tokens from a staking or safety module                                                                                                        |
| Credit Delegation     | A feature that allows one user to delegate their borrowing power to another user. The delegate can then take out loans using the delegator’s collateral, facilitated through Tydro’s smart contracts                    |
| Debt Ceiling          | The maximum amount of debt that can be issued against an isolated asset, used to limit risk exposure to a single collateral type.                                                                                       |
| E-Mode                | Efficiency Mode allows borrowers to access higher borrowing power when using correlated assets (e.g., stablecoins).                                                                                                     |
| Flash Loan            | A type of uncollateralised loan offered by Tydro, which must be borrowed and repaid within a single transaction block.                                                                                                  |
| GHO                   | A decentralised, overcollateralised stablecoin that is fully backed, transparent, and native to the Ink ecosystem.                                                                                                      |
| Health Factor         | A ratio that determines the safety of a user’s loan position. It compares the user’s collateral value against borrowed assets. A health factor below 1 triggers liquidation.                                            |
| Isolation Mode        | A mode that restricts borrowing certain assets in isolation to mitigate risk. It limits exposure by restricting debt expansion to a single collateral type.                                                             |
| Liquidation           | The process triggered when a borrower’s health factor falls below 1. Collateral is sold to repay part of the debt and restore the position to a safer level.                                                            |
| Liquidation Bonus     | An additional incentive paid to liquidators when purchasing undercollateralised assets during liquidation. Expressed as a percentage.                                                                                   |
| Liquidation Threshold | The collateral-to-debt ratio at which a loan becomes eligible for liquidation. Defined per asset.                                                                                                                       |
| Liquidity Index       | Tracks cumulative interest earned by a reserve over time, used to calculate interest accrual accurately.                                                                                                                |
| Loan To Value (LTV)   | The maximum percentage of a collateral asset’s value that can be borrowed. For example, an LTV of 75% means 1 ETH of collateral allows borrowing up to 0.75 ETH.                                                        |
| Network Risk          | Risks associated with the underlying blockchains where Tydro is deployed, such as congestion, security vulnerabilities, or downtime.                                                                                    |
| Oracle                | A decentralised service providing external data (such as asset prices) to Tydro. Oracles are critical for determining collateral values and triggering liquidations.                                                    |
| Ray units             | A unit of precision with 27 decimals used internally by Tydro for calculations such as interest and exchange rates.                                                                                                     |
| Reserve Factor        | A portion of interest paid by borrowers that is allocated to the protocol treasury to support long-term sustainability.                                                                                                 |
| Risk Admin            | An entity or automated process responsible for adjusting risk parameters such as LTVs, borrow caps, or liquidation thresholds. These adjustments ensure the protocol remains secure and aligned with market conditions. |
| Safety Module         | A staking mechanism where tokens are staked as insurance in case of a shortfall event. Stakers may earn rewards but are exposed to slashing risk.                                                                       |
| Siloed Borrowing      | A restriction that allows certain assets to be borrowed only in isolation. This helps mitigate risks of illiquid or volatile assets.                                                                                    |
| Supply Cap            | A limit on the total amount of a specific asset that can be supplied to the protocol. Helps control exposure to risky assets.                                                                                           |
| Utilization Rate      | The ratio of borrowed assets to total supplied assets in a reserve. Higher utilisation indicates stronger borrowing demand.                                                                                             |


# Brand Kit 🟡

### Logo

The Tydro logo consists of an icon and word mark.

* ﻿﻿You may use the icon alone on websites and social media
* ﻿﻿You may never use the word mark alone

<figure><img src="/files/YOMMOYpgLmBYQoU6Istq" alt=""><figcaption></figcaption></figure>

<mark style="color:blue;">► Downloadable Assets 📂</mark>

### Brand Colors

The core colors are

\#031C43 - Navy blue

\#EAEA3B - Accent Font Color Yellow

\#686B82 - Accent Background Color Yellow

Linear Accent - Gradients are used sparingly and contain a small amount of glow

\#686B82 - Neon Yellow

\#0OFFFF - Neon Green

\#7285FF - Neon Blue

<figure><img src="/files/zbXQLSROumOqm0VqyR43" alt=""><figcaption></figcaption></figure>

### Typography

**Primary Font**                                                         &#x20;

Britti Sans                                                            &#x20;

Usage: Headlines   &#x20;

**Secondary Font**          &#x20;

Geist                                &#x20;

<figure><img src="/files/yqA8bfGrSwgXN8VZFqqw" alt=""><figcaption></figcaption></figure>

### **Expansions & Buttons**

**Connect Wallet Config**                                      &#x20;

Usage: Headlines           &#x20;

**Not Connected**                                   &#x20;

Usage: Body text, paragraphs, labels


