# Aave V3 Documentation (full) > Every Aave V3 page in one file. It covers Aave V3 only: other sections have their own files, listed at https://aave.com/docs/llms.txt. Source: https://aave.com/docs/aave-v3/overview.md # Aave V3 Overview Aave V3 is a non-custodial liquidity protocol on Ethereum and other major networks. It provides onchain infrastructure to integrate supply and borrow into applications via smart contracts and AaveKit. Developers can use [AaveKit React](./getting-started/react), [AaveKit TypeScript](./getting-started/typescript), or [AaveKit API](./getting-started/graphql) to integrate core protocol [operations](./markets/supply) and [data](./markets/data) for wallets, exchanges, fintech platforms, and DeFi-native products. ## Supply Supplying assets to Aave lets users earn interest and, optionally, use supplied tokens as collateral for borrowing. When an asset is supplied, aTokens (e.g., aUSDC, aWETH) are minted as interest-bearing ERC-20 tokens whose balance increases over time from borrowing activity in the pool. Withdrawing redeems aTokens for the underlying asset, including accrued interest, subject to available unborrowed liquidity and the collateralization of any active borrow positions. ## Borrow Borrowing lets users access liquidity by posting supplied assets as collateral. Positions are always over-collateralized, meaning the collateral value must exceed the borrowed amount. Risk is tracked with a _Health Factor_ and per-reserve liquidation thresholds; when the Health Factor drops below 1, collateral can be liquidated. When a user borrows, their debt is represented by variableDebtTokens (e.g., variableDebtUSDC), ERC-20 tokens that track the outstanding borrow balance and accrue interest over time. Borrowers can repay at any time, and positions remain open as long as over-collateralization is maintained. The Health Factor moves with collateral and debt values (prices from oracles and accrued interest). When it falls below 1, the position becomes eligible for liquidation and external liquidators can repay part of the debt in exchange for collateral. ## Interest Rates Interest rates adjust with utilization. V3 uses an interest rate model based on two slopes with an optimal utilization point: below the optimal point, borrow rates rise with the first slope; above it, they rise faster with the second slope. Supplier yields are funded by borrower interest net of the reserve factor. ## Liquidations Positions become eligible for liquidation when a position’s Health Factor falls below 1. A liquidator repays part of the debt and receives collateral at a discount (liquidation bonus). Liquidation threshold and bonus are defined per reserve and surfaced via onchain views. ## Aave Earn Vaults Aave Earn Vaults are ERC-4626 compliant yield-bearing vaults that enable Aave supply positions to be managed with customizable ownership and fee structure. By depositing supported tokens, users receive vault shares that represent their proportional claim on the underlying assets and any yield earned. Shares can be withdrawn at any time for the underlying assets plus accrued yield subject to available liquidity, providing a simple and efficient way to grow holdings. For vault managers, Aave Earn Vaults offer a customizable framework to deploy and manage yield strategies while earning fees on the yield generated by user deposits. The standardized ERC-4626 interface provides compatibility with a wide range of DeFi protocols and applications, making it easy to integrate vaults into broader strategies or platforms. This structure benefits both users seeking passive income and managers looking to build scalable, revenue-generating products on Aave. See the [Vaults Overview](/vaults/simple-earn/overview) for guides to deploy and manage instances of Aave Earn Vaults. ## Aave V3 Key Features Aave V3 improves capital efficiency and risk management over previous versions and runs on multiple networks. ### Efficiency Mode (E-Mode) Efficiency Mode maximizes capital efficiency for correlated assets. When a user supplies and borrows assets within the same E-Mode category (e.g., USD-pegged stablecoins), they benefit from a higher _loan-to-value (LTV)_ ratio. This enables low-slippage, high-leverage strategies like yield farming with staked ETH derivatives or efficient forex trading. Since Aave V3.7, an E-Mode category can be _isolated_. In an isolated category, only the category’s collateral assets contribute to borrowing power, and every other supplied asset is treated as LTV 0. Users with other collateral enabled cannot enter the category, and users inside it cannot enable other collateral. ### Isolation Mode Aave V3.7 removed Isolation Mode, including debt ceilings and the borrowable in isolation flag. Isolated E-Mode categories now cover the same need: listing new or more volatile assets as collateral without exposing the rest of the protocol. ### Siloed Borrowing Aave V3.7 removed Siloed Borrowing, the reserve-level flag that restricted users who borrowed a given asset to borrowing only that asset. > [!NOTE] > Some Aave V3 instances may still run Aave V3.6, with Isolation Mode and Siloed > Borrowing active. `POOL_REVISION()` on the Pool returns `10` on [Aave > V3.6](/resources/changelog#aave-v36) and `11` on [Aave > V3.7](/resources/changelog#aave-v37-part-1). --- ## Next Steps --- Source: https://aave.com/docs/aave-v3/getting-started/react.md # Aave V3 React Quickstart AaveKit React is a collection of React hooks for building decentralized applications on top of the Aave Protocol. It provides a type-safe way to interact with Aave markets, manage user positions, and execute transactions. ## Getting Started ### 1. Install SDK First, install the AaveKit React packages using your package manager of choice. ```bash title="npm" npm install @aave/react@latest ``` ```bash title="yarn" yarn add @aave/react@latest ``` ```bash title="pnpm" pnpm add @aave/react@latest ``` ### 2. Set Up the Client Then, create an `AaveClient` instance that will be used to interact with the protocol. ```ts title="client.ts" import { AaveClient } from "@aave/react"; export const client = AaveClient.create(); ``` > [!NOTE] > `@aave/react` already includes and re-exports `@aave/client`, so you don’t > need to install it. ### 3. Set Up the Provider Next, wrap your app with the `` component and pass the client instance. ```tsx title="App.tsx" import { AaveProvider } from "@aave/react"; import { client } from "./client"; export function App() { return ( ); } ``` ### 4. Start Building You can now start using AaveKit React. ```tsx title="Example" import { useAaveChains } from "@aave/react"; export function SupportedChains() { const { data: chains } = useAaveChains({}); return (

Supported Chains

{chains?.map((chain) => (

{chain.name}

Chain ID: {chain.chainId}
))}
); } ``` ## Integrations AaveKit React includes first-class support for [viem](https://viem.sh/), [ethers v6](https://docs.ethers.org/v6/), [Privy](https://docs.privy.io/wallets/using-wallets/ethereum/send-a-transaction#react), [Dynamic](https://www.dynamic.xyz/docs/react-sdk/quickstart), [thirdweb](https://portal.thirdweb.com/react/v5) and [Turnkey](https://docs.turnkey.com/sdks/react/getting-started). Ensure you have `viem` package installed in your project. ```bash title="npm" npm install viem@2 ``` ```bash title="yarn" yarn add viem@2 ``` ```bash title="pnpm" pnpm add viem@2 ``` Ensure you have `ethers` package installed in your project. ```bash title="npm" npm install ethers ``` ```bash title="yarn" yarn add ethers ``` ```bash title="pnpm" pnpm add ethers ``` Ensure you have `viem` and `@privy-io/react-auth` packages installed in your project. ```bash title="npm" npm install viem@2 @privy-io/react-auth ``` ```bash title="yarn" yarn add viem@2 @privy-io/react-auth ``` ```bash title="pnpm" pnpm add viem@2 @privy-io/react-auth ``` > [!NOTE] > `@privy-io/react-auth` requires the `viem` package. Ensure you have `@dynamic-labs/sdk-react-core` and `@dynamic-labs/ethereum` packages installed in your project. ```bash title="npm" npm install @dynamic-labs/sdk-react-core @dynamic-labs/ethereum ``` ```bash title="yarn" yarn add @dynamic-labs/sdk-react-core @dynamic-labs/ethereum ``` ```bash title="pnpm" pnpm add @dynamic-labs/sdk-react-core @dynamic-labs/ethereum ``` Ensure you have `thirdweb` package installed in your project. ```bash title="npm" npm install thirdweb@5 ``` ```bash title="yarn" yarn add thirdweb@5 ``` ```bash title="pnpm" pnpm add thirdweb@5 ``` Ensure you have `viem`, `@turnkey/viem` and `@turnkey/react-wallet-kit` packages installed in your project. ```bash title="npm" npm install viem@2 @turnkey/viem @turnkey/react-wallet-kit ``` ```bash title="yarn" yarn add viem@2 @turnkey/viem @turnkey/react-wallet-kit ``` ```bash title="pnpm" pnpm add viem@2 @turnkey/viem @turnkey/react-wallet-kit ``` ### Send Aave Transactions To send transactions through the connected wallet, use the `useSendTransaction` imperative hook. ```tsx const [sendTransaction, { loading, error }] = useSendTransaction(/* args */); ``` This hook abstracts the wallet interaction and provides an interface for submitting transactions. Import the `useSendTransaction` hook from the `@aave/react/viem` entry point and wire it up with the viem’s `WalletClient`. ```tsx title="Viem" import { useSendTransaction } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; function MyComponent() { const { data: walletClient } = useWalletClient(); const [sendTransaction, sending] = useSendTransaction(walletClient); // Use with transaction hooks… } ``` > [!NOTE] > The example uses [wagmi](https://wagmi.sh/) to get the `WalletClient` from the > connected wallet. Import the `useSendTransaction` hook from the `@aave/react/ethers` entry point and wire it up with the ethers’s `Signer`. ```tsx title="Ethers" import { useSendTransaction } from "@aave/react/ethers"; import { ethers } from "ethers"; const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); function MyComponent() { const [sendTransaction, sending] = useSendTransaction(signer); // Use with transaction hooks… } ``` Import the `useSendTransaction` hook from the `@aave/react/privy` entry point. ```tsx title="Privy" import { useSendTransaction } from "@aave/react/privy"; function MyComponent() { const [sendTransaction, sending] = useSendTransaction(); // Use with transaction hooks… } ``` Import the `useSendTransaction` hook from the `@aave/react/viem` entry point and pass the Dynamic wallet client. ```tsx title="Dynamic" import { useSendTransaction } from "@aave/react/viem"; import { isEthereumWallet } from "@dynamic-labs/ethereum"; import { useDynamicContext } from "@dynamic-labs/sdk-react-core"; import { useEffect, useState } from "react"; import { WalletClient } from "viem"; function MyComponent() { const { primaryWallet } = useDynamicContext(); const [walletClient, setWalletClient] = useState(null); const [sendTransaction, sending] = useSendTransaction(walletClient); useEffect(() => { if (primaryWallet && isEthereumWallet(primaryWallet)) { primaryWallet.getWalletClient().then(setWalletClient); } }, [primaryWallet]); // Use with transaction hooks… } ``` Import the `useSendTransaction` hook from the `@aave/react/thirdweb` entry point and configure it with your thirdweb client. ```tsx title="thirdweb" import { useSendTransaction } from "@aave/react/thirdweb"; import { createThirdwebClient } from "thirdweb"; const thirdwebClient = createThirdwebClient({ clientId: "", }); function MyComponent() { const [sendTransaction, sending] = useSendTransaction(thirdwebClient); // Use with transaction hooks… } ``` Import the `useSendTransaction` hook from the `@aave/react/viem` entry point and wire it up with a viem `WalletClient` created from Turnkey’s account. ```tsx title="Turnkey" import { useSendTransaction } from "@aave/react/viem"; import { createAccount } from "@turnkey/viem"; import { useTurnkey } from "@turnkey/react-wallet-kit"; import { useEffect, useState } from "react"; import { createWalletClient, http, type WalletClient } from "viem"; import { mainnet } from "viem/chains"; function MyComponent() { const { httpClient, wallets, fetchWalletAccounts } = useTurnkey(); const [walletClient, setWalletClient] = useState(null); const [sendTransaction, sending] = useSendTransaction(walletClient); useEffect(() => { if (!httpClient || !wallets.length) return; fetchWalletAccounts({ wallet: wallets[0] }).then(async ([account]) => { const tkAccount = await createAccount({ client: httpClient, organizationId: account.organizationId, signWith: account.address, }); setWalletClient( createWalletClient({ account: tkAccount, chain: mainnet, transport: http(), }) ); }); }, [httpClient, wallets, fetchWalletAccounts]); // Use with transaction hooks… } ``` Then, use it as described in each operation guide. ### Sign ERC-20 Permits Aave makes use of [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) to allow users to avoid ERC-20 approval before sending transactions. Use the `useERC20Permit` hook to sign ERC-20 permits. Import the `useERC20Permit` hook from the `@aave/react/viem` entry point and wire it up with the viem’s `WalletClient`. ```tsx title="Viem" import { useERC20Permit } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; function MyComponent() { const { data: walletClient } = useWalletClient(); const [signPermit, sending] = useERC20Permit(walletClient); // Use with transaction hooks… } ``` > [!NOTE] > The example uses [wagmi](https://wagmi.sh/) to get the `WalletClient` from the > connected wallet. Import the `useERC20Permit` hook from the `@aave/react/ethers` entry point and wire it up with the ethers’s `Signer`. ```tsx title="Ethers" import { useERC20Permit } from "@aave/react/ethers"; import { ethers } from "ethers"; const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); function MyComponent() { const [signPermit, sending] = useERC20Permit(signer); // Use with transaction hooks… } ``` Import the `useERC20Permit` hook from the `@aave/react/privy` entry point. ```tsx title="Privy" import { useERC20Permit } from "@aave/react/privy"; function MyComponent() { const [signPermit, sending] = useERC20Permit(); // Use with transaction hooks… } ``` Import the `useERC20Permit` hook from the `@aave/react/viem` entry point and pass the Dynamic wallet client. ```tsx title="Dynamic" import { useERC20Permit } from "@aave/react/viem"; import { isEthereumWallet } from "@dynamic-labs/ethereum"; import { useDynamicContext } from "@dynamic-labs/sdk-react-core"; import { useEffect, useState } from "react"; import { WalletClient } from "viem"; function MyComponent() { const { primaryWallet } = useDynamicContext(); const [walletClient, setWalletClient] = useState(null); const [signPermit, sending] = useERC20Permit(walletClient); useEffect(() => { if (primaryWallet && isEthereumWallet(primaryWallet)) { primaryWallet.getWalletClient().then(setWalletClient); } }, [primaryWallet]); // Use with transaction hooks… } ``` Import the `useERC20Permit` hook from the `@aave/react/thirdweb` entry point. ```tsx title="thirdweb" import { useERC20Permit } from "@aave/react/thirdweb"; function MyComponent() { const [signPermit, sending] = useERC20Permit(); // Use with transaction hooks… } ``` Import the `useERC20Permit` hook from the `@aave/react/viem` entry point and wire it up with a viem `WalletClient` created from Turnkey’s account. ```tsx title="Turnkey" import { useERC20Permit } from "@aave/react/viem"; import { createAccount } from "@turnkey/viem"; import { useTurnkey } from "@turnkey/react-wallet-kit"; import { useEffect, useState } from "react"; import { createWalletClient, http, type WalletClient } from "viem"; import { mainnet } from "viem/chains"; function MyComponent() { const { httpClient, wallets, fetchWalletAccounts } = useTurnkey(); const [walletClient, setWalletClient] = useState(null); const [signPermit, sending] = useERC20Permit(walletClient); useEffect(() => { if (!httpClient || !wallets.length) return; fetchWalletAccounts({ wallet: wallets[0] }).then(async ([account]) => { const tkAccount = await createAccount({ client: httpClient, organizationId: account.organizationId, signWith: account.address, }); setWalletClient( createWalletClient({ account: tkAccount, chain: mainnet, transport: http(), }) ); }); }, [httpClient, wallets, fetchWalletAccounts]); // Use with transaction hooks… } ``` Then, use the `signPermit` function as described in the specific operation guide. ## Declarative Hooks All declarative hooks (market data, user positions, etc.) support two ways of operating: loading state and React Suspense. ### Loading State Handle loading state manually in your component: ```tsx title="Loading States" function ChainsList() { const { data, loading, error } = useAaveChains({}); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((chain) => (
{chain.name}
))}
); } ``` ### React Suspense Let React handle loading states automatically through a [Suspense boundary](https://react.dev/reference/react/Suspense). ```tsx title="With Suspense" // Component - no loading states needed function ChainsList() { const { data: chains } = useAaveChains({ suspense: true, // Enable suspense mode }); return (
{chains.map((chain) => (
{chain.name}
))}
); } // Parent - wrap with Suspense boundary function ChainsPage() { return ( Loading …}> ); } ``` You can handle errors in the parent component by wrapping the component with an [error boundary component](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary). ```tsx title="With Error Boundary" import { ErrorBoundary } from "react-error-boundary"; // … function ChainsPage() { return ( Loading …}> ); } ``` ## Imperative Hooks AaveKit React provides imperative hooks that are designed to be triggered manually when you need to perform an operation. Imperative hooks return an execute function and a state object. ```tsx const [execute, state] = useActionHook(); ``` ### Execute Function The `execute` function returns a `ResultAsync`, a thenable object that represents one of two states: - `Ok`: A successful result containing a value of type `T` - `Err`: A failure containing an error of type `E` Awaiting a `ResultAsync` resolves to a `Result`. With a `Result`, you can use the convenient `isOk()` and `isErr()` methods to check the outcome and narrow the type. If you have a `ResultAsync`, you must first `await` it to access those methods. ```ts const result = await execute(); if (result.isOk()) { console.log("Result:", result.value); } else { console.error("Error:", result.error); } ``` This approach avoids reliance on `try/catch` blocks and promotes predictable, type-safe code by ensuring errors are handled explicitly. > [!NOTE] > AaveKit re-exports the [NeverThrow](https://github.com/supermacro/neverthrow) > library. See its docs for details. ### State Object The state object returned by imperative hooks provides information about the current operation status: ```ts const { called, data, error, loading } = state; ``` Where: - `called`: `true` when the operation has been executed at least once, `false` otherwise - `data`: Contains the last successful result of type `T`, `undefined` otherwise - `error`: Contains the error of type `E` if the operation failed, `undefined` otherwise - `loading`: `true` when the operation is in progress, `false` otherwise ## Transaction Hooks Transaction hooks are a specific type of imperative hook that handle protocol interactions like supply, borrow, withdraw, repay, and more. There are two types of transaction hooks: - **Simple transactions** - single transactions that can be sent directly to the wallet - **Complex transactions** - transactions that could require approval beforehand ### Simple Transactions To handle a simple transaction hook, follow the steps below. #### 1. Use Simple Transaction Hooks First, instantiate the transaction hook and the `useSendTransaction` hook according to the [wallet provider](#send-aave-transactions) you are using. ```tsx title="Instantiate Hooks" const [prepare, preparing] = useSimpleTransaction(); const [sendTransaction, sending] = useSendTransaction(/* … */); ``` #### 2. Execute the Transaction Next, execute the transaction in your app by chaining the prepare and send operations. ```ts const result = await prepare(/* args */).andThen(sendTransaction); ``` Optionally, combine the state objects to drive your UI components. ```ts const loading = preparing.loading || sending.loading; const error = preparing.error || sending.error; ``` #### 3. Handle the Simple Transaction Result Finally, handle the result of the operation. ```ts title="Imperative" if (result.isErr()) { switch (result.error.name) { case "SigningError": // Most likely the user rejected the transaction console.error(`Failed to sign the transaction: ${result.error.message}`); break; case "TimeoutError": console.error(`Transaction timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Transaction failed: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Transaction sent with hash:", result.value); } ``` ```tsx title="Declarative" function MyComponent() { // … const loading = preparing.loading || sending.loading; const error = preparing.error || sending.error; return (
{error &&

{error.message}

}
); } ``` ### Complex Transactions To handle a complex transaction hook, follow the steps below. #### 1. Use Complex Transaction Hooks First, instantiate the transaction hook and the `useSendTransaction` hook according to the [wallet provider](#send-aave-transactions) you are using. ```tsx title="Instantiate Hooks" const [prepare, preparing] = useComplexTransaction(); const [sendTransaction, sending] = useSendTransaction(/* … */); ``` Optionally, combine the state objects to drive your UI components. ```ts const loading = preparing.loading || sending.loading; const error = preparing.error || sending.error; ``` #### 2. Process the Execution Plan Next, handle the execution plan in your transaction flow. Some operations may require token approval before executing the main transaction. ```ts import { errAsync } from "@aave/react"; const result = await prepare(/* args */).andThen((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "ApprovalRequired": return sendTransaction(plan.approval).andThen(() => sendTransaction(plan.originalTransaction) ); case "InsufficientBalanceError": return errAsync( new Error(`Insufficient balance: ${plan.required.value} required.`) ); } }); // … ``` > [!NOTE] > To ask the user for confirmation before sending, add your app’s confirmation > UI here. #### 3. Handle the Complex Transaction Result Finally, handle the result of the operation. ```ts title="Imperative" if (result.isErr()) { switch (result.error.name) { case "SigningError": // Most likely the user rejected the transaction console.error(`Failed to sign the transaction: ${result.error.message}`); break; case "TimeoutError": console.error(`Transaction timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Transaction failed: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Transaction sent with hash:", result.value); } ``` ```tsx title="Declarative" function MyComponent() { // … const loading = preparing.loading || sending.loading; const error = preparing.error || sending.error; return (
{error &&

{error.message}

}
); } ``` --- ## Next Steps --- Source: https://aave.com/docs/aave-v3/getting-started/typescript.md # Aave V3 TypeScript Quickstart AaveKit TypeScript provides a type-safe, low-level API client for interacting with Aave Protocol V3. It offers a lightweight abstraction over the GraphQL API and is ideal for server-to-server communication. Built with a modular, functional approach inspired by the _viem client-actions architecture_, the SDK structures functionality into distinct, reusable actions focused on specific protocol features like lending, borrowing, and vault management. ## Getting Started To get started, follow the steps below. ### 1. Install SDK First, install the `@aave/client` package using your package manager of choice. ```bash title="npm" npm install @aave/client@latest ``` ```bash title="yarn" yarn add @aave/client@latest ``` ```bash title="pnpm" pnpm add @aave/client@latest ``` ### 2. Set Up the Client Then, create an `AaveClient` instance that will be used to interact with the protocol. ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ### 3. Start Building You can now start using the `@aave/client/actions` to interact with the Aave Protocol. ```ts title="example.ts" import { chains } from "@aave/client/actions"; import { client } from "./client"; // Fetch all chains supported by Aave const result = await chains(client); if (result.isOk()) { console.log("Chains:", result.value); } else { console.error("Error:", result.error); } ``` ## Result Objects AaveKit actions use a functional approach to error handling. They return a `ResultAsync`: a thenable object that represents one of two states: - `Ok`: A successful result containing a value of type `T` - `Err`: A failure containing an error of type `E` When you await a `ResultAsync`, it resolves to a `Result`. With a `Result`, you can use the convenient `isOk()` and `isErr()` methods to check the outcome and narrow the type. If you have a `ResultAsync`, you must first `await` it to access those methods. ```ts const result = await actionName(/* args */); if (result.isOk()) { console.log("Result:", result.value); } else { console.error("Error:", result.error); } ``` This approach avoids reliance on `try/catch` blocks and promotes predictable, type-safe code by ensuring errors are handled explicitly. > [!NOTE] > AaveKit re-exports the [NeverThrow](https://github.com/supermacro/neverthrow) > library. See its docs for details. For example: ```ts import { ok, err, type Result } from "@aave/client"; function parseNumber(input: string): Result { return isNaN(Number(input)) ? err("Invalid number") : ok(Number(input)); } const result = parseNumber("42"); ``` You can chain multiple operations: ```ts title="Chaining" function divide(a: number, b: number): Result { return b === 0 ? err("Division by zero") : ok(a / b); } const result = parseNumber("42").andThen((num) => divide(num, 2)); if (result.isOk()) { console.log("Result:", result.value); } else { console.error("Error:", result.error); } ``` You can also provide a default value: ```ts title="Default Value" const value = parseNumber("invalid").unwrapOr(0); // 0 ``` NeverThrow also provides a `ResultAsync` type for handling asynchronous operations. This is a _thenable object_ that can be awaited, and/or chained with other operations: ```ts title="Async" const result = await ResultAsync.fromPromise( fetch("https://api.example.com/data") ) .map((response) => response.json()) .mapErr((error) => `Failed to fetch data: ${error}`); if (result.isOk()) { console.log("Data:", result.value); } else { console.error("Error:", result.error); } ``` ## Integrations AaveKit TypeScript includes first-class support for [viem](https://viem.sh/), [ethers v6](https://docs.ethers.org/v6/), [Privy](https://docs.privy.io/wallets/using-wallets/ethereum/send-a-transaction#nodejs), [thirdweb](https://docs.thirdweb.com/sdk/wallets/thirdweb) and [Turnkey](https://docs.turnkey.com/sdks/javascript-server) wallets. Ensure you have `viem` package installed in your project. ```bash title="npm" npm install viem@2 ``` ```bash title="yarn" yarn add viem@2 ``` ```bash title="pnpm" pnpm add viem@2 ``` Ensure you have `ethers` package installed in your project. ```bash title="npm" npm install ethers ``` ```bash title="yarn" yarn add ethers ``` ```bash title="pnpm" pnpm add ethers ``` Ensure you have `viem` and `@privy-io/server-auth` packages installed in your project. ```bash title="npm" npm install viem@2 @privy-io/server-auth ``` ```bash title="yarn" yarn add viem@2 @privy-io/server-auth ``` ```bash title="pnpm" pnpm add viem@2 @privy-io/server-auth ``` > [!NOTE] > The Aave Privy adapter uses Viem to monitor the transaction status afterwards. Ensure you have `thirdweb` installed in your project. ```bash title="npm" npm install thirdweb@5 ``` ```bash title="yarn" yarn add thirdweb@5 ``` ```bash title="pnpm" pnpm add thirdweb@5 ``` Ensure you have `viem`, `@turnkey/viem` and `@turnkey/sdk-server` packages installed in your project. ```bash title="npm" npm install viem@2 @turnkey/viem @turnkey/sdk-server ``` ```bash title="yarn" yarn add viem@2 @turnkey/viem @turnkey/sdk-server ``` ```bash title="pnpm" pnpm add viem@2 @turnkey/viem @turnkey/sdk-server ``` ### Send Aave Transactions Among the actions provided by AaveKit TypeScript, some are specifically designed to handle protocol interactions such as supplying, borrowing, withdrawing, repaying, and more. There are two main types of transaction actions: - **Simple transactions** – single-step transactions that can be sent directly to the wallet. - **Complex transactions** – transactions that may require prior approvals before they can be executed. To send transactions, follow the steps below. #### 1. Import the Helper First, import the `sendWith` helper function for the wallet library of your choice. Import the `sendWith` helper from the `@aave/client/viem` entry point. ```tsx title="Viem" import { sendWith } from "@aave/client/viem"; ``` Import the `sendWith` helper from the `@aave/client/ethers` entry point. ```tsx title="Ethers" import { sendWith } from "@aave/client/ethers"; ``` Import the `sendWith` helper from the `@aave/client/privy` entry point. ```tsx title="Privy" import { sendWith } from "@aave/client/privy"; ``` Import the `sendWith` helper from the `@aave/client/thirdweb` entry point. ```tsx title="thirdweb" import { sendWith } from "@aave/client/thirdweb"; ``` Import the `sendWith` helper from the `@aave/client/viem` entry point. ```tsx title="Turnkey" import { sendWith } from "@aave/client/viem"; ``` #### 2. Send the Transaction Then, use the `sendWith` helper to send the transaction. To demonstrate how this helper works, assume we have a transaction action named `foobar`. ```ts title="example.ts" import { foobar } from "@aave/client/actions"; import { client } from "./client"; const result = foobar(client); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` To send the transaction, chain the action with `sendWith` for your wallet library, then use `client.waitForTransaction` to wait until it’s confirmed and indexed by AaveKit API. ```tsx title="Viem" import { foobar } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { createWalletClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { client } from "./client"; const wallet = createWalletClient({ account: privateKeyToAccount(""), transport: http(), }); const result = await foobar(client) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```tsx title="Ethers" import { foobar } from "@aave/client/actions"; import { sendWith } from "@aave/client/ethers"; import { Wallet, getDefaultProvider } from "ethers"; import { client } from "./client"; const wallet = new Wallet("", getDefaultProvider("mainnet")); const result = await foobar(client) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```tsx title="Privy" import { foobar } from "@aave/client/actions"; import { sendWith } from "@aave/client/privy"; import { PrivyClient } from "@privy-io/server-auth"; import { client } from "./client"; const privy = new PrivyClient("", ""); const result = await foobar(client) .andThen(sendWith(privy, "")) .andThen(client.waitForTransaction); ``` ```tsx title="thirdweb" import { foobar } from "@aave/client/actions"; import { sendWith } from "@aave/client/thirdweb"; import { createThirdwebClient } from "thirdweb"; import { client } from "./client"; const thirdwebClient = createThirdwebClient({ secretKey: "", }); const result = await foobar(client) .andThen(sendWith(thirdwebClient)) .andThen(client.waitForTransaction); ``` ```tsx title="Turnkey" import { foobar } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { createAccount } from "@turnkey/viem"; import { Turnkey } from "@turnkey/sdk-server"; import { createWalletClient, http } from "viem"; import { mainnet } from "viem/chains"; import { client } from "./client"; const turnkeyClient = new Turnkey({ apiBaseUrl: "https://api.turnkey.com", apiPrivateKey: "", apiPublicKey: "", defaultOrganizationId: "", }); const turnkeyAccount = await createAccount({ client: turnkeyClient.apiClient(), organizationId: "", signWith: "", }); const wallet = createWalletClient({ account: turnkeyAccount, chain: mainnet, transport: http(), }); const result = await foobar(client) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` #### 3. Handle the Result Finally, handle the result of the operation. ```ts if (result.isErr()) { switch (result.error.name) { case "SigningError": console.error(`Failed to sign the transaction: ${result.error.message}`); break; case "TimeoutError": console.error(`Transaction timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Transaction failed: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Transaction sent with hash:", result.value); } ``` You’ve sent the transaction. ### Sign ERC-20 Permits Some operations support _permit functionality_ using [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) signatures to authorize ERC-20 token transfers within the same transaction. To use permits, you’ll need both the `permitTypedData` action to generate the permit data and a `signERC20PermitWith` helper specific to your wallet library. Import the `signERC20PermitWith` helper from the `@aave/client/viem` entry point. ```tsx title="Viem" import { signERC20PermitWith } from "@aave/client/viem"; ``` Import the `signERC20PermitWith` helper from the `@aave/client/ethers` entry point. ```tsx title="Ethers" import { signERC20PermitWith } from "@aave/client/ethers"; ``` Import the `signERC20PermitWith` helper from the `@aave/client/privy` entry point. ```tsx title="Privy" import { signERC20PermitWith } from "@aave/client/privy"; ``` Import the `signERC20PermitWith` helper from the `@aave/client/thirdweb` entry point. ```tsx title="thirdweb" import { signERC20PermitWith } from "@aave/client/thirdweb"; ``` Import the `signERC20PermitWith` helper from the `@aave/client/viem` entry point. ```tsx title="Turnkey" import { signERC20PermitWith } from "@aave/client/viem"; ``` Use `permitTypedData` to generate the permit data, then chain it with your wallet-specific `signERC20PermitWith` helper: ```tsx title="Viem" import { permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { createWalletClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { client } from "./client"; const wallet = createWalletClient({ account: privateKeyToAccount(""), transport: http(), }); const result = await permitTypedData(client, { // permit parameters }).andThen(signERC20PermitWith(wallet)); ``` ```tsx title="Ethers" import { permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/ethers"; import { Wallet, getDefaultProvider } from "ethers"; import { client } from "./client"; const wallet = new Wallet("", getDefaultProvider("mainnet")); const result = await permitTypedData(client, { // permit parameters }).andThen(signERC20PermitWith(wallet)); ``` ```tsx title="Privy" import { permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/privy"; import { PrivyClient } from "@privy-io/server-auth"; import { client } from "./client"; const privy = new PrivyClient("", ""); const result = await permitTypedData(client, { // permit parameters }).andThen(signERC20PermitWith(privy, "")); ``` ```tsx title="thirdweb" import { permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/thirdweb"; import { createThirdwebClient } from "thirdweb"; import { client } from "./client"; const thirdwebClient = createThirdwebClient({ secretKey: "", }); const result = await permitTypedData(client, { // permit parameters }).andThen(signERC20PermitWith(thirdwebClient)); ``` ```tsx title="Turnkey" import { permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { createAccount } from "@turnkey/viem"; import { Turnkey } from "@turnkey/sdk-server"; import { createWalletClient, http } from "viem"; import { mainnet } from "viem/chains"; import { client } from "./client"; const turnkeyClient = new Turnkey({ apiBaseUrl: "https://api.turnkey.com", apiPrivateKey: "", apiPublicKey: "", defaultOrganizationId: "", }); const turnkeyAccount = await createAccount({ client: turnkeyClient.apiClient(), organizationId: "", signWith: "", }); const wallet = createWalletClient({ account: turnkeyAccount, chain: mainnet, transport: http(), }); const result = await permitTypedData(client, { // permit parameters }).andThen(signERC20PermitWith(wallet)); ``` For complete permit parameter examples, refer to the specific operation documentation. --- ## Next Steps --- Source: https://aave.com/docs/aave-v3/getting-started/graphql.md # Aave V3 GraphQL Quickstart AaveKit API is a GraphQL API to query market data and user positions and to prepare transactions. Use it where the TypeScript SDK does not fit. ## Getting Started AaveKit API for Aave V3 is available at `https://api.v3.aave.com/graphql`. > [!NOTE] > The URL above is also a GraphQL playground for testing queries. You can query the API directly using any HTTP client. Here’s a basic example using curl: ```bash curl -X POST https://api.v3.aave.com/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query Chains { chains { name chainId icon } }" }' ``` ## Query Operations AaveKit API has two types of queries: - **Read queries** – queries that return data from the Aave Protocol. - **Transaction queries** – queries that prepare transactions to be executed on the Aave Protocol. The transactions queries are in turn divided into two categories: - **Simple transactions** – single-step transactions that can be sent directly to the wallet. - **Complex transactions** – transactions that may require prior approvals before they can be executed. ### Simple Transactions Simple transactions query returns a `TransactionRequest` object that can be used to send the transaction to the wallet. ```graphql title="TransactionRequest" type TransactionRequest { to: EvmAddress! from: EvmAddress! data: BlockchainData! value: BigInt! chainId: ChainId! operation: OperationType } ``` ### Complex Transactions Complex transactions query returns an `ExecutionPlan` union. The `ExecutionPlan` union represents the different scenarios that can occur when preparing a transaction: - `TransactionRequest`: The transaction can be executed directly. - `ApprovalRequired`: An approval transaction must be sent first, then the original transaction can be executed. - `InsufficientBalanceError`: The user doesn’t have enough balance of the token to be used in the transaction. ```graphql title="ExecutionPlan" union ExecutionPlan = TransactionRequest | ApprovalRequired | InsufficientBalanceError ``` ```graphql title="ApprovalRequired" type ApprovalRequired { approval: TransactionRequest! reason: String! requiredAmount: DecimalValue! currentAllowance: DecimalValue! originalTransaction: TransactionRequest! } ``` ```graphql title="InsufficientBalanceError" type InsufficientBalanceError { required: DecimalValue! available: DecimalValue! } ``` ## Transaction Monitoring After sending a transaction, AaveKit API may take a short time to process and reflect the new state in its responses due to caching and background invalidation. To reliably know when your transaction has been processed and data is up to date, use the `hasProcessedKnownTransaction` query. This query lets you check if a transaction (by hash and operation type) has been indexed and processed by the API, so you can safely fetch updated user or market data. Note that this can only be used with transactions where the `TransactionRequest` has a non-null `operation` field. ```graphql title="Query" query { value: hasProcessedKnownTransaction( request: { operation: SUPPLY, txHash: "0x1234…" } ) } ``` ```json title="Response" { "data": { "value": true } } ``` - Returns `true` if the transaction has been processed and data is fresh. - Returns `false` if the transaction is not yet processed (wait and retry). After sending a transaction, poll this query until it returns `true` before fetching updated positions or balances, so your UI does not show cached data. --- ## Scalars A non-exhaustive list of the custom scalars used in AaveKit API. | Scalar | Description | Example | | ---------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------- | | `BlockchainData` | A string representing binary data as a hex string. | `0x0000000000000000000000000000000000000000000000000000000000000020` | | `BigInt` | A string representing a big integer in decimal format. | `1000000000000000000000` | | `BigDecimal` | A string representing a decimal number with arbitrary precision. | `1.0000000000000000001` | | `ChainId` | A number representing a Chain ID. | `1`, `8453`, `42161` | | `EvmAddress` | A string representing an EVM address. | `0x0000000000000000000000000000000000000000` | | `TxHash` | A string representing an EVM transaction hash. | `0x0000000000000000000000000000000000000000000000000000000000000000` | | `DateTime` | A string representing a date and time. | `2021-01-01T00:00:00Z` | ## Common Types Some of the common types used in AaveKit API. A `Currency` object represents an ERC-20 token. ```graphql type Currency { """ The token address """ address: EvmAddress! """ The chain id """ chainId: ChainId! """ The token name """ name: String! """ The token image """ imageUrl: String! """ The token symbol """ symbol: String! """ The token decimals """ decimals: Int! } ``` A `DecimalValue` object represents a decimal value with arbitrary precision. ```graphql type DecimalValue { """ The raw unformatted value """ raw: BigInt! """ The decimals the value formatted into """ decimals: Int! """ The formatted value """ value: BigDecimal! } ``` A `TokenAmount` object represents an amount of a token. ```graphql type TokenAmount { """ The USD exchange rate for the token """ usdPerToken: BigDecimal! """ The amount """ amount: DecimalValue! """ The amount in USD """ usd: BigDecimal! } ``` A `PercentValue` object represents a percentage value with precision and formatting. ```graphql type PercentValue { """ The raw unnormalized percentage (the value that lives onchain) """ raw: BigInt! """ The decimals representing the precision of the onchain raw value """ decimals: Int! """ The normalized percentage (1.0 = 100%) """ value: BigDecimal! """ The human-readable formatted value you can render on a UI straight away. For example, this will turn `0.01232343` to `1.23`, it will always round to `2` decimal points. """ formatted: BigDecimal! } ``` A `Chain` object represents a blockchain network supported by the Aave Protocol. ```graphql type Chain { """ The chain name """ name: String! """ The chain icon """ icon: String! """ The chain id """ chainId: ChainId! } ``` ## Utility Queries ### Supported Chains Use the `chains` query to list the chains supported by the Aave Protocol V3. ```graphql title="Query" query Chains { chains { __typename name chainId icon } } ``` ```json title="Response" { "data": { "chains": [ { "__typename": "Chain", "chainId": 1, "icon": "https://statics.aave.com/ethereum.svg", "name": "Ethereum" }, { "__typename": "Chain", "chainId": 42161, "icon": "https://statics.aave.com/arbitrum.svg", "name": "Arbitrum" }, { "__typename": "Chain", "chainId": 8453, "icon": "https://statics.aave.com/base.svg", "name": "Base" } ] } } ``` ### USD Exchange Rates Use the `usdExchangeRates` query to get the USD exchange rate for a list of tokens. ```graphql title="Query" query UsdExchangeRates($request: UsdExchangeRatesRequest!) { usdExchangeRates(request: $request) { __typename currency { symbol name address decimals } rate } } ``` ```json title="Variables" { "request": { "market": "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2", "underlyingTokens": ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], "chainId": 1 } } ``` ```json title="Response" { "data": { "usdExchangeRates": [ { "__typename": "UsdExchangeRate", "currency": { "symbol": "USDC", "name": "USD Coin", "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "decimals": 6 }, "rate": "1.0" } ] } } ``` --- ## Next Steps --- Source: https://aave.com/docs/aave-v3/concepts/liquidity-pool.md # Aave V3 Liquidity Pool A _liquidity pool_ is an Aave market instance that enables users to participate as suppliers or borrowers. Governance-approved parameters, such as reserve configurations and collateralization thresholds, define each pool. Suppliers provide liquidity into the pool that borrowers can access through overcollateralized positions. In return, suppliers earn interest, while borrowers can obtain liquidity against their collateral, all facilitated through decentralized smart contracts. Aave liquidity pools operate on a blockchain network governed by decisions that define the chain and reserve parameters. Parameter decisions must balance liquidity demands for various actions with risk management. Smart contracts validate parameters and execute borrowing, repaying and liquidations without intermediaries. This decentralized approach enhances the transparency, efficiency, and security of financial interactions within the pool. The core actions on a liquidity pool are described below. ## Supply Supplying tokens to the Aave Protocol allows users to earn interest on their digital assets and utilize supplied tokens as collateral. When tokens are supplied, they are transferred to the Aave liquidity pool, a system of smart contracts that facilitates overcollateralized borrowing of tokens. In Aave, 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 the borrow utilization rate, which measures the proportion of assets currently borrowed against the total supplied in the pool, and by governance parameters that can be adjusted through community decisions. These parameters, including collateralization requirements and interest rates for suppliers and borrowers, are influenced by onchain inputs such as token balances, oracle prices, and the borrow utilization ratio. As liquidity is supplied, borrowed, repaid, or withdrawn from the pool, the interest rates are updated accordingly. ## Withdraw Aave Protocol 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 liquidity and by the need to keep the borrow position sufficiently collateralized. 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 collateralization ratio to avoid liquidation. Reducing collateral can lower the health factor, increasing the risk of liquidation. After the withdrawal, the Health Factor must stay at or above 1. Therefore, withdrawals require careful management and consideration of the overall borrow positions to avoid liquidation. ## Borrow Borrowing tokens from the Aave Protocol allows users to access liquidity by using their supplied tokens as collateral, unlocking capital without selling their assets. However, borrowers face liquidation risk if the value of their collateral falls below the required threshold. Interest rates are determined dynamically, influenced by protocol factors and governance decisions, and can change over time based on community input. Interest accrues based on the utilization rate, which reflects the percentage of supplied liquidity that is borrowed. Higher utilization rates lead to higher interest rates, adjusting with demand. Each reserve has specific parameters designed to incentivize both borrowers and suppliers. To maintain a healthy ratio and avoid liquidation risk, borrowers should actively monitor their collateralization level, keeping their health factor in check, to assure their borrow positions remain overcollateralized even as market conditions change or interest accrues. ## Repay Repaying borrowed tokens in the Aave Protocol is an important step for managing borrow positions. Borrowers can repay using the same tokens they borrowed, or repay with aTokens (collateral tokens) of the same underlying token. In addition, there are [periphery contracts](https://github.com/aave-dao/aave-v3-origin) available that simplify the process by allowing repayment with other tokens, such as other collateral assets, without the need to manually convert them beforehand. This flexibility makes it easier for borrowers to manage and close their positions when needed. Repaying reduces debt, which raises the Health Factor, prevents liquidation and frees collateral for withdrawal. --- Source: https://aave.com/docs/aave-v3/concepts/reserve.md # Aave V3 Reserves A _reserve_ is an instance of a token within an Aave [liquidity pool](./liquidity-pool). Each reserve is governed by a set of parameters that manage risk and optimize liquidity. These parameters can vary across different markets, even for the same underlying token, allowing Aave to adapt to various network and pool conditions. ## Key Reserve Parameters 1. **Loan-to-Value (LTV)**: The maximum amount that can be borrowed relative to the collateral’s value. For example, a 75% LTV allows borrowing 75% of the collateral’s value. An asset with an LTV of 0% cannot be enabled as collateral. 2. **Liquidation Threshold**: The collateral ratio at which a position can be liquidated. When debt exceeds collateral value times this threshold (Health Factor below 1), liquidators can repay part of the debt. 3. **Borrowing Enabled**: Determines whether liquidity of a reserve can be borrowed. 4. **Caps**: Supply and Borrow caps limit the total amount of a token that can be supplied and borrowed from a reserve. These caps are crucial for maintaining liquidity and preventing overexposure during volatile market conditions. 5. **Interest Rate Model**: Interest rates in Aave adjust dynamically based on the utilization of the liquidity pool. As more liquidity is borrowed, interest rates rise to reflect the reduced availability of assets, so that enough liquidity remains for withdrawals and liquidations. The rates are controlled by parameters that set the base rate and slopes for utilization. ## Dynamic Parameters and Governance The parameters for each reserve are not fixed; they vary between markets and can change over time as Aave Governance monitors market conditions and adjusts settings accordingly. For example, the same underlying token, such as WETH, might have different LTVs or interest rates in Ethereum versus Polygon markets. These adjustments are made to optimize liquidity and risk management for each market. Governance proposals allow the community to vote on changes, such as raising borrow caps or adjusting LTVs, enabling reserves to remain aligned with current market dynamics. --- Source: https://aave.com/docs/aave-v3/concepts/incentives.md # Aave V3 Incentives Incentives within the Aave Protocol encourage active participation from suppliers and borrowers, enhancing liquidity and the overall efficiency of the protocol. Incentives can come from the Aave DAO treasury or from external parties that want to promote liquidity for specific [reserves](./reserve). The Aave DAO, governed by AAVE token holders through proposals and voting, can allocate funds from the DAO treasury to incentivize certain activities within the protocol. Incentive programs funded by the DAO are proposed, discussed, and approved through the [Aave Governance](../../ecosystem/governance) process, ensuring community involvement and transparency. ## Liquidity Pool Incentives Incentives can also be applied to the supply or borrow side of Aave liquidity pools, promoting activity of the incentivized [reserve](./reserve). By offering rewards to suppliers and borrowers of certain assets on Aave, the visibility and adoption of tokens can be boosted. Such external incentives require governance approval. Approved incentives are distributed continuously over time proportional to the amount of liquidity a user supplies or borrows. Users can claim these rewards via the protocol’s incentive controller, which manages the allocation and distribution of incentives. This system adds value for those actively participating in the protocol while aligning user interests with the health and stability of the Aave ecosystem. ## Umbrella Users can stake aTokens and GHO in [Umbrella](../umbrella) to cover bad debt in the Aave Protocol. In return for taking on slashing risk, stakers earn Safety Incentives in reward tokens set by governance. ## Merit Program Merit is an Aave-alignment user reward system, designed as a merkle-tree-based periodic airdrop to incentivize Aave-aligned behaviors and enhance the competitiveness of the Aave Protocol. Rewards are available on the [Merit dashboard](https://apps.aavechan.com/merit). --- Source: https://aave.com/docs/aave-v3/markets/data.md # Aave V3 Market Data Learn how to discover available markets and access detailed market information in Aave. ## Market Structure Aave market data describes lending pools across different chains: - Market identification (name, chain, address) - The reserves in the market - Efficiency Mode (E-Mode) categories and configurations - Market metrics (total size, available liquidity) When you provide a user account address, the data also includes user-specific information such as net worth, health factor, and current positions. The following TypeScript interfaces illustrate the core Market type and its related types: ```ts title="Market" interface Market { name: string; chain: Chain; address: EvmAddress; icon: string; totalMarketSize: BigDecimal; totalAvailableLiquidity: BigDecimal; eModeCategories: EmodeMarketCategory[]; userState?: MarketUserState; borrowReserves: Reserve[]; supplyReserves: Reserve[]; } ``` ```ts title="EmodeMarketCategory" interface EmodeMarketCategory { id: number; label: string; maxLTV: PercentValue; liquidationThreshold: PercentValue; liquidationPenalty: PercentValue; reserves: EmodeMarketReserveInfo[]; } ``` ```ts title="MarketUserState" interface MarketUserState { netWorth: BigDecimal; netAPY: PercentValue; userEarnedAPY: PercentValue; userDebtAPY: PercentValue; healthFactor: BigDecimal | null; eModeEnabled: boolean; totalCollateralBase: BigDecimal; totalDebtBase: BigDecimal; availableBorrowsBase: BigDecimal; currentLiquidationThreshold: PercentValue; ltv: PercentValue; isInIsolationMode: boolean; // deprecated in Aave V3.7 } ``` ```ts title="EmodeReserveInfo" interface EmodeReserveInfo { categoryId: number; label: string; maxLTV: PercentValue; liquidationThreshold: PercentValue; liquidationPenalty: PercentValue; canBeCollateral: boolean; canBeBorrowed: boolean; hasLtvZero: boolean; } ``` The following GraphQL fragments illustrate the core Market type and its related types: ```graphql title="Market" fragment Market on Market { __typename name chain { ...Chain } address icon totalMarketSize totalAvailableLiquidity eModeCategories { ...EmodeMarketCategory } userState { ...MarketUserState } borrowReserves: reserves(request: { reserveType: BORROW }) { ...Reserve } supplyReserves: reserves(request: { reserveType: SUPPLY }) { ...Reserve } } ``` ```graphql title="EmodeMarketCategory" fragment EmodeMarketCategory on EmodeMarketCategory { __typename id label maxLTV { ...PercentValue } liquidationThreshold { ...PercentValue } liquidationPenalty { ...PercentValue } isolated reserves { ...EmodeMarketReserveInfo } } fragment EmodeMarketReserveInfo on EmodeMarketReserveInfo { __typename underlyingToken { ...Currency } canBeCollateral canBeBorrowed } ``` ```graphql title="MarketUserState" fragment MarketUserState on MarketUserState { __typename netWorth netAPY { ...PercentValue } userEarnedAPY { ...PercentValue } userDebtAPY { ...PercentValue } healthFactor eModeEnabled totalCollateralBase totalDebtBase availableBorrowsBase currentLiquidationThreshold { ...PercentValue } ltv { ...PercentValue } isInIsolationMode # deprecated in Aave V3.7 } ``` ```graphql title="MarketInfo" fragment MarketInfo on MarketInfo { __typename name chain { ...Chain } icon } ``` ```graphql title="EmodeReserveInfo" fragment EmodeReserveInfo on EmodeReserveInfo { __typename categoryId label maxLTV { ...PercentValue } liquidationThreshold { ...PercentValue } liquidationPenalty { ...PercentValue } canBeCollateral canBeBorrowed hasLtvZero } ``` ```graphql title="Common" fragment Chain on Chain { __typename name icon chainId } fragment DecimalValue on DecimalValue { __typename raw decimals value } fragment PercentValue on PercentValue { __typename raw decimals value formatted } fragment Currency on Currency { __typename address imageUrl name symbol decimals chainId } fragment NativeCurrency on NativeCurrency { __typename imageUrl name symbol decimals chainId } fragment TokenAmount on TokenAmount { __typename usdPerToken amount { ...DecimalValue } usd } ``` ## Reserve Structure Each reserve within an Aave market describes the lending and borrowing data for a specific asset: - Token information (underlying, aToken, vToken addresses and metadata) - Supply information (APY, liquidity, caps, collateral configuration) - Borrow information (APY, available liquidity, utilization rates, caps) - Reserve incentives (Merit programs, Aave governance rewards) - Market mechanics (flash loans, permits, pause/freeze states) - Efficiency Mode (E-Mode) configurations for the asset - Isolation Mode settings Deprecated in Aave V3.7 - User-specific state (balances, borrowable amounts, collateral usage) When you provide a user account address, the reserve data also includes user-specific information such as current balances, borrowing capacity, and collateral status. The following TypeScript interfaces and GraphQL fragments illustrate the core Reserve type and its related types: ```ts title="Reserve" interface Reserve { market: MarketInfo; underlyingToken: Currency; aToken: Currency; vToken: Currency; acceptsNative?: NativeCurrency; size: TokenAmount; usdExchangeRate: BigDecimal; usdOracleAddress: EvmAddress; isFrozen: boolean; isPaused: boolean; flashLoanEnabled: boolean; permitSupported: boolean; supplyInfo: ReserveSupplyInfo; borrowInfo?: ReserveBorrowInfo; isolationModeConfig?: ReserveIsolationModeConfig; // deprecated in Aave V3.7 eModeInfo: EmodeReserveInfo[]; incentives: ReserveIncentive[]; userState?: ReserveUserState; } ``` ```ts title="Borrow & Supply" interface ReserveSupplyInfo { apy: PercentValue; total: DecimalValue; maxLTV: PercentValue; liquidationThreshold: PercentValue; liquidationBonus: PercentValue; canBeCollateral: boolean; supplyCap: TokenAmount; supplyCapReached: boolean; } interface ReserveBorrowInfo { apy: PercentValue; total: TokenAmount; borrowCap: TokenAmount; reserveFactor: PercentValue; availableLiquidity: TokenAmount; utilizationRate: PercentValue; variableRateSlope1: PercentValue; variableRateSlope2: PercentValue; optimalUsageRate: PercentValue; borrowingState: ReserveBorrowingState; borrowCapReached: boolean; } ``` ```ts title="Isolation Mode" // Deprecated in Aave V3.7: Isolation Mode was removed interface ReserveIsolationModeConfig { canBeCollateral: boolean; canBeBorrowed: boolean; debtCeiling: TokenAmount; debtCeilingDecimals: number; totalBorrows: TokenAmount; } ``` ```ts title="User State" interface ReserveUserState { balance: TokenAmount; suppliable: TokenAmount; borrowable: TokenAmount; emode?: EmodeReserveInfo; canBeCollateral: boolean; canBeBorrowed: boolean; isInIsolationMode: boolean; // deprecated in Aave V3.7 } ``` ```ts title="Incentives" type ReserveIncentive = | MeritSupplyIncentive | MeritBorrowIncentive | MeritBorrowAndSupplyIncentiveCondition | AaveSupplyIncentive | AaveBorrowIncentive; interface MeritSupplyIncentive { __typename: "MeritSupplyIncentive"; extraSupplyApr: PercentValue; claimLink: string; } interface MeritBorrowIncentive { __typename: "MeritBorrowIncentive"; borrowAprDiscount: PercentValue; claimLink: string; } interface MeritBorrowAndSupplyIncentiveCondition { __typename: "MeritBorrowAndSupplyIncentiveCondition"; extraApr: PercentValue; supplyToken: Currency; borrowToken: Currency; claimLink: string; } interface AaveSupplyIncentive { __typename: "AaveSupplyIncentive"; extraSupplyApr: PercentValue; rewardTokenAddress: EvmAddress; rewardTokenSymbol: string; } interface AaveBorrowIncentive { __typename: "AaveBorrowIncentive"; borrowAprDiscount: PercentValue; rewardTokenAddress: EvmAddress; rewardTokenSymbol: string; } ``` ```graphql title="Reserve" fragment Reserve on Reserve { __typename market { ...MarketInfo } underlyingToken { ...Currency } aToken { ...Currency } vToken { ...Currency } acceptsNative { ...NativeCurrency } size { ...TokenAmount } usdExchangeRate usdOracleAddress isFrozen isPaused flashLoanEnabled permitSupported supplyInfo { ...ReserveSupplyInfo } borrowInfo { ...ReserveBorrowInfo } isolationModeConfig { ...ReserveIsolationModeConfig } eModeInfo { ...EmodeReserveInfo } incentives { ...ReserveIncentive } userState { ...ReserveUserState } } ``` ```graphql title="Borrow & Supply" fragment ReserveSupplyInfo on ReserveSupplyInfo { __typename apy { ...PercentValue } total { ...DecimalValue } maxLTV { ...PercentValue } liquidationThreshold { ...PercentValue } liquidationBonus { ...PercentValue } canBeCollateral supplyCap { ...TokenAmount } supplyCapReached } fragment ReserveBorrowInfo on ReserveBorrowInfo { __typename apy { ...PercentValue } total { ...TokenAmount } borrowCap { ...TokenAmount } reserveFactor { ...PercentValue } availableLiquidity { ...TokenAmount } utilizationRate { ...PercentValue } variableRateSlope1 { ...PercentValue } variableRateSlope2 { ...PercentValue } optimalUsageRate { ...PercentValue } borrowingState borrowCapReached } ``` ```graphql title="Isolation Mode" # Deprecated in Aave V3.7: Isolation Mode was removed fragment ReserveIsolationModeConfig on ReserveIsolationModeConfig { __typename canBeCollateral canBeBorrowed debtCeiling { ...TokenAmount } debtCeilingDecimals totalBorrows { ...TokenAmount } } ``` ```graphql title="User State" fragment ReserveUserState on ReserveUserState { __typename balance { ...TokenAmount } suppliable { ...TokenAmount } borrowable { ...TokenAmount } emode { ...EmodeReserveInfo } canBeCollateral canBeBorrowed isInIsolationMode # deprecated in Aave V3.7 } ``` ```graphql title="Incentives" fragment ReserveIncentive on ReserveIncentive { __typename ... on MeritSupplyIncentive { ...MeritSupplyIncentive } ... on MeritBorrowIncentive { ...MeritBorrowIncentive } ... on MeritBorrowAndSupplyIncentiveCondition { ...MeritBorrowAndSupplyIncentiveCondition } ... on AaveSupplyIncentive { ...AaveSupplyIncentive } ... on AaveBorrowIncentive { ...AaveBorrowIncentive } } fragment MeritSupplyIncentive on MeritSupplyIncentive { __typename extraSupplyApr { ...PercentValue } claimLink } fragment MeritBorrowIncentive on MeritBorrowIncentive { __typename borrowAprDiscount { ...PercentValue } claimLink } fragment MeritBorrowAndSupplyIncentiveCondition on MeritBorrowAndSupplyIncentiveCondition { __typename extraApr { ...PercentValue } supplyToken { ...Currency } borrowToken { ...Currency } claimLink } fragment AaveSupplyIncentive on AaveSupplyIncentive { __typename extraSupplyApr { ...PercentValue } rewardTokenAddress rewardTokenSymbol } fragment AaveBorrowIncentive on AaveBorrowIncentive { __typename borrowAprDiscount { ...PercentValue } rewardTokenAddress rewardTokenSymbol } ``` > [!NOTE] > See [Incentive Programs](./incentives) for details. ## Listing Available Markets Discover all available Aave markets across supported blockchain networks. Use the `useAaveMarkets` hook in React, the `markets` action in TypeScript, or the `markets` query in GraphQL to fetch available markets across different chains. In React, the `useAaveMarkets` hook supports both a loading state and React Suspense. ```ts title="Loading State" const { data, loading, error } = useAaveMarkets({ chainIds: ChainId[], user: EvmAddress | undefined, borrowsOrderBy: MarketReservesRequestOrderBy | undefined, suppliesOrderBy: MarketReservesRequestOrderBy | undefined, }); ``` ```ts title="React Suspense" const { data } = useAaveMarkets({ chainIds: ChainId[], user: EvmAddress | undefined, borrowsOrderBy: MarketReservesRequestOrderBy | undefined, suppliesOrderBy: MarketReservesRequestOrderBy | undefined, suspense: true, }); ``` Specify one or more chains to retrieve markets for. ```ts title="Ethereum Markets" import { useAaveMarkets, chainId } from "@aave/react"; // … const { data, loading, error } = useAaveMarkets({ chainIds: [chainId(1)], }); if (loading) { return Loading…; } if (error) { return {error.message}; } // data: Market[] ``` ```ts title="Ethereum Markets" import { chainId } from "@aave/client"; import { markets } from "@aave/client/actions"; import { client } from "./client"; const result = await markets(client, { chainIds: [chainId(1)], }); if (result.isErr()) { console.error(result.error); } else { // result.value: Market[] console.log(result.value); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { markets( request: { chainIds: [1] # Optional: include account-level data for each market and reserve # user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" } ) { name chain { name chainId } address icon totalMarketSize totalAvailableLiquidity } } ``` ```json title="Response" { "data": { "markets": [ { "name": "Aave V3 Ethereum", "chain": { "name": "Ethereum", "chainId": 1 }, "address": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "icon": "https://app.aave.com/icons/networks/ethereum.svg", "totalMarketSize": "12345678900.50", "totalAvailableLiquidity": "987654321.75" } ] } } ``` Use a user address to include account-level data for each market and reserve. In GraphQL, set the optional `user` field shown in the query above. ```tsx title="With User State" import { useAaveMarkets, evmAddress, chainId } from "@aave/react"; const { data, loading, error } = useAaveMarkets({ chainIds: [chainId(1)], user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); ``` ```ts title="With User State" import { markets } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await markets(client, { chainIds: [chainId(1)], user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); ``` ## Fetching a Single Market Retrieve detailed information about a specific market including reserves and user state. Use the `useAaveMarket` hook in React, the `market` action in TypeScript, or the `market` query in GraphQL to fetch detailed information about a specific market. In React, the `useAaveMarket` hook supports both a loading state and React Suspense. ```ts title="Loading State" const { data, loading, error } = useAaveMarket({ address: EvmAddress, chainId: ChainId, user: EvmAddress | undefined, borrowsOrderBy: MarketReservesRequestOrderBy | undefined, suppliesOrderBy: MarketReservesRequestOrderBy | undefined, }); ``` ```ts title="React Suspense" const { data } = useAaveMarket({ address: EvmAddress, chainId: ChainId, user: EvmAddress | undefined, borrowsOrderBy: MarketReservesRequestOrderBy, suppliesOrderBy: MarketReservesRequestOrderBy, suspense: true, }); ``` Fetch a specific market by address and chain. ```tsx title="Ethereum Market" import { useAaveMarket, evmAddress, chainId } from "@aave/react"; // … const { data, loading, error } = useAaveMarket({ address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), }); if (loading) { return Loading market…; } if (error) { return Error: {error.message}; } if (!data) { return Market not found; } // data: Market ``` ```ts title="Ethereum Market" import { market } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await market(client, { address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), }); if (result.isErr()) { console.error(result.error); } else { // result.value: Market | null console.log(result.value); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { market( request: { address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" chainId: 1 # Optional: include account-level data for the market and its reserves # user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" } ) { name chain { name chainId } address totalMarketSize totalAvailableLiquidity userState { netWorth healthFactor eModeEnabled } reserves { underlyingToken { symbol name } supplyInfo { apy { raw decimals value formatted } canBeCollateral } borrowInfo { apy { raw decimals value formatted } } incentives { __typename ... on MeritSupplyIncentive { extraSupplyApr { formatted } claimLink } ... on AaveSupplyIncentive { extraSupplyApr { formatted } rewardTokenSymbol } } } } } ``` ```json title="Response" { "data": { "market": { "name": "Aave V3 Ethereum", "chain": { "name": "Ethereum", "chainId": 1 }, "address": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "totalMarketSize": "12345678900.50", "totalAvailableLiquidity": "987654321.75", "userState": { "netWorth": "5000.0", "healthFactor": "2.5", "eModeEnabled": false }, "reserves": [ { "underlyingToken": { "symbol": "USDC", "name": "USD Coin" }, "supplyInfo": { "apy": { "raw": "45000000000000000000000000", "decimals": 27, "value": "0.045", "formatted": "4.5" }, "canBeCollateral": true }, "borrowInfo": { "apy": { "raw": "65000000000000000000000000", "decimals": 27, "value": "0.065", "formatted": "6.5" } }, "incentives": [] } ] } } } ``` Use a user address to include account-level data for the market and its reserves. In GraphQL, set the optional `user` field shown in the query above. ```tsx title="With User State" import { useAaveMarket, evmAddress, chainId } from "@aave/react"; // … const { data, loading, error } = useAaveMarket({ address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); ``` ```ts title="With User State" import { market } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await market(client, { address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); ``` ## APY History Retrieve historical APY data for reserves to analyze interest rate trends over time. Use the `useBorrowAPYHistory` and `useSupplyAPYHistory` hooks in React, the `borrowAPYHistory` and `supplyAPYHistory` actions in TypeScript, or the `borrowAPYHistory` and `supplyAPYHistory` queries in GraphQL to fetch historical APY data for specific reserves. In React, both hooks support a loading state and React Suspense. ```ts title="Loading State" const { data, loading, error } = useBorrowAPYHistory({ chainId: ChainId, underlyingToken: EvmAddress, market: EvmAddress, window: TimeWindow, }); const { data, loading, error } = useSupplyAPYHistory({ chainId: ChainId, underlyingToken: EvmAddress, market: EvmAddress, window: TimeWindow, }); ``` ```ts title="React Suspense" const { data } = useBorrowAPYHistory({ chainId: ChainId, underlyingToken: EvmAddress, market: EvmAddress, window: TimeWindow, suspense: true, }); const { data } = useSupplyAPYHistory({ chainId: ChainId, underlyingToken: EvmAddress, market: EvmAddress, window: TimeWindow, suspense: true, }); ``` Fetch borrow and supply APY history for a specific reserve over a given time window. ```tsx title="Borrow APY History" import { useBorrowAPYHistory, evmAddress, chainId, TimeWindow, } from "@aave/react"; // … const { data, loading, error } = useBorrowAPYHistory({ chainId: chainId(1), underlyingToken: evmAddress("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"), // USDC market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), window: TimeWindow.LastWeek, }); if (loading) { return Loading APY history…; } if (error) { return Error: {error.message}; } // data: APYSample[] ``` ```tsx title="Supply APY History" import { useSupplyAPYHistory, evmAddress, chainId, TimeWindow, } from "@aave/react"; // … const { data, loading, error } = useSupplyAPYHistory({ chainId: chainId(1), underlyingToken: evmAddress("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"), // USDC market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), window: TimeWindow.LastMonth, }); if (loading) { return Loading APY history…; } if (error) { return Error: {error.message}; } // data: APYSample[] ``` ```ts title="Borrow APY History" import { borrowAPYHistory } from "@aave/client/actions"; import { evmAddress, chainId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await borrowAPYHistory(client, { chainId: chainId(1), underlyingToken: evmAddress("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"), // USDC market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), window: TimeWindow.LastWeek, }); if (result.isErr()) { console.error(result.error); } else { // result.value: APYSample[] | null result.value?.forEach((sample) => { console.log(`Date: ${sample.date}, APY: ${sample.avgRate.formatted}%`); }); } ``` ```ts title="Supply APY History" import { supplyAPYHistory } from "@aave/client/actions"; import { evmAddress, chainId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await supplyAPYHistory(client, { chainId: chainId(1), underlyingToken: evmAddress("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"), // USDC market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), window: TimeWindow.LastMonth, }); if (result.isErr()) { console.error(result.error); } else { // result.value: APYSample[] | null } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Borrow APY History Query" query { history: borrowAPYHistory( request: { chainId: 1 underlyingToken: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" window: LAST_WEEK } ) { avgRate { raw decimals value formatted } date } } ``` ```graphql title="Supply APY History Query" query { history: supplyAPYHistory( request: { chainId: 1 underlyingToken: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" window: LAST_MONTH } ) { avgRate { raw decimals value formatted } date } } ``` ```json title="Response" { "data": { "history": [ { "avgRate": { "raw": "45000000000000000000000000", "decimals": 27, "value": "0.045", "formatted": "4.5" }, "date": "2024-01-15T00:00:00Z" }, { "avgRate": { "raw": "46000000000000000000000000", "decimals": 27, "value": "0.046", "formatted": "4.6" }, "date": "2024-01-16T00:00:00Z" } ] } } ``` Each returned `APYSample` contains: - `avgRate`: Average APY for the time period - `date`: Timestamp for the data point Available time windows include (GraphQL enum value in parentheses): - `TimeWindow.LastDay` (`LAST_DAY`) - `TimeWindow.LastWeek` (`LAST_WEEK`) - `TimeWindow.LastMonth` (`LAST_MONTH`) - `TimeWindow.LastSixMonths` (`LAST_SIX_MONTHS`) - `TimeWindow.LastYear` (`LAST_YEAR`) --- Source: https://aave.com/docs/aave-v3/markets/positions.md # Aave V3 User Positions Monitor user positions and account health across Aave markets. ## User Positions Track user supplied and borrowed assets across Aave markets. Use the `useUserSupplies` and `useUserBorrows` hooks in React, the `userSupplies` and `userBorrows` actions in TypeScript, or the `userSupplies` and `userBorrows` queries in GraphQL to fetch user supplied and borrowed assets across markets. In React, both hooks support a loading state and React Suspense. ```ts title="Loading State" const { data, loading, error } = useUserSupplies({ markets: MarketInput[], user: EvmAddress, }); const { data, loading, error } = useUserBorrows({ markets: MarketInput[], user: EvmAddress, }); ``` ```ts title="React Suspense" const { data } = useUserSupplies({ markets: MarketInput[], user: EvmAddress, suspense: true, }); const { data } = useUserBorrows({ markets: MarketInput[], user: EvmAddress, suspense: true, }); ``` Fetch user positions across one or more markets. ```tsx title="useUserSupplies" import { useUserSupplies, evmAddress } from "@aave/react"; import { markets } from "./markets"; // … const user = evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"); const { data, error, loading } = useUserSupplies({ markets, user, }); if (error) { return Error: {error.message}; } if (loading) { return Loading positions…; } // data: MarketUserReserveSupplyPosition[] ``` ```tsx title="useUserBorrows" import { useUserBorrows, evmAddress } from "@aave/react"; import { markets } from "./markets"; // … const user = evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"); const { data, error, loading } = useUserBorrows({ markets, user, }); if (error) { return Error: {error.message}; } if (loading) { return Loading positions…; } // data: MarketUserReserveBorrowPosition[] ``` ```ts title="markets.ts" import { evmAddress, chainId } from "@aave/react"; export const markets = [ { address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), }, ]; ``` ```ts title="userSupplies.ts" import { userSupplies } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { markets } from "./markets"; const user = evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"); const result = await userSupplies(client, { markets, user, }); if (result.isErr()) { console.error("Supplies error:", result.error); } else { // result.value: MarketUserReserveSupplyPosition[] console.log(result.value); } ``` ```ts title="userBorrows.ts" import { userBorrows } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { markets } from "./markets"; const user = evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"); const result = await userBorrows(client, { markets, user, }); if (result.isErr()) { console.error("Borrows error:", result.error); } else { // result.value: MarketUserReserveBorrowPosition[] console.log(result.value); } ``` ```ts title="markets.ts" import { evmAddress, chainId } from "@aave/client"; export const markets = [ { address: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), chainId: chainId(1), }, ]; ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="UserSupplies" query { userSupplies( request: { markets: [ { address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chainId: 1 } ] user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" } ) { market { name chain { chainId } } currency { symbol name } balance { amount { value } usd } apy { raw decimals value formatted } isCollateral canBeCollateral } } ``` ```graphql title="UserBorrows" query { userBorrows( request: { markets: [ { address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chainId: 1 } ] user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" } ) { market { name chain { chainId } } currency { symbol name } debt { amount { value } usd } apy { raw decimals value formatted } } } ``` ```json title="UserSupplies Response" { "data": { "userSupplies": [ { "market": { "name": "Aave V3 Ethereum", "chain": { "chainId": 1 } }, "currency": { "symbol": "USDC", "name": "USD Coin" }, "balance": { "amount": { "value": "1000.0" }, "usd": "1000.0" }, "apy": { "raw": "45000000000000000000000000", "decimals": 27, "value": "0.045", "formatted": "4.5" }, "isCollateral": true, "canBeCollateral": true } ] } } ``` ```json title="UserBorrows Response" { "data": { "userBorrows": [ { "market": { "name": "Aave V3 Ethereum", "chain": { "chainId": 1 } }, "currency": { "symbol": "WETH", "name": "Wrapped Ether" }, "debt": { "amount": { "value": "0.5" }, "usd": "1250.0" }, "apy": { "raw": "28000000000000000000000000", "decimals": 27, "value": "0.028", "formatted": "2.8" } } ] } } ``` ## Account Health Monitor user account health and risk metrics across Aave positions. > [!NOTE] > The health factor is null unless the user has at least one active borrow. Use the `useUserMarketState` hook in React, the `userMarketState` action in TypeScript, or the `userMarketState` query in GraphQL to fetch user account health and market state. In React, the `useUserMarketState` hook supports both a loading state and React Suspense. ```ts title="Loading State" const { data, loading, error } = useUserMarketState({ market: EvmAddress, user: EvmAddress, chainId: ChainId, }); ``` ```ts title="React Suspense" const { data } = useUserMarketState({ market: EvmAddress, user: EvmAddress, chainId: ChainId, suspense: true, }); ``` Monitor account health for a specific market. ```tsx title="User Market State" import { useUserMarketState, evmAddress, chainId } from "@aave/react"; // … const { data, loading, error } = useUserMarketState({ market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), }); if (loading) { return Loading account health…; } if (error) { return Error: {error.message}; } return (
Health Factor: {data.healthFactor ?? "N/A"} Net Worth: {data.netWorth} eMode Enabled: {data.eModeEnabled ? "Yes" : "No"}
); ```
```ts title="userMarketState" import { evmAddress, chainId } from "@aave/client"; import { userMarketState } from "@aave/client/actions"; import { client } from "./client"; const result = await userMarketState(client, { market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), }); if (result.isErr()) { console.error(result.error); } else { // result.value: MarketUserState console.log("Health Factor:", result.value.healthFactor); console.log("Net Worth:", result.value.netWorth); console.log("eMode Enabled:", result.value.eModeEnabled); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { userMarketState( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } ) { netWorth netAPY { raw decimals value formatted } healthFactor eModeEnabled totalCollateralBase totalDebtBase availableBorrowsBase currentLiquidationThreshold { raw decimals value formatted } ltv { raw decimals value formatted } isInIsolationMode # deprecated in Aave V3.7 } } ``` ```json title="Response" { "data": { "userMarketState": { "netWorth": "5000.0", "netAPY": { "raw": "25000000000000000000000000", "decimals": 27, "value": "0.025", "formatted": "2.5" }, "healthFactor": "2.55", "eModeEnabled": false, "totalCollateralBase": "6000.0", "totalDebtBase": "2000.0", "availableBorrowsBase": "2500.0", "currentLiquidationThreshold": { "raw": "850000000000000000000000000", "decimals": 27, "value": "0.85", "formatted": "85.0" }, "ltv": { "raw": "750000000000000000000000000", "decimals": 27, "value": "0.75", "formatted": "75.0" }, "isInIsolationMode": false } } } ```
--- Source: https://aave.com/docs/aave-v3/markets/supply.md # Supply Assets on Aave V3 Supply assets to Aave V3 markets to earn interest, and enable or disable them as collateral. ## Permit Overview Some Aave operations support _permit functionality_ using [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) signatures to authorize ERC-20 token transfers within the same transaction. ### Benefits of Permit - **Single Transaction**: Execute operations without separate approval transactions - **Exact Amounts**: Sign permissions for specific amounts instead of infinite approvals - **Time Limited**: Permits have deadlines for enhanced security > [!NOTE] > Permit is available for ERC-20 tokens that implement > [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612). ## Supply Assets By supplying assets to an Aave market, users earn interest on their deposits according to the reserve’s supply APY rate. When supplying assets to an Aave market, you can use the following methods: | Method | Description | Typical Scenario | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | **Direct Supply** | Supply ERC-20 or native tokens directly from the sender’s wallet. aTokens are sent to the sender’s address. | User supplies assets from their own wallet. | | **On Behalf of Another** | Supply from the sender’s wallet, but send aTokens to another address. | User supplies from one wallet and the supply position (aTokens) belongs to another. | | **With Permit** | Use a permit signature to skip ERC-20 approval and supply in a single transaction. | User signs a permit and sends a single transaction. No ERC-20 allowance left behind. | | **With Permit, On Behalf of Another** | Same as permit supply, but aTokens are sent to another address. | No ERC-20 allowance needed and the supply position belongs to another wallet. | To supply assets to an Aave market, follow these steps. ### 1. Identify the Supply Reserve First, determine which reserve you want to supply assets to. Given this `Reserve` object for WETH on an Ethereum market: ```ts title="Reserve" const reserve: Reserve = { __typename: "Reserve", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, underlyingToken: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, acceptsNative: { __typename: "NativeCurrency", symbol: "ETH", name: "Ethereum", // … }, isFrozen: false, isPaused: false, permitSupported: true, userState: { __typename: "ReserveUserState", suppliable: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "1245.67", raw: "1245670000000000000000", decimals: 18, // … }, // … }, }, // … }; ``` To supply to the reserve, you need to verify these conditions: - `Reserve.isFrozen` is `false` - the reserve is not frozen - `Reserve.isPaused` is `false` - the reserve is not paused - `Reserve.userState.suppliable.amount.value` is **greater than 0** - the amount the user can supply to the reserve given their unique circumstances > [!NOTE] > Include a user address when fetching market and reserve data, or > `Reserve.userState` will be empty. The `Reserve.permitSupported` flag indicates whether the underlying token supports EIP-2612 permits. Additionally, if `Reserve.acceptsNative` is not `null`, users can choose to supply the asset as the chain’s native token and it will be automatically wrapped before being sent to the reserve. This is typical for reserves of the wrapped version of the chain’s native token (e.g., WETH on Ethereum). ### 2. Prepare the Supply Execution Plan Next, if all of these conditions are met, we can proceed with creating the execution plan for the supply operation. Use the `useSupply` hook in React, the `supply` action in TypeScript, or the `supply` query in GraphQL to create the execution plan for supplying assets to a market reserve. In React and TypeScript, you can optionally supply on behalf of another address. ```tsx title="Direct ERC-20 Supply" import { useWalletClient } from "wagmi"; import { useSupply, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [supply, supplying] = useSupply(); const execute = async () => { const result = await supply({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }); // … }; ``` ```tsx title="Direct Native Supply" import { useWalletClient } from "wagmi"; import { useSupply, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [supply, supplying] = useSupply(); const execute = async () => { const result = await supply({ market: reserve.market.address, amount: { native: bigDecimal(42), // 42 ETH }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }); // … }; ``` ```tsx title="Supply On Behalf of Another" import { useWalletClient } from "wagmi"; import { useSupply, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [supply, supplying] = useSupply(); const execute = async () => { const result = await supply({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, // OR // native: bigDecimal(42), // 42 ETH }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); // … }; ``` ```ts title="Direct ERC-20 Supply" import { supply } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await supply(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }); // … ``` ```ts title="Direct Native Supply" import { supply } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await supply(client, { market: reserve.market.address, amount: { native: bigDecimal(42), // 42 ETH }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }); // … ``` ```ts title="Supply On Behalf of Another" import { supply } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await supply(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, // OR // native: bigDecimal(42), // 42 ETH }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { supply( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: "42" } # OR # native: "42" # if the reserve accepts native currency } sender: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } ) { __typename ... on TransactionRequest { to from data value chainId operation } ... on ApprovalRequired { reason requiredAmount { value decimals } currentAllowance { value decimals } approval { to from data value chainId operation } originalTransaction { to from data value chainId operation } } ... on InsufficientBalanceError { required { value decimals } available { value decimals } } } } ``` If `Reserve.permitSupported` is `true` and you supply ERC-20 tokens, you can sign permits and prepare supply transactions. - **React**: Use the `useSupply` and `useERC20Permit` hooks, with the `useERC20Permit` implementation for the [wallet library of choice](../getting-started/react#sign-erc-20-permits). - **TypeScript**: Use the `supply` and `permitTypedData` actions together with the `signERC20PermitWith` helper, with the `signERC20PermitWith` implementation for the [wallet library of choice](../getting-started/typescript#sign-erc-20-permits). ```tsx title="Supply ERC-20 with Permit" import { useSupply, bigDecimal, evmAddress } from "@aave/react"; import { useERC20Permit } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; // … const { data: walletClient } = useWalletClient(); const [signPermit, signing] = useERC20Permit(walletClient); const [supply, supplying] = useSupply(); const execute = async () => { const amount = bigDecimal(42); // 42 WETH const permit = await signPermit({ amount, chainId: reserve.market.chain.chainId, currency: reserve.underlyingToken.address, owner: evmAddress(walletClient!.account.address), spender: reserve.market.address, }).andThen((signature) => supply({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: amount, // 42 WETH permitSig: signature, }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }) ); // … }; ``` ```tsx title="Supply ERC-20 with Permit On Behalf of Another" import { useSupply, bigDecimal, evmAddress } from "@aave/react"; import { useERC20Permit } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; // … const { data: walletClient } = useWalletClient(); const [signPermit, signing] = useERC20Permit(walletClient); const [supply, supplying] = useSupply(); const execute = async () => { const amount = bigDecimal(42); // 42 WETH const permit = await signPermit({ amount, chainId: reserve.market.chain.chainId, currency: reserve.underlyingToken.address, owner: evmAddress(walletClient!.account.address), spender: reserve.market.address, }).andThen((signature) => supply({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: amount, // 42 WETH permitSig: signature, }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }) ); // … }; ``` ```tsx title="Supply ERC-20 with Permit" import { supply, permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const amount = bigDecimal(42); // 42 WETH const result = await permitTypedData(client, { amount, chainId: reserve.market.chain.chainId, currency: reserve.underlyingToken.address, owner: evmAddress(wallet.account.address), spender: reserve.market.address, }) .andThen(signERC20PermitWith(wallet)) .andThen((signature) => supply(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: amount, permitSig: signature, }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }) ); // … ``` ```tsx title="Supply ERC-20 with Permit On Behalf of Another" import { supply, permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const amount = bigDecimal(42); // 42 WETH const result = await permitTypedData(client, { amount, chainId: reserve.market.chain.chainId, currency: reserve.underlyingToken.address, owner: evmAddress(wallet.account.address), spender: reserve.market.address, }) .andThen(signERC20PermitWith(wallet)) .andThen((signature) => supply(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: amount, permitSig: signature, }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }) ); // … ``` ### 3. Process the Supply Execution Plan Finally, you need to handle the execution plan, and the process is the same whether or not you used a permit in the previous step. > [!NOTE] > With a permit signature, the execution plan runs as a single transaction. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transactions in the execution plan. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. - **GraphQL**: If the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { errAsync, useSupply } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [supply, supplying] = useSupply(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = supplying.loading || sending.loading; const error = supplying.error || sending.error; // … const execute = async () => { const result = await supply({ // … }).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("Supply failed:", result.error); } else { console.log("Supply successful with hash:", result.value); } }; ``` ```ts title="Viem" import { supply } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await supply(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Supply failed:", result.error); } else { console.log("Supply successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "supply": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x617ba037000000000000000000000000c0…", "value": "0", "chainId": 1, "operation": "SUPPLY" } } } ``` In GraphQL, if the response is an `ApprovalRequired`, you must first send the `approval` transaction. Once it succeeds, you can then send the `originalTransaction`. ```json title="ApprovalRequired" { "data": { "supply": { "__typename": "ApprovalRequired", "reason": "Insufficient allowance for ERC-20 token transfer", "requiredAmount": { "value": "42.0", "decimals": 18 }, "currentAllowance": { "value": "0.0", "decimals": 18 }, "approval": { "to": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operation": null }, "originalTransaction": { "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x617ba037000000000000000000000000c0…", "value": "0", "chainId": 1, "operation": "SUPPLY" } } } } ``` In GraphQL, if the response is an `InsufficientBalanceError`, inform the user that they don’t have enough balance to supply the requested amount. ```json title="InsufficientBalanceError" { "data": { "supply": { "__typename": "InsufficientBalanceError", "required": { "value": "42.0", "decimals": 18 }, "available": { "value": "15.5", "decimals": 18 } } } } ``` ## Collateral Management To manage which supplied assets are used as collateral for borrowing, follow these steps. ### 1. Identify the Collateral Position First, determine which user supply position you want to enable or disable as collateral. Given this `MarketUserReserveSupplyPosition` object: ```ts title="MarketUserReserveSupplyPosition" const position: MarketUserReserveSupplyPosition = { __typename: "MarketUserReserveSupplyPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, balance: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "5.0", raw: "5000000000000000000", decimals: 18, // … }, // … }, isCollateral: false, // Currently not used as collateral canBeCollateral: true, // Can be enabled as collateral // … }; ``` To enable a position as collateral, you need to verify these conditions: - `position.canBeCollateral` is `true` - the asset can be used as collateral - `position.isCollateral` is `false` - the asset is not currently used as collateral To disable a position as collateral, you only need to check if `position.isCollateral` is `true`. > [!NOTE] > An Aave DAO vote can disable a reserve as collateral. This blocks new > collateral use but doesn’t affect existing positions. ### 2. Prepare the Collateral Transaction Request Next, we can proceed with creating the transaction request for the collateral toggle operation. Use the `useCollateralToggle` hook in React, the `collateralToggle` action in TypeScript, or the `collateralToggle` query in GraphQL to create the transaction request for enabling or disabling collateral. ```tsx title="Toggle Collateral" import { useWalletClient } from "wagmi"; import { useCollateralToggle, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [toggleCollateral, toggling] = useCollateralToggle(); const execute = async () => { const result = await toggleCollateral({ market: position.market.address, underlyingToken: position.currency.address, user: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```ts title="Toggle Collateral" import { collateralToggle } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await collateralToggle(client, { market: position.market.address, underlyingToken: position.currency.address, user: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { collateralToggle( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" underlyingToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } ) { to from data value chainId } } ``` ### 3. Send the Collateral Transaction Finally, send the transaction. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transaction. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to initiate the transaction, and await indexing with `client.waitForTransaction`. - **GraphQL**: The response is a `TransactionRequest` that can be sent directly using the wallet associated with the `from` address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useCollateralToggle } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [toggleCollateral, toggling] = useCollateralToggle(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = toggling.loading || sending.loading; const error = toggling.error || sending.error; // … const execute = async () => { const result = await toggleCollateral({ // … }).andThen(sendTransaction); if (result.isErr()) { console.error("Collateral toggle failed:", result.error); } else { console.log("Collateral toggle successful with hash:", result.value); } }; ``` ```ts title="Viem" import { collateralToggle } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await collateralToggle(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Collateral toggle failed:", result.error); } else { console.log("Collateral toggle successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "collateralToggle": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x5a3b74b9000000000000000000000000c02…", "value": "0", "chainId": 1, "operation": "RESERVE_USED_AS_COLLATERAL_ENABLED" } } } ``` --- Source: https://aave.com/docs/aave-v3/markets/borrow.md # Borrow Assets on Aave V3 Borrow assets from Aave V3 markets against your collateral, or delegate your borrowing power. ## Borrow Assets Users can borrow assets from Aave markets at the reserve’s borrow APY using supply positions as collateral. When borrowing assets from an Aave market, you can use the following methods: | Method | Description | Typical Scenario | | --------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | **Direct Borrow** | Borrow assets from a reserve using supplied collateral | User borrows from a reserve against their own supplied collateral. | | **Credit Delegation** | Borrow assets from a reserve using delegated borrow credits | User borrows from a reserve using credits from collateral supplied by a credit delegator. | To borrow assets from an Aave market, follow these steps. ### 1. Identify the Borrow Reserve First, determine which reserve you want to borrow assets from. Given this `Reserve` object for WETH on an Ethereum market: ```ts title="Reserve" const reserve: Reserve = { __typename: "Reserve", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, underlyingToken: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, acceptsNative: { __typename: "NativeCurrency", symbol: "ETH", name: "Ethereum", // … }, isFrozen: false, isPaused: false, userState: { __typename: "ReserveUserState", borrowable: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "15.75", raw: "15750000000000000000", decimals: 18, // … }, // … }, }, // … }; ``` To borrow from the reserve, you need to verify these conditions: - `Reserve.isFrozen` is `false` - the reserve is not frozen - `Reserve.isPaused` is `false` - the reserve is not paused - `Reserve.userState.borrowable.amount.value` is **greater than 0** - the amount the user can borrow from the reserve given their unique circumstances > [!NOTE] > Include a user address when fetching market and reserve data, or > `Reserve.userState` will be empty. Additionally, if `Reserve.acceptsNative` is not `null`, users can choose to receive any borrowed assets as the chain’s native token and it will be automatically unwrapped before being sent to the user’s wallet. This is typical for reserves of the wrapped version of the chain’s native token (e.g., WETH on Ethereum). ### 2. Prepare the Borrow Execution Plan Next, if all of these conditions are met, we can proceed with creating the execution plan for the borrow operation. Use the `useBorrow` hook in React, the `borrow` action in TypeScript, or the `borrow` query in GraphQL to create the execution plan for a direct borrow operation. ```tsx title="Direct ERC-20 Borrow" import { useWalletClient } from "wagmi"; import { useBorrow, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [borrow, borrowing] = useBorrow(); const execute = async () => { const result = await borrow({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(2), // 2 WETH }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }); // … }; ``` ```tsx title="Direct Native Borrow" import { useWalletClient } from "wagmi"; import { useBorrow, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [borrow, borrowing] = useBorrow(); const execute = async () => { const result = await borrow({ market: reserve.market.address, amount: { native: bigDecimal(2), // 2 ETH }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }); // … }; ``` ```ts title="Direct ERC-20 Borrow" import { borrow } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await borrow(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(2), // 2 WETH }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }); // … ``` ```ts title="Direct Native Borrow" import { borrow } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await borrow(client, { market: reserve.market.address, amount: { native: bigDecimal(2), // 2 ETH }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Direct Borrow" query { borrow( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: "2" } # OR # native: "2" # if the reserve accepts native currency } sender: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } ) { __typename ... on TransactionRequest { to from data value chainId operation } ... on ApprovalRequired { reason requiredAmount { value decimals } currentAllowance { value decimals } approval { to from data value chainId operation } originalTransaction { to from data value chainId operation } } ... on InsufficientBalanceError { required { value decimals } available { value decimals } } } } ``` If you intend to leverage credit delegation, you can first check the credit delegation allowance. ```tsx title="Check Credit Delegation Allowance" import { useCreditDelegateeAllowance, evmAddress } from "@aave/react"; // … const { data: allowance, loading } = useCreditDelegateeAllowance({ market: reserve.market.address, underlyingToken: reserve.underlyingToken.address, user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), // Delegator delegatee: evmAddress(walletClient!.account.address), // Your address chainId: reserve.market.chain.chainId, }); if (allowance && BigInt(allowance.amount.raw) > 0n) { console.log("Available delegation allowance:", allowance.amount.value); } else { console.log("No credit delegation allowance available"); } ``` ```ts title="Check Credit Delegation Allowance" import { creditDelegateeAllowance } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const allowanceResult = await creditDelegateeAllowance(client, { market: reserve.market.address, underlyingToken: reserve.underlyingToken.address, user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), // Delegator delegatee: evmAddress(wallet.account.address), // Your address chainId: reserve.market.chain.chainId, }); if (allowanceResult.isOk() && BigInt(allowanceResult.value.amount.raw) > 0n) { console.log( "Available delegation allowance:", allowanceResult.value.amount.value ); } else { console.log("No credit delegation allowance available"); } ``` ```graphql title="Check Credit Delegation Allowance Query" query { creditDelegateeAllowance( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" underlyingToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" # Delegator delegatee: "0x8ba1f109551bd432803012645ac136ddd64dba72" # Your address chainId: 1 } ) { usdPerToken amount { value raw decimals } usd } } ``` And then, you can proceed with preparing the execution plan for the borrow operation. ```tsx title="Borrow with Credit Delegation" import { useWalletClient } from "wagmi"; import { useBorrow, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [borrow, borrowing] = useBorrow(); const execute = async () => { const result = await borrow({ market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(2), // 2 WETH }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), // Delegator }); // … }; ``` ```ts title="Borrow with Credit Delegation" import { borrow } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await borrow(client, { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(2), // 2 WETH }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), // Delegator }); // … ``` ```graphql title="Borrow with Credit Delegation" query { borrow( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: "2" } # OR # native: "2" # if the reserve accepts native currency } sender: "0x8ba1f109551bd432803012645ac136ddd64dba72" # Delegatee chainId: 1 onBehalfOf: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" # Delegator } ) { # … } } ``` ### 3. Process the Borrow Execution Plan Finally, handle the execution plan. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transactions in the execution plan. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. - **GraphQL**: If the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { errAsync, useBorrow } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [borrow, borrowing] = useBorrow(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = borrowing.loading || sending.loading; const error = borrowing.error || sending.error; // … const execute = async () => { const result = await borrow({ // … }).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("Borrow failed:", result.error); } else { console.log("Borrow successful with hash:", result.value); } }; ``` ```ts title="Viem" import { borrow } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await borrow(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Borrow failed:", result.error); } else { console.log("Borrow successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "borrow": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xa415bcad000000000000000000000000a0b…", "value": "0", "chainId": 1, "operation": "BORROW" } } } ``` In GraphQL, if the response is an `ApprovalRequired`, you must first send the `approval` transaction. Once it succeeds, you can then send the `originalTransaction`. This happens only for native borrows, which need credit delegation to the WrappedTokenGateway. ```json title="ApprovalRequired" { "data": { "borrow": { "__typename": "ApprovalRequired", "reason": "Insufficient credit delegation to the WrappedTokenGateway", "requiredAmount": { "value": "2.0", "decimals": 18 }, "currentAllowance": { "value": "0.0", "decimals": 18 }, "approval": { "to": "0xeA51d7853EEFb32b6ee06b1C12E6dcCA88Be0fFE", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xc04a8a10000000000000000000000000d01…", "value": "0", "chainId": 1, "operation": null }, "originalTransaction": { "to": "0xd01607c3C5eCABa394D8be377a08590149325722", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xe74f7b85000000000000000000000000878…", "value": "0", "chainId": 1, "operation": "BORROW" } } } } ``` In GraphQL, if the response is an `InsufficientBalanceError`, inform the user that they don’t have enough balance to borrow the requested amount. ```json title="InsufficientBalanceError" { "data": { "borrow": { "__typename": "InsufficientBalanceError", "required": { "value": "2.0", "decimals": 18 }, "available": { "value": "1.0", "decimals": 18 } } } } ``` ## Credit Delegation Credit delegation allows a user to approve another user (delegatee) to borrow assets against their own supply position. The supply position must be enabled as collateral. To delegate credit to another address, follow these steps. ### 1. Identify the Delegated Position First, choose the asset the delegatee may borrow and make sure your collateral is enabled. Given this `MarketUserReserveSupplyPosition` object: ```ts title="MarketUserReserveSupplyPosition" const position: MarketUserReserveSupplyPosition = { __typename: "MarketUserReserveSupplyPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, balance: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "5.0", raw: "5000000000000000000", decimals: 18, // … }, // … }, isCollateral: true, canBeCollateral: true, // … }; ``` Ensure `MarketUserReserveSupplyPosition.isCollateral` is `true`, if not [enable it as collateral](./supply#collateral-management) first. ### 2. Prepare the Delegation Transaction Request Next, we can proceed with creating the transaction request for the credit delegation operation. Use the `useApproveBorrowCreditDelegation` hook in React, the `approveBorrowCreditDelegation` action in TypeScript, or the `approveBorrowCreditDelegation` query in GraphQL to create the transaction request for approving credit delegation. `underlyingToken` is the asset the delegatee will borrow; the example uses WETH. ```tsx title="Approve Credit Delegation" import { useWalletClient } from "wagmi"; import { useApproveBorrowCreditDelegation, evmAddress, bigDecimal, } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [approveDelegation, approving] = useApproveBorrowCreditDelegation(); const execute = async () => { const result = await approveDelegation({ market: position.market.address, underlyingToken: position.currency.address, amount: bigDecimal(1000), user: evmAddress(walletClient!.account.address), delegatee: evmAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"), chainId: position.market.chain.chainId, }); // … }; ``` ```ts title="Approve Credit Delegation" import { approveBorrowCreditDelegation } from "@aave/client/actions"; import { evmAddress, bigDecimal } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await approveBorrowCreditDelegation(client, { market: position.market.address, underlyingToken: position.currency.address, amount: bigDecimal(1000), user: evmAddress(wallet.account.address), delegatee: evmAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"), chainId: position.market.chain.chainId, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { approveBorrowCreditDelegation( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" underlyingToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" amount: "1000" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" delegatee: "0x8ba1f109551bd432803012645ac136ddd64dba72" chainId: 1 } ) { to from data value chainId } } ``` ### 3. Send the Delegation Transaction Finally, send the transaction. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transaction. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to initiate the transaction, and await indexing with `client.waitForTransaction`. - **GraphQL**: The response is a `TransactionRequest` that can be sent directly using the wallet associated with the `from` address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useApproveBorrowCreditDelegation } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [approveDelegation, approving] = useApproveBorrowCreditDelegation(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = approving.loading || sending.loading; const error = approving.error || sending.error; // … const execute = async () => { const result = await approveDelegation({ // … }).andThen(sendTransaction); if (result.isErr()) { console.error("Credit delegation failed:", result.error); } else { console.log("Credit delegation successful with hash:", result.value); } }; ``` ```ts title="Viem" import { approveBorrowCreditDelegation } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await approveBorrowCreditDelegation(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Credit delegation failed:", result.error); } else { console.log("Credit delegation successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "approveBorrowCreditDelegation": { "__typename": "TransactionRequest", "to": "0xeA51d7853EEFb32b6ee06b1C12E6dcCA88Be0fFE", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xc04a8a10…", "value": "0", "chainId": 1, "operation": null } } } ``` The delegatee can now borrow against the user’s supply position. --- Source: https://aave.com/docs/aave-v3/markets/repay.md # Repay Loans on Aave V3 Repay borrowed assets to Aave V3 markets. ## Repay Loans By repaying borrowed assets to an Aave market, users reduce or clear their debt position. When repaying borrowed assets to an Aave market, you can use the following methods: | Method | Description | Typical Scenario | | ----------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | **Direct Repay** | Repay ERC-20 or native tokens directly from the sender’s wallet. | User repays borrowed assets from their own wallet balance. | | **On Behalf of Another** | Repay debt for another address. | User borrowed with one wallet and wants to repay from a different wallet. | | **With Permit** | Use a permit signature to skip ERC-20 approval and repay in a single transaction. | User signs a permit and sends a single transaction. No ERC-20 allowance left behind. | | **With Permit, On Behalf of Another** | Same as permit repay, but the debt position is owned by another wallet. | No ERC-20 allowance needed when repaying debt for another wallet. | To repay borrowed assets from an Aave market, follow these steps. ### 1. Identify the Borrow Position First, determine which user borrow position you want to repay debt for. Given this `MarketUserReserveBorrowPosition` object: ```ts title="MarketUserReserveBorrowPosition" const position: MarketUserReserveBorrowPosition = { __typename: "MarketUserReserveBorrowPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, debt: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "1.5", raw: "1500000000000000000", decimals: 18, // … }, // … }, // … }; ``` That is tied to the following `Reserve` object. ```ts title="Reserve" const reserve: Reserve = { __typename: "Reserve", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, underlyingToken: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, permitSupported: true, acceptsNative: { __typename: "NativeCurrency", // … }, }; ``` The `Reserve.permitSupported` flag indicates whether the underlying token supports EIP-2612 permits. Additionally, if `Reserve.acceptsNative` is not `null`, users can choose to repay the borrow position as the chain’s native token and it will be automatically wrapped before being sent to the reserve. This is typical for reserves of the wrapped version of the chain’s native token (e.g., WETH on Ethereum). ### 2. Prepare the Repay Execution Plan Next, we can proceed with creating the execution plan for the repay operation. Use the `useRepay` hook in React, the `repay` action in TypeScript, or the `repay` query in GraphQL to create the execution plan for repaying debt from a market reserve, optionally on behalf of another address. ```tsx title="Repay ERC-20" import { useWalletClient } from "wagmi"; import { useRepay, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [repay, repaying] = useRepay(); const execute = async () => { const result = await repay({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Repay Native" import { useWalletClient } from "wagmi"; import { useRepay, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [repay, repaying] = useRepay(); const execute = async () => { const result = await repay({ market: position.market.address, amount: { native: bigDecimal(1), // 1 ETH }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Repay Max ERC-20" import { useWalletClient } from "wagmi"; import { useRepay, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [repay, repaying] = useRepay(); const execute = async () => { const result = await repay({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Repay On Behalf of Another" import { useWalletClient } from "wagmi"; import { useRepay, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [repay, repaying] = useRepay(); const execute = async () => { const result = await repay({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); // … }; ``` ```ts title="Repay ERC-20" import { repay } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Repay Native" import { repay } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { market: position.market.address, amount: { native: bigDecimal(1), // 1 ETH }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Repay Max ERC-20" import { repay } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Repay On Behalf of Another" import { repay } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { repay( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: { exact: "1" # OR # max: true } } # OR if the reserve accepts native currency # native: "1" } sender: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 # optional # onBehalfOf: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" } ) { __typename ... on TransactionRequest { to from data value chainId operation } ... on ApprovalRequired { reason requiredAmount { value decimals } currentAllowance { value decimals } approval { to from data value chainId operation } originalTransaction { to from data value chainId operation } } ... on InsufficientBalanceError { required { value decimals } available { value decimals } } } } ``` If `Reserve.permitSupported` is `true` and your borrow position is an ERC-20 token, you can sign [permits](./supply#permit-overview) and prepare repay transactions. - **React**: Use the `useRepay` and `useERC20Permit` hooks, with the `useERC20Permit` implementation for the [wallet library of choice](../getting-started/react#sign-erc-20-permits). - **TypeScript**: Use the `repay` and `permitTypedData` actions together with the `signERC20PermitWith` helper, with the `signERC20PermitWith` implementation for the [wallet library of choice](../getting-started/typescript#sign-erc-20-permits). ```tsx title="Repay ERC-20 with Permit" import { useRepay, bigDecimal, evmAddress } from "@aave/react"; import { useERC20Permit } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; // … const { data: walletClient } = useWalletClient(); const [signPermit, signing] = useERC20Permit(walletClient); const [repay, repaying] = useRepay(); const execute = async () => { const amount = bigDecimal(1); // 1 WETH const permit = await signPermit({ amount, chainId: position.market.chain.chainId, currency: position.currency.address, owner: evmAddress(walletClient!.account.address), spender: position.market.address, }).andThen((signature) => repay({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: amount, // 1 WETH }, permitSig: signature, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }) ); // … }; ``` ```tsx title="Repay ERC-20 with Permit On Behalf of Another" import { useRepay, bigDecimal, evmAddress } from "@aave/react"; import { useERC20Permit } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; // … const { data: walletClient } = useWalletClient(); const [signPermit, signing] = useERC20Permit(walletClient); const [repay, repaying] = useRepay(); const execute = async () => { const amount = bigDecimal(1); // 1 WETH const permit = await signPermit({ amount, chainId: position.market.chain.chainId, currency: position.currency.address, owner: evmAddress(walletClient!.account.address), spender: position.market.address, }).andThen((signature) => repay({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: amount, // 1 WETH }, permitSig: signature, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }) ); // … }; ``` ```tsx title="Repay ERC-20 with Permit" import { repay, permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const amount = bigDecimal(1); // 1 WETH const result = await permitTypedData(client, { amount, chainId: position.market.chain.chainId, currency: position.currency.address, owner: evmAddress(wallet.account.address), spender: position.market.address, }) .andThen(signERC20PermitWith(wallet)) .andThen((signature) => repay(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: amount, }, permitSig: signature, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }) ); // … ``` ```tsx title="Repay ERC-20 with Permit On Behalf of Another" import { repay, permitTypedData } from "@aave/client/actions"; import { signERC20PermitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const amount = bigDecimal(1); // 1 WETH const result = await permitTypedData(client, { amount, chainId: position.market.chain.chainId, currency: position.currency.address, owner: evmAddress(wallet.account.address), spender: position.market.address, }) .andThen(signERC20PermitWith(wallet)) .andThen((signature) => repay(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: amount, }, permitSig: signature, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, onBehalfOf: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), }) ); // … ``` ### 3. Process the Repay Execution Plan Finally, handle the execution plan. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transactions in the execution plan. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. - **GraphQL**: If the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { errAsync, useRepay } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [repay, repaying] = useRepay(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = repaying.loading || sending.loading; const error = repaying.error || sending.error; // … const execute = async () => { const result = await repay({ // … }).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("Repay failed:", result.error); } else { console.log("Repay successful with hash:", result.value); } }; ``` ```ts title="Viem" import { repay } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Repay failed:", result.error); } else { console.log("Repay successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "repay": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x573ade81000000000000000000000000c02…", "value": "0", "chainId": 1, "operation": "REPAY" } } } ``` In GraphQL, if the response is an `ApprovalRequired`, you must first send the `approval` transaction. Once it succeeds, you can then send the `originalTransaction`. ```json title="ApprovalRequired" { "data": { "repay": { "__typename": "ApprovalRequired", "reason": "Insufficient allowance for ERC-20 token transfer", "requiredAmount": { "value": "1.0", "decimals": 18 }, "currentAllowance": { "value": "0.0", "decimals": 18 }, "approval": { "to": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operation": null }, "originalTransaction": { "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x573ade81000000000000000000000000c02…", "value": "0", "chainId": 1, "operation": "REPAY" } } } } ``` In GraphQL, if the response is an `InsufficientBalanceError`, inform the user that they don’t have enough balance to repay the requested amount. ```json title="InsufficientBalanceError" { "data": { "repay": { "__typename": "InsufficientBalanceError", "required": { "value": "1.0", "decimals": 18 }, "available": { "value": "0.5", "decimals": 18 } } } } ``` --- Source: https://aave.com/docs/aave-v3/markets/withdraw.md # Withdraw Assets on Aave V3 Withdraw supplied assets from Aave V3 markets. ## Withdraw Assets Users can withdraw assets from Aave markets using their previously supplied reserves. When withdrawing assets from an Aave market, you can use the following methods: | Method | Description | Typical Scenario | | --------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------- | | **Direct Withdraw** | Withdraw ERC-20 or native tokens directly to supplier wallet. | User withdraws supplied assets from their own wallet balance. | | **Another Recipient** | Withdraw supplied assets to another address. | User supplied with one wallet and wants to withdraw to a different wallet. | To withdraw supplied assets from an Aave market, follow these steps. ### 1. Identify the Supply Position First, determine which user supply position you want to withdraw assets from. Given this `MarketUserReserveSupplyPosition` object: ```ts title="MarketUserReserveSupplyPosition" const position: MarketUserReserveSupplyPosition = { __typename: "MarketUserReserveSupplyPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, balance: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "5.0", raw: "5000000000000000000", decimals: 18, // … }, // … }, // … }; ``` That is tied to the following `Reserve` object. ```ts title="Reserve" const reserve: Reserve = { __typename: "Reserve", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, underlyingToken: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, acceptsNative: { __typename: "NativeCurrency", // … }, }; ``` ### 2. Prepare the Withdraw Execution Plan Next, we can proceed with creating the execution plan for the withdraw operation. Use the `useWithdraw` hook in React, the `withdraw` action in TypeScript, or the `withdraw` query in GraphQL to create the execution plan for withdrawing assets from a market reserve. ```tsx title="Withdraw ERC-20 Amount" import { useWalletClient } from "wagmi"; import { useWithdraw, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(2), // 2 WETH }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Withdraw Max ERC-20 Amount" import { useWalletClient } from "wagmi"; import { useWithdraw, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Withdraw to Another Recipient" import { useWalletClient } from "wagmi"; import { useWithdraw, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(2), // 2 WETH }, }, }, recipient: evmAddress("0x1234567890123456789012345678901234567890"), sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```ts title="Withdraw ERC-20 Amount" import { withdraw } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(2), // 2 WETH }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Withdraw Max ERC-20 Amount" import { withdraw } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Withdraw to Another Recipient" import { withdraw } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(2), // 2 WETH }, }, }, recipient: evmAddress("0x1234567890123456789012345678901234567890"), sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Withdraw Native to Another Recipient" import { withdraw } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { native: { value: { exact: bigDecimal(2) }, // 2 ETH }, }, recipient: evmAddress("0x1234567890123456789012345678901234567890"), sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { withdraw( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: { exact: "2" # OR # max: true } } # OR if the reserve accepts native currency # native: { # value: { exact: "2" } # # OR # # max: true # } } sender: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 # OPTIONAL: if you want to withdraw to a different address # recipient: "0x1234567890123456789012345678901234567890" } ) { __typename ... on TransactionRequest { to from data value chainId operation } ... on ApprovalRequired { reason requiredAmount { value decimals } currentAllowance { value decimals } approval { to from data value chainId operation } originalTransaction { to from data value chainId operation } } ... on InsufficientBalanceError { required { value decimals } available { value decimals } } } } ``` If `Reserve.acceptsNative` is not `null`, you can choose to withdraw the assets as the chain’s native token. ```tsx title="Withdraw Exact Native Amount" import { useWalletClient } from "wagmi"; import { useWithdraw, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { native: { value: { exact: bigDecimal(2) }, // 2 ETH }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Withdraw Max Native Amount" import { useWalletClient } from "wagmi"; import { useWithdraw, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { native: { value: { max: true }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```tsx title="Withdraw Native to Another Recipient" import { useWalletClient } from "wagmi"; import { useWithdraw, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const execute = async () => { const result = await withdraw({ market: position.market.address, amount: { native: { value: { exact: bigDecimal(2) }, // 2 ETH }, }, recipient: evmAddress("0x1234567890123456789012345678901234567890"), sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }); // … }; ``` ```ts title="Withdraw Exact Native Amount" import { withdraw } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { native: { value: { exact: bigDecimal(2) }, // 2 ETH }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ```ts title="Withdraw Max Native Amount" import { withdraw } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { market: position.market.address, amount: { native: { value: { max: true }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }); // … ``` ### 3. Process the Withdraw Execution Plan Finally, handle the execution plan. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transactions in the execution plan. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. - **GraphQL**: If the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { errAsync, useWithdraw } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [withdraw, withdrawing] = useWithdraw(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = withdrawing.loading || sending.loading; const error = withdrawing.error || sending.error; // … const execute = async () => { const result = await withdraw({ // … }).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("Withdraw failed:", result.error); } else { console.log("Withdraw successful with hash:", result.value); } }; ``` ```ts title="Viem" import { withdraw } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await withdraw(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Withdraw failed:", result.error); } else { console.log("Withdraw successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "withdraw": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x69328dec000000000000000000000000c02…", "value": "0", "chainId": 1, "operation": "WITHDRAW" } } } ``` In GraphQL, if the response is an `ApprovalRequired`, you must first send the `approval` transaction. Once it succeeds, you can then send the `originalTransaction`. ```json title="ApprovalRequired" { "data": { "withdraw": { "__typename": "ApprovalRequired", "reason": "Insufficient allowance for aToken transfer", "requiredAmount": { "value": "2.0", "decimals": 18 }, "currentAllowance": { "value": "0.0", "decimals": 18 }, "approval": { "to": "0x4d5F47FA6A74757f35C14fD3a6Ef8E3C9BC514E8", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operation": null }, "originalTransaction": { "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x69328dec000000000000000000000000c02…", "value": "0", "chainId": 1, "operation": "WITHDRAW" } } } } ``` In GraphQL, if the response is an `InsufficientBalanceError`, inform the user that they don’t have enough balance to withdraw the requested amount. ```json title="InsufficientBalanceError" { "data": { "withdraw": { "__typename": "InsufficientBalanceError", "required": { "value": "2.0", "decimals": 18 }, "available": { "value": "1.5", "decimals": 18 } } } } ``` --- Source: https://aave.com/docs/aave-v3/markets/health-factor.md # Aave V3 Health Factor Preview Preview how a supply, borrow, repay or withdraw changes a user’s health factor before sending it. The health factor compares the liquidation-weighted collateral to the debt: A health factor below 1 makes the position eligible for liquidation. > [!NOTE] > The health factor is null unless the user has at least one active borrow. To preview how a user’s health factor will change before executing a market operation (supply, borrow, repay, withdraw), use the `useAaveHealthFactorPreview` hook in React, the `healthFactorPreview` client action in TypeScript, or the `healthFactorPreview` query in GraphQL. ```tsx title="Borrow" import { useWalletClient } from "wagmi"; import { useAaveHealthFactorPreview, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [preview, { loading, error }] = useAaveHealthFactorPreview(); const execute = async () => { const result = await preview({ action: { borrow: { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } }; ``` ```tsx title="Supply" import { useWalletClient } from "wagmi"; import { useAaveHealthFactorPreview, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [preview, { loading, error }] = useAaveHealthFactorPreview(); const execute = async () => { const result = await preview({ action: { supply: { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(walletClient!.account.address), chainId: reserve.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } }; ``` ```tsx title="Repay" import { useWalletClient } from "wagmi"; import { useAaveHealthFactorPreview, bigDecimal, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [preview, { loading, error }] = useAaveHealthFactorPreview(); const execute = async () => { const result = await preview({ action: { repay: { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } }; ``` ```tsx title="Withdraw" import { useWalletClient } from "wagmi"; import { useAaveHealthFactorPreview, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [preview, { loading, error }] = useAaveHealthFactorPreview(); const execute = async () => { const result = await preview({ action: { withdraw: { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(walletClient!.account.address), chainId: position.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } }; ``` ```ts title="Borrow" import { bigDecimal, evmAddress } from "@aave/client"; import { healthFactorPreview } from "@aave/client/actions"; import { client } from "./client"; const result = await healthFactorPreview(client, { action: { borrow: { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } ``` ```ts title="Supply" import { bigDecimal, evmAddress } from "@aave/client"; import { healthFactorPreview } from "@aave/client/actions"; import { client } from "./client"; const result = await healthFactorPreview(client, { action: { supply: { market: reserve.market.address, amount: { erc20: { currency: reserve.underlyingToken.address, value: bigDecimal(42), // 42 WETH }, }, sender: evmAddress(wallet.account.address), chainId: reserve.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } ``` ```ts title="Repay" import { bigDecimal, evmAddress } from "@aave/client"; import { healthFactorPreview } from "@aave/client/actions"; import { client } from "./client"; const result = await healthFactorPreview(client, { action: { repay: { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { exact: bigDecimal(1), // 1 WETH }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } ``` ```ts title="Withdraw" import { evmAddress } from "@aave/client"; import { healthFactorPreview } from "@aave/client/actions"; import { client } from "./client"; const result = await healthFactorPreview(client, { action: { withdraw: { market: position.market.address, amount: { erc20: { currency: position.currency.address, value: { max: true, }, }, }, sender: evmAddress(wallet.account.address), chainId: position.market.chain.chainId, }, }, }); if (result.isErr()) { console.error(result.error); } else { console.log(result.value.after); // 1.5 or null } ``` ```graphql title="Query" query { healthFactorPreview( request: { action: { borrow: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" amount: { erc20: { currency: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" value: "42" } } sender: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } # OR # supply: { # … # } # OR # repay: { # … # } # OR # withdraw: { # … # } } } ) { before after } } ``` ```json title="Response" { "data": { "healthFactorPreview": { "after": "1.5", "before": null } } } ``` --- Source: https://aave.com/docs/aave-v3/markets/incentives.md # Aave V3 Incentive Programs Aave reserves may offer additional incentives beyond base lending rates. ## Incentive Types - **Supply Incentives**: Extra APR for supplying assets to reserves - **Borrow Incentives**: APR discounts for borrowing from reserves - **Conditional Incentives**: Bonus rewards requiring specific supply and borrow combinations Each reserve’s `incentives` array contains all active incentive programs. The incentive data includes: - APR bonuses/discounts with formatted percentages - Reward token information (for Aave governance incentives) - Claim links (for Merit programs) - Conditional requirements (for complex incentives) You can find the incentives associated with a reserve in the `incentives` array of the [Reserve](./data#reserve-structure) object. ```ts title="Reserve" interface Reserve { // … incentives: ReserveIncentive[]; } ``` ```ts title="ReserveIncentive" type ReserveIncentive = | MeritSupplyIncentive | MeritBorrowIncentive | MeritBorrowAndSupplyIncentiveCondition | AaveSupplyIncentive | AaveBorrowIncentive | MerklSupplyIncentive | MerklBorrowIncentive | SupplyPointsIncentive | BorrowPointsIncentive; ``` These incentives come from two main sources: - [Merit Programs](#merit-programs) - [Aave Governance Rewards](#aave-governance-rewards) ### Merit Programs [Third-party programs](https://apps.aavechan.com/merit) that provide extra APR rewards for specific lending activities. These require separate claiming through external platforms. > [!WARNING] > Merit programs are third-party initiatives. Aave Labs does not guarantee these > programs and accepts no liability for third-party rewards. ```ts title="MeritSupplyIncentive" interface MeritSupplyIncentive { __typename: "MeritSupplyIncentive"; extraSupplyApr: PercentValue; claimLink: string; } ``` ```ts title="MeritBorrowIncentive" interface MeritBorrowIncentive { __typename: "MeritBorrowIncentive"; borrowAprDiscount: PercentValue; claimLink: string; } ``` ```ts title="MeritBorrowAndSupplyIncentiveCondition" interface MeritBorrowAndSupplyIncentiveCondition { __typename: "MeritBorrowAndSupplyIncentiveCondition"; extraApr: PercentValue; supplyToken: Currency; borrowToken: Currency; claimLink: string; } ``` Where: - `MeritSupplyIncentive`: Extra APR for supplying assets to reserves - `MeritBorrowIncentive`: APR discounts for borrowing from reserves - `MeritBorrowAndSupplyIncentiveCondition`: Extra APR for supplying and borrowing the specified pair of assets For each of these types, a claim link to the [ACI Merit UI](https://apps.aavechan.com/merit) is provided. ### Aave Governance Rewards Incentives set by Aave governance through the [RewardsController](../smart-contracts/incentives), typically distributed in AAVE tokens or other approved reward tokens. ```ts title="AaveSupplyIncentive" interface AaveSupplyIncentive { __typename: "AaveSupplyIncentive"; extraSupplyApr: PercentValue; rewardTokenAddress: EvmAddress; rewardTokenSymbol: string; } ``` ```ts title="AaveBorrowIncentive" interface AaveBorrowIncentive { __typename: "AaveBorrowIncentive"; borrowAprDiscount: PercentValue; rewardTokenAddress: EvmAddress; rewardTokenSymbol: string; } ``` Where: - `AaveSupplyIncentive`: Extra APR for supplying assets to reserves - `AaveBorrowIncentive`: APR discounts for borrowing from reserves In both cases, the reward token address and symbol are provided. ## Claim Merit Rewards To check for and claim [Merit](https://apps.aavechan.com/merit) rewards, follow these steps. ### 1. Fetch the Claimable Rewards First, determine if a user has claimable rewards. Use the `useUserRewards` hook in React, the `userRewards` action in TypeScript, or the `userRewards` query in GraphQL to fetch the user’s claimable rewards and the transaction to claim them. ```ts title="Loading State" const { data, loading, error } = useUserRewards({ user: EvmAddress, chainId: ChainId, }); ``` ```ts title="React Suspense" const { data } = useUserRewards({ user: EvmAddress, chainId: ChainId, suspense: true, }); ``` Fetch the user’s claimable rewards, optionally filtered by token. ```tsx title="Merit Rewards" import { useUserRewards, evmAddress, chainId } from "@aave/react"; // … const { data, loading, error } = useUserRewards({ user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), }); if (loading) { return Loading claimable rewards…; } if (error) { return Error: {error.message}; } // data: UserRewards | null ``` ```tsx title="Filter by Token" import { useUserRewards, evmAddress, chainId } from "@aave/react"; // … const { data, loading, error } = useUserRewards({ user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), filter: { // Filter rewards by token address tokens: [evmAddress("0x000000000000000000000000000000000000000A")], }, }); if (loading) { return Loading claimable rewards…; } if (error) { return Error: {error.message}; } // data: UserRewards | null ``` ```ts title="Merit Rewards" import { userRewards } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userRewards(client, { user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), }); if (result.isErr()) { console.error("Merit claim rewards error:", result.error); } else { // result.value: UserRewards | null console.log(result.value); } ``` ```ts title="Filter by Token" import { userRewards } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userRewards(client, { user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), filter: { // Filter rewards by token address tokens: [evmAddress("0x000000000000000000000000000000000000000A")], }, }); if (result.isErr()) { console.error("Merit claim rewards error:", result.error); } else { // result.value: UserRewards | null console.log(result.value); } ``` ```graphql title="Query" query { userRewards( request: { user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 # Optional filter # filter: { # tokens: ["0x000000000000000000000000000000000000000A"] # } } ) { chain claimable { amount { usdPerToken usd amount { value decimals raw } } currency { address imageUrl name symbol decimals chainId } } transaction { to from data value chainId operation } } } ``` The user has no claimable rewards if `data` is `null` in React, if `result.value` is `null` in TypeScript, or if the query result is `null` in GraphQL. ### 2. Claim Rewards Finally, if the user has claimable rewards, they can claim them by sending the transaction. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send `data.transaction`. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to send the transaction. - **GraphQL**: Send the `transaction` request directly using the wallet associated with the from address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useUserRewards } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const { data } = useUserRewards({ // … 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("Merit claim rewards successful with hash:", result.value); } } }; ``` ```ts title="Viem" import { userRewards } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const meritRewards = await userRewards(client, { // … }); if (meritRewards.isErr()) { console.error(meritRewards.error); process.exit(1); // or eager return if in a function } if (!meritRewards.value) { console.log("No rewards to claim"); process.exit(1); // or eager return if in a function } const result = await sendWith(wallet)(meritRewards.value.transaction); if (result.isErr()) { console.error("Claiming Merit rewards failed:", result.error); } else { console.log("Merit rewards claimed successfully:", result.value); } ``` Send `transaction` from the `from` wallet. ```json title="UserRewards" { "data": { "userRewards": { "chain": 1, "claimable": [ { "amount": { "usdPerToken": "1.000000000000000000", "usd": "1.00", "amount": { "value": "1.000000000000000000", "decimals": 18, "raw": "1000000000000000000" } }, "currency": { "address": "0x000000000000000000000000000000000000000A", "name": "Example Token", "symbol": "EXAMPLE", "decimals": 18, "chainId": 1, "imageUrl": "https://example.com/image.png" } } ], "transaction": { "to": "0x000000000000000000000000000000000000000B", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x…", "value": "0", "chainId": 1, "operation": null } } } } ``` --- Source: https://aave.com/docs/aave-v3/markets/advanced.md # Aave V3 Advanced Market Features Implement advanced Aave features in DeFi applications. ## User Transaction History Track user transaction history across Aave markets with detailed transaction information. Use the `useUserTransactionHistory` hook in React, the `userTransactionHistory` action in TypeScript, or the `userTransactionHistory` query in GraphQL to fetch paginated transaction history for a user. ```ts title="Loading State" const { data, loading, error } = useUserTransactionHistory({ market: EvmAddress, user: EvmAddress, chainId: ChainId, filter?: UserTransactionType[], orderBy?: UserTransactionHistoryRequestOrderBy, pageSize?: PageSize, cursor?: Cursor, }); ``` ```ts title="React Suspense" const { data } = useUserTransactionHistory({ market: EvmAddress, user: EvmAddress, chainId: ChainId, filter?: UserTransactionType[], orderBy?: UserTransactionHistoryRequestOrderBy, pageSize?: PageSize, cursor?: Cursor, suspense: true, }); ``` Fetch the history ordered by date, or filter it by transaction type. ```tsx title="User Transaction History" import { useUserTransactionHistory, evmAddress, chainId, PageSize, OrderDirection, } from "@aave/react"; // … const { data, loading, error } = useUserTransactionHistory({ market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), orderBy: { date: OrderDirection.Desc }, pageSize: PageSize.Fifty, }); if (loading) { return Loading transaction history…; } if (error) { return Error: {error.message}; } // data.items: UserTransactionItem[] // data.pageInfo.next: Cursor | null // data.pageInfo.prev: Cursor | null ``` ```tsx title="Filtered Transaction History" import { useUserTransactionHistory, evmAddress, chainId, PageSize, OrderDirection, } from "@aave/react"; // … const { data, loading, error } = useUserTransactionHistory({ market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), filter: ["SUPPLY", "WITHDRAW"], orderBy: { date: OrderDirection.Desc }, pageSize: PageSize.Ten, }); ``` ```ts title="User Transaction History" import { userTransactionHistory } from "@aave/client/actions"; import { evmAddress, chainId, PageSize, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userTransactionHistory(client, { market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), orderBy: { date: OrderDirection.Desc }, pageSize: PageSize.Fifty, }); if (result.isErr()) { console.error("User transaction history error:", result.error); } else { // result.value.items: UserTransactionItem[] // result.value.pageInfo.next: Cursor | null // result.value.pageInfo.prev: Cursor | null console.log(result.value); } ``` ```ts title="Filtered Transaction History" import { userTransactionHistory } from "@aave/client/actions"; import { evmAddress, chainId, PageSize, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userTransactionHistory(client, { market: evmAddress("0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), filter: ["SUPPLY", "WITHDRAW"], orderBy: { date: OrderDirection.Desc }, pageSize: PageSize.Ten, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { userTransactionHistory( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 orderBy: { date: DESC } pageSize: FIFTY } ) { items { ... on UserSupplyTransaction { ...UserSupplyTransaction } ... on UserWithdrawTransaction { ...UserWithdrawTransaction } ... on UserBorrowTransaction { ...UserBorrowTransaction } ... on UserRepayTransaction { ...UserRepayTransaction } ... on UserUsageAsCollateralTransaction { ...UserUsageAsCollateralTransaction } ... on UserLiquidationCallTransaction { ...UserLiquidationCallTransaction } } pageInfo { next prev } } } ``` ```graphql title="Filtered Query" query { userTransactionHistory( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 filter: [SUPPLY, WITHDRAW] orderBy: { date: DESC } pageSize: TEN } ) { items { __typename ...UserSupplyTransaction ...UserWithdrawTransaction } pageInfo { next prev } } } ``` ```graphql title="fragments" fragment UserSupplyTransaction on UserSupplyTransaction { blockExplorerUrl txHash timestamp amount { amount { value raw decimals } usd } reserve { underlyingToken { symbol name address } } } fragment UserWithdrawTransaction on UserWithdrawTransaction { blockExplorerUrl txHash timestamp amount { amount { value raw decimals } usd } reserve { underlyingToken { symbol name address } } } fragment UserBorrowTransaction on UserBorrowTransaction { blockExplorerUrl txHash timestamp amount { amount { value raw decimals } usd } reserve { underlyingToken { symbol name address } } } fragment UserRepayTransaction on UserRepayTransaction { blockExplorerUrl txHash timestamp amount { amount { value raw decimals } usd } reserve { underlyingToken { symbol name address } } } fragment UserUsageAsCollateralTransaction on UserUsageAsCollateralTransaction { blockExplorerUrl txHash timestamp enabled reserve { underlyingToken { symbol name address } } } fragment UserLiquidationCallTransaction on UserLiquidationCallTransaction { blockExplorerUrl txHash timestamp collateral { reserve { underlyingToken { symbol name address } } amount { amount { value } usd } } debtRepaid { reserve { underlyingToken { symbol name address } } amount { amount { value } usd } } } ``` ```json title="Response" { "data": { "userTransactionHistory": { "items": [ { "__typename": "UserSupplyTransaction", "amount": { "amount": { "value": "1000.0", "raw": "1000000000", "decimals": 6 }, "usd": "1000.0" }, "reserve": { "underlyingToken": { "symbol": "USDC", "name": "USD Coin", "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" } }, "blockExplorerUrl": "https://etherscan.io/tx/0xeef2ffc57b99ce887edd8362c6d57e5c7a4d8c8a9b2c3d4e5f6789abc123def45", "txHash": "0xeef2ffc57b99ce887edd8362c6d57e5c7a4d8c8a9b2c3d4e5f6789abc123def45", "timestamp": "2024-03-15T14:30:00Z" }, { "__typename": "UserBorrowTransaction", "amount": { "amount": { "value": "0.5", "raw": "500000000000000000", "decimals": 18 }, "usd": "1250.0" }, "reserve": { "underlyingToken": { "symbol": "WETH", "name": "Wrapped Ether", "address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } }, "blockExplorerUrl": "https://etherscan.io/tx/0xabc123def456789012345678901234567890abcdef456789012345678901234", "txHash": "0xabc123def456789012345678901234567890abcdef456789012345678901234", "timestamp": "2024-03-14T10:15:00Z" } ], "pageInfo": { "next": "eyJpZCI6IjB4MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWYxMjM0NTY3OC00MSJ9", "prev": null } } } } ``` ### Transaction Types The user transaction history includes the following transaction types with their specific data: - `SUPPLY` - Asset supply transactions with amount and reserve information - `WITHDRAW` - Asset withdrawal transactions with amount and reserve information - `BORROW` - Asset borrowing transactions with amount and reserve information - `REPAY` - Debt repayment transactions with amount and reserve information - `USAGE_AS_COLLATERAL` - Collateral enable/disable transactions with `enabled` flag - `LIQUIDATION_CALL` - Liquidation transactions with collateral and debt repaid details ### Filtering Options Use the `filter` parameter to narrow down transaction results by transaction types: ```tsx filter: ["SUPPLY", "WITHDRAW"]; ``` Available filter values: `SUPPLY`, `WITHDRAW`, `BORROW`, `REPAY`, `USAGE_AS_COLLATERAL`, `LIQUIDATION_CALL` ### Ordering Options Order transactions using the `orderBy` parameter: - `date` - Order by transaction date (ASC or DESC) ## Efficiency Mode (E-Mode) Efficiency Mode (E-Mode) in Aave optimizes borrowing power for price-correlated assets. This feature is particularly useful when both supplied and borrowed assets share similar economic price movements, such as stablecoins or derivatives that track the same underlying asset. By using E-Mode, users benefit from lower collateral requirements, effectively increasing their available borrowing capacity for correlated assets. To enable efficiency mode and maximize capital efficiency for correlated assets, follow these steps. ### 1. Check Available E-Mode Categories First, check the available E-Mode categories on the market to understand which category to enable. Given the following market object with available E-Mode categories: ```ts title="Market" const market: Market = { __typename: "Market", name: "Aave V3 Ethereum", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { __typename: "Chain", chainId: 1, name: "Ethereum", // … }, eModeCategories: [ { __typename: "EmodeMarketCategory", id: 1, label: "Stablecoins", maxLTV: { __typename: "PercentValue", value: "0.97", // … }, liquidationThreshold: { __typename: "PercentValue", value: "0.975", // … }, liquidationPenalty: { __typename: "PercentValue", value: "0.01", // … }, reserves: [ { __typename: "EmodeMarketReserveInfo", underlyingToken: { __typename: "Currency", symbol: "USDC", name: "USD Coin", address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // … }, canBeCollateral: true, canBeBorrowed: true, }, // … more reserves ], // … }, // … more categories ], // … }; ``` Where each `EmodeMarketCategory` object has the following properties: - `maxLTV.value` - Maximum borrowing power (% of supplied collateral you can borrow) - `liquidationThreshold.value` - The debt-to-collateral ratio at which a position becomes liquidatable - `liquidationPenalty.value` - How much you lose if liquidation happens (lower = better) - `reserves[]` - an array of `EmodeMarketReserveInfo` objects, each representing a reserve that indicates if the asset can be used as collateral and/or borrowed in this specific E-Mode. ### 2. Prepare the Transaction Request Next, we can proceed with creating the transaction request for the desired E-Mode operation. Use the `useUserEMode` hook in React, the `userSetEmode` action in TypeScript, or the `userSetEmode` query in GraphQL to create the transaction request for enabling or disabling efficiency mode. ```tsx title="Enable eMode Category" import { useWalletClient } from "wagmi"; import { useUserEMode, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [setEmode, settingEmode] = useUserEMode(); const execute = async () => { const result = await setEmode({ market: market.address, user: evmAddress(walletClient!.account.address), categoryId: 1, // Enable category 1 (Stablecoins) chainId: market.chain.chainId, }); // … }; ``` ```tsx title="Disable eMode" import { useWalletClient } from "wagmi"; import { useUserEMode, evmAddress } from "@aave/react"; // … const { data: walletClient } = useWalletClient(); const [setEmode, settingEmode] = useUserEMode(); const execute = async () => { const result = await setEmode({ market: market.address, user: evmAddress(walletClient!.account.address), categoryId: null, // Disable eMode chainId: market.chain.chainId, }); // … }; ``` ```ts title="Enable eMode" import { userSetEmode } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await userSetEmode(client, { market: market.address, user: evmAddress(wallet.account.address), categoryId: 1, // Enable category 1 (Stablecoins) chainId: market.chain.chainId, }); // … ``` ```ts title="Disable eMode" import { userSetEmode } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await userSetEmode(client, { market: market.address, user: evmAddress(wallet.account.address), categoryId: null, // Disable eMode chainId: market.chain.chainId, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```graphql title="Query" query { userSetEmode( request: { market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" categoryId: 1 # Enable category 1, or null to disable chainId: 1 } ) { to from data value chainId } } ``` ### 3. Send the Transaction Finally, send the transaction. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transaction. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to initiate the transaction, and await indexing with `client.waitForTransaction`. - **GraphQL**: The response is a `TransactionRequest` that can be sent directly using the wallet associated with the `from` address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useUserEMode } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [setEmode, settingEmode] = useUserEMode(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = settingEmode.loading || sending.loading; const error = settingEmode.error || sending.error; // … const execute = async () => { const result = await setEmode({ // … }).andThen(sendTransaction); if (result.isErr()) { console.error("eMode operation failed:", result.error); } else { console.log("eMode operation successful with hash:", result.value); } }; ``` ```ts title="Viem" import { userSetEmode } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await userSetEmode(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("eMode operation failed:", result.error); } else { console.log("eMode operation successful:", result.value); } ``` ```json title="TransactionRequest" { "data": { "userSetEmode": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x28530a47000000000000000000000000000000000000000000000000000000000000000001", "value": "0", "chainId": 1, "operation": "USER_EMODE_SET" } } } ``` ## Liquidations Liquidate undercollateralized positions to earn liquidation bonuses and help maintain protocol stability. ### 1. Identify an Undercollateralized Position First, identify a target user with a health factor below 1.0, and one of their borrow positions that is eligible for liquidation. ```ts const targetUser = evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"); ``` Given the following user borrow position: ```ts title="MarketUserReserveBorrowPosition" const position: MarketUserReserveBorrowPosition = { __typename: "MarketUserReserveBorrowPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "WETH", name: "Wrapped Ether", address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // … }, debt: { __typename: "TokenAmount", amount: { __typename: "DecimalValue", value: "1.5", raw: "1500000000000000000", decimals: 18, // … }, // … }, // … }; ``` > [!NOTE] > Finding users with a health factor below 1.0 is out of scope for this guide. ### 2. Choose the Collateral to Receive Next, choose which of the target user’s collateral assets to receive, including the liquidation bonus. Given the following collateral position: ```ts title="MarketUserReserveSupplyPosition" const collateral: MarketUserReserveSupplyPosition = { __typename: "MarketUserReserveSupplyPosition", market: { __typename: "MarketInfo", address: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", chain: { chainId: 1 }, // … }, currency: { __typename: "Currency", symbol: "USDC", name: "USD Coin", address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // … }, isCollateral: true, canBeCollateral: true, // … }; ``` ### 3. Prepare the Transaction Request Then, create the transaction request for the liquidation operation. Use the `useLiquidate` hook in React, the `liquidate` action in TypeScript, or the `liquidate` query in GraphQL to create the transaction request for liquidating the undercollateralized position. ```tsx title="Liquidate Position" import { useLiquidate } from "@aave/react"; // … const [liquidate, liquidating] = useLiquidate(); const execute = async () => { const result = await liquidate({ chainId: position.market.chain.chainId, market: position.market.address, user: targetUser, underlyingToken: position.currency.address, debtToCover: { max: true }, // Liquidate maximum debt collateralToken: collateral.currency.address, receiveAToken: false, // Receive the underlying collateral token }); // … }; ``` ```ts title="Liquidate Position" import { liquidate } from "@aave/client/actions"; import { client } from "./client"; const result = await liquidate(client, { chainId: position.market.chain.chainId, market: position.market.address, user: targetUser, underlyingToken: position.currency.address, debtToCover: { max: true }, // Liquidate maximum debt collateralToken: collateral.currency.address, receiveAToken: false, // Receive the underlying collateral token }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { liquidate( request: { chainId: 1 market: "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2" user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" # targetUser underlyingToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" debtToCover: { max: true } collateralToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" receiveAToken: false } ) { to from data value chainId } } ``` ### 4. Send the Transaction Finally, send the transaction to execute the liquidation. - **React**: Use the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#send-aave-transactions) to send the transaction. - **TypeScript**: Use `sendWith` for your [chosen wallet library](../getting-started/typescript#send-aave-transactions) to initiate the transaction, and await indexing with `client.waitForTransaction`. - **GraphQL**: The response is a `TransactionRequest` that can be sent directly using the wallet associated with the `from` address. ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useLiquidate } from "@aave/react"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: walletClient } = useWalletClient(); const [liquidate, liquidating] = useLiquidate(); const [sendTransaction, sending] = useSendTransaction(walletClient); // … // Optional: combine loading states const loading = liquidating.loading || sending.loading; const error = liquidating.error || sending.error; // … const execute = async () => { const result = await liquidate({ // … }).andThen(sendTransaction); if (result.isErr()) { console.error("Liquidation failed:", result.error); } else { console.log("Liquidation successful with hash:", result.value); } }; ``` ```ts title="Viem" import { liquidate } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await liquidate(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); if (result.isErr()) { console.error("Liquidation failed:", result.error); } else { console.log("Liquidation successful:", result.value); } ``` ```ts title="wallet.ts" import { createWalletClient, http, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { mainnet } from "viem/chains"; export const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), chain: mainnet, transport: http(), }); ``` ```json title="TransactionRequest" { "data": { "liquidate": { "__typename": "TransactionRequest", "to": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x00a718a9000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2…", "value": "0", "chainId": 1, "operation": "LIQUIDATION" } } } ``` --- Source: https://aave.com/docs/aave-v3/guides/flash-loans.md # Aave V3 Flash Loans Flash Loans let you borrow an asset without collateral, as long as the borrowed amount and a fee are returned before the end of the same transaction. They have no real-world equivalent, so using them requires a basic understanding of how state is managed within a blockchain block. > [!NOTE] > Flash Loans require a good understanding of the EVM and smart contracts. ## Overview A flash loan gives access to the pool’s liquidity, for reserves with borrowing enabled, for one transaction. By the end of that transaction, the amount plus the fee must be returned or, where allowed, a debt position must be opened. Aave V3 offers two options for flash loans: - [`flashLoan()`](/aave-v3/smart-contracts/pool#flashloan): borrows from **multiple reserves** in a single transaction. The borrower can also open a variable rate borrow position, backed by supplied collateral or credit delegation, instead of repaying. The fee is waived for approved `flashBorrowers`, managed by the [ACLManager](/aave-v3/smart-contracts/acl-manager). - [`flashLoanSimple()`](/aave-v3/smart-contracts/pool#flashloansimple): borrows from a **single reserve**. The fee is never waived and no debt position can be opened, but it uses less gas, which makes it the better choice for simple single-asset flash loans. ### Execution Flow A helpful mental model when building with flash loans: 1. Your contract calls the [`Pool`](/aave-v3/smart-contracts/pool) contract, requesting a flash loan of one or more assets using [`flashLoanSimple()`](/aave-v3/smart-contracts/pool#flashloansimple) or [`flashLoan()`](/aave-v3/smart-contracts/pool#flashloan). 2. After some sanity checks, the [`Pool`](/aave-v3/smart-contracts/pool) transfers the requested `amounts` of the `reserves` to your contract, then calls `executeOperation()` on the receiver contract. 3. Your contract, now holding the flash loaned `amount(s)`, executes any arbitrary operation in its code: - With `flashLoanSimple()`, once your code has finished, approve the Pool for the flash loaned amount + fee. - With `flashLoan()`, depending on the `interestRateMode` passed for each asset, either approve the Pool for the flash loaned amount + fee, or have enough collateral or credit delegation available to open a debt position. - If the amount owed is not available, because of a missing balance, missing approval or insufficient collateral, **the transaction reverts**. 4. All of the above happens in one transaction, and therefore in a single block. ### Applications of Flash Loans Aave V3 itself uses flash loans for its liquidity switch feature. Other common uses: - Arbitrage between assets, without holding the principal needed for the trade. - Liquidating borrow positions without holding the debt amount, using the discounted collateral received to pay back the flash loan amount + fee. ### Flash Loan Fee The flash loan fee is set to 0.05% at deployment and can be changed by governance vote. Read [`FLASHLOAN_PREMIUM_TOTAL`](/aave-v3/smart-contracts/pool#flashloan-premium-total) for the current value. The fee can be split between _liquidity providers (LPs)_ and the protocol treasury. [`FLASHLOAN_PREMIUM_TOTAL`](/aave-v3/smart-contracts/pool#flashloan-premium-total) is the total fee paid by borrowers, of which: - Fee to LPs: [`FLASHLOAN_PREMIUM_TOTAL`](/aave-v3/smart-contracts/pool#flashloan-premium-total) - [`FLASHLOAN_PREMIUM_TO_PROTOCOL`](/aave-v3/smart-contracts/pool#flashloan-premium-to-protocol) - Fee to Protocol: [`FLASHLOAN_PREMIUM_TO_PROTOCOL`](/aave-v3/smart-contracts/pool#flashloan-premium-to-protocol) > [!NOTE] > At initialization, > [`FLASHLOAN_PREMIUM_TO_PROTOCOL`](/aave-v3/smart-contracts/pool#flashloan-premium-to-protocol) > is set to 0. ## Step by Step ### 1. Set Up the Receiver Contract Your contract that receives the flash loaned amounts **must** conform to the [`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) interface by implementing the relevant `executeOperation()` function. Because the owed amounts are _pulled_ from your contract, your contract must give allowance to the [`Pool`](/aave-v3/smart-contracts/pool) to pull those funds to pay back the flash loan amount + premiums. ### 2. Call flashLoan() or flashLoanSimple() You can call either flash loan method on the Pool in 3 ways. #### From an EOA To use an EOA (a regular Ethereum account), send a transaction to the [`Pool`](/aave-v3/smart-contracts/pool) calling the [`flashLoan()`](/aave-v3/smart-contracts/pool#flashloan) or [`flashLoanSimple()`](/aave-v3/smart-contracts/pool#flashloansimple) function. See the [`Pool`](/aave-v3/smart-contracts/pool) docs for parameter details, and use your contract address from [step 1](#section-1-set-up-the-receiver-contract) as the `receiverAddress`. #### From a Different Contract As with an EOA, use your contract address from [step 1](#section-1-set-up-the-receiver-contract) as the `receiverAddress`. #### From the Same Contract To call from the contract you set up in step 1, use `address(this)` as the `receiverAddress` in the flash loan method. > [!WARNING] > Never keep funds on your > [`FlashLoanReceiverBase`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/flashloan/base/FlashLoanReceiverBase.sol) > contract. An attacker can use them in a [griefing > attack](https://ethereum.stackexchange.com/a/92457/19365). ### 3. Complete the Flash Loan Once your logic in `executeOperation()` has run, you must pay back the flash loaned amounts if you used [`flashLoanSimple()`](/aave-v3/smart-contracts/pool#flashloansimple), or passed `0` in the `interestRateModes` of [`flashLoan()`](/aave-v3/smart-contracts/pool#flashloan) for an asset. #### Paying Back a Flash Loaned Asset Make sure your contract holds the amount + premium for each borrowed asset. For each asset, it’s the sum of its entries in the `amounts` and `premiums` arrays passed to `executeOperation()`. You **don’t** need to transfer the owed amount back to the [`Pool`](/aave-v3/smart-contracts/pool). The funds are _pulled_ automatically at the end of your operation. #### Incurring a Debt (Not Immediately Paying Back) If you passed `2` (variable rate) in `interestRateModes` for an asset, the `onBehalfOf` address takes on the debt, **but only if** it has previously approved `msg.sender` to borrow on its behalf. Stable rate borrowing is deprecated, so `1` reverts. This means some assets can be paid back immediately while others become debt. --- Source: https://aave.com/docs/aave-v3/guides/credit-delegation.md # Aave V3 Credit Delegation Credit delegation allows a supplier to contribute liquidity to the Aave protocol to earn interest, and delegate borrowing power (i.e. their credit) to other users. The enforcement of the borrow position and its terms are agreed upon between the supplier and borrowers, which can be either offchain via legal agreements or onchain via smart contracts. This enables: - The supplier (aka _delegator_) to earn extra yield on top of the yield they already earn from the protocol. - The borrowers (aka _delegatees_) to access uncollateralized liquidity. The delegatee can only borrow assets allowed in the delegator’s E-Mode category. For example, if the delegator is in a stablecoin E-Mode category, a delegated borrow of WETH reverts. A borrow that would drop the delegator’s Health Factor below 1 reverts, so a delegatee cannot force the delegator into liquidation. ## Approve the Delegation The `approveDelegation` or `delegationWithSig` function on the [`VariableDebtToken`](/aave-v3/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. ## Borrow the Credit The borrower (delegatee) calls the `borrow` function on the [`Pool`](/aave-v3/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. ## Repay the Credit Anyone can repay the debt on the delegator’s behalf with the [`Pool`](/aave-v3/smart-contracts/pool) `repay` or `repayWithPermit` functions. The delegator can also use `repayWithATokens` to repay with aTokens of the same underlying asset. --- Source: https://aave.com/docs/aave-v3/smart-contracts/testing-and-debugging.md # Testing and Debugging Aave V3 Contracts This guide covers testing and debugging Aave V3 integrations. ## Testing There are two primary methods for testing the Aave protocol: using a _testnet_ or creating _fork networks_. ### Testnet The Aave protocol is available for testing on the Sepolia testnet. You can access the Sepolia V3 testnet market by visiting [app.aave.com](https://app.aave.com) and enabling testnet mode in the top right corner. To get started: 1. Visit the test market on [app.aave.com](https://app.aave.com). 2. Use the **Faucet** tab to acquire test tokens available in the market. 3. Supply these tokens to the protocol. 4. Perform operations such as borrowing, repaying, and withdrawing to test different functionalities. ### Fork Networks A fork network replicates the state of a blockchain, allowing you to interact with it in a sandbox environment. This is especially useful for testing scenarios that depend on contracts and states existing on the mainnet. #### Creating a Fork Network Several tools can help you create a fork network: - **[Tenderly](https://docs.tenderly.co/simulations-and-forks/forks)**: Debugging toolkit with fork networks, simulations, and online dashboard. - **[Foundry](https://book.getfoundry.sh/forge/fork-testing)**: Smart contract development framework. - **[Hardhat](https://hardhat.org/hardhat-network/docs/guides/forking-other-networks)**: Smart contract development framework. To acquire tokens on a fork network, you can impersonate an address that holds the desired tokens (holders can be found using block explorers) and transfer them to your address. #### Connecting the Fork Network to the UI The [app.aave.com](https://app.aave.com) interface can be configured to connect to a fork network. By setting specific variables via the browser console, you can enable this functionality. Refer to [this guide](https://github.com/aave/interface/blob/main/CONTRIBUTING.md#running-against-a-chain-fork) for detailed instructions. ## Debugging When interacting with the Aave protocol, you may encounter smart contract errors. This section helps you understand how to interpret errors, use debugging tools, and resolve common issues. ### Errors Aave V3 reverts with Solidity custom errors defined in [Errors.sol](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/helpers/Errors.sol), such as `CallerNotPoolAdmin()`. Decode the 4-byte selector of the revert data against that file. Aave V2 uses numeric error codes defined in its own [Errors.sol](https://github.com/aave/protocol-v2/blob/master/contracts/protocol/libraries/helpers/Errors.sol). ### Debugging Tools To effectively debug transactions, you can use tools like Tenderly, Hardhat, and Foundry. These tools allow you to simulate transactions, inspect state changes, and step through execution to identify issues. #### Tenderly Tenderly allows you to simulate transactions and debug them step-by-step. By inputting the transaction details (`to`, `from`, `data`, and `value`), you can simulate the call and identify the cause of any revert, including error codes and stack traces. #### Hardhat Hardhat provides a local Ethereum environment for testing and debugging. It offers features like console logs in Solidity, detailed stack traces, and the ability to fork mainnet state for testing. #### Foundry Foundry is a fast, portable, and modular toolkit for Ethereum application development. It includes tools like Forge for testing and debugging smart contracts, allowing you to simulate and debug transactions effectively. ### Understanding “Gas Estimation Failed” The “Gas estimation failed” error is a generic message indicating that the transaction would fail if executed. To diagnose this issue: 1. Use the transaction’s `to`, `from`, `data`, and `value` fields. 2. Simulate the transaction using one of the debugging tools mentioned above. 3. Identify the specific error code or exception causing the failure. 4. Examine the stack trace to pinpoint the issue. ### Common Aave V3 Pool Errors When interacting with the Aave V3 Pool, you may encounter issues related to token approvals, insufficient collateral, or reaching protocol limits. For more detailed explanations of potential revert cases, refer to this [DeFi Integration Guide](https://github.com/Walodja1987/DeFi-Integration-Guide/blob/main/AaveV3.1.md). #### ERC-20 Token Approval for Supply and Repay Before supplying or repaying tokens, ensure that you have granted the Aave `Pool` contract an allowance to transfer tokens. This is performed by calling the `approve` function on the ERC-20 token contract to authorize the `Pool` as the `spender`. #### Insufficient Collateral If you’re unable to borrow assets, it may be due to insufficient collateral or not meeting the required _Loan-to-Value (LTV)_ ratios. Ensure that you have supplied enough collateral and that it satisfies the protocol’s requirements. #### Borrow Cap Reached Sometimes, you may not be able to borrow a specific asset because the borrow cap has been reached. In this case, you may need to wait for borrowers to repay or supply more liquidity to the pool. #### Loan To Value = 0% When an Aave [reserve](../concepts/reserve) has a Loan To Value (LTV) parameter configured to 0%, commonly referred to as _LTV0_, it impacts reserve interactions in several ways: - **Borrowing power**: Any existing collateral of this asset will no longer contribute to borrowing power. - **Collateral status**: The asset can no longer be enabled as collateral. - **Transfers**: If received via transfer, the asset will not be automatically enabled as collateral. - **Withdrawals**: Assets with LTV0 must be disabled as collateral (using `Pool.setUserUseReserveAsCollateral` or by fully withdrawing the supplied balance) before other assets can be withdrawn. ### Common WrappedTokenGateway Errors When interacting with Ether (ETH) in the Aave protocol, the `WrappedTokenGateway` is used to wrap ETH into WETH and vice versa. Common issues may include not sending ETH with the transaction when required or using incorrect functions for depositing or withdrawing ETH. For detailed usage and potential revert causes, refer to the [WrappedTokenGateway documentation](./wrapped-token-gateway). --- Source: https://aave.com/docs/aave-v3/smart-contracts.md # Aave V3 Smart Contracts The source code of the Aave V3 Protocol contracts is available on [GitHub](https://github.com/aave-dao/aave-v3-origin). Contract addresses can be imported as Solidity or JavaScript package with the [Aave Address Book](https://github.com/aave-dao/aave-address-book). The core contracts fall into the following categories in the GitHub repository: - Pool - Configuration - Logic - Tokenization - Rewards - Helpers - Misc ## Pool Contracts ### Pool The [`Pool`](/aave-v3/smart-contracts/pool) is the main entry point into the Aave Protocol. Most user interactions with the Aave Protocol occur via the `Pool` contract. `Pool` is owned by the `PoolAddressesProvider` of the specific market. All admin functions are callable by the `PoolConfigurator` contract, which is defined in `PoolAddressesProvider`. ### L2Pool The [`L2Pool`](/aave-v3/smart-contracts/l2-pool) is a calldata-optimized extension of `Pool` for L2 rollups that takes byte-encoded arguments to reduce transaction costs. ### PoolConfigurator The [`PoolConfigurator`](/aave-v3/smart-contracts/pool-configurator) provides configuration methods for the `Pool` contract. The write methods of this contract can only be called by addresses with corresponding permissioned system roles that are managed by `ACLManager`. ## Configuration ### ACLManager The [`ACLManager`](/aave-v3/smart-contracts/acl-manager) contract is the main registry of system roles and permissions. ### PoolAddressesProvider The [`PoolAddressesProvider`](/aave-v3/smart-contracts/pool-addresses-provider) is a registry of various components of the protocol, including the `ACLManager` and `Pool` contracts, and has the ability to update pointers or update the implementation of proxy contracts. ## Logic [Libraries](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/libraries/logic/) that implement the base logic for various actions and functions. ## Tokenization ### AToken [`ATokens`](/aave-v3/smart-contracts/tokenization) are yield-generating tokens that are minted and burnt upon supply and withdraw of assets to Aave Pool. ### VariableDebtToken [`VariableDebtTokens`](/aave-v3/smart-contracts/tokenization) are non-transferable interest accruing tokens representing variable borrow rate positions. ## Rewards ### RewardsController The [`RewardsController`](/aave-v3/smart-contracts/incentives) distributes liquidity mining rewards to aToken and variable debt token holders. ## 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. ### AaveProtocolDataProvider The [`AaveProtocolDataProvider`](/aave-v3/smart-contracts/view-contracts) is a peripheral contract to collect and pre-process information from the `Pool`. ### WrappedTokenGatewayV3 The [`WrappedTokenGatewayV3`](/aave-v3/smart-contracts/wrapped-token-gateway) wraps and unwraps the native token so users can supply, borrow, repay and withdraw it directly. ## Misc ### AaveOracle The [`AaveOracle`](/aave-v3/smart-contracts/oracles) is the registry of reserve oracle to get asset prices and manage price sources. ### DefaultReserveInterestRateStrategyV2 The [`DefaultReserveInterestRateStrategyV2`](/aave-v3/smart-contracts/interest-rate-strategy) implements the calculation of the interest rates depending on the reserve state. This contract holds the information needed to calculate and update the yield relating to specific liquidity pools. ### PriceOracleSentinel Aave V3.7 removed the [`PriceOracleSentinel`](/aave-v3/smart-contracts/oracles#priceoraclesentinel), which paused borrows and delayed liquidations after an L2 sequencer outage. --- Source: https://aave.com/docs/aave-v3/smart-contracts/pool.md # Aave V3 Pool Contract This contract is the main user-facing contract. Most user interactions with the Aave Protocol occur via the `Pool` contract. It exposes the liquidity management methods that can be invoked using either Solidity or Web3 libraries. `Pool.sol` allows users to: - Supply - Withdraw - Borrow - Repay - Enable/disable supplied assets as collateral - Liquidate positions - Execute Flash Loans Pool is covered by a proxy contract and is owned by the [`PoolAddressesProvider`](./pool-addresses-provider) of the specific market. All admin functions are callable by the [`PoolConfigurator`](./pool-configurator) contract defined in the [`PoolAddressesProvider`](./pool-addresses-provider). The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/Pool.sol). ## Write Methods ### initialize ```solidity 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`](./pool-addresses-provider) of the market. Caches the address of the [`PoolAddressesProvider`](./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 ```solidity 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 Aave Governance. > [!NOTE] > The `Pool` needs an `allowance()` from `msg.sender` of at least the supply > amount. Set it with ERC-20 `approve()` on the underlying token. **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 ```solidity 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 [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612). > [!NOTE] > Permit signature must be signed by `msg.sender` with spender as Pool address. **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 EIP-712 permit signature | | **permitR** | `bytes32` | The r parameter of the EIP-712 permit signature | | **permitS** | `bytes32` | The s parameter of the EIP-712 permit signature | ### withdraw ```solidity 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 `amount` available to withdraw is the `amount` that will not leave user’s health factor < 1 after withdrawal. > [!NOTE] > When withdrawing `to` another address, `msg.sender` must hold the `aToken` > that `Pool` burns. Before withdrawing other assets, disable 0% LTV reserves as > collateral (with `Pool.setUserUseReserveAsCollateral` or a full withdrawal). **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(uint256).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 ```solidity 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. > [!NOTE] > If `onBehalfOf` differs from `msg.sender`, `onBehalfOf` must have enough > collateral via `supply()` and must delegate credit to `msg.sender` via > `approveDelegation()`. **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 ```solidity 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 `onBehalfOf` address will be burned. > [!NOTE] > `msg.sender` must first `approve()` the `Pool` on the underlying ERC-20 token > for at least the repay `amount`. **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 ```solidity 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 [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612). > [!NOTE] > Permit signature must be signed by `msg.sender` with spender value as `Pool` > address. **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` to repay the whole debt (only when repaying your own debt). 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 EIP-712 permit signature | | **permitR** | `bytes32` | The r parameter of the EIP-712 permit signature | | **permitS** | `bytes32` | The s parameter of the EIP-712 permit signature | **Return Values:** | Type | Description | | :-------- | :---------------------- | | `uint256` | The final amount repaid | ### repayWithATokens ```solidity 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 `type(uint256).max` as 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 ```solidity function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) public virtual override ``` Allows suppliers to enable/disable a specific supplied asset as collateral. Sets the `asset` of `msg.sender` to be used as collateral or not. > [!NOTE] > - In an isolated E-Mode category, only assets in its collateral bitmap can be enabled as collateral. > - Assets with 0% LTV can’t be enabled as collateral. > - With open debt, you can’t disable collateral if that drops the Health Factor below `HEALTH_FACTOR_LIQUIDATION_THRESHOLD`. **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 ```solidity 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 `debtToCover` amount 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 repay up to 50% of the user’s total debt. The full debt of the reserve can be liquidated when the health factor is at or below 0.95, or when the user’s collateral or debt in the reserve is worth less than 2,000 base currency units (USD on most markets). The liquidation discount applies to this amount. See [Liquidations](/aave-v3/overview#liquidations). - In most scenarios, profitable liquidators will choose to liquidate as much as they can. - `debtToCover` parameter can be set to `type(uint256).max` and the protocol will proceed with the highest possible liquidation allowed by the close factor. - To check a user’s health factor, use [`getUserAccountData()`](#getuseraccountdata). > [!NOTE] > Liquidators must `approve()` the `Pool` contract to use `debtToCover` of the > underlying ERC-20 of the `asset` used for the liquidation. **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 ```solidity 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`. > [!WARNING] > Flash loan receiver contracts carry security risks. Read the [Flash Loan > Developers Guide](/aave-v3/guides/flash-loans) first. **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 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 ```solidity 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. > [!WARNING] > Flash loan receiver contracts carry security risks. Read the [Flash Loan > Developers Guide](/aave-v3/guides/flash-loans) first. **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 ```solidity 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 ```solidity function finalizeTransfer( address asset, address from, address to, uint256 scaledAmount, uint256 scaledBalanceFromBefore ) 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 | | **scaledAmount** | `uint256` | The scaled amount being transferred/withdrawn | | **scaledBalanceFromBefore** | `uint256` | The aToken scaled balance of the `from` user before the transfer | ### setUserEMode ```solidity 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_. > [!NOTE] > Reverts if the user borrows an incompatible asset or if the change drops the > Health Factor below `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 | ### initReserve ```solidity function initReserve( address asset, address aTokenAddress, address variableDebtAddress ) external virtual override onlyPoolConfigurator ``` Initializes a reserve, activating it, assigning an aToken and debt tokens. All reserves share the interest rate strategy returned by `RESERVE_INTEREST_RATE_STRATEGY()`. > [!NOTE] > Only callable by the [`PoolConfigurator`](./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 | | **variableDebtAddress** | `address` | The address of the VariableDebtToken that will be assigned to the reserve | ### setConfiguration ```solidity function setConfiguration(address asset, DataTypes.ReserveConfigurationMap calldata configuration) external virtual override onlyPoolConfigurator ``` Sets the configuration bitmap of the reserve as a whole. > [!NOTE] > Only callable by the [`PoolConfigurator`](./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 | See the bit layout under [getConfiguration](#getconfiguration). ### updateFlashloanPremium ```solidity function updateFlashloanPremium(uint128 flashLoanPremium) external virtual override onlyPoolConfigurator ``` Updates the flash loan premium. The protocol treasury collects the whole premium, which is calculated on the total borrowed amount. > [!NOTE] > Only callable by the [`PoolConfigurator`](./pool-configurator) contract. **Input Parameters:** | Name | Type | Description | | :--------------- | :-------- | :--------------------------------------- | | **flashLoanPremium** | `uint128` | The flash loan premium, expressed in bps | ### configureEModeCategory ```solidity function configureEModeCategory(uint8 id, DataTypes.EModeCategoryBaseConfiguration calldata category) external virtual override onlyPoolConfigurator ``` Configures a new eMode category or alters an existing one. 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. > [!NOTE] > Only callable by the [`PoolConfigurator`](./pool-configurator) contract. **Input Parameters:** | Name | Type | Description | | :------- | :---------------------------------------- | :-------------------------------- | | **id** | `uint8` | The id of the category | | **category** | `DataTypes.EModeCategoryBaseConfiguration` | The configuration of the category | The [DataTypes.EModeCategoryBaseConfiguration](https://github.com/aave-dao/aave-v3-origin/blob/8305565ae342f1773c42cd2e4593f175fe5968a0/src/contracts/protocol/libraries/types/DataTypes.sol#L133) 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 | | **isolated** | `bool` | If `true`, only assets in the category’s collateral bitmap contribute LTV (Aave V3.7) | | **label** | `string` | The custom label describing the eMode category | ### configureEModeCategoryIsolated ```solidity function configureEModeCategoryIsolated(uint8 id, bool isolated) external virtual override onlyPoolConfigurator ``` Sets the isolated flag of an eMode category. When a category is isolated, users with collateral enabled on assets outside the category cannot enter it, and assets outside the category’s collateral bitmap are treated as LTV 0. Added in Aave V3.7. > [!NOTE] > Only callable by the [`PoolConfigurator`](./pool-configurator) contract. **Input Parameters:** | Name | Type | Description | | :------- | :------ | :------------------------------------------ | | **id** | `uint8` | The id of the category | | **isolated** | `bool` | `true` if the eMode category is isolated | ### rescueTokens ```solidity function rescueTokens(address token, address to, uint256 amount) external virtual override onlyPoolAdmin ``` Rescue and transfer tokens locked in this contract. > [!NOTE] > Only callable by the [`POOL_ADMIN`](./acl-manager#pool-admin) role, which > governance selects. **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 ```solidity function eliminateReserveDeficit(address asset, uint256 amount) external override onlyUmbrella returns (uint256) ``` 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. **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 | **Return Values:** | Type | Description | | :-------- | :---------------------------- | | `uint256` | The amount of tokens burned | ## View Methods ### getUserAccountData ```solidity 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 ```solidity 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 | | `60` | Asset is paused | | `61` | Borrowing in isolation mode is enabled | | `62` | Siloed borrowing is 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 | | `176-211` | Unbacked mint cap | | `212-251` | Debt ceiling for isolation mode | | `252` | Virtual accounting is enabled | | `253-255` | Unused | ### getUserConfiguration ```solidity 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: | Name | Type | Description | | :--- | :-------- | :---------- | | **data** | `uint256` | Bitmap of the user’s collaterals and borrows, two bits per reserve in `getReservesList()` order. For reserve index `i`, bit `2*i` is set if the user borrows the reserve and bit `2*i+1` is set if the user uses it as collateral | For example, `0x40020` (binary `1000000000000100000`) sets bit 5 and bit 18: bit 5 = 3rd reserve used as collateral, bit 18 = 10th reserve borrowed. ### getReserveNormalizedIncome ```solidity 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 ```solidity 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*1e27` means 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 ```solidity 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 ```solidity 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 ```solidity function getEModeCategoryData(uint8 id) external view virtual override returns (DataTypes.EModeCategoryLegacy memory) ``` Returns the data of an eMode category. > [!WARNING] > Deprecated. Use the independent getters instead, such as > `getEModeCategoryCollateralConfig`, `getEModeCategoryLabel` and > [`getIsEModeCategoryIsolated`](#getisemodecategoryisolated). **Input Parameters:** | Name | Type | Description | | :--- | :------ | :--------------------- | | **id** | `uint8` | The id of the category | **Return Values:** | Type | Description | | :------------------------------ | :------------------------------------- | | `DataTypes.EModeCategoryLegacy` | The configuration data of the category | The [DataTypes.EModeCategoryLegacy](https://github.com/aave-dao/aave-v3-origin/blob/8305565ae342f1773c42cd2e4593f175fe5968a0/src/contracts/protocol/libraries/types/DataTypes.sol#L117) 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 | | **priceSource** | `address` | | | **label** | `string` | The custom label describing the eMode category | ### getIsEModeCategoryIsolated ```solidity function getIsEModeCategoryIsolated(uint8 id) external view returns (bool) ``` Returns whether an eMode category is isolated. Added in Aave V3.7. **Input Parameters:** | Name | Type | Description | | :--- | :------ | :--------------------- | | **id** | `uint8` | The id of the category | **Return Values:** | Type | Description | | :----- | :--------------------------------------- | | `bool` | `true` if the eMode category is isolated | ### getReserveData ```solidity function getReserveData(address asset) external view virtual override returns (DataTypes.ReserveDataLegacy 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.ReserveDataLegacy` | The state and configuration data of the reserve | The [DataTypes.ReserveDataLegacy](https://github.com/aave-dao/aave-v3-origin/blob/8305565ae342f1773c42cd2e4593f175fe5968a0/src/contracts/protocol/libraries/types/DataTypes.sol#L9) struct is composed of the following fields: | Name | Type | Description | | :-------------------------- | :------------------------ | :---------------------------------------------------------------------------------------------------- | | **configuration** | `ReserveConfigurationMap` | Stores the [reserve configuration](#setconfiguration) | | **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 | | **currentStableBorrowRate** | `uint128` | Deprecated in Aave V3.2 | | **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 | | **aTokenAddress** | `address` | The address of associated aToken | | **stableDebtTokenAddress** | `address` | Deprecated in Aave V3.2 | | **variableDebtTokenAddress** | `address` | The address of associated variable debt token | | **interestRateStrategyAddress** | `address` | Deprecated in Aave V3.4. Use `RESERVE_INTEREST_RATE_STRATEGY()` on the Pool | | **accruedToTreasury** | `uint128` | The current treasury balance (scaled) | | **unbacked** | `uint128` | Deprecated in Aave V3.4 | | **isolationModeTotalDebt** | `uint128` | Deprecated in Aave V3.7 | ### getUserEMode ```solidity 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 ```solidity function FLASHLOAN_PREMIUM_TOTAL() public view virtual override returns (uint128) ``` Returns the percent of total flashloan premium paid by the borrower. The whole premium is accrued to the treasury. **Return Values:** | Type | Description | | :-------- | :-------------------------- | | `uint128` | The total fee on flashloans | ### FLASHLOAN_PREMIUM_TO_PROTOCOL ```solidity function FLASHLOAN_PREMIUM_TO_PROTOCOL() public view virtual override returns (uint128) ``` Returns the share of the flash loan premium sent to the treasury. Always `100_00` (100%) since Aave V3.4. **Return Values:** | Type | Description | | :-------- | :-------------------------------------------------- | | `uint128` | The share of the premium sent to the treasury, in bps | ### MAX_NUMBER_RESERVES ```solidity 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 ```solidity function getLiquidationGracePeriod(address asset) external view virtual override returns (uint40) ``` Returns the liquidation grace period of the given asset **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------- | | **asset** | `address` | Underlying token address | **Return Values:** | Type | Description | | :------- | :--------------------------------------------------- | | `uint40` | Timestamp when the liquidation grace period will end | ### getReserveDeficit ```solidity function getReserveDeficit(address asset) external view returns (uint256); ``` Returns the current deficit of a reserve. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------- | | **asset** | `address` | Underlying token address | **Return Values:** | Type | Description | | :-------- | :---------------------------------------------------------------- | | `uint256` | Current reserve deficit from undercollateralized borrow positions | ### getReserveAToken ```solidity function getReserveAToken(address asset) external view returns (address); ``` Returns the aToken address of a reserve. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------- | | **asset** | `address` | Underlying token address | **Return Values:** | Type | Description | | :-------- | :------------------------ | | `address` | The address of the AToken | ### getReserveVariableDebtToken ```solidity function getReserveVariableDebtToken(address asset) external view returns (address); ``` Returns the variableDebtToken address of a reserve. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------- | | **asset** | `address` | Underlying token address | **Return Values:** | Type | Description | | :-------- | :----------------------------------- | | `address` | The address of the VariableDebtToken | --- Source: https://aave.com/docs/aave-v3/smart-contracts/l2-pool.md # Aave V3 L2 Pool Contract The main transaction cost on L2 comes from calldata. To minimize this cost, Aave V3 uses a different contract on L2 networks that allows calldata of Pool methods to be compressed. `L2Pool` is the contract for the L2 optimized user facing methods of the protocol that takes byte encoded input arguments. It exposes the liquidity management methods that can be invoked using either Solidity or Web3 libraries. The `L2Pool` contract is a calldata optimized extension of the Pool contract allowing users to pass compact calldata representation to reduce transaction costs on L2 rollups. > [!NOTE] > Pool methods not exposed in `L2Pool.sol`, such as flashLoan and setUserEMode, > work the same as on other networks. See [Pool](./pool). Encoded arguments use the 16-bit asset id (the reserve index in `getReservesList()`) instead of the 160-bit asset address. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/L2Pool.sol). There is an additional [L2Encoder](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) helper contract with view methods to encode transaction params for compressed methods. ## Methods ### supply ```solidity 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`. > [!NOTE] > Build the input with `encodeSupplyParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :--------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the supply function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :-------------- | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time | | 144-159 | `uint16` | referralCode | Used for 3rd party integrations | ### supplyWithPermit ```solidity 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. > [!NOTE] > Build the input with `encodeSupplyWithPermitParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :--------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the supply function packed in one bytes32. See the `args` bit layout below | | **r** | `bytes32` | The R parameter of EIP-712 permit signature | | **s** | `bytes32` | The S parameter of EIP-712 permit signature | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :---------------- | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time | | 144-159 | `uint16` | referralCode | Used for 3rd party integrations | | 160-191 | `uint32` | shortenedDeadline | Shortened deadline from the original `uint256` | | 192-199 | `uint8` | permitV | The V parameter of EIP-712 permit signature | ### withdraw ```solidity 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. > [!NOTE] > Build the input with `encodeWithdrawParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :----------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the withdraw function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :----- | :-------- | :-------------- | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time, if `type(uint128).max` the value will be expanded to `type(uint256).max` | **Return Values:** | 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 ```solidity 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`, and `msg.sender` incurs the debt. > [!NOTE] > Build the input with `encodeBorrowParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :--------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the borrow function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :------------------------ | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time | | 144-151 | `uint8` | shortenedInterestRateMode | Must be 2 (variable) | | 152-167 | `uint16` | referralCode | Used for 3rd party integrations | ### repay ```solidity 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`. > [!NOTE] > Build the input with `encodeRepayParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :-------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the repay function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :------------------------ | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time, if `type(uint128).max` the value will be expanded to `type(uint256).max` | | 144-151 | `uint8` | shortenedInterestRateMode | Must be 2 (variable) | **Return Values:** | Type | Description | | :-------- | :---------------------- | | `uint256` | The final amount repaid | ### repayWithPermit ```solidity 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. > [!NOTE] > Build the input with `encodeRepayWithPermitParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :------------------------------------------------------------------------------------------------ | | **args** | `bytes32` | Arguments for the repayWithPermit function packed in one bytes32. See the `args` bit layout below | | **r** | `bytes32` | The R parameter of EIP-712 permit signature | | **s** | `bytes32` | The S parameter of EIP-712 permit signature | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :------------------------ | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time, if `type(uint128).max` the value will be expanded to `type(uint256).max` | | 144-151 | `uint8` | shortenedInterestRateMode | Must be 2 (variable) | | 152-183 | `uint32` | shortenedDeadline | Shortened deadline from original `uint256` | | 184-191 | `uint8` | permitV | The V parameter of EIP-712 permit signature | **Return Values:** | Type | Description | | :-------- | :---------------------- | | `uint256` | The final amount repaid | ### repayWithATokens ```solidity 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. > [!NOTE] > Build the input with `encodeRepayWithATokensParams()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :------------------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the repayWithATokens function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :------ | :-------- | :------------------------ | :-------------------------------------------------------------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16-143 | `uint128` | shortenedAmount | Cast to 256 bits at decode time, if `type(uint128).max` the value will be expanded to `type(uint256).max` | | 144-151 | `uint8` | shortenedInterestRateMode | Must be 2 (variable) | **Return Values:** | Type | Description | | :-------- | :---------------------- | | `uint256` | The final amount repaid | ### setUserUseReserveAsCollateral ```solidity 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. > [!NOTE] > Build the input with `encodeSetUserUseReserveAsCollateral()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :--- | :-------- | :-------------------------------------------------------------------------------------------------------------- | | **args** | `bytes32` | Arguments for the setUserUseReserveAsCollateral function packed in one bytes32. See the `args` bit layout below | The `args` bit layout: | Bits | Type | Field | Description | | :--- | :------- | :-------------- | :----------------------------------------------------- | | 0-15 | `uint16` | assetId | The index of the asset in the reservesList | | 16 | `bool` | useAsCollateral | 1 to enable the reserve as collateral, 0 to disable it | ### liquidationCall ```solidity function liquidationCall(bytes32 args1, bytes32 args2) external override ``` Calldata efficient wrapper of the liquidationCall function. Liquidate positions with a health factor below 1. > [!NOTE] > Build the input with `encodeLiquidationCall()` in the > [`L2Encoder`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/L2Encoder.sol) > helper contract. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :------------------------------------------------------------------------------------------------------------- | | **args1** | `bytes32` | Part of the arguments for the liquidationCall function packed in one bytes32. See the `args1` bit layout below | | **args2** | `bytes32` | Part of the arguments for the liquidationCall function packed in one bytes32. See the `args2` bit layout below | The `args1` bit layout: | Bits | Type | Field | Description | | :----- | :-------- | :---------------- | :---------------------------------------------------- | | 0-15 | `uint16` | collateralAssetId | The index of the collateral asset in the reservesList | | 16-31 | `uint16` | debtAssetId | The index of the debt asset in the reservesList | | 32-191 | `address` | user | The address of the user being liquidated | The `args2` bit layout: | Bits | Type | Field | Description | | :---- | :-------- | :------------------- | :--------------------------------------------------------------------------------------------------------- | | 0-127 | `uint128` | shortenedDebtToCover | Cast to 256 bits at decode time , if `type(uint128).max` the value will be expanded to `type(uint256).max` | | 128 | `bool` | receiveAToken | 1 to receive aTokens, 0 to receive the underlying asset | --- Source: https://aave.com/docs/aave-v3/smart-contracts/pool-configurator.md # Aave V3 Pool Configurator Contract The `PoolConfigurator` contract implements the configuration methods for the Aave Protocol. The 'write methods' below are grouped by permissioned system roles that are managed by [`ACLManager`](./acl-manager). The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/pool/PoolConfigurator.sol). ## Asset Listing or Pool Admin Methods ### initReserves ```solidity function initReserves(ConfiguratorInputTypes.InitReserveInput[] calldata input) external override onlyAssetListingOrPoolAdmins ``` Initializes multiple reserves using the array of initialization parameters as input. **Input Parameters:** | Name | Type | Description | | :---- | :------------------------------------------ | :------------------------------------- | | **input** | `ConfiguratorInputTypes.InitReserveInput[]` | The array of initialization parameters | The [ConfiguratorInputTypes.InitReserveInput[]](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 | | **underlyingAsset** | `address` | The address of the underlying asset | | **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 | ## Emergency or Pool Admin Methods ### setPoolPause ```solidity function setPoolPause(bool paused, uint40 gracePeriod) public override onlyEmergencyOrPoolAdmin function setPoolPause(bool paused) external override onlyEmergencyOrPoolAdmin ``` Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions are suspended. The overload without `gracePeriod` uses a grace period of 0. **Input Parameters:** | Name | Type | Description | | :---------- | :------- | :--------------------------------------------------------------------------------------------------- | | **paused** | `bool` | `true` if the protocol needs to be paused, otherwise `false` | | **gracePeriod** | `uint40` | Seconds after unpausing during which liquidations stay blocked, capped by `MAX_GRACE_PERIOD()` | ### setReservePause ```solidity function setReservePause(address asset, bool paused, uint40 gracePeriod) public override onlyEmergencyOrPoolAdmin function setReservePause(address asset, bool paused) external override onlyEmergencyOrPoolAdmin ``` Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, liquidate, aToken transfers). The overload without `gracePeriod` uses a grace period of 0. **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 | | **gracePeriod** | `uint40` | Seconds after unpausing during which liquidations stay blocked, capped by `MAX_GRACE_PERIOD()` | ### disableLiquidationGracePeriod ```solidity 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 | ## Pool Admin Methods ### updateAToken ```solidity 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 | | **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 ```solidity function updateVariableDebtToken(ConfiguratorInputTypes.UpdateDebtTokenInput calldata input) external override onlyPoolAdmin ``` Updates the variable debt token implementation for the reserve. **Input Parameters:** | Name | Type | Description | | :---- | :-------------------------------------------- | :-------------------------------------- | | **input** | `ConfiguratorInputTypes.UpdateDebtTokenInput` | The variableDebtToken update parameters | The [ConfiguratorInputTypes.UpdateDebtTokenInput](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 | | **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 ```solidity 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 | ### updateFlashloanPremium ```solidity function updateFlashloanPremium(uint128 newFlashloanPremium) external override onlyPoolAdmin ``` Updates the flash loan premium. The premium is calculated on the total amount borrowed, is expressed in bps, and is collected in full by the protocol treasury. **Input Parameters:** | Name | Type | Description | | :------------------ | :-------- | :--------------------------------------- | | **newFlashloanPremium** | `uint128` | The flash loan premium, expressed in bps | ## Risk or Pool Admin Methods ### setReserveFlashLoaning ```solidity 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 | ### setReserveBorrowing ```solidity function setReserveBorrowing(address asset, bool enabled) external override onlyRiskOrPoolAdmins ``` Enables or disables borrowing on a reserve. **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 ```solidity 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 | ### setReserveFactor ```solidity 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 | ### setBorrowCap ```solidity function setBorrowCap(address asset, uint256 newBorrowCap) external override onlyRiskOrPoolAdmins ``` Updates the borrow cap of a reserve. Allows [`RISK_ADMIN`](./acl-manager#risk-admin) and [`POOL_ADMIN`](./acl-manager#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 ```solidity function setSupplyCap(address asset, uint256 newSupplyCap) external override onlyRiskOrPoolAdmins ``` Updates the supply cap of a reserve. Allows [`RISK_ADMIN`](./acl-manager#risk-admin) and [`POOL_ADMIN`](./acl-manager#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 | ### setLiquidationProtocolFee ```solidity 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 ```solidity function setEModeCategory( uint8 categoryId, uint16 ltv, uint16 liquidationThreshold, uint16 liquidationBonus, string calldata label, bool isolated ) external override onlyRiskOrPoolAdmins ``` Adds a new efficiency mode (E-Mode) category. Allows [`RISK_ADMIN`](./acl-manager#risk-admin) and [`POOL_ADMIN`](./acl-manager#pool-admin) to configure existing or add new `eModeCategory` **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-E-Mode | | **ltv** | `uint16` | The loan to value for the associated E-Mode 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 | | **isolated** | `bool` | If `true`, users with collateral outside the category cannot enter it, and assets outside the category get LTV 0 (Aave V3.7) | ### setAssetCollateralInEMode ```solidity function setAssetCollateralInEMode(address asset, uint8 categoryId, bool allowed) external override onlyRiskOrPoolAdmins ``` Assign collateral status to an asset for a particular efficiency mode (E-Mode) category. Allows [`RISK_ADMIN`](./acl-manager#risk-admin) and [`POOL_ADMIN`](./acl-manager#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` | E-Mode category id to set asset collateral status for | | **allowed** | `bool` | `true` if `asset` is enabled as collateral in designated `categoryId` | ### setAssetBorrowableInEMode ```solidity function setAssetBorrowableInEMode(address asset, uint8 categoryId, bool borrowable) external override onlyRiskOrPoolAdmins ``` Configures if an asset can be borrowed in a specific E-Mode category. **Input Parameters:** | Name | Type | Description | | :--------- | :-------- | :------------------------------- | | **asset** | `address` | Address of the reserve asset | | **categoryId** | `uint8` | E-Mode category ID | | **borrowable** | `bool` | true to enable, false to disable | ### setReserveInterestRateData ```solidity 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 | ## Risk, Pool or Emergency Admin Methods ### setReserveFreeze ```solidity function setReserveFreeze(address asset, bool freeze) external override onlyRiskOrPoolOrEmergencyAdmins ``` Freeze or unfreeze a reserve. A frozen reserve doesn’t allow new supply or borrow but allows repayments, liquidations and withdrawals. Freezing also sets the reserve LTV to zero, including in every E-Mode where it is collateral. **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 | ### setEModeCategoryIsolated ```solidity function setEModeCategoryIsolated(uint8 categoryId, bool isolated) external onlyRiskOrPoolOrEmergencyAdmins ``` Sets the isolated flag of an E-Mode category. When `true`, users with collateral enabled outside the category cannot enter it, and assets outside the category get LTV 0. The liquidation threshold is unaffected, so the Health Factor of existing positions is preserved. Added in Aave V3.7. **Input Parameters:** | Name | Type | Description | | :--------- | :------ | :---------------------------------------- | | **categoryId** | `uint8` | The E-Mode category id | | **isolated** | `bool` | `true` if the E-Mode category is isolated | --- Source: https://aave.com/docs/aave-v3/smart-contracts/acl-manager.md # Aave V3 ACL Manager Contract The Access Control List Manager (`ACLManager`) is the main registry of system roles and permissions. The Aave Protocol 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`](./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`](./pool-addresses-provider) beforehand. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/configuration/ACLManager.sol). ## 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`](#flash-borrower) and [`BRIDGE`](#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`](./pool): - [`flashLoan()`](./pool#flashloan) ### BRIDGE Deprecated. Since Aave V3.4 this role grants no access: `mintUnbacked()` and `backUnbacked()` were removed from the `Pool`. `ACLManager` still exposes `BRIDGE_ROLE`, `addBridge()`, `removeBridge()` and `isBridge()`. ### ASSET_LISTING_ADMIN Holders of this role can: - Update asset oracle sources and the fallback oracle. - Add new assets to the Aave market. **Methods Accessible:** [`AaveOracle`](./oracles): - [`setAssetSources()`](./oracles#setassetsources) - [`setFallbackOracle()`](./oracles#setfallbackoracle) [`PoolConfigurator`](./pool-configurator): - [`initReserves()`](./pool-configurator#initreserves) ### RISK_ADMIN Holders of this role can: - 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), including their isolated flag. - Update the liquidation protocol fee. **Methods Accessible:** [`PoolConfigurator`](./pool-configurator): - [`setReserveBorrowing()`](./pool-configurator#setreserveborrowing) - [`configureReserveAsCollateral()`](./pool-configurator#configurereserveascollateral) - [`setReserveFreeze()`](./pool-configurator#setreservefreeze) - [`setReserveFactor()`](./pool-configurator#setreservefactor) - [`setBorrowCap()`](./pool-configurator#setborrowcap) - [`setSupplyCap()`](./pool-configurator#setsupplycap) - [`setLiquidationProtocolFee()`](./pool-configurator#setliquidationprotocolfee) - [`setEModeCategory()`](./pool-configurator#setemodecategory) - [`setAssetCollateralInEMode()`](./pool-configurator#setassetcollateralinemode) - [`setAssetBorrowableInEMode()`](./pool-configurator#setassetborrowableinemode) - [`setEModeCategoryIsolated()`](./pool-configurator#setemodecategoryisolated) - `setReserveLtvzero()` - `setAssetLtvzeroInEMode()` - [`setReserveInterestRateData()`](./pool-configurator#setreserveinterestratedata) - [`setReserveFlashLoaning()`](./pool-configurator#setreserveflashloaning) ### 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`](./acl-manager): - [`setRoleAdmin()`](#setroleadmin) - [`addPoolAdmin()`](#addpooladmin) - [`removePoolAdmin()`](#removepooladmin) - [`addEmergencyAdmin()`](#addemergencyadmin) - [`removeEmergencyAdmin()`](#removeemergencyadmin) - [`addRiskAdmin()`](#addriskadmin) - [`removeRiskAdmin()`](#removeriskadmin) - [`addFlashBorrower()`](#addflashborrower) - [`removeFlashBorrower()`](#removeflashborrower) - `addBridge()` - `removeBridge()` - [`addAssetListingAdmin()`](#addassetlistingadmin) - [`removeAssetListingAdmin()`](#removeassetlistingadmin) ### EMERGENCY_ADMIN Holders of this role can pause and unpause the pool or an individual reserve. **Methods Accessible:** [`PoolConfigurator`](./pool-configurator): - [`setReservePause()`](./pool-configurator#setreservepause) - [`setPoolPause()`](./pool-configurator#setpoolpause) - [`setReserveFreeze()`](./pool-configurator#setreservefreeze) - [`disableLiquidationGracePeriod()`](./pool-configurator#disableliquidationgraceperiod) - [`setEModeCategoryIsolated()`](./pool-configurator#setemodecategoryisolated) - `setReserveLtvzero()` - `setAssetLtvzeroInEMode()` ### POOL_ADMIN Holders of this role can update token implementations, (un)pause and (de)activate reserves, update premiums along with everything the [`ASSET_LISTING_ADMIN`](#asset-listing-admin) and [`RISK_ADMIN`](#risk-admin) can do. All deployers have resigned their [`POOL_ADMIN`](#pool-admin) roles. All instances of the [`POOL_ADMIN`](#pool-admin) role, across all V3 networks, are now governed by the [Guardians multisig](/ecosystem/governance#guardians) or by the [Governance Bridge executors](https://github.com/aave/governance-crosschain-bridges). **Methods Accessible:** All methods accessible to `ASSET_LISTING_ADMIN`. All methods accessible to `RISK_ADMIN`. [`AToken`](./tokenization): - [`rescueTokens()`](./tokenization#rescuetokens) [`Pool`](./pool): - [`rescueTokens()`](./pool#rescuetokens) [`PoolConfigurator`](./pool-configurator): - [`updateAToken()`](./pool-configurator#updateatoken) - [`updateVariableDebtToken()`](./pool-configurator#updatevariabledebttoken) - [`setReserveActive()`](./pool-configurator#setreserveactive) - [`updateFlashloanPremium()`](./pool-configurator#updateflashloanpremium) - [`setReserveInterestRateData()`](./pool-configurator#setreserveinterestratedata) ## Write Methods ### setRoleAdmin ```solidity function setRoleAdmin(bytes32 role, bytes32 adminRole) external override onlyRole(DEFAULT_ADMIN_ROLE) ``` Sets `adminRole` as the admin of `role`. By default, the `adminRole` for all roles is [`DEFAULT_ADMIN_ROLE`](#acl-admin). > [!NOTE] > Only callable by an address with [`DEFAULT_ADMIN_ROLE`](#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 ```solidity 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`](#pool-admin) role. Holders of this role can update token implementations, (un)pause and (de)activate reserves, update premiums and do everything the [`ASSET_LISTING_ADMIN`](#asset-listing-admin) and [`RISK_ADMIN`](#risk-admin) can do. > [!NOTE] > Only callable by the _Role Admin_ of the [`POOL_ADMIN`](#pool-admin) role, set > by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :------------------------------------------------------ | | **admin** | `address` | The address which will be granted the `POOL_ADMIN` role | ### removePoolAdmin ```solidity 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`](#pool-admin) role. > [!NOTE] > Only callable by the _Role Admin_ of the [`POOL_ADMIN`](#pool-admin) role, set > by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :---------------------------------------------------------------------- | | **admin** | `address` | The address for which the `POOL_ADMIN` role permissions will be removed | ### addEmergencyAdmin ```solidity 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`](#emergency-admin) role. Holders of this role can pause and unpause the pool or an individual reserve. > [!NOTE] > Only callable by the _Role Admin_ of the [`EMERGENCY_ADMIN`](#emergency-admin) > role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------------------------------------------- | | **admin** | `address` | The address which will be granted the `EMERGENCY_ADMIN` role | ### removeEmergencyAdmin ```solidity 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`](#emergency-admin) role. > [!NOTE] > Only callable by the _Role Admin_ of the [`EMERGENCY_ADMIN`](#emergency-admin) > role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :--------------------------------------------------------------------------- | | **admin** | `address` | The address for which the `EMERGENCY_ADMIN` role permissions will be removed | ### addRiskAdmin ```solidity 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`](#risk-admin) role. Holders of this role can update reserve params, liquidation fee and E-Mode categories. > [!NOTE] > Only callable by the _Role Admin_ of the [`RISK_ADMIN`](#risk-admin) role, set > by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :------------------------------------------------------ | | **admin** | `address` | The address which will be granted the `RISK_ADMIN` role | ### removeRiskAdmin ```solidity 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`](#risk-admin) role. > [!NOTE] > Only callable by the _Role Admin_ of the [`RISK_ADMIN`](#risk-admin) role, set > by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :---------------------------------------------------------------------- | | **admin** | `address` | The address for which the `RISK_ADMIN` role permissions will be removed | ### addFlashBorrower ```solidity 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`](#flash-borrower) role. Holders of this role do not pay premium for flash loan (does not apply to `flashLoanSimple`). > [!NOTE] > Only callable by the _Role Admin_ of the [`FLASH_BORROWER`](#flash-borrower) > role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :------- | :-------- | :---------------------------------------------------------- | | **borrower** | `address` | The address which will be granted the `FLASH_BORROWER` role | ### removeFlashBorrower ```solidity function removeFlashBorrower(address borrower) external override ``` Removes `borrower` as _Flash Borrower_. The given `borrower` address is removed from the list of members with the [`FLASH_BORROWER`](#flash-borrower) role. > [!NOTE] > Only callable by the _Role Admin_ of the [`FLASH_BORROWER`](#flash-borrower) > role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :------- | :-------- | :-------------------------------------------------------------------------- | | **borrower** | `address` | The address for which the `FLASH_BORROWER` role permissions will be removed | ### addAssetListingAdmin ```solidity 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`](#asset-listing-admin) role. Holders of this role can update oracles and add new assets to the Aave market. > [!NOTE] > Only callable by the _Role Admin_ of the > [`ASSET_LISTING_ADMIN`](#asset-listing-admin) role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :----------------------------------------------------------- | | **admin** | `address` | The address which will be granted `ASSET_LISTING_ADMIN` role | ### removeAssetListingAdmin ```solidity 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`](#asset-listing-admin) role. > [!NOTE] > Only callable by the _Role Admin_ of the > [`ASSET_LISTING_ADMIN`](#asset-listing-admin) role, set by _Aave Governance_. **Input Parameters:** | Name | Type | Description | | :---- | :-------- | :--------------------------------------------------------------------------- | | **admin** | `address` | The address for which `ASSET_LISTING_ADMIN` role permissions will be removed | ## View Methods ### isPoolAdmin ```solidity function isPoolAdmin(address admin) external view override returns (bool) ``` Returns `true` if the address has the [`POOL_ADMIN`](#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 ```solidity function isEmergencyAdmin(address admin) external view override returns (bool) ``` Returns `true` if the address has the [`EMERGENCY_ADMIN`](#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 ```solidity function isRiskAdmin(address admin) external view override returns (bool) ``` Returns `true` if the address has the [`RISK_ADMIN`](#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 ```solidity function isFlashBorrower(address borrower) external view override returns (bool) ``` Returns `true` if the address has the [`FLASH_BORROWER`](#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 ```solidity function isBridge(address bridge) external view override returns (bool) ``` Returns `true` if the address has [`BRIDGE`](#bridge) 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 ```solidity function isAssetListingAdmin(address admin) external view override returns (bool) ``` Returns `true` if the address has the [`ASSET_LISTING_ADMIN`](#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 | --- Source: https://aave.com/docs/aave-v3/smart-contracts/pool-addresses-provider.md # Aave V3 Pool Addresses Provider The `PoolAddressesProvider` contract is the main registry of addresses that are part of, or connected to the Protocol, including permissioned roles. It acts as a factory of proxies and is the admin of those, and therefore has the right to change its implementations. The addresses provider manages various protocol modules and has the ability to update pointers (e.g. update the [`ACLManager`](./acl-manager) contract) or update the implementation of proxy contracts (e.g. update the [`Pool`](./pool) implementation). It stores the ACL admin, which receives [`DEFAULT_ADMIN_ROLE`](./acl-manager) when the ACLManager is deployed. > [!NOTE] > Always fetch the [`Pool`](./pool) address from this `PoolAddressesProvider` > contract. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/configuration/PoolAddressesProvider.sol). > [!NOTE] > This contract is owned by the [Aave Governance](https://governance.aave.com/). ## Write Methods ### setMarketId ```solidity 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 ```solidity 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`. > [!WARNING] > This hard-replaces the current address in the addresses map. Use it carefully. **Input Parameters:** | Name | Type | Description | | :--------- | :-------- | :--------------------------------------------------------- | | **id** | `bytes32` | A bytes32 identifier, e.g. `bytes32('POOL')` for core contracts or `keccak256('INCENTIVES_CONTROLLER')` for custom entries | | **newAddress** | `address` | The new address to be set corresponding to the id | ### setAddressAsProxy ```solidity 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`. > [!WARNING] > Use only for ids without an explicit setter function, to avoid unexpected > results. **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 ```solidity function setPoolImpl(address newPoolImpl) external override onlyOwner ``` Updates the implementation of the [`Pool`](./pool) contract, or creates a proxy. **Input Parameters:** | Name | Type | Description | | :---------- | :-------- | :------------------------------------------------ | | **newPoolImpl** | `address` | The address of new `Pool` implementation contract | ### setPoolConfiguratorImpl ```solidity function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external override onlyOwner ``` Updates the implementation of the [`PoolConfigurator`](./pool-configurator) contract, or creates a proxy. **Input Parameters:** | Name | Type | Description | | :---------------------- | :-------- | :---------------------------------------------------------- | | **newPoolConfiguratorImpl** | `address` | The address of new PoolConfigurator implementation contract | ### setPriceOracle ```solidity 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 ```solidity 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 ```solidity 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 ```solidity function setPriceOracleSentinel(address newPriceOracleSentinel) external override onlyOwner ``` Updates the address of the price oracle sentinel. Since Aave V3.7 the Pool no longer reads this address, so it has no effect on borrows or liquidations. **Input Parameters:** | Name | Type | Description | | :--------------------- | :-------- | :------------------------------------- | | **newPriceOracleSentinel** | `address` | The address of new PriceOracleSentinel | ### setPoolDataProvider ```solidity 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 ```solidity function getMarketId() external view override returns (string memory) ``` Returns the market id of the associated Aave market. **Return Values:** | Type | Description | | :------- | :--------------------------------------- | | `string` | A string representation of the market id | ### getAddress ```solidity 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 `bytes32('DATA_PROVIDER')` | **Return Values:** | Type | Description | | :-------- | :---------------------------------------- | | `address` | The address associated with the id passed | **Example:** ```ts import { Contract, getDefaultProvider, keccak256, toUtf8Bytes } from "ethers"; const poolAddressesProvider = new Contract( "0x2f39d218133AFaB8F2B819B1066c7E434Ad94E9e", ["function getAddress(bytes32 id) view returns (address)"], getDefaultProvider() ); const address = await poolAddressesProvider.getAddress( keccak256(toUtf8Bytes("INCENTIVES_CONTROLLER")) ); ``` ### getPool ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ACLManager contract managing the system role of the associated market | ### getACLAdmin ```solidity 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 ```solidity function getPriceOracleSentinel() external view override returns (address) ``` Returns the address of the price oracle sentinel. Since Aave V3.7 the Pool no longer uses it. **Return Values:** | Type | Description | | :-------- | :-------------------------------------------------------------- | | `address` | The address of the PriceOracleSentinel of the associated market | ### getPoolDataProvider ```solidity 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 | --- Source: https://aave.com/docs/aave-v3/smart-contracts/tokenization.md # Aave V3 Tokenization Contracts Reference for `AToken`, `RwaAToken`, `StataTokenFactory` and `VariableDebtToken`. ## AToken aTokens are tokens minted and burned upon `supply` and `withdraw` of assets to an Aave market. aTokens denote the amount of crypto assets supplied to the protocol and the yield earned on those assets. The aTokens’ value is pegged to the value of the corresponding supplied asset at a 1:1 ratio and can be safely stored, transferred or traded. All yield collected by the aTokens' reserves are distributed to aToken holders directly by continuously increasing their wallet balance. This contract is the implementation of the interest bearing token for the Aave Protocol. It inherits the [ScaledBalanceTokenBase](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/ScaledBalanceTokenBase.sol) and [EIP712Base](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 for aTokens, such as `balanceOf`, `transfer`, `transferFrom`, `approve`, `totalSupply` etc. `balanceOf` will always return the most up to date balance of the user, which includes their principal balance and the yield generated by the principal balance. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/AToken.sol). ### Write Methods #### initialize ```solidity function initialize( IPool initializingPool, address underlyingAsset, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) public virtual ``` Called when aToken instance is initialized. The treasury and incentives controller are immutable and set in the constructor. **Input Parameters:** | Name | Type | Description | | :--------------- | :-------- | :-------------------------------------------------------- | | **initializingPool** | `IPool` | The address of the associated pool | | **underlyingAsset** | `address` | The address of the underlying asset | | **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 ```solidity function mint( address caller, address onBehalfOf, uint256 scaledAmount, uint256 index ) external virtual override onlyPool returns (bool) ``` Mints aTokens to `onBehalfOf`. **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 | | **scaledAmount** | `uint256` | The scaled amount of tokens getting minted | | **index** | `uint256` | The next liquidity index of the reserve | **Return Values:** | Type | Description | | :----- | :----------------------------------------------- | | `bool` | `true` if the previous balance of the user was 0 | #### burn ```solidity function burn( address from, address receiverOfUnderlying, uint256 amount, uint256 scaledAmount, uint256 index ) external virtual override onlyPool returns (bool) ``` Burns aTokens from `from` and sends the equivalent amount of underlying to `receiverOfUnderlying`. 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 underlying to be burned (non-scaled) | | **scaledAmount** | `uint256` | The scaled amount of aTokens to be burned | | **index** | `uint256` | The next liquidity index of the reserve | **Return Values:** | Type | Description | | :----- | :----------------------------------------- | | `bool` | `true` if the new balance of the user is 0 | #### mintToTreasury ```solidity function mintToTreasury(uint256 scaledAmount, uint256 index) external virtual override onlyPool ``` Mints aTokens to the reserve treasury. **Input Parameters:** | Name | Type | Description | | :----------- | :-------- | :----------------------------------------- | | **scaledAmount** | `uint256` | The scaled amount of tokens getting minted | | **index** | `uint256` | The next liquidity index of the reserve | #### transferOnLiquidation ```solidity function transferOnLiquidation( address from, address to, uint256 amount, uint256 scaledAmount, uint256 index ) external 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 | | **amount** | `uint256` | The amount of tokens getting transferred | | **scaledAmount** | `uint256` | The scaled amount of tokens getting transferred | | **index** | `uint256` | The next liquidity index of the reserve | #### transferUnderlyingTo ```solidity function transferUnderlyingTo(address target, uint256 amount) external virtual override onlyPool ``` Transfers the underlying asset to `target`. Used by the [`Pool`](./pool) to transfer assets in `borrow()`, `withdraw()` and `flashLoan()`. **Input Parameters:** | Name | Type | Description | | :----- | :-------- | :------------------------------ | | **target** | `address` | The recipient of the underlying | | **amount** | `uint256` | The amount getting transferred | #### permit ```solidity 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: ```ts import { Contract, Signature, Wallet, getDefaultProvider } from "ethers"; const signer = new Wallet(process.env.PRIVATE_KEY!, getDefaultProvider()); const aTokenAddress = "ATOKEN_ADDRESS"; const aToken = new Contract( aTokenAddress, [ "function name() view returns (string)", "function nonces(address owner) view returns (uint256)", "function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)", ], signer ); const owner = await signer.getAddress(); const spender = "SPENDER_ADDRESS"; const value = 100n; const nonce = await aToken.nonces(owner); const deadline = BigInt(Math.floor(Date.now() / 1000) + 3600); const signature = await signer.signTypedData( { name: await aToken.name(), version: "1", chainId: 1, verifyingContract: aTokenAddress, }, { Permit: [ { name: "owner", type: "address" }, { name: "spender", type: "address" }, { name: "value", type: "uint256" }, { name: "nonce", type: "uint256" }, { name: "deadline", type: "uint256" }, ], }, { owner, spender, value, nonce, deadline } ); const { v, r, s } = Signature.from(signature); await aToken.permit(owner, spender, value, deadline, v, r, s); ``` #### rescueTokens ```solidity function rescueTokens( address token, address to, uint256 amount ) external override onlyPoolAdmin ``` Rescue and transfer tokens locked in this contract. Only callable by [`POOL_ADMIN`](./acl-manager#pool-admin). **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 ```solidity 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 ```solidity 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 ```solidity function RESERVE_TREASURY_ADDRESS() external view override returns (address) ``` Returns the address of the Aave treasury, controlled by governance, receiving the fees on this aToken. **Return Values:** | Type | Description | | :-------- | :------------------------------- | | `address` | The address of the Aave treasury | #### UNDERLYING_ASSET_ADDRESS ```solidity 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 ```solidity 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 ```solidity 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: ```jsx const token = new Contract(aTokenAddress, aToken.abi, provider); await token.nonces(user); ``` ## RwaAToken `RwaAToken` is a specialized version of the `AToken` contract designed for _Real-World Assets (RWAs)_. It represents a user’s supplied collateral in the Aave Horizon market. To comply with regulatory requirements, `RwaAToken` instances are non-transferable by default for end-users. Key functionalities such as `transfer`, `approve`, and `permit` are disabled to prevent peer-to-peer movement of these tokens. Aave Horizon introduces an `ATOKEN_ADMIN_ROLE`, which can be granted to RWA issuers or their designated managers to manage functions such as wallet recovery or position migration. An address holding this role can execute authorized transfers on behalf of users, as detailed below. ### Write Methods #### authorizedTransfer ```solidity function authorizedTransfer(address from, address to, uint256 amount) external returns (bool) ``` Transfers an amount of aTokens between two users. This function can only be called by the [`RwaATokenManager`](https://github.com/aave/aave-v3-horizon/blob/main/src/contracts/misc/RwaATokenManager.sol#L9) address holding the `ATOKEN_ADMIN_ROLE` to granularly manage aToken-specific transfers. It is intended for administrative actions, such as migrating a user’s position to a new wallet. The transfer is still subject to the protocol’s health factor checks. **Input Parameters:** | Name | Type | Description | | :----- | :-------- | :------------------------------- | | **from** | `address` | The address to transfer from | | **to** | `address` | The address to transfer to | | **amount** | `uint256` | The amount of tokens to transfer | **Return Values:** | Type | Description | | :----- | :------------------------------------ | | `bool` | `true` if the transfer was successful | #### mint ```solidity function mint( address caller, address onBehalfOf, uint256 amount, uint256 index ) public virtual returns (bool) ``` Mints `amount` aTokens to a user. This function overrides the standard `mint` to enforce that the `caller` of the transaction must be the same as the `onBehalfOf` address. This effectively disables the `supplyOnBehalfOf` functionality for RWAs. **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 previous balance of the user was 0 | ### Pure Methods #### ATOKEN_ADMIN_ROLE ```solidity function ATOKEN_ADMIN_ROLE() external pure returns (bytes32) ``` Returns the `bytes32` identifier for the `ATOKEN_ADMIN_ROLE`. This role grants permission to call `authorizedTransfer`. **Return Values:** | Type | Description | | :-------- | :------------------------------------- | | `bytes32` | The identifier of the ATokenAdmin role | ### Unsupported Operations To enforce the non-transferable and compliant nature of RWA collateral, most standard ERC-20 interactions are disabled for `RwaAToken`. Calling any of the following functions will revert with an `OPERATION_NOT_SUPPORTED` error: - `permit` - `approve` - `increaseAllowance` - `decreaseAllowance` - `transfer` - `transferFrom` - `mintToTreasury` - `transferOnLiquidation` - `transferUnderlyingTo` ## StataTokenFactory 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 `StataToken` addresses. `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 [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/extensions/stata-token/StataTokenFactory.sol). ### Write Methods #### initialize ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 | #### INITIAL_OWNER ```solidity function INITIAL_OWNER() external view returns (address) ``` Returns the initial owner of the `StataToken` proxies created by this factory. **Return Values:** | Type | Description | | :------ | :------------------------------- | | address | The address of the initial owner | #### TRANSPARENT_PROXY_FACTORY ```solidity 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 ```solidity function STATA_TOKEN_IMPL() external view returns (address) ``` Returns the address of the `StataToken` implementation used when deploying new `StataToken` instances. **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 [`DebtTokenBase`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/base/DebtTokenBase.sol) and [`ScaledBalanceTokenBase`](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 [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/protocol/tokenization/VariableDebtToken.sol). ### Write Methods #### initialize ```solidity function initialize( IPool initializingPool, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external virtual ``` Called when variableDebtToken instance is initialized. **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 variable debt token (e.g. WETH for variableDebtWETH) | | **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 ```solidity function mint( address user, address onBehalfOf, uint256 amount, uint256 scaledAmount, uint256 index ) external virtual override onlyPool returns (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 unscaled amount of debt, used for the borrow allowance | | **scaledAmount** | `uint256` | The scaled amount of variable debt tokens to mint | | **index** | `uint256` | The variable debt index of the reserve | **Return Values:** | Type | Description | | :-------- | :----------------------------------- | | `uint256` | The scaled total debt of the reserve | #### burn ```solidity function burn( address from, uint256 scaledAmount, uint256 index ) external virtual override onlyPool returns (bool, 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 | | **scaledAmount** | `uint256` | The scaled amount of debt getting burned | | **index** | `uint256` | The variable debt index of the reserve | **Return Values:** | Type | Description | | :-------- | :----------------------------------- | | `bool` | `true` if the new balance is zero | | `uint256` | The scaled total debt of the reserve | ### View Methods #### UNDERLYING_ASSET_ADDRESS ```solidity 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 ```solidity 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 ERC-20 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 ```solidity 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 ERC-20 function. **Return Values:** | Type | Description | | :-------- | :-------------------------------- | | `uint256` | The amount of tokens in existence | ### Unsupported Operations Being non-transferable, the variable debt token does not implement any of the standard ERC-20 functions for `transfer` and `allowance`. The following functions revert with `OperationNotSupported()`: `transfer`, `allowance`, `approve`, `transferFrom`, `renounceAllowance`, `increaseAllowance`, `decreaseAllowance`. --- Source: https://aave.com/docs/aave-v3/smart-contracts/oracles.md # Aave V3 Oracle Contract The `AaveOracle` contract returns asset prices and manages price sources. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/AaveOracle.sol). > [!NOTE] > Write methods are restricted to `POOL_ADMIN` and `ASSET_LISTING_ADMIN` via the > ACLManager. ## AaveOracle ### Write Methods #### setAssetSources ```solidity function setAssetSources(address[] calldata assets, address[] calldata sources) external override onlyAssetListingOrPoolAdmins ``` Sets the price `sources` for given list of `assets`. > [!NOTE] > Only callable by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See > [`ACLManager`](./acl-manager) for 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 ```solidity function setFallbackOracle(address fallbackOracle) external override onlyAssetListingOrPoolAdmins ``` Sets/updates the `fallbackOracle`. > [!NOTE] > Only callable by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See > [`ACLManager`](./acl-manager) for roles. **Input Parameters:** | Name | Type | Description | | :------------- | :-------- | :--------------------------------- | | **fallbackOracle** | `address` | The address of the fallback oracle | ### View Methods #### getAssetPrice ```solidity function getAssetPrice(address asset) public view override returns (uint256) ``` Returns the price of the supported `asset` in [`BASE_CURRENCY`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/interfaces/IPriceOracleGetter.sol) of the Aave Market, scaled by `BASE_CURRENCY_UNIT` (8 decimals on USD markets). **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 Aave market, scaled by `BASE_CURRENCY_UNIT` (8 decimals on USD markets) | #### getAssetsPrices ```solidity 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 [`BASE_CURRENCY`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/interfaces/IPriceOracleGetter.sol) of the Aave Market. All prices are scaled by `BASE_CURRENCY_UNIT` (8 decimals on USD markets). **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 Aave market, scaled by `BASE_CURRENCY_UNIT` (8 decimals on USD markets) | #### getSourceOfAsset ```solidity 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 ```solidity 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 Aave V3.7 removed the `PriceOracleSentinel` and its sequencer oracle. Borrows and liquidations are no longer gated by L2 sequencer uptime: borrows succeed when the standard checks pass, and liquidations proceed whenever the Health Factor is below 1 and the liquidation grace period has elapsed. > [!NOTE] > Some Aave V3 instances may still run Aave V3.6, where the sentinel can block > borrows and delay liquidations after a sequencer outage. `POOL_REVISION()` on > the Pool returns `10` on [Aave V3.6](/resources/changelog#aave-v36) and `11` > on [Aave V3.7](/resources/changelog#aave-v37-part-1). See the [Aave V3.6 > source](https://github.com/aave-dao/aave-v3-origin/blob/v3.6.0/src/contracts/misc/PriceOracleSentinel.sol). --- Source: https://aave.com/docs/aave-v3/smart-contracts/interest-rate-strategy.md # Aave V3 Interest Rate Strategy Implements the calculation of the interest rates depending on the reserve state. The model of interest rate is based on two slopes, one before the reserve’s optimal usage ratio and another from that point to 100%. Rates are set per reserve through [`PoolConfigurator.setReserveInterestRateData`](./pool-configurator#setreserveinterestratedata). With utilization _U_ and optimal usage ratio _U_optimal, the variable borrow rate is: > [!NOTE] > Each Aave market needs its own instance of this contract, because it caches > the [PoolAddressesProvider](./pool-addresses-provider). The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/misc/DefaultReserveInterestRateStrategyV2.sol). ## View Methods ### getInterestRateData ```solidity function getInterestRateData(address reserve) external view returns (InterestRateDataRay memory) ``` Returns the interest rate parameters of the specified reserve, in ray. **Input Parameters:** | Name | Type | Description | | :------ | :-------- | :------------------------- | | **reserve** | `address` | The address of the reserve | **Return Values:** | Type | Description | | :-------------------- | :------------------------------------------------------------------------------------------------------------------ | | `InterestRateDataRay` | `optimalUsageRatio`, `baseVariableBorrowRate`, `variableRateSlope1` and `variableRateSlope2`, all expressed in ray | ### getInterestRateDataBps ```solidity function getInterestRateDataBps(address reserve) external view returns (InterestRateData memory) ``` Returns the interest rate parameters of the specified reserve, in bps. **Input Parameters:** | Name | Type | Description | | :------ | :-------- | :------------------------- | | **reserve** | `address` | The address of the reserve | **Return Values:** | Type | Description | | :----------------- | :------------------------------------------------------------------------------------------------------------------ | | `InterestRateData` | `optimalUsageRatio`, `baseVariableBorrowRate`, `variableRateSlope1` and `variableRateSlope2`, all expressed in bps | ### getOptimalUsageRatio ```solidity function getOptimalUsageRatio(address reserve) external view returns (uint256) ``` Returns the optimal usage ratio of the specified reserve. **Input Parameters:** | Name | Type | Description | | :------ | :-------- | :------------------------- | | **reserve** | `address` | The address of the reserve | **Return Values:** | Type | Description | | :-------- | :---------------------------------------- | | `uint256` | The optimal usage ratio, expressed in ray | ### getVariableRateSlope1 ```solidity function getVariableRateSlope1(address reserve) external view returns (uint256) ``` Returns the variable rate slope below the optimal usage ratio for the specified reserve. Applies while the usage ratio is below the optimal usage ratio. **Input Parameters:** | Name | Type | Description | | :------ | :-------- | :------------------------- | | **reserve** | `address` | The address of the reserve | **Return Values:** | Type | Description | | :-------- | :---------------------------------------- | | `uint256` | The variable rate slope, expressed in ray | ### getVariableRateSlope2 ```solidity function getVariableRateSlope2(address reserve) external view returns (uint256) ``` Returns the variable rate slope above the optimal usage ratio for the specified reserve. Applies while the usage ratio is above the optimal usage ratio. **Input Parameters:** | Name | Type | Description | | :------ | :-------- | :------------------------- | | **reserve** | `address` | The address of the reserve | **Return Values:** | Type | Description | | :-------- | :---------------------------------------- | | `uint256` | The variable rate slope, expressed in ray | ### getBaseVariableBorrowRate ```solidity 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 ```solidity 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 ```solidity 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 reserve deficit (field kept under its pre-V3.4 name); added to the denominator of the supply usage ratio | | **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` | Deprecated since Aave V3.4, always `true` | | **virtualUnderlyingBalance** | `uint256` | The virtual balance of the underlying asset held by the reserve | **Return Values:** | Name | Type | Description | | :----------------- | :-------- | :----------------------------------------- | | **liquidityRate** | `uint256` | The liquidity rate, expressed in ray | | **variableBorrowRate** | `uint256` | The variable borrow rate, expressed in ray | --- Source: https://aave.com/docs/aave-v3/smart-contracts/incentives.md # Aave V3 Incentives Contracts The [`UiIncentiveDataProvider`](./view-contracts) provides methods to query all active incentive emissions, and claimable user incentives for a particular Aave market. ## RewardsController `RewardsController` is the main rewards contract, where users claim the ERC-20 rewards of their positions. It inherits from the abstract [`RewardsDistributor`](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/rewards/RewardsDistributor.sol), which handles reward distribution. Holders of incentivized ERC-20 assets accrue rewards just by holding them, with no staking or locking. The users can claim all the rewards or an individual reward per transaction, with a variety of functions that allow more granularity at claim. > [!NOTE] > At every transfer, the asset must call the `handleAction` method to account > for the user’s rewards. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/rewards/RewardsController.sol). ### Write Methods #### initialize ```solidity function initialize(address) external initializer ``` Initialize `RewardsController` instance. **Input Parameters:** | **Type** | Description | | :-------- | :------------------------------------------------------------------------------------ | | **`address`** | Unused but required due to being initialized by `PoolAddressesProvider._updateImpl()` | #### configureAssets ```solidity 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 array of reward configurations, one per asset/reward pair | The [RewardsDataTypes.RewardsConfigInput](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** | `ITransferStrategyBase` | The TransferStrategy address with the install hook and claim logic | | **rewardOracle** | `AggregatorInterface` | The Price Oracle of a reward to visualize the incentives at the UI frontend. Must follow the Chainlink `AggregatorInterface` and return a positive `latestAnswer()`. | #### setTransferStrategy ```solidity 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** | `ITransferStrategyBase` | The address of the TransferStrategy logic contract | #### setRewardOracle ```solidity function setRewardOracle(address reward, AggregatorInterface 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 follows the Chainlink `AggregatorInterface` and returns a positive `latestAnswer()`. 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** | `AggregatorInterface` | The address of price aggregator that follows the Chainlink `AggregatorInterface` and returns a positive `latestAnswer()` | #### handleAction ```solidity 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 total supply of the asset before the balance change | | **userBalance** | `uint256` | The user balance of the asset before the balance change | #### claimRewards ```solidity 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 (aToken or variableDebtToken addresses) | | **amount** | `uint256` | The amount of rewards to claim, expressed in wei. Pass `type(uint256).max` 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 | #### claimRewardsOnBehalf ```solidity function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to, address reward ) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) ``` 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 set as claimer for `user` via [`setClaimer()`](#setclaimer) by the `EmissionManager`. 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 (aToken or variableDebtToken addresses) | | **amount** | `uint256` | The amount of rewards to claim, expressed in wei. Pass `type(uint256).max` 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 ```solidity 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 (aToken or variableDebtToken addresses) | | **amount** | `uint256` | The amount of rewards to claim, expressed in wei. Pass `type(uint256).max` 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 ```solidity 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 `to` address. **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 ```solidity 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 set as claimer for `user` via [`setClaimer()`](#setclaimer) by the `EmissionManager`. 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 (aToken or variableDebtToken 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 ```solidity 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 (aToken or variableDebtToken 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 ```solidity 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`. **Input Parameters:** | Name | Type | Description | | :----- | :-------- | :------------------------- | | **user** | `address` | The address of the user | | **caller** | `address` | The address of the claimer | ### View Methods #### getClaimer ```solidity 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 ```solidity function getRewardOracle(address reward) external view override returns (address) ``` Get the price aggregator oracle address. **Input Parameters:** | Name | Type | Description | | :----- | :-------- | :------------------------------ | | **reward** | `address` | The address of the reward token | **Return Values:** | Type | Description | | :-------- | :------------------------------- | | `address` | The address of the reward oracle | #### getTransferStrategy ```solidity function getTransferStrategy(address reward) external view override returns (address) ``` Returns the Transfer Strategy implementation contract address being used for a reward address. **Input Parameters:** | Name | Type | Description | | :----- | :-------- | :------------------------ | | **reward** | `address` | The address of the reward | **Return Values:** | Type | Description | | :-------- | :------------------------------------------- | | `address` | The address of the TransferStrategy contract | --- Source: https://aave.com/docs/aave-v3/smart-contracts/wrapped-token-gateway.md # Aave V3 Wrapped Token Gateway The Aave Protocol operates exclusively with ERC-20 [reserve](../concepts/reserve) tokens. To accommodate network gas tokens, the `WrappedTokenGateway` (previously called `WETHGateway`) is a helper contract that enables gas tokens (ETH, POL, etc.) to be wrapped or unwrapped to perform Aave Pool methods: - Supply - Borrow - Repay - Withdraw The smart contract source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/WrappedTokenGatewayV3.sol). ## Write Methods The first `address` argument of each method is unused and kept for backward compatibility; the pool is fixed at deployment. ### depositETH ```solidity function depositETH( address, address onBehalfOf, uint16 referralCode ) external payable override ``` Wraps and supplies gas tokens to the Aave Protocol. A corresponding amount of the wrapped aTokens are minted to the `onBehalfOf` address. > [!NOTE] > Pass the gas token amount to supply in `msg.value`. **Input Parameters:** | Name | Type | Description | | :----------- | :-------- | :------------------------------------------------------------------------------------ | | **onBehalfOf** | `address` | The address of the user who will receive the aTokens representing the supplied tokens | | **referralCode** | `uint16` | Inactive, can pass `0` as placeholder | ### withdrawETH ```solidity function withdrawETH( address, uint256 amount, address to ) external override ``` Withdraws `amount` of the supplied wrapped gas token, unwraps it and transfers to the `to` address. If the `amount` is `type(uint256).max`, the entire balance is withdrawn. > [!NOTE] > First approve the WrappedTokenGateway to spend the user’s aWETH, for example > `IERC20(aWETHAddress).approve(wrappedTokenGatewayAddress, amount)`. **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 | ### repayETH ```solidity function repayETH( address, uint256 amount, 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 `type(uint256).max` is passed). > [!NOTE] > Pass the gas token amount to repay in `msg.value`. **Input Parameters:** | Name | Type | Description | | :--------- | :-------- | :-------------------------------------------------------------------------- | | **amount** | `uint256` | The amount to repay, or `type(uint256).max` if the user wants to repay everything | | **onBehalfOf** | `address` | The address for which `msg.sender` is repaying | ### borrowETH ```solidity function borrowETH( address, uint256 amount, uint16 referralCode ) external override ``` Borrows `amount` of unwrapped network gas tokens to `msg.sender`. > [!NOTE] > First grant the WrappedTokenGateway [credit > delegation](/aave-v3/guides/credit-delegation) on WETH (or the network’s > wrapped gas token), for example > `IVariableDebtToken(variableDebtWETHAddress).approveDelegation(wrappedTokenGatewayAddress, > amount)`. **Input Parameters:** | Name | Type | Description | | :--------------- | :-------- | :--------------------------------------------------------------------------- | | **amount** | `uint256` | The amount of ETH to borrow | | **referralCode** | `uint16` | Inactive, can pass `0` as placeholder | ### withdrawETHWithPermit ```solidity 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 `to` address. If the `amount` is `type(uint256).max`, 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 EIP-712 permit signature | | **permitR** | `bytes32` | R parameter of EIP-712 permit signature | | **permitS** | `bytes32` | S parameter of EIP-712 permit signature | ## View Methods ### getWETHAddress ```solidity function getWETHAddress() external view returns (address) ``` Get WETH address used by WrappedTokenGatewayV3. **Return Values:** | Type | Description | | :-------- | :--------------------------------------------- | | `address` | The WETH address used by WrappedTokenGatewayV3 | --- Source: https://aave.com/docs/aave-v3/smart-contracts/swap-features.md # Aave V3 Swap Contracts The [Aave Labs interface](https://app.aave.com) offers several swap-based features, detailed below. ## Swap Tokens The _Swap Tokens_ feature enables users to swap between tokens using [ParaSwap](https://app.paraswap.io) or [CoW Protocol](https://swap.cow.fi/) as the swap provider, depending on network availability. Tokens traded using CoW Protocol will incur a fee depending on the token pair and swap type: - **Debt Swap**: 0 bps fee across all pairs. - **All other swap operations**: a discounted fee of 15 bps is applied to swaps between correlated assets (e.g. ETH/wstETH); for all other swaps a fee of 25 bps 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** | | | | | | | **Sonic** | | | | | | | **Metis** | | | | | | | **Scroll** | | | | | | | **ZKsync** | | | | | | | **Celo** | | | | | | | **Soneium** | | | | | | | **Linea** | | | | | | | **Plasma** | | | | | | | **Ink** | | | | | | ## 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. Uses flash loans and ParaSwap to repay debt with collateral in one transaction. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/v3.6.0/src/contracts/extensions/paraswap-adapters/ParaSwapRepayAdapter.sol). Reference Integration: [useCollateralRepaySwap.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useCollateralRepaySwap.tsx) ### executeOperation ```solidity 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. Must be 2 (variable). - `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 ```solidity 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. Must be 2 (variable). | | **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 ```solidity 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/v3.6.0/src/contracts/extensions/paraswap-adapters/ParaSwapLiquiditySwapAdapter.sol). Reference Integration: [useCollateralSwap.tsx](https://github.com/aave/interface/blob/main/src/hooks/paraswap/useCollateralSwap.tsx) ### executeOperation ```solidity 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 ```solidity 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 | ## Debt 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/aave/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/aave/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. #### executeOperation ```solidity function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata, address initiator, bytes calldata params ) external returns (bool) ``` 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 `FlashParams` struct: - `address debtAsset`: the borrow position asset to repay - `uint256 debtRepayAmount`: the amount of debt to repay - `uint256 debtRateMode`: the rate mode of the debt to repay - `address nestedFlashloanDebtAsset`: the new debt asset when extra collateral is flashed, otherwise the zero address - `uint256 nestedFlashloanDebtAmount`: the new debt amount for the nested flash loan - `bytes paraswapData`: ParaSwap swap data - `uint256 offset`: offset in the ParaSwap calldata if swapping all balance - `address user`: the user whose debt is swapped **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. #### onFlashLoan ```solidity 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. Withdraws and swaps in one transaction. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/v3.6.0/src/contracts/extensions/paraswap-adapters/ParaSwapWithdrawSwapAdapter.sol). Reference Integration: [WithdrawAndSwitchActions.tsx](https://github.com/aave/interface/blob/main/src/components/transactions/Withdraw/WithdrawAndSwitchActions.tsx) `executeOperation` reverts with `NOT_SUPPORTED`. ### withdrawAndSwap ```solidity 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 | --- Source: https://aave.com/docs/aave-v3/smart-contracts/vaults.md # Aave V3 ATokenVault Contract 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 [GitHub](https://github.com/aave/aave-vault). ## Write Methods ### initialize ```solidity 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 (`1e18` = 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 (`1e18` = 100%). | ### withdrawFees ```solidity 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 ```solidity function claimRewards(address to) public override onlyOwner ``` Claims any pending rewards accumulated by the vault and sends them to the specified `to` address. 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 ```solidity 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 ```solidity 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 | | :------- | :-------- | :---------- | | **receiver** | `address` | Unused | **Return Values:** | Type | Description | | :-------- | :------------------------------------------------------------- | | `uint256` | The maximum amount of underlying assets that can be deposited. | ### maxMint ```solidity 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 | | :------- | :-------- | :---------- | | **receiver** | `address` | Unused | **Return Values:** | Type | Description | | :-------- | :----------------------------------------------------- | | `uint256` | The maximum amount of vault shares that can be minted. | ### maxWithdraw ```solidity 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 ```solidity 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 ```solidity 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 `assets` deposit. **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 ```solidity 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 ```solidity 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 `assets` withdrawal. **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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 (`1e18` = 100%). | --- Source: https://aave.com/docs/aave-v3/smart-contracts/view-contracts.md # Aave V3 View Contracts The Aave Protocol 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 [Aave Interface](https://github.com/aave/interface/) to display Markets and Dashboard data. To fetch the same reserve and user data already formatted for frontends, use [AaveKit](/aave-v3/markets/data). The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/UiPoolDataProviderV3.sol). ### getReservesList ```solidity function getReservesList(IPoolAddressesProvider provider) public view override returns (address[] memory) ``` Returns the list of initialized reserves in the Pool associated with the given [`provider`](./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 initialized reserves in the Pool | ### getReservesData ```solidity function getReservesData(IPoolAddressesProvider provider) public view override returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory) ``` Returns `BaseCurrencyInfo` of the Pool and `AggregatedReserveData[]` for all the initialized reserves in the Pool associated with the given [`provider`](./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` | Unit of the base currency (e.g. 1e8) | | **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 reserve | | **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 | | **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 the asset in the base currency | | **priceOracle** | `address` | The address of the price oracle used by the associated market | | **variableRateSlope1** | `uint256` | Slope below the optimal usage ratio, in ray | | **variableRateSlope2** | `uint256` | Slope above the optimal usage ratio, in ray | | **baseVariableBorrowRate** | `uint256` | The base variable borrow rate, expressed in ray | | **optimalUsageRatio** | `uint256` | The optimal usage ratio | | **isPaused** | `bool` | `true` if the reserve is paused, `false` otherwise | | **isSiloedBorrowing** | `bool` | Deprecated, always `false` since Aave V3.7 | | **accruedToTreasury** | `uint128` | The amount of tokens accrued to treasury that is to be minted | | **isolationModeTotalDebt** | `uint128` | Deprecated, always `0` since Aave V3.7 | | **flashLoanEnabled** | `bool` | `true` if asset is available to borrow in flash loan transaction | | **debtCeiling** | `uint256` | Deprecated, always `0` since Aave V3.7 | | **debtCeilingDecimals** | `uint256` | Deprecated, always `0` since Aave V3.7 | | **borrowCap** | `uint256` | The borrow cap of the reserve | | **supplyCap** | `uint256` | The supply cap of the reserve | | **borrowableInIsolation** | `bool` | Deprecated, always `false` since Aave V3.7 | | **virtualUnderlyingBalance** | `uint128` | Balance of reserve if virtual accounting is used | | **deficit** | `uint128` | The current deficit of the reserve | ### getUserReservesData ```solidity 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`](./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 | | :------------------ | :--------------------------------- | | `UserReserveData[]` | The user reserve data | | `uint8` | The user’s E-Mode category id | 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 \* variable borrow index) | ### getEModes Returns an array of all available E-Mode categories in the Pool associated with the [provider](./pool-addresses-provider). ```solidity function getEModes(IPoolAddressesProvider provider) external view returns (Emode[] memory) ``` **Input Parameters:** | Name | Type | Description | | :------- | :--------------------- | :------------------------------------------------------------------------------ | | **provider** | `IPoolAddressesProvider` | The PoolAddressesProvider for the associated Pool to fetch E-Mode categories for | **Return Values:** | 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 | | **isolated** | `bool` | `true` if only the category’s collateral contributes LTV (Aave V3.7) | | **label** | `string` | The label describing the E-Mode category | | **borrowableBitmap** | `uint128` | Bitmap representing borrowable assets for this E-Mode | | **ltvzeroBitmap** | `uint128` | Bitmap of assets treated as LTV 0 in this E-Mode | ## WalletBalanceProvider Fetches tokens balances for all underlying tokens of Aave reserves for one user address. > [!NOTE] > An accessory contract outside the Aave Protocol, used by the Aave backend to > reduce blockchain calls. For getting ETH (native chain token) balance use `MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/WalletBalanceProvider.sol). ### balanceOf ```solidity 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 ```solidity 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[]` | Balances of every token for every user, at index `userIndex * tokens.length + tokenIndex` | ### getUserWalletBalances ```solidity 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[]` | The reserve token addresses, followed by `MOCK_ETH_ADDRESS` | | `uint256[]` | The user’s balance of each token, in the same order | ## UiIncentiveDataProviderV3 Contract that returns an array of all reserve incentives or user claimable rewards within a particular market, used by the [Aave Labs Interface](https://github.com/aave/interface/) to display incentives data. To fetch incentives and claimable rewards already formatted for frontends, use [AaveKit](/aave-v3/markets/incentives). The source code is available on [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/UiIncentiveDataProviderV3.sol). ### getFullReservesIncentiveData ```solidity 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`](./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 Aave Pool i.e. rewards for aToken holders | | **vIncentiveData** | `IncentiveData` | Details of rewards distributed for variable debt borrowed from Aave 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 Aave Pool i.e. rewards for aToken | | **vTokenIncentivesUserData** | `UserIncentiveData` | Details of user rewards received for borrowing at variable rate from Aave Pool i.e. rewards for vToken | ### getReservesIncentivesData ```solidity function getReservesIncentivesData(IPoolAddressesProvider provider) external view override returns (AggregatedReserveIncentiveData[] memory) ``` Returns `AggregatedReserveIncentiveData[]` for the pool associated with the given [`provider`](./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 Aave Pool i.e. rewards for aToken holders | | **vIncentiveData** | `IncentiveData` | Details of rewards distributed for variable debt borrowed from Aave Pool i.e. rewards for vToken holders | ### getUserReservesIncentivesData ```solidity 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`](./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 | | :--------------------------- | :------------------------------ | | `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 Aave Pool i.e. rewards for aToken | | **vTokenIncentivesUserData** | `UserIncentiveData` | Details of user rewards received for borrowing at variable rate from Aave Pool i.e. rewards for vToken | ## AaveProtocolDataProvider The `AaveProtocolDataProvider` is a peripheral contract to collect and pre-process information from the [`Pool`](./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 [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/AaveProtocolDataProvider.sol). ### getAllReservesTokens ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity function getPaused(address asset) external view returns (bool isPaused) ``` Returns `true` if the reserve is paused. **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 reserve is paused, `false` otherwise | ### getSiloedBorrowing ```solidity function getSiloedBorrowing(address asset) external view override returns (bool) ``` > [!WARNING] > Deprecated in Aave V3.7, which removed Siloed Borrowing. Always returns `false`. Returns the siloed borrowing flag. It returns true if the `asset` is [siloed for borrowing](/aave-v3/overview#siloed-borrowing). **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 ```solidity 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 ```solidity function getUnbackedMintCap(address asset) external view override returns (uint256) ``` > [!WARNING] > Deprecated in Aave V3.4. Always returns `0`. 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 ```solidity function getDebtCeiling(address asset) external view override returns (uint256) ``` > [!WARNING] > Deprecated in Aave V3.7, which removed Isolation Mode. Always returns `0`. 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 ```solidity 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 Returns the current deficit of the reserve. ```solidity 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 | ### getDebtCeilingDecimals ```solidity function getDebtCeilingDecimals() external pure override returns (uint256) ``` > [!WARNING] > Deprecated in Aave V3.7. Always returns `2`. 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 [GitHub](https://github.com/aave-dao/aave-v3-origin/blob/main/src/contracts/helpers/LiquidationDataProvider.sol). ### getUserPositionFullInfo ```solidity function 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 ```solidity function 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 ```solidity function 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) ```solidity function 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) ```solidity function 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 | --- Source: https://aave.com/docs/aave-v3/aptos.md # Aave V3 on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). This is the official Aptos version of the Aave V3 Protocol. Access the [Aave Protocol on Aptos](https://aptos.aave.com/). The Aptos Move codebase represents a faithful implementation of the Aave V3.3 protocol on the Aptos blockchain using the Move language. While maintaining the core financial logic and security properties of the original Solidity implementation, this port leverages Aptos’s unique architectural features to enhance performance, security, and composability. ## High-Level Summary - **Modular Design:** Organized into specialized modules with `friend` functions enforcing controlled inter-module access (no inheritance). - **Resource-Oriented Programming:** Assets are linear resources that cannot be copied or implicitly discarded, only moved, which prevents accidental loss and double-spending. - **Ability-Based Types:** Types declare abilities (`copy`, `drop`, `store`, `key`) that control how values can be used. - **Native Token Support:** Integrates Aptos’s native fungible asset standard. - **Reduced Reentrancy Risk:** Move has no fallback functions and restricts module cycles, which reduces reentrancy risk. - **Safety & Verification:** Strong type enforcement and the Move Prover allow formal verification of protocol correctness against specifications written alongside the code. - **Predictable Gas:** Static dispatch and a simpler VM make execution costs more deterministic. ## Core Features - **Full Liquidity Protocol Implementation:** Complete supply and borrow functionality, including variable interest rates, liquidations, collateral management, and risk parameters. - **E-Mode:** Efficiency mode for correlated assets that allows higher borrowing power. - **Isolation Mode:** Risk containment for new assets with customizable debt ceilings. - **Fungible Asset Integration:** Native support for Aptos’s fungible asset standard, Aptos’s version of ERC-20. - **Price Oracles:** Integration with external price feeds for accurate asset valuations. - **Flexible Interest Rate Strategy:** Adaptable interest rate models based on utilization. ## Aptos Move Implementation Approach The implementation adapts the Solidity logic to Move’s paradigms: - **Resource-Oriented Design:** Instead of Solidity contracts, the implementation uses Move’s resource model to store protocol state. - **Object-Centric Architecture:** Leverages Aptos’s object model for reserve data and token management, providing stronger ownership guarantees. - **Resource Groups:** Utilizes resource groups to organize related data structures efficiently. ## Key Architectural Differences - **Module Structure:** - Functionality is divided into specialized modules (`pool_logic`, `generic_logic`, `liquidation_logic`, etc.) rather than monolithic contracts. - `friend` functions provide controlled access between modules for specific functions, enabling a permission-based composition model. - Move has no inheritance, forcing explicit composition patterns instead of the hierarchical inheritance common in Solidity. - **Token Implementation:** - Uses Aptos’s Fungible Asset standard instead of ERC-20. - Implements a `token_base` module that abstracts common token functionality. - Provides a `coin_migrator` to bridge between Aptos Coin and Fungible Asset standards. - **State Management:** - Leverages Move’s ability to pass references to resources, enabling more efficient state updates. - Uses `SmartTable` for mapping-like storage with better gas efficiency. - **Type Safety:** - Takes advantage of Move’s strong type system to prevent runtime errors common in Solidity. - Uses generics where appropriate to enhance code reusability. - **Object References:** - Reserve data is stored as objects with explicit access controls, improving security. - Capabilities are used to control privileged operations instead of address-based access control. ## Notable Implementation Details - **Precise Math:** Implements ray math (27 decimal places) and wad math (18 decimal places) for high-precision financial calculations. - **Interest Rate Accrual:** Uses the same compound interest model with liquidity and borrow indices for efficient interest tracking. - **Configuration Data:** Uses dedicated resource structures for storing protocol configuration. - **Event Emission:** Maps Solidity events to Move events for protocol monitoring and analytics. The protocol keeps the economic and security properties of the Solidity implementation while embracing the strengths of the Aptos blockchain and Move language, providing a robust and efficient DeFi liquidity protocol for the Aptos ecosystem. --- ## Next Steps --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts.md # Aave V3 Smart Contracts on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Aave V3.3 on Aptos is architected using a modular design that leverages Move’s strengths. Each module encapsulates distinct functionality (from access control and configuration to data management and token operations), enabling isolated updates, robust permissioning, and scalable, secure protocol logic. > [!NOTE] > Differences from EVM Solidity: > - **Credit Delegation:** not supported, since the Aptos Fungible Asset standard has no `approve`. > - **aToken Balances:** read them with `a_token_factory::balance_of(owner, metadata_address)`, not the wallet fungible asset balance. Transfer aTokens only through the Aave modules. ## Modules ### [@aave-pool](/aave-v3/aptos/smart-contracts/pool) Main pool implementation that coordinates reserve management and user interactions. Includes configurator modules for protocol admins to adjust parameters and data providers for external queries. ### [@aave-acl](/aave-v3/aptos/smart-contracts/acl-manager) Access Control List Manager that serves as the main registry of system roles and permissions. Implements role-based access control for various admin functions across the Aave protocol. ### @aave-config Configuration module that defines error codes and implements bitmap logic for reserve and user configurations. Provides utilities for managing protocol parameters like LTV ratios, liquidation thresholds, and borrowing limits. ### [@aave-oracle](/aave-v3/aptos/smart-contracts/oracles) Price oracle implementation that fetches and validates asset prices for the Aave protocol. Includes price cap adapters for stablecoins and sentinel functionality to handle oracle outages. ### [@aave-tokens](/aave-v3/aptos/smart-contracts/tokenization) Token factory modules for creating and managing aTokens and variable debt tokens. Handles token minting, burning, and transfer operations with proper scaling based on interest accrual. ### @aave-data Data storage module that maintains protocol configuration values and token naming conventions. Stores interest rate strategies, E-Mode configurations, and other protocol parameters for both mainnet and testnet. ### [@aave-logic](/aave-v3/aptos/smart-contracts/aave-logic) Core business logic modules implementing liquidity pool operations like borrowing, supplying, and liquidations. Contains specialized logic for features like flash loans, E-Mode, and isolation mode. ### [@aave-periphery](/aave-v3/aptos/smart-contracts/incentives) Auxiliary modules that extend core functionality with features like rewards, emissions, and UI data providers. The collector module for protocol fees, coin migration utilities and the UI pool data provider are on the [Periphery](/aave-v3/aptos/smart-contracts/periphery) page. --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/pool.md # Aave V3 Pool on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `aave-pool` Move package. ## Overview The `pool` module maintains the state of reserves, user configurations, and protocol-wide settings. It doesn’t directly expose public entry functions for users to interact with. Instead, it provides view functions and friend-accessible functions that other modules use to implement protocol features like supplying, borrowing, repaying, and liquidations. ## Key View Functions ### pool::get_reserve_data ```move #[view] public fun get_reserve_data(asset: address): Object ``` Returns the state and configuration of a specific reserve. This includes information such as liquidity index, borrow rates, token addresses, and other reserve-specific parameters. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | ### get_user_configuration ```move #[view] public fun get_user_configuration(user: address): UserConfigurationMap ``` Returns the configuration of a user across all reserves, indicating which assets they are using as collateral and which they have borrowed. **Input Parameters:** | Name | Type | Description | | ---- | ------- | ---------------- | | **user** | address | The user address | ### get_reserve_normalized_income ```move #[view] public fun get_reserve_normalized_income(asset: address): u256 ``` Returns the ongoing normalized income for the reserve. A value of 1e27 means there is no income. As time passes, the yield is accrued. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | ### get_reserve_normalized_variable_debt ```move #[view] public fun get_reserve_normalized_variable_debt(asset: address): u256 ``` 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. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | ### get_reserve_configuration ```move #[view] public fun get_reserve_configuration(asset: address): &ReserveConfigurationMap ``` Returns the configuration of a reserve, including parameters like `LTV`, `liquidation threshold`, `borrowing enabled flags`, etc. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | ### get_reserves_list ```move #[view] public fun get_reserves_list(): vector
``` Returns the list of the underlying assets of all initialized reserves. ### get_reserve_address_by_id ```move #[view] public fun get_reserve_address_by_id(id: u256): address ``` Returns the address of the reserve corresponding to a given ID. **Input Parameters:** | Name | Type | Description | | ---- | ---- | ------------------------------------------ | | **id** | u256 | The ID of the reserve in the reserves list | ## Protocol Configuration View Functions ```move #[view] public fun get_flashloan_premium_total(): u128 #[view] public fun get_flashloan_premium_to_protocol(): u128 #[view] public fun max_number_reserves(): u16 ``` These functions return various protocol-wide configuration parameters: - The total flashloan premium percentage - The portion of flashloan premium that goes to the protocol - The maximum number of reserves supported by the pool ## Internal State Management While not directly accessible to users, the `pool` module contains friend-accessible functions that other modules use to implement protocol features: - Reserve initialization and configuration - Interest rate updates - Liquidity and debt management - Collateral management - Health factor calculations - E-Mode operations - Isolation mode operations - Flash loan handling ## Key Differences from Solidity Implementation The Move implementation differs from the Solidity version in several ways: 1. **Separation of Concerns**: The Move implementation separates data storage (in the `pool` module) from business logic (in modules like `supply_logic`, `borrow_logic`, etc.) 2. **No Direct User Entry Points**: Users interact with the protocol through other modules that have friend access to the `pool` module 3. **Resource-Oriented Design**: The Move implementation leverages Move’s resource model for safer asset management 4. **Streamlined Interest Rate Strategy**: The interest rate calculation still follows the utilization-based approach where: - Interest rates increase as utilization increases - There are optimal utilization points and slope parameters - But the implementation only needs to track and update variable rate indices 5. **Native Token Integration**: The implementation is designed to work with Aptos’s native token model This architecture provides strong safety guarantees while maintaining the core functionality of the Aave protocol, adapted for the Move language and Aptos blockchain environment. ## Pool Data Provider View Functions The `pool_data_provider` module in Aave’s Move implementation serves as a utility contract to collect and pre-process information from the Pool. This module contains methods for querying token addresses, reserve data, and other protocol information, similar to the AaveProtocolDataProvider in the Solidity implementation. ### get_all_reserves_tokens ```move #[view] public fun get_all_reserves_tokens(): vector ``` Returns a list of the existing reserves in the pool, pairs include the symbols and token addresses. **Return Values:** | Type | Description | | ------------------- | ---------------------------------------------------- | | vector\ | 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 | | **token_address** | address | The address of the underlying reserve asset | ### get_all_a_tokens ```move #[view] public fun get_all_a_tokens(): vector ``` Returns a list of the existing ATokens in the pool, pairs include the symbols and token addresses. **Return Values:** | Type | Description | | ------------------- | --------------------------------------------------- | | vector\ | 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 | | **token_address** | address | The address of aToken of the reserve | ### get_all_var_tokens ```move #[view] public fun get_all_var_tokens(): vector ``` Returns a list of the existing variable debt tokens in the pool, pairs include the symbols and token addresses. **Return Values:** | Type | Description | | ------------------- | -------------------------------------------------------------- | | vector\ | The list of variableDebtTokens, pairs of symbols and addresses | The TokenData struct is composed of the following fields: | Name | Type | Description | | ------------- | ------- | ------------------------------------------------- | | **symbol** | String | The symbol of variable debt token of the reserve | | **token_address** | address | The address of variable debt token of the reserve | ### get_reserve_configuration_data ```move #[view] public fun get_reserve_configuration_data( asset: address ): (u256, u256, u256, u256, u256, bool, bool, bool, bool) ``` Returns the configuration data of the reserve. Not returning borrow and supply caps for compatibility, nor pause flag. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | **Return Values:** | Type | Description | | ---- | ----------------------------------------------------------- | | u256 | The number of decimals of the reserve | | u256 | The ltv of the reserve | | u256 | The liquidation threshold of the reserve | | u256 | The liquidation bonus of the reserve | | u256 | The reserve factor of the reserve | | bool | True if the usage as collateral is enabled, false otherwise | | bool | True if borrowing is enabled, false otherwise | | bool | True if it is active, false otherwise | | bool | True if it is frozen, false otherwise | ### pool_data_provider::get_reserve_data ```move #[view] public fun get_reserve_data( asset: address ): (u256, u256, u256, u256, u256, u256, u256, u64) ``` Returns the state of the reserve. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | **Return Values:** | Type | Description | | ---- | -------------------------------------------------------------------- | | u256 | The scaled amount of tokens accrued to treasury that is to be minted | | u256 | The total supply of the aToken | | u256 | The total variable debt of the reserve | | u256 | The liquidity rate of the reserve | | u256 | The variable borrow rate of the reserve | | u256 | The liquidity index of the reserve | | u256 | The variable borrow index of the reserve | | u64 | The timestamp of the last update of the reserve | ### get_user_reserve_data ```move #[view] public fun get_user_reserve_data( asset: address, user: address ): (u256, u256, u256, u256, bool) ``` Returns the user data in the reserve. **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:** | Type | Description | | ---- | ------------------------------------------------------------- | | u256 | The current aToken balance of the user | | u256 | The current variable debt of the user | | u256 | The scaled variable debt of the user | | u256 | The liquidity rate of the reserve | | bool | True if the user is using the asset as collateral, else false | ### get_reserve_tokens_addresses ```move #[view] public fun get_reserve_tokens_addresses( asset: address ): (address, address) ``` Returns the addresses of the aToken and variableDebtToken of the reserve. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | **Return Values:** | Type | Description | | ------- | -------------------------------------------- | | address | The AToken address of the reserve | | address | The VariableDebtToken address of the reserve | ### get_reserve_caps ```move #[view] public fun get_reserve_caps( asset: address ): (u256, u256) ``` 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:** | Type | Description | | ---- | ----------------------------- | | u256 | The borrow cap of the reserve | | u256 | The supply cap of the reserve | ### get_siloed_borrowing ```move #[view] public fun get_siloed_borrowing( asset: address ): bool ``` Returns the siloed borrowing flag. It returns true if the asset is siloed for borrowing. **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 | ### get_debt_ceiling ```move #[view] public fun get_debt_ceiling( asset: address ): u256 ``` 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 | | ---- | ------------------------------- | | u256 | The debt ceiling of the reserve | ### get_liquidation_protocol_fee ```move #[view] public fun get_liquidation_protocol_fee( asset: address ): u256 ``` 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 | | ---- | ------------------------------- | | u256 | The protocol fee on liquidation | ### get_reserve_emode_category ```move #[view] public fun get_reserve_emode_category(asset: address): u256 ``` Returns the E-Mode category of the reserve. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | **Return Values:** | Type | Description | | ---- | ---------------------- | | u256 | The E-Mode category ID | The borrowable-in-isolation flag has no `pool_data_provider` getter. Read it from the reserve configuration with the `reserve_config` helper: `reserve_config::get_borrowable_in_isolation(&pool::get_reserve_configuration(asset))`. ### get_flash_loan_enabled ```move #[view] public fun get_flash_loan_enabled( asset: address ): bool ``` Returns true if flash loans are enabled for the reserve. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------------- | | **asset** | address | The address of the underlying asset of the reserve | **Return Values:** | Type | Description | | ---- | ------------------------------------------------ | | bool | True if flash loans are enabled, false otherwise | ## E-Mode Logic View Functions Functions from the `emode_logic` module. ### get_user_emode ```move #[view] public fun get_user_emode( user: address ): u8 ``` Returns the eMode the user is using. **Input Parameters:** | Name | Type | Description | | ---- | ------- | ----------------------- | | **user** | address | The address of the user | **Return Values:** | Type | Description | | ---- | ----------------------------------------------------- | | u8 | The eMode ID (0 means the user isn’t using any eMode) | ### get_emode_category_data ```move #[view] public fun get_emode_category_data( id: u8 ): EModeCategory ``` Returns the E-Mode category configuration for the specified category ID. **Input Parameters:** | Name | Type | Description | | ---- | ---- | ---------------------- | | **id** | u8 | The ID of the category | **Return Values:** | Field Name | Type | Description | | --------------------- | ------ | ----------------------------------------- | | **ltv** | u16 | The loan-to-value of the category | | **liquidation_threshold** | u16 | The liquidation threshold of the category | | **liquidation_bonus** | u16 | The liquidation bonus of the category | | **label** | String | The label of the category | ## User Logic View Functions Functions from the `user_logic` module. ### get_user_account_data ```move #[view] public fun get_user_account_data( user: address ): (u256, u256, u256, u256, u256, u256) ``` Returns the user account data across all reserves, including total collateral, total debt, available borrows, liquidation threshold, LTV, and health factor. **Input Parameters:** | Name | Type | Description | | ---- | ------- | ----------------------- | | **user** | address | The address of the user | **Return Values:** | Type | Description | | ---- | ---------------------------------- | | u256 | Total collateral in base currency | | u256 | Total debt in base currency | | u256 | Available borrows in base currency | | u256 | Current liquidation threshold | | u256 | Loan to value ratio | | u256 | Health factor | --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/acl-manager.md # Aave V3 ACL Manager on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `aave-acl` Move package. ## Overview The ACL Manager implements a role-based access control system where different addresses can be assigned specific roles that grant them permissions to perform certain actions within the Aave protocol. Each role has an admin role that controls who can grant or revoke that role. ## Roles The module defines several key roles that align with the Ethereum implementation: - `DEFAULT_ADMIN_ROLE`: The highest-level administrative role. - `POOL_ADMIN_ROLE`: Can update token implementations, manage reserves, and more. - `EMERGENCY_ADMIN_ROLE`: Can pause/unpause the pool or individual reserves. - `RISK_ADMIN_ROLE`: Can update reserve parameters and risk settings. - `FLASH_BORROWER_ROLE`: Has premium on flash loans waived. - `ASSET_LISTING_ADMIN_ROLE`: Can update oracle sources and add new assets. - `FUNDS_ADMIN_ROLE`: Manages funds-related operations. - `EMISSION_ADMIN_ROLE`: Manages emission-related settings. - `ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN_ROLE`: Manages ecosystem reserve funds. - `REWARDS_CONTROLLER_ADMIN_ROLE`: Manages reward controllers. ## Write Methods ### set_role_admin ```move public fun set_role_admin(admin: &signer, role: String, admin_role: String) ``` Sets a new admin role for a specific role. Only addresses with the `DEFAULT_ADMIN_ROLE` can call this function. **Input Parameters:** | Name | Type | Description | | ---------- | ------- | ---------------------------------------- | | **admin** | &signer | The signer with the `DEFAULT_ADMIN_ROLE` | | **role** | String | The role whose admin role is being set | | **admin_role** | String | The new admin role for `role` | ### grant_role ```move public fun grant_role(admin: &signer, role: String, user: address) ``` Grants a role to an address. Can only be called by an address that has the admin role for the role being granted. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ---------------------------------------- | | **admin** | &signer | The signer with the admin role of `role` | | **role** | String | The role to grant | | **user** | address | The address receiving the role | ### renounce_role ```move public entry fun renounce_role(admin: &signer, role: String, user: address) ``` Allows an address to renounce a role it has been granted. The caller must be the same as the address renouncing the role. **Input Parameters:** | Name | Type | Description | | ----- | ------- | -------------------------------------------- | | **admin** | &signer | The signer renouncing the role | | **role** | String | The role to renounce | | **user** | address | The address renouncing the role (the signer) | ### revoke_role ```move public fun revoke_role(admin: &signer, role: String, user: address) ``` Revokes a role from an address. Can only be called by an address that has the admin role for the role being revoked. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ---------------------------------------- | | **admin** | &signer | The signer with the admin role of `role` | | **role** | String | The role to revoke | | **user** | address | The address losing the role | ### Pool Admin Functions ```move public entry fun add_pool_admin(admin: &signer, user: address) public entry fun remove_pool_admin(admin: &signer, user: address) ``` These functions add and remove the `POOL_ADMIN_ROLE`. Pool admins can update token implementations, manage reserves, and perform other high-level administrative actions. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ------------------------------------------------ | | **admin** | &signer | The signer with the admin role of the pool admin | | **user** | address | The address to add or remove as pool admin | ### Emergency Admin Functions ```move public entry fun add_emergency_admin(admin: &signer, user: address) public entry fun remove_emergency_admin(admin: &signer, user: address) ``` These functions manage the `EMERGENCY_ADMIN_ROLE`, which allows addresses to pause and unpause the pool or individual reserves in emergency situations. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ----------------------------------------------------- | | **admin** | &signer | The signer with the admin role of the emergency admin | | **user** | address | The address to add or remove as emergency admin | ### Risk Admin Functions ```move public entry fun add_risk_admin(admin: &signer, user: address) public entry fun remove_risk_admin(admin: &signer, user: address) ``` These functions manage the `RISK_ADMIN_ROLE`, which allows addresses to update reserve parameters, grace periods, and other risk-related settings. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ------------------------------------------------ | | **admin** | &signer | The signer with the admin role of the risk admin | | **user** | address | The address to add or remove as risk admin | ### Flash Borrower Functions ```move public entry fun add_flash_borrower(admin: &signer, borrower: address) public entry fun remove_flash_borrower(admin: &signer, borrower: address) ``` These functions manage the `FLASH_BORROWER_ROLE`, which allows addresses to have the premium on flash loans waived. **Input Parameters:** | Name | Type | Description | | -------- | ------- | ---------------------------------------------------- | | **admin** | &signer | The signer with the admin role of the flash borrower | | **borrower** | address | The address to add or remove as flash borrower | ### Asset Listing Admin Functions ```move public entry fun add_asset_listing_admin(admin: &signer, user: address) public entry fun remove_asset_listing_admin(admin: &signer, user: address) ``` These functions manage the `ASSET_LISTING_ADMIN_ROLE`, which allows addresses to update oracle sources and add new assets to the Aave market. **Input Parameters:** | Name | Type | Description | | ----- | ------- | --------------------------------------------------------- | | **admin** | &signer | The signer with the admin role of the asset listing admin | | **user** | address | The address to add or remove as asset listing admin | ### Additional Admin Roles The module also includes functions for managing several other specialized roles: - **Funds Admin:** Manages funds-related operations - **Emission Admin:** Manages emission-related settings - **Admin Controlled Ecosystem Reserve Funds Admin:** Manages ecosystem reserve funds - **Rewards Controller Admin:** Manages reward controllers ## View Methods ### default_admin_role ```move #[view] public fun default_admin_role(): String ``` Returns the identifier for the default admin role, which has the highest level of permissions in the system. **Return Values:** | Type | Description | | ------ | -------------------------------------- | | String | The identifier of `DEFAULT_ADMIN_ROLE` | ### get_role_admin ```move #[view] public fun get_role_admin(role: String): String ``` Returns the admin role that controls a specific role. By default, all roles are controlled by the `DEFAULT_ADMIN_ROLE`. **Input Parameters:** | Name | Type | Description | | ---- | ------ | ------------------- | | **role** | String | The role to look up | **Return Values:** | Type | Description | | ------ | ------------------------ | | String | The admin role of `role` | ### has_role ```move #[view] public fun has_role(role: String, user: address): bool ``` Checks if an address has a specific role. **Input Parameters:** | Name | Type | Description | | ---- | ------- | -------------------- | | **role** | String | The role to check | | **user** | address | The address to check | **Return Values:** | Type | Description | | ---- | --------------------------- | | bool | `true` if `user` has `role` | ### Role Checks ```move #[view] public fun is_pool_admin(admin: address): bool #[view] public fun is_emergency_admin(admin: address): bool #[view] public fun is_risk_admin(admin: address): bool #[view] public fun is_flash_borrower(borrower: address): bool #[view] public fun is_asset_listing_admin(admin: address): bool ``` These functions check whether an address has the matching role. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------- | | **admin / borrower** | address | The address to check | **Return Values:** | Type | Description | | ---- | ---------------------------------- | | bool | `true` if the address has the role | ### Role Identifier Getters ```move #[view] public fun get_pool_admin_role(): String #[view] public fun get_emergency_admin_role(): String #[view] public fun get_risk_admin_role(): String #[view] public fun get_flash_borrower_role(): String #[view] public fun get_asset_listing_admin_role(): String #[view] public fun get_funds_admin_role(): String #[view] public fun get_emission_admin_role(): String #[view] public fun get_admin_controlled_ecosystem_reserve_funds_admin_role(): String #[view] public fun get_rewards_controller_admin_role(): String ``` These functions return the standardized string identifier for each role, for use when interacting with the ACL Manager. **Return Values:** | Type | Description | | ------ | -------------------------- | | String | The identifier of the role | ## Events The module emits events for key role management actions: - `RoleAdminChanged`: Emitted when a role’s admin role is changed. - `RoleGranted`: Emitted when a role is granted to an address. - `RoleRevoked`: Emitted when a role is revoked from an address. These events allow for tracking changes to the access control system over time. --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/pool-configurator.md # Aave V3 Pool Configurator on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `pool_configurator` module in the `aave-pool` package. The asset listing and risk parameter methods. ## Asset Listing or Pool Admin Methods ### init_reserves ```move public entry fun init_reserves( account: &signer, underlying_asset: vector
, treasury: vector
, a_token_name: vector, a_token_symbol: vector, variable_debt_token_name: vector, variable_debt_token_symbol: vector, incentives_controller: vector>, optimal_usage_ratio: vector, base_variable_borrow_rate: vector, variable_rate_slope1: vector, variable_rate_slope2: vector ) ``` Initializes multiple reserves using the arrays of initialization parameters as input. Only callable by accounts with the Asset Listing Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | -------------------------- | --------------------------- | ------------------------------------------------------------------------------------ | | **account** | &signer | The signer account of the caller | | **underlying_asset** | vector\ | The addresses of the underlying assets | | **treasury** | vector\ | The treasury addresses | | **a_token_name** | vector\ | The names of the aTokens | | **a_token_symbol** | vector\ | The symbols of the aTokens | | **variable_debt_token_name** | vector\ | The names of the variable debt tokens | | **variable_debt_token_symbol** | vector\ | The symbols of the variable debt tokens | | **incentives_controller** | vector\\> | The incentives controllers of the reserves | | **optimal_usage_ratio** | vector\ | The optimal usage ratios, in bps | | **base_variable_borrow_rate** | vector\ | The base variable borrow rates, in bps | | **variable_rate_slope1** | vector\ | The slopes of the variable interest curve before hitting the optimal ratio, in bps | | **variable_rate_slope2** | vector\ | The slopes of the variable interest curve after hitting the optimal ratio, in bps | ## Emergency or Pool Admin Methods ### set_pool_pause ```move public entry fun set_pool_pause( account: &signer, paused: bool, grace_period: u64 ) ``` Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions are suspended. Only callable by accounts with the Emergency Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------ | | **account** | &signer | The signer account of the caller | | **paused** | bool | true if the protocol needs to be paused, otherwise false | | **grace_period** | u64 | Count of seconds after unpause during which liquidations will not be available | ### set_reserve_pause ```move public entry fun set_reserve_pause( account: &signer, asset: address, paused: bool, grace_period: u64 ) ``` Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, liquidate, aToken transfers). Only callable by accounts with the Emergency Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------ | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **paused** | bool | true if pausing the reserve, false if unpausing the reserve | | **grace_period** | u64 | Count of seconds after unpause during which liquidations will not be available | ### disable_liquidation_grace_period ```move public entry fun disable_liquidation_grace_period( account: &signer, asset: address ) ``` Disables the liquidation grace period for a reserve. Only callable by accounts with the Emergency Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | -------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | Address of the reserve asset | ## Pool Admin Methods ### drop_reserve ```move public entry fun drop_reserve( account: &signer, asset: address ) ``` Drops a reserve entirely. Only callable by accounts with the Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ---------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the reserve to drop | ### set_reserve_active ```move public entry fun set_reserve_active( account: &signer, asset: address, active: bool ) ``` Activate or deactivate a reserve. Only callable by accounts with the Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **active** | bool | true if the reserve needs to be active, false otherwise | ### update_flashloan_premium_total ```move public entry fun update_flashloan_premium_total( account: &signer, new_flashloan_premium_total: u128 ) ``` Updates the total flash loan premium. The premium is calculated on the total amount borrowed, and is expressed in bps. Only callable by accounts with the Pool Admin role. **Input Parameters:** | Name | Type | Description | | --------------------------- | ------- | -------------------------------- | | **account** | &signer | The signer account of the caller | | **new_flashloan_premium_total** | u128 | The total flashloan premium | ### update_flashloan_premium_to_protocol ```move public entry fun update_flashloan_premium_to_protocol( account: &signer, new_flashloan_premium_to_protocol: u128 ) ``` 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. Only callable by accounts with the Pool Admin role. **Input Parameters:** | Name | Type | Description | | --------------------------------- | ------- | --------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **new_flashloan_premium_to_protocol** | u128 | The part of the flashloan premium sent to the protocol treasury | ## Risk or Pool Admin Methods ### set_reserve_borrowing ```move public entry fun set_reserve_borrowing( account: &signer, asset: address, enabled: bool ) ``` Enables or disables borrowing on a reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ------------------------------------------------------ | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **enabled** | bool | true if borrowing needs to be enabled, false otherwise | ### set_reserve_flash_loaning ```move public entry fun set_reserve_flash_loaning( account: &signer, asset: address, enabled: bool ) ``` Enables or disables flash loans for a reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | -------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | Address of the reserve asset | | **enabled** | bool | true to enable, false to disable | ### configure_reserve_as_collateral ```move public entry fun configure_reserve_as_collateral( account: &signer, asset: address, ltv: u256, liquidation_threshold: u256, liquidation_bonus: u256 ) ``` Configures the reserve collateralization parameters. All the values are expressed in bps. A value of 10000 results in 100.00%. The liquidation_bonus is always above 100%. A value of 10500 means the liquidator will receive a 5% bonus. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | --------------------- | ------- | -------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **ltv** | u256 | The loan to value of the asset when used as collateral | | **liquidation_threshold** | u256 | The threshold at which loans using this asset as collateral will be considered undercollateralized | | **liquidation_bonus** | u256 | The bonus liquidators receive to liquidate this asset | ### set_reserve_freeze ```move public entry fun set_reserve_freeze( account: &signer, asset: address, freeze: bool ) ``` Freeze or unfreeze a reserve. A frozen reserve doesn’t allow any new supply or borrow but allows repayments, liquidations and withdrawals. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **freeze** | bool | true if the reserve needs to be frozen, false otherwise | ### set_borrowable_in_isolation ```move public entry fun set_borrowable_in_isolation( account: &signer, asset: address, borrowable: bool ) ``` 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 callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ---------- | ------- | -------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **borrowable** | bool | true if the asset should be borrowable in isolation, false otherwise | ### set_reserve_factor ```move public entry fun set_reserve_factor( account: &signer, asset: address, new_reserve_factor: u256 ) ``` Updates the reserve factor of a reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------------------ | ------- | -------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_reserve_factor** | u256 | The new reserve factor of the reserve | ### set_debt_ceiling ```move public entry fun set_debt_ceiling( account: &signer, asset: address, new_debt_ceiling: u256 ) ``` Sets the debt ceiling for an asset. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_debt_ceiling** | u256 | The new debt ceiling | ### set_siloed_borrowing ```move public entry fun set_siloed_borrowing( account: &signer, asset: address, new_siloed: bool ) ``` Sets siloed borrowing for an asset. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ---------- | ------- | ----------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_siloed** | bool | The new siloed borrowing state - enable or disable siloed borrowing for the reserve | ### set_borrow_cap ```move public entry fun set_borrow_cap( account: &signer, asset: address, new_borrow_cap: u256 ) ``` Updates the borrow cap of a reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | -------------- | ------- | --------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_borrow_cap** | u256 | The new borrow cap of the reserve in whole tokens. A borrow cap of 0 signifies that there is no cap | ### set_supply_cap ```move public entry fun set_supply_cap( account: &signer, asset: address, new_supply_cap: u256 ) ``` Updates the supply cap of a reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | -------------- | ------- | --------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_supply_cap** | u256 | The new supply cap of the reserve in whole tokens. A supply cap of 0 signifies that there is no cap | ### set_liquidation_protocol_fee ```move public entry fun set_liquidation_protocol_fee( account: &signer, asset: address, new_fee: u256 ) ``` Updates the liquidation protocol fee of reserve. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ----------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_fee** | u256 | The new liquidation protocol fee of the reserve, expressed in bps | ### set_emode_category ```move public entry fun set_emode_category( account: &signer, category_id: u8, ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, label: String ) ``` Adds a new efficiency mode (eMode) category. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ | | **account** | &signer | The signer account of the caller | | **category_id** | u8 | The id of the category to be configured. category_id ≠ 0. NOTE: category 0 is reserved for the default category i.e. non-eMode | | **ltv** | u16 | The loan to value for the associated eMode category. It must be less than or equal to the liquidationThreshold | | **liquidation_threshold** | u16 | The liquidation threshold associated with the category | | **liquidation_bonus** | u16 | The liquidation bonus associated with the category | | **label** | String | A custom label identifying the category | ### set_asset_emode_category ```move public entry fun set_asset_emode_category( account: &signer, asset: address, new_category_id: u8 ) ``` Sets the efficiency mode category for an asset. Only callable by accounts with the Risk Admin or Pool Admin role. **Input Parameters:** | Name | Type | Description | | --------------- | ------- | -------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset of the reserve | | **new_category_id** | u8 | The new eMode category for the asset | --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/oracles.md # Aave V3 Oracles on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `aave-oracle` Move package. ## Overview The Aave Oracle is a contract that manages asset prices and price sources for the Aave Protocol on Aptos. It allows authorized administrators to set, update, and remove price feeds for assets, and provides functions to query asset prices. ## Write Methods ### set_asset_feed_id ```move public entry fun set_asset_feed_id(account: &signer, asset: address, feed_id: vector) ``` Sets the price feed ID for a given asset. This method can only be called by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See the [`acl_manage` module](/aave-v3/aptos/smart-contracts/acl-manager) for system roles. **Input Parameters:** | Name | Type | Description | | ------- | ------------ | ------------------------------------------------ | | **account** | &signer | The signer with admin privileges | | **asset** | address | The address of the asset for which feed is set | | **feed_id** | vector\ | The ID of the Chainlink price feed for the asset | ### batch_set_asset_feed_ids ```move public entry fun batch_set_asset_feed_ids(account: &signer, assets: vector
, feed_ids: vector>) ``` Sets the price feed IDs for multiple assets in a single transaction. This method can only be called by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See the [`acl_manage` module](/aave-v3/aptos/smart-contracts/acl-manager) for system roles. **Input Parameters:** | Name | Type | Description | | -------- | ---------------------- | ---------------------------------------------------------------------------------------- | | **account** | &signer | The signer with admin privileges | | **assets** | vector\ | The addresses of the assets for which feeds are being set | | **feed_ids** | vector\\> | The IDs of the Chainlink price feeds for each asset. Length must match the assets vector | ### remove_asset_feed_id ```move public entry fun remove_asset_feed_id(account: &signer, asset: address) ``` Removes the price feed for a given asset. This method can only be called by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See the [`acl_manage` module](/aave-v3/aptos/smart-contracts/acl-manager) for system roles. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ----------------------------------------------- | | **account** | &signer | The signer with admin privileges | | **asset** | address | The address of the asset to remove the feed for | ### batch_remove_asset_feed_ids ```move public entry fun batch_remove_asset_feed_ids(account: &signer, assets: vector
) ``` Removes the price feeds for multiple assets in a single transaction. This method can only be called by a `POOL_ADMIN` or `ASSET_LISTING_ADMIN`. See the [`acl_manage` module](/aave-v3/aptos/smart-contracts/acl-manager) for system roles. **Input Parameters:** | Name | Type | Description | | ------- | ----------------- | ----------------------------------------------- | | **account** | &signer | The signer with admin privileges | | **assets** | vector\ | The addresses of the assets to remove feeds for | ## View Methods Prices are in the market base currency with 18 decimals (see `get_asset_price_decimals`). ### get_asset_price ```move #[view] public fun get_asset_price(asset: address): u256 ``` Returns the price of the supported asset in BASE_CURRENCY of the Aave Market. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ------------------------ | | **asset** | address | The address of the asset | **Return Values:** | Type | Description | | ---- | ---------------------------------------------------------- | | u256 | The price of the asset in BASE_CURRENCY of the Aave market | ### get_assets_prices ```move #[view] public fun get_assets_prices(assets: vector
): vector ``` Returns a list of prices from a list of the supported assets addresses in BASE_CURRENCY of the Aave Market. **Input Parameters:** | Name | Type | Description | | ------ | ----------------- | ------------------------------------------------------------- | | **assets** | vector\ | The list of assets addresses for which price is being queried | **Return Values:** | Type | Description | | -------------- | ------------------------------------------------------------------ | | vector\ | The prices of the given assets in BASE_CURRENCY of the Aave market | ### get_asset_price_decimals ```move #[view] public fun get_asset_price_decimals(): u8 ``` Returns the number of decimals used for asset prices. **Return Values:** | Type | Description | | ---- | -------------------------------------------- | | u8 | The number of decimals for asset prices (18) | ### oracle_address ```move #[view] public fun oracle_address(): address ``` Returns the address of the oracle resource account. **Return Values:** | Type | Description | | ------- | --------------------------------- | | address | The address of the oracle account | --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/tokenization.md # Aave V3 Tokenization on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `aave-tokens` Move package. This documentation covers the tokenization modules in the Aave protocol implementation on Aptos. Similar to Aave on EVM chains, the Aptos implementation uses specialized tokens to represent user positions in the protocol. ## aToken Factory The `a_token_factory` module manages the creation and operations of aTokens, which represent user supply positions in the Aave protocol. aTokens are interest-bearing tokens that automatically accrue interest to their holders. ### Write Methods #### create_token ```move public(friend) fun create_token( signer: &signer, name: String, symbol: String, decimals: u8, icon_uri: String, project_uri: String, incentives_controller: Option
, underlying_asset: address, treasury: address ): address ``` Creates a new aToken for a specific underlying asset. **Input Parameters:** | Name | Type | Description | | --------------------- | ----------------- | -------------------------------------------------------- | | **signer** | &signer | The signer of the caller | | **name** | String | The name of the aToken | | **symbol** | String | The symbol of the aToken | | **decimals** | u8 | The decimals of the aToken | | **icon_uri** | String | The icon URI of the aToken | | **project_uri** | String | The project URI of the aToken | | **incentives_controller** | Option\ | The address of the incentives controller for this aToken | | **underlying_asset** | address | The address of the underlying asset | | **treasury** | address | The address of the treasury | **Return Values:** | Type | Description | | ------- | --------------------------------- | | address | The address of the created aToken | **Emits:** - `Initialized` event with details about the created aToken #### mint ```move public(friend) fun mint( caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address ): bool ``` Mints aTokens to a user. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------------------------------ | | **caller** | address | The address performing the mint | | **on_behalf_of** | address | The address that will receive the minted aTokens | | **amount** | u256 | The amount of tokens getting minted | | **index** | u256 | The next liquidity index of the reserve | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | ---------------------------------------------- | | bool | true if the previous balance of the user was 0 | #### burn ```move public(friend) fun burn( from: address, receiver_of_underlying: address, amount: u256, index: u256, metadata_address: address ) ``` Burns aTokens from a user and sends the equivalent amount of underlying to the receiver. In some instances, a 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 | | **receiver_of_underlying** | address | The address that will receive the underlying asset | | **amount** | u256 | The amount of tokens that will be burned | | **index** | u256 | The next liquidity index of the reserve | | **metadata_address** | address | The address of the aToken | #### mint_to_treasury ```move public(friend) fun mint_to_treasury( amount: u256, index: u256, metadata_address: address ) ``` Mints aTokens to the reserve treasury. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | --------------------------------------- | | **amount** | u256 | The amount of tokens getting minted | | **index** | u256 | The next liquidity index of the reserve | | **metadata_address** | address | The address of the aToken | #### transfer_on_liquidation ```move public(friend) fun transfer_on_liquidation( from: address, to: address, amount: u256, index: u256, metadata_address: address ) ``` 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 | | **amount** | u256 | The amount of tokens getting transferred | | **index** | u256 | The next liquidity index of the reserve | | **metadata_address** | address | The address of the aToken | **Emits:** - Balance transfer event with the scaled amount and index #### handle_repayment ```move public fun handle_repayment( _user: address, _on_behalf_of: address, _amount: u256, _metadata_address: address ) ``` Handles the underlying received by the aToken after the transfer has been completed. The default implementation is empty as with standard 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, `handle_repayment()` would perform the staking of the underlying asset. **Input Parameters:** | Name | Type | Description | | ------------------ | ------- | --------------------------------------------------- | | **\_user** | address | The user executing the repayment | | **\_on_behalf_of** | address | The address for which the borrow position is repaid | | **\_amount** | u256 | The amount getting repaid | | **\_metadata_address** | address | The address of the aToken | #### drop_token ```move public(friend) fun drop_token(metadata_address: address) ``` Drops the aToken associated data. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ---------------------------------- | | **metadata_address** | address | The address of the metadata object | ### View Methods #### get_underlying_asset_address ```move public fun get_underlying_asset_address( metadata_address: address ): address ``` Returns the address of the underlying asset of this aToken. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ------- | ----------------------------------- | | address | The address of the underlying asset | #### get_previous_index ```move public fun get_previous_index( user: address, metadata_address: address ): u256 ``` Returns the last index interest was accrued to the user’s balance. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **user** | address | The address of the user | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | --------------------------------------------------------------------------- | | u256 | The last index interest was accrued to the user’s balance, expressed in ray | #### get_scaled_user_balance_and_supply ```move public fun get_scaled_user_balance_and_supply( owner: address, metadata_address: address ): (u256, u256) ``` Returns the scaled balance of the user and the scaled total supply. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **owner** | address | The address of the user | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | ------------------------------ | | u256 | The scaled balance of the user | | u256 | The scaled total supply | #### scaled_balance_of ```move public fun scaled_balance_of( owner: address, metadata_address: address ): u256 ``` Returns the scaled balance of the user. The scaled balance is the sum of all the updated stored balance divided by the reserve’s liquidity index at the moment of the update. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **owner** | address | The address of the user | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | ------------------------------ | | u256 | The scaled balance of the user | #### scaled_total_supply ```move public fun scaled_total_supply( metadata_address: address ): u256 ``` Returns the scaled total supply of the aToken. The scaled total supply is the sum of all scaled balances of the users. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | ----------------------- | | u256 | The scaled total supply | #### decimals ```move public fun decimals(metadata_address: address): u8 ``` Returns the decimals of the aToken. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ------------------------- | | **metadata_address** | address | The address of the aToken | **Return Values:** | Type | Description | | ---- | -------------------------- | | u8 | The decimals of the aToken | ## Variable Debt Token Factory The `variable_debt_token_factory` module manages the creation and operations of variable debt tokens in the Aave protocol on Aptos. Variable debt tokens represent user borrowing positions with a variable interest rate. ### Write Methods #### create_token ```move public(friend) fun create_token( signer: &signer, name: String, symbol: String, decimals: u8, icon_uri: String, project_uri: String, incentives_controller: Option
, underlying_asset: address ): address ``` Creates a new variable debt token for a specific underlying asset. **Input Parameters:** | Name | Type | Description | | --------------------- | ----------------- | ------------------------------------------------------------ | | **signer** | &signer | The signer of the caller | | **name** | String | The name of the variable debt token | | **symbol** | String | The symbol of the variable debt token | | **decimals** | u8 | The decimals of the variable debt token | | **icon_uri** | String | The icon URI of the variable debt token | | **project_uri** | String | The project URI of the variable debt token | | **incentives_controller** | Option\ | The address of the incentives controller for this debt token | | **underlying_asset** | address | The address of the underlying asset | **Return Values:** | Type | Description | | ------- | ------------------------------------- | | address | The address of the created debt token | **Emits:** - `Initialized` event with details about the created variable debt token #### mint ```move public(friend) fun mint( caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address ): bool ``` Mints debt tokens to the `on_behalf_of` address. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | | **caller** | address | The address receiving the borrowed underlying (same as on_behalf_of on Aptos) | | **on_behalf_of** | address | The address receiving the debt tokens | | **amount** | u256 | The amount of debt being minted | | **index** | u256 | The variable debt index of the reserve | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | -------------------------------------------------------------------------- | | bool | Whether this is the first time we mint the variable debt token to the user | **Emits:** - `Transfer` event from zero address to recipient - `Mint` event with details about the mint operation #### burn ```move public(friend) fun burn( from: address, amount: u256, index: u256, metadata_address: address ) ``` Burns debt tokens from a user. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ----------------------------------------------------- | | **from** | address | The address from which the debt tokens will be burned | | **amount** | u256 | The amount of debt tokens that will be burned | | **index** | u256 | The variable debt index of the reserve | | **metadata_address** | address | The address of the variable debt token | **Emits:** - `Transfer` event to zero address - `Burn` event with details about the burn operation - If the balance increase is greater than the amount, also emits `Transfer` and `Mint` events #### drop_token ```move public(friend) fun drop_token(metadata_address: address) ``` Drops the variable debt token associated data. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ---------------------------------- | | **metadata_address** | address | The address of the metadata object | ### View Methods #### get_underlying_asset_address ```move public fun get_underlying_asset_address( metadata_address: address ): address ``` Returns the address of the underlying asset of this variable debt token. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ------- | ----------------------------------- | | address | The address of the underlying asset | #### get_previous_index ```move public fun get_previous_index( user: address, metadata_address: address ): u256 ``` Returns the last index interest was accrued to the user’s balance. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **user** | address | The address of the user | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | --------------------------------------------------------------------------- | | u256 | The last index interest was accrued to the user’s balance, expressed in ray | #### get_scaled_user_balance_and_supply ```move public fun get_scaled_user_balance_and_supply( owner: address, metadata_address: address ): (u256, u256) ``` Returns the scaled balance of the user and the scaled total supply. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **owner** | address | The address of the user | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | ------------------------------ | | u256 | The scaled balance of the user | | u256 | The scaled total supply | #### scaled_balance_of ```move public fun scaled_balance_of( owner: address, metadata_address: address ): u256 ``` Returns the scaled balance of the user. The scaled balance is the sum of all the updated stored balance divided by the reserve’s variable debt index at the moment of the update. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **owner** | address | The address of the user | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | ------------------------------ | | u256 | The scaled balance of the user | #### scaled_total_supply ```move public fun scaled_total_supply( metadata_address: address ): u256 ``` Returns the scaled total supply of the variable debt token. The scaled total supply is the sum of all scaled balances of the users with debt. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | ----------------------- | | u256 | The scaled total supply | #### name ```move public fun name(metadata_address: address): String ``` Returns the name of the variable debt token. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ------ | ----------------------------------- | | String | The name of the variable debt token | #### symbol ```move public fun symbol(metadata_address: address): String ``` Returns the symbol of the variable debt token. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ------ | ------------------------------------- | | String | The symbol of the variable debt token | #### decimals ```move public fun decimals(metadata_address: address): u8 ``` Returns the decimals of the variable debt token. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | -------------------------------------- | | **metadata_address** | address | The address of the variable debt token | **Return Values:** | Type | Description | | ---- | --------------------------------------- | | u8 | The decimals of the variable debt token | ### Comparison with Ethereum The variable debt token implementation in Aptos follows similar principles to the Ethereum implementation but is adapted to the Move language and Aptos blockchain architecture: 1. **Object-based Model**: Instead of ERC-20 contracts, Aptos uses an object-based model for fungible assets. 2. **Scaled Balances**: Like in Ethereum, the variable debt tokens use scaled balances to track user debt positions, which automatically accrue interest over time. 3. **Index-based Interest Accrual**: Interest accrual is handled through index-based calculations, similar to the Ethereum implementation. 4. **No Transfers**: Variable debt tokens cannot be transferred between users, as they represent a specific user’s debt position. The variable debt tokens in Aave on Aptos serve the same purpose as in the Ethereum implementation: they represent a user’s variable-rate debt position in the protocol and automatically accrue interest over time based on the variable interest rate of the corresponding reserve. --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/aave-logic.md # Aave V3 Logic Modules on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the `aave-logic` Move package. The supply, borrow, repay and liquidation entry points. ## Supply Functions ### supply ```move public entry fun supply( account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16 ) ``` Supplies a certain amount of an asset into the protocol, minting the same amount of corresponding aTokens and transferring them to the `on_behalf_of` address. For example, if a user supplies 100 USDC and `on_behalf_of` address is the same as the signer’s address, they will get 100 aUSDC in return. The supplied amount is transferred from the signer’s fungible store within the entry function; no separate approval is needed. **Input Parameters:** | Name | Type | Description | | ------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset being supplied to the pool | | **amount** | u256 | The amount of asset to be supplied | | **on_behalf_of** | 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 the signer’s address 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 | | **referral_code** | u16 | Referral codes are currently inactive; pass 0. | ## Borrow Functions ### borrow ```move public entry fun borrow( account: &signer, asset: address, amount: u256, interest_rate_mode: u8, referral_code: u16, on_behalf_of: address ) ``` Allows users to borrow a specific amount of the underlying asset, provided that the borrower already supplied enough collateral. Borrowers can borrow at a variable rate, represented by `interest_rate_mode` value of 2. **Input Parameters:** | Name | Type | Description | | ------------------ | ------- | -------------------------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset to borrow | | **amount** | u256 | The amount to be borrowed | | **interest_rate_mode** | u8 | The interest rate mode at which the user wants to borrow: 2 for Variable | | **referral_code** | u16 | Referral codes are currently inactive; pass 0. | | **on_behalf_of** | address | The address of the user who will receive the debt. Should be the address of the borrower itself calling the function | ## Repay Functions ### repay ```move public entry fun repay( account: &signer, asset: address, amount: u256, interest_rate_mode: u8, on_behalf_of: address ) ``` Repays a borrowed amount on a specific reserve, burning the equivalent debt tokens. For example, if a user repays 100 USDC, 100 variable debt tokens will be burned and the underlying will be transferred from the user to the aToken contract. The amount parameter can be set to math_utils::u256_max() to repay the entire debt. **Input Parameters:** | Name | Type | Description | | ------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the borrowed underlying asset previously borrowed | | **amount** | u256 | The amount to repay. Can be math_utils::u256_max() to repay the whole debt | | **interest_rate_mode** | u8 | The interest rate mode at which the user wants to repay: 2 for Variable | | **on_behalf_of** | address | The address whose debt is reduced. Use the caller’s own address, or another borrower’s address to repay their debt. | ### repay_with_a_tokens ```move public entry fun repay_with_a_tokens( account: &signer, asset: address, amount: u256, interest_rate_mode: u8 ) ``` Repays a borrowed amount on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. For example, if a user repays 100 USDC using aUSDC, 100 variable debt tokens will be burned and 100 aUSDC will be burned. The amount parameter can be set to math_utils::u256_max() to repay the entire debt. **Input Parameters:** | Name | Type | Description | | ------------------ | ------- | -------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the borrowed underlying asset previously borrowed | | **amount** | u256 | The amount to repay. Can be math_utils::u256_max() to repay the whole debt | | **interest_rate_mode** | u8 | The interest rate mode at which the user wants to repay: 2 for Variable | ## Withdraw Functions ### withdraw ```move public entry fun withdraw( account: &signer, asset: address, amount: u256, to: address ) ``` Withdraws an amount of underlying asset from the reserve, burning the equivalent aTokens owned by account. For example, if a user withdraws 100 USDC, 100 aUSDC will be burned and 100 USDC will be transferred to the specified to address. The amount parameter can be set to math_utils::u256_max() to withdraw the entire balance. **Input Parameters:** | Name | Type | Description | | ------- | ------- | ---------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset to withdraw | | **amount** | u256 | The amount to be withdrawn. Can be math_utils::u256_max() to withdraw the entire balance | | **to** | address | The address that will receive the underlying asset | ## Collateral Management Functions ### set_user_use_reserve_as_collateral ```move public entry fun set_user_use_reserve_as_collateral( account: &signer, asset: address, use_as_collateral: bool ) ``` Allows users to enable or disable a specific supplied asset as collateral. Assets used as collateral can be liquidated if the user’s health factor drops below 1.0. **Input Parameters:** | Name | Type | Description | | ----------------- | ------- | ---------------------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **asset** | address | The address of the underlying asset supplied | | **use_as_collateral** | bool | true if the user wants to use the asset as collateral, false otherwise | ## E-Mode Functions ### set_user_emode ```move public entry fun set_user_emode( account: &signer, category_id: u8 ) ``` Allows users to switch between different efficiency modes (E-Modes). E-Mode allows users to get higher borrowing power on a set of assets that have correlated prices. For example, if a user is in the “Stablecoins” E-Mode category, they can borrow more stablecoins against their stablecoin collateral than they would be able to in regular mode. **Input Parameters:** | Name | Type | Description | | ----------- | ------- | -------------------------------------------------------- | | **account** | &signer | The signer account of the caller | | **category_id** | u8 | The id of the category to switch to. 0 to disable E-Mode | ## Isolation Mode Isolation mode is a risk management feature in the Aave protocol that limits borrowing power for assets that might pose higher risk to the protocol. ### Overview When a user supplies an asset marked as “isolated collateral” (via reserve configuration), they enter isolation mode. In isolation mode: 1. Users can only borrow assets up to a specific debt ceiling. 2. Users can only borrow stablecoins and other assets explicitly allowed for isolated collateral. 3. Users cannot supply other assets as collateral while in isolation mode. This feature protects the protocol by limiting the maximum debt that can be borrowed against riskier assets, reducing potential systemic risk. ### Relationship with E-Mode While E-Mode increases borrowing power for correlated assets, Isolation Mode does the opposite - it restricts borrowing power for higher-risk assets. These features serve different purposes: - **E-Mode**: Optimizes capital efficiency for correlated assets (like stablecoins). - **Isolation Mode**: Limits protocol exposure to riskier assets. Users cannot be in both modes simultaneously. If a user has an isolated asset as collateral, they cannot enter E-Mode until they either disable the isolated asset as collateral or withdraw it completely. ## Flash Loan Functions ### flash_loan_simple ```move public fun flash_loan_simple( initiator: &signer, receiver_address: address, asset: address, amount: u256, referral_code: u16 ) ``` Allows smart contracts to access the liquidity of the pool within one transaction, as long as the amount taken plus a fee is returned. This is a simpler version of the flash loan function that only allows borrowing a single asset. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | ----------------------------------------------- | | **initiator** | &signer | The signer account of the flash loan initiator | | **receiver_address** | address | The address of the contract receiving the funds | | **asset** | address | The address of the asset being flash-borrowed | | **amount** | u256 | The amount of the asset being flash-borrowed | | **referral_code** | u16 | Referral codes are currently inactive; pass 0. | ### flash_loan ```move public fun flash_loan( initiator: &signer, receiver_address: address, assets: vector
, amounts: vector, interest_rate_modes: vector, on_behalf_of: address, referral_code: u16 ) ``` Flash-borrows multiple assets in one transaction, optionally opening variable debt instead of repaying. **Input Parameters:** | Name | Type | Description | | ------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **initiator** | &signer | The signer account of the flash loan initiator | | **receiver_address** | address | The address of the contract receiving the funds | | **assets** | vector\ | The addresses of the assets being flash-borrowed | | **amounts** | vector\ | The amounts of the assets being flash-borrowed | | **interest_rate_modes** | vector\ | Types of the debt to open if the flash loan is not returned: 0 -> Don’t open any debt, just revert if funds can’t be transferred from the receiver, 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the on_behalf_of address | | **on_behalf_of** | address | The address that will receive the debt in the case of using interest_rate_modes 2, on_behalf_of should be the account address | | **referral_code** | u16 | Referral codes are currently inactive; pass 0. | ## Liquidation Functions ### liquidation_call ```move public entry fun liquidation_call( account: &signer, collateral_asset: address, debt_asset: address, user: address, debt_to_cover: u256, receive_a_token: bool ) ``` Allows liquidators to liquidate positions with a health factor below 1.0. The liquidator repays a portion of the debt and receives a portion of the collateral in return, plus a liquidation bonus. **Input Parameters:** | Name | Type | Description | | ---------------- | ------- | --------------------------------------------------------------------------------------------------- | | **account** | &signer | The signer account of the liquidator | | **collateral_asset** | address | The address of the collateral asset to receive | | **debt_asset** | address | The address of the debt asset to be repaid | | **user** | address | The address of the borrower | | **debt_to_cover** | u256 | The amount of debt to cover. Can be math_utils::u256_max() to liquidate the maximum possible amount | | **receive_a_token** | bool | true if the liquidator wants to receive aTokens instead of the underlying asset | ## Token Logic Functions Functions from the `pool_token_logic` module. ### Transfer Functions #### transfer ```move public entry fun transfer( sender: &signer, recipient: address, amount: u256, a_token_address: address ) ``` Transfers aTokens from the user to the recipient. This function allows users to transfer their aTokens directly to another address. **Input Parameters:** | Name | Type | Description | | --------------- | ------- | ------------------------------------- | | **sender** | &signer | The account signer of the caller | | **recipient** | address | The recipient of the aTokens | | **amount** | u256 | The amount of aTokens to transfer | | **a_token_address** | address | The address of the aToken to transfer | ### Admin Functions #### set_incentives_controller ```move public entry fun set_incentives_controller( admin: &signer, underlying_asset: address, incentives_controller: Option
) ``` Sets an incentives controller for both the aToken and variable debt token of a given underlying asset. **Input Parameters:** | Name | Type | Description | | --------------------- | ----------------- | ---------------------------------------- | | **admin** | &signer | The signer account of the admin | | **underlying_asset** | address | The address of the underlying asset | | **incentives_controller** | Option\ | The address of the incentives controller | #### mint_to_treasury ```move public entry fun mint_to_treasury( assets: vector
) ``` Mints the assets accrued through the reserve factor to the treasury in the form of aTokens. **Input Parameters:** | Name | Type | Description | | ------ | ----------------- | --------------------------------------------------------------- | | **assets** | vector\ | The list of reserves for which the minting needs to be executed | --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/incentives.md # Aave V3 Incentives on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the incentives modules in `sources/aave-periphery` of the `aave-pool` package. The fee collector, coin migration and UI pool data provider modules are on the [Periphery](/aave-v3/aptos/smart-contracts/periphery) page. ## Incentives The incentives system in Aave allows for distributing rewards to users who supply or borrow assets in the protocol. The system is managed through several key modules that work together to configure, track, and distribute rewards. ## RewardsController The `rewards_controller` module is the main component for managing incentives in the Aave protocol. It handles the distribution of rewards to protocol participants who hold incentivized assets (aTokens or variableDebtTokens). Users accrue rewards automatically when they hold these tokens without needing to stake or lock their assets. The rewards can be claimed through various functions that provide flexibility in how rewards are collected. ### Key Structures ```move struct RewardsConfigInput has store, drop { emission_per_second: u128, total_supply: u256, distribution_end: u32, asset: address, reward: address, pull_rewards_transfer_strategy: Object } ``` This structure defines the configuration for a reward emission, including: - `emission_per_second`: The rate at which rewards are distributed - `total_supply`: The total supply of the asset being incentivized - `distribution_end`: When the reward distribution ends - `asset`: The address of the asset being incentivized (aToken or variableDebtToken) - `reward`: The address of the reward token - `pull_rewards_transfer_strategy`: The strategy for transferring rewards ### Write Methods #### claim_rewards ```move public fun claim_rewards( caller: &signer, assets: vector
, amount: u256, to: address, reward: address, rewards_controller_address: address ): u256 ``` Claims rewards of one reward token for the caller on specific assets, with the rewards sent to a designated address. **Input Parameters:** | Name | Type | Description | | -------------------------- | ----------------- | ---------------------------------------- | | **caller** | &signer | The signer claiming the rewards | | **assets** | vector\ | The addresses of the incentivized assets | | **amount** | u256 | The amount of rewards to claim | | **to** | address | The address receiving the rewards | | **reward** | address | The address of the reward token | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ---- | ----------------------------- | | u256 | The amount of rewards claimed | `rewards_distributor` also exposes `claim_rewards_on_behalf`, which takes an extra `user: address` and requires the caller to be an authorized claimer for that user, and `claim_rewards_to_self`, which omits `to` and sends the rewards to the caller. #### claim_all_rewards ```move public fun claim_all_rewards( caller: &signer, assets: vector
, to: address, rewards_controller_address: address ): (vector
, vector) ``` Claims all available rewards for the caller across specified assets, returning the list of reward tokens and amounts claimed. **Input Parameters:** | Name | Type | Description | | -------------------------- | ----------------- | ---------------------------------------- | | **caller** | &signer | The signer claiming the rewards | | **assets** | vector\ | The addresses of the incentivized assets | | **to** | address | The address receiving the rewards | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ----------------- | ----------------------------------------- | | vector\ | The reward tokens claimed | | vector\ | The amounts claimed for each reward token | `rewards_distributor` also exposes `claim_all_rewards_on_behalf`, which takes an extra `user: address`, and `claim_all_rewards_to_self`, which omits `to`. ### Friend Functions Callable only by friend modules (emission_manager, pool logic); integrators use the emission_manager entry functions. #### configure_assets ```move public(friend) fun configure_assets( config_inputs: vector, rewards_controller_address: address ) ``` Configures assets to incentivize with an emission of rewards per second until the end of distribution. **Input Parameters:** | Name | Type | Description | | -------------------------- | ---------------------------- | ------------------------------------- | | **config_inputs** | vector\ | The reward configurations to apply | | **rewards_controller_address** | address | The address of the rewards controller | #### set_pull_rewards_transfer_strategy ```move public(friend) fun set_pull_rewards_transfer_strategy( reward: address, strategy: Object, rewards_controller_address: address ) ``` Sets a transfer strategy for a specific reward token that determines how rewards are transferred to users. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------------------------------------- | ------------------------------------- | | **reward** | address | The address of the reward token | | **strategy** | Object\ | The pull rewards transfer strategy | | **rewards_controller_address** | address | The address of the rewards controller | #### handle_action ```move // This function is called when users perform actions like supply, withdraw, // transfer, etc. to update reward calculations public(friend) fun handle_action( asset: address, user: address, total_supply: u256, user_balance: u256, rewards_controller_address: address ) ``` Called when a user performs an action that affects their balance of an incentivized asset, updating the rewards distribution accordingly. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------------------------- | | **asset** | address | The address of the incentivized asset (aToken or variableDebtToken) | | **user** | address | The address of the user | | **total_supply** | u256 | The total supply of the asset | | **user_balance** | u256 | The balance of the user in the asset | | **rewards_controller_address** | address | The address of the rewards controller | ### View Methods #### get_pull_rewards_transfer_strategy ```move #[view] public fun get_pull_rewards_transfer_strategy( reward: address, rewards_controller_address: address ): Option> ``` Returns the pull rewards transfer strategy for a reward, if one is set. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------- | ------------------------------------- | | **reward** | address | The address of the reward token | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ----------------------------------------------- | ------------------------------------------- | | Option\\> | The transfer strategy of the reward, if set | #### get_rewards_data ```move #[view] public fun get_rewards_data( asset: address, reward: address, rewards_controller_address: address ): (u256, u256, u256, u256) ``` Returns reward data for a specific asset and reward token, including emission rates and distribution end time. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------------------------- | | **asset** | address | The address of the incentivized asset (aToken or variableDebtToken) | | **reward** | address | The address of the reward token | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ---- | ------------------------------- | | u256 | The current index of the reward | | u256 | The emission per second | | u256 | The last update timestamp | | u256 | The distribution end timestamp | #### get_user_asset_index ```move // Used to get the user's index for a specific asset and reward #[view] public fun get_user_asset_index( user: address, asset: address, reward: address, rewards_controller_address: address ): u256 ``` Returns the user’s index for a specific asset and reward, used for calculating accrued rewards. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------- | ------------------------------------------------------------------- | | **user** | address | The address of the user | | **asset** | address | The address of the incentivized asset (aToken or variableDebtToken) | | **reward** | address | The address of the reward token | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ---- | ---------------------------------------------- | | u256 | The index of the user for the asset and reward | #### get_user_accrued_rewards ```move // Used to get the user's accrued rewards for a specific reward token #[view] public fun get_user_accrued_rewards( user: address, reward: address, rewards_controller_address: address ): u256 ``` Returns the amount of rewards accrued by a user for a specific reward token. **Input Parameters:** | Name | Type | Description | | -------------------------- | ------- | ------------------------------------- | | **user** | address | The address of the user | | **reward** | address | The address of the reward token | | **rewards_controller_address** | address | The address of the rewards controller | **Return Values:** | Type | Description | | ---- | ------------------------------- | | u256 | The rewards accrued by the user | ## EmissionManager The `emission_manager` module manages the configuration of reward emissions and acts as an administrative layer above the `rewards_controller`. ### Key Functions #### configure_assets ```move public entry fun configure_assets( account: &signer, emissions_per_second: vector, total_supplies: vector, distribution_ends: vector, assets: vector
, rewards: vector
, pull_rewards_transfer_strategies: vector> ) ``` Configures assets for incentives, creating reward configurations and passing them to the rewards controller. **Input Parameters:** | Name | Type | Description | | -------------------------------- | ----------------------------------------------- | -------------------------------------------------- | | **account** | &signer | The signer with emission admin privileges | | **emissions_per_second** | vector\ | The emission per second for each reward | | **total_supplies** | vector\ | The total supply of each asset | | **distribution_ends** | vector\ | The distribution end timestamp for each reward | | **assets** | vector\ | The addresses of the incentivized assets | | **rewards** | vector\ | The addresses of the reward tokens | | **pull_rewards_transfer_strategies** | vector\\> | The pull rewards transfer strategy for each reward | #### set_pull_rewards_transfer_strategy ```move public entry fun set_pull_rewards_transfer_strategy( caller: &signer, reward: address, pull_rewards_transfer_strategy: Object ) ``` Sets the transfer strategy for a specific reward token. **Input Parameters:** | Name | Type | Description | | ------------------------------ | ------------------------------------- | ----------------------------------------- | | **caller** | &signer | The signer with emission admin privileges | | **reward** | address | The address of the reward token | | **pull_rewards_transfer_strategy** | Object\ | The pull rewards transfer strategy | #### set_distribution_end ```move public entry fun set_distribution_end( caller: &signer, asset: address, reward: address, new_distribution_end: u32 ) ``` Updates the end time for a reward distribution on a specific asset. **Input Parameters:** | Name | Type | Description | | -------------------- | ------- | ------------------------------------------------------------------- | | **caller** | &signer | The signer with emission admin privileges | | **asset** | address | The address of the incentivized asset (aToken or variableDebtToken) | | **reward** | address | The address of the reward token | | **new_distribution_end** | u32 | The new distribution end timestamp | #### set_emission_admin ```move // Sets the admin for a specific reward token public entry fun set_emission_admin( account: &signer, reward: address, new_admin: address ) ``` Sets the address that has permission to configure emissions for a specific reward token. **Input Parameters:** | Name | Type | Description | | --------- | ------- | ------------------------------------- | | **account** | &signer | The signer with admin privileges | | **reward** | address | The address of the reward token | | **new_admin** | address | The address of the new emission admin | ### View Methods #### get_rewards_controller ```move #[view] public fun get_rewards_controller(): address ``` Returns the address of the rewards controller. **Return Values:** | Type | Description | | ------- | ------------------------------------- | | address | The address of the rewards controller | #### get_emission_admin ```move #[view] public fun get_emission_admin(reward: address): address ``` Returns the admin address for a specific reward token. **Input Parameters:** | Name | Type | Description | | ------ | ------- | ------------------------------- | | **reward** | address | The address of the reward token | **Return Values:** | Type | Description | | ------- | -------------------------------- | | address | The emission admin of the reward | ## TransferStrategy The `transfer_strategy` module defines how rewards are transferred to users when they claim them. ### PullRewardsTransferStrategy ```move struct PullRewardsTransferStrategy has key { rewards_admin: address, incentives_controller: address, rewards_vault: SignerCapability } ``` This strategy pulls rewards from a vault resource account to the recipient address. ### Key Functions #### pull_rewards_transfer_strategy_perform_transfer ```move public(friend) fun pull_rewards_transfer_strategy_perform_transfer( incentives_controller: address, to: address, reward: address, amount: u256, strategy: Object ): bool ``` Transfers rewards from the vault to the recipient. **Input Parameters:** | Name | Type | Description | | --------------------- | ------------------------------------- | ---------------------------------------- | | **incentives_controller** | address | The address of the incentives controller | | **to** | address | The address receiving the rewards | | **reward** | address | The address of the reward token | | **amount** | u256 | The amount of rewards to transfer | | **strategy** | Object\ | The pull rewards transfer strategy | **Return Values:** | Type | Description | | ---- | -------------------------------- | | bool | `true` if the transfer succeeded | ### View Methods #### pull_rewards_transfer_strategy_get_incentives_controller ```move public fun pull_rewards_transfer_strategy_get_incentives_controller( strategy: Object ): address ``` Returns the incentives controller address associated with the strategy. **Input Parameters:** | Name | Type | Description | | -------- | ------------------------------------- | ---------------------------------- | | **strategy** | Object\ | The pull rewards transfer strategy | **Return Values:** | Type | Description | | ------- | ---------------------------------------- | | address | The address of the incentives controller | #### pull_rewards_transfer_strategy_get_rewards_admin ```move public fun pull_rewards_transfer_strategy_get_rewards_admin( strategy: Object ): address ``` Returns the rewards admin address for the strategy. **Input Parameters:** | Name | Type | Description | | -------- | ------------------------------------- | ---------------------------------- | | **strategy** | Object\ | The pull rewards transfer strategy | **Return Values:** | Type | Description | | ------- | -------------------------------- | | address | The address of the rewards admin | #### pull_rewards_transfer_strategy_get_rewards_vault ```move public fun pull_rewards_transfer_strategy_get_rewards_vault( strategy: Object ): address ``` Returns the address of the rewards vault. **Input Parameters:** | Name | Type | Description | | -------- | ------------------------------------- | ---------------------------------- | | **strategy** | Object\ | The pull rewards transfer strategy | **Return Values:** | Type | Description | | ------- | -------------------------------- | | address | The address of the rewards vault | ## UI Incentive Data Provider The `ui_incentive_data_provider_v3` module provides view functions to query incentive data for UI display. ### Key Structures ```move struct AggregatedReserveIncentiveData has store, drop { underlying_asset: address, a_incentive_data: IncentiveData, v_incentive_data: IncentiveData } struct IncentiveData has store, drop { token_address: address, incentive_controller_address: address, rewards_token_information: vector } struct RewardInfo has store, drop { reward_token_symbol: String, reward_token_address: address, emission_per_second: u256, // Additional fields… } ``` ### View Methods #### get_reserves_incentives_data ```move #[view] public fun get_reserves_incentives_data(): vector ``` Returns incentive data for all reserves in the protocol, including information about reward tokens, emission rates, and other parameters. **Return Values:** | Type | Description | | ---------------------------------------- | ----------------------------------- | | vector\ | The incentive data of every reserve | #### get_user_reserves_incentives_data ```move #[view] public fun get_user_reserves_incentives_data(user: address): vector ``` Returns incentive data specific to a user, including their accrued rewards and other user-specific incentive information. **Input Parameters:** | Name | Type | Description | | ---- | ------- | ----------------------- | | **user** | address | The address of the user | **Return Values:** | Type | Description | | ---------------------------------- | ------------------------------------------------ | | vector\ | The incentive data of the user for every reserve | --- Source: https://aave.com/docs/aave-v3/aptos/smart-contracts/periphery.md # Aave V3 Periphery on Aptos > [!WARNING] > Aave V3 on Aptos is deprecated. Supplying and borrowing are disabled, but > users can still repay debt and withdraw supplied assets. See the [governance > proposal](https://app.aave.com/governance/v3/proposal/?proposalId=521). Reference for the non-incentives modules in `sources/aave-periphery` of the `aave-pool` package: the fee collector, coin migration and the UI pool data provider. ## Collector The `collector` module manages the collection and distribution of protocol fees. ### Key Functions #### deposit ```move public fun deposit(sender: &signer, fa: FungibleAsset) ``` Deposits fungible assets into the collector. **Input Parameters:** | Name | Type | Description | | ------ | ------------- | ----------------------------- | | **sender** | &signer | The signer of the transaction | | **fa** | FungibleAsset | The fungible asset to deposit | #### withdraw ```move public fun withdraw( sender: &signer, asset_metadata: Object, receiver: address, amount: u64 ) ``` Withdraws assets from the collector to a specified receiver. **Input Parameters:** | Name | Type | Description | | -------------- | ------------------ | -------------------------------- | | **sender** | &signer | The signer of the transaction | | **asset_metadata** | Object\ | The metadata object of the asset | | **receiver** | address | The address receiving the assets | | **amount** | u64 | The amount to withdraw | ### View Methods #### get_collected_fees ```move #[view] public fun get_collected_fees(asset_metadata: Object): u64 ``` Returns the amount of fees collected for a specific asset. **Input Parameters:** | Name | Type | Description | | -------------- | ------------------ | -------------------------------- | | **asset_metadata** | Object\ | The metadata object of the asset | **Return Values:** | Type | Description | | ---- | -------------------------------- | | u64 | The fees collected for the asset | ## CoinMigrator The `coin_migrator` module provides functionality to convert between Coin and FungibleAsset representations. ### View Methods #### get_fa_address ```move public fun get_fa_address(): address ``` Returns the address of the fungible asset associated with a specific coin type. **Return Values:** | Type | Description | | ------- | --------------------------------- | | address | The address of the fungible asset | #### get_fa_balance ```move #[view] public fun get_fa_balance(owner: address): u64 ``` Returns the fungible asset balance for a specific coin type and owner. **Input Parameters:** | Name | Type | Description | | ----- | ------- | ------------------------ | | **owner** | address | The address of the owner | **Return Values:** | Type | Description | | ---- | --------------------------------------- | | u64 | The fungible asset balance of the owner | ## UI Pool Data Provider The `ui_pool_data_provider_v3` module provides view functions to query pool data for UI display. ### View Methods #### get_reserves_list ```move #[view] public fun get_reserves_list(): vector
``` Returns the list of all reserves in the protocol. **Return Values:** | Type | Description | | ----------------- | ----------------------------- | | vector\ | The addresses of all reserves | #### get_reserves_data ```move #[view] public fun get_reserves_data(): (vector, BaseCurrencyInfo) ``` Returns detailed data about all reserves in the protocol, including configuration, rates, and other parameters. **Return Values:** | Type | Description | | ------------------------------- | ----------------------------- | | vector\ | The data of every reserve | | BaseCurrencyInfo | The base currency information | #### get_user_reserves_data ```move #[view] public fun get_user_reserves_data(user: address): (vector, u8) ``` Returns data about a user’s positions in the protocol, including balances and configuration. --- Source: https://aave.com/docs/aave-v3/umbrella.md # Aave Umbrella Aave Umbrella is a modular, onchain risk management system that automates bad debt coverage for Aave V3 pools. Umbrella introduces a more capital-efficient and automated way to protect the protocol without requiring governance intervention. Umbrella allows users to stake two types of assets: aTokens (supplied tokens such as aUSDC, aUSDT, and aWETH) and GHO (Aave’s native stablecoin). By staking these protocol assets, users actively contribute to risk management while earning rewards. Umbrella enhances the resilience of the Aave Protocol by replacing the existing Safety Module with an automated staking system. If a deficit occurs in a given asset, Umbrella enables the corresponding staked assets to be burned and offset the bad debt, removing the need for governance decisions or manual intervention. This creates a more efficient, responsive, and predictable safety mechanism for the protocol and its users. Umbrella can be interacted with using the [Aave Labs Interface](https://app.aave.com). ## Key Benefits **Automated Coverage**: Eliminates reliance on governance for bad debt resolution by responding directly to measurable, onchain deficit data. **aToken Staking**: Allows users to stake aTokens they already hold within Aave, continuing to earn underlying yield while participating in risk management. This empowers suppliers who aren’t borrowing to participate in risk management while earning rewards, creating broader participation in protocol security and aligning incentives with protocol health. **Increased Efficiency**: aTokens are the most capital-efficient assets to cover deficits. For example, burning aUSDT directly covers USDT bad debt without requiring market sales. **Enhanced Security**: Creates a more resilient protocol by tying coverage directly to the borrow assets through an automated mechanism. ## Rewards and Safety Incentives With Umbrella, users who stake their aTokens continue earning yield on their supplied assets while gaining additional rewards for helping secure the protocol. For aToken staking (USDC, USDT, WETH), you earn dual yield streams. The underlying aToken yield continues accruing automatically in your staked position, while additional Safety Incentives compensate you for assuming slashing risk. For GHO staking, you earn Safety Incentives directly since GHO doesn’t generate underlying yield like aTokens. These rewards can be paid in various tokens like AAVE, GHO, or USDC, depending on governance configuration. Unlike automatic aToken yield, Safety Incentives must be actively claimed through blockchain transactions. The rewards system uses a mathematically modeled _Emission Curve_ that targets optimal staking levels. Total emission peaks when total staked assets reach the target. Below the target, fewer stakers share the emission, so APY per staker is higher; above the target, emission decreases to discourage over-staking. This creates a natural balancing mechanism that prevents extreme APY fluctuations. As a general rule, the maximum APY when minimal assets are staked is double the APY at target liquidity, but the curve avoids misleading triple-digit scenarios that disappear with increased participation. ## Slashing Risk and Deficit Protection In return for earning rewards, stakers accept the **possibility of slashing** if a deficit arises on the specific pool and asset they have staked. Staking risk is isolated to the specific asset and network where the aTokens are staked. For example, staking aUSDC helps cover bad debt in USDC only. The system includes crucial _deficit offset_ mechanisms that provide first-loss protection. For example, USDT staking has a 100,000 USDT offset, meaning the Aave DAO covers the first 100,000 USDT of bad debt before any staker assets are affected. While the protocol design allows for slashing up to the full staked amount in extreme scenarios, the offset mechanisms significantly reduce the likelihood of any slashing for typical deficit scenarios. ## Network Coverage and Initial Activation Umbrella is active on Ethereum for USDC, USDT, WETH and GHO. Activation parameters, including reward rates and target liquidity levels, are set by the Aave DAO, with ongoing management delegated to the Aave Finance Committee. Each Umbrella deployment protects only the specific asset and network where it’s staked, providing precise risk isolation. The system maintains a 20-day cooldown period and 2-day withdrawal window, consistent with the previous Safety Module. ## Transition from the Legacy Safety Module Umbrella will gradually replace the legacy Safety Module. Current participants have different migration paths depending on their staked assets. **stkAAVE and stkABPT** will remain active during the transition, with slashing disabled once Umbrella reaches sufficient scale. No immediate action is required for these positions. **Staked GHO (stkGHO)** is being transitioned to the new savings GHO (sGHO), a native ERC-4626 vault that earns a fixed APR via an onchain yield index with no cooldown period, no slashing risk, and no rehypothecation. Users should withdraw GHO from the legacy stkGHO contract and deposit into the new sGHO vault. See the [sGHO guide](/ecosystem/gho/sgho) for integration details. For higher rewards with slashing risk, users can instead migrate to Umbrella stkGHO by activating cooldown on legacy stkGHO, unstaking their GHO, then staking in the new Umbrella system. See the [Umbrella FAQ](https://aave.com/faq#umbrella) for more common questions. ## Architecture Umbrella is built from four main contract types: - `UmbrellaCore`: Orchestrates deficit monitoring, slashing, and asset coverage for each Aave V3 pool. - `StakeToken`: ERC-4626 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. StakeTokens hold wrapped aTokens (stataTokens). `UmbrellaBatchHelper` wraps plain aTokens and stakes them in one transaction. Staking can be performed with a standard ERC-20 `approve` and `deposit`, or with EIP-2612 permit signature using `depositWithPermit`. Users may also set a cooldown operator to manage their cooldowns. ```solidity 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. ```solidity 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. ```solidity function slash(address destination, uint256 amount) external onlyOwner returns (uint256); ``` ## Rewards Rewards are managed by the RewardsController, which supports up to 8 reward tokens per StakeToken. Emission rates follow the piecewise linear [Emission Curve](#rewards-and-safety-incentives). 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. ```solidity rewardsController.claimAllRewards(address(stakeToken), msg.sender); ``` To claim a specific reward: ```solidity address[] memory rewards = new address[](1); rewards[0] = rewardToken; rewardsController.claimSelectedRewards(address(stakeToken), rewards, msg.sender); ``` To set a claimer: ```solidity rewardsController.setClaimer(claimer, true); ``` ## Deployed Contracts | Name | Address | | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `UMBRELLA` |
| | `UMBRELLA_IMPL` |
| | `UMBRELLA_STAKE_TOKEN_IMPL` |
| | `UMBRELLA_REWARDS_CONTROLLER` |
| | `UMBRELLA_REWARDS_CONTROLLER_IMPL` |
| | `PERMISSIONED_PAYLOADS_CONTROLLER` |
| | `PERMISSIONED_PAYLOADS_CONTROLLER_EXECUTOR` |
| | `UMBRELLA_BATCH_HELPER` |
| | `UMBRELLA_CONFIG_ENGINE` |
| | `DATA_AGGREGATION_HELPER` |
| | `DEFICIT_OFFSET_CLINIC_STEWARD` |
| | `AAVE` |
| | `AAVE_ORACLE` |
| | `STK_AAVE` |
| | `GHO` |
| | `GHO_ORACLE` |
| | `STK_GHO` |
| | `STK_AAVE_WSTETH_BALANCER_POOL_V2` |
| | `STK_AAVE_WSTETH_BALANCER_POOL_V2_ORACLE` |
| | `STK_AAVE_WSTETH_BALANCER_POOL_V2_MIGRATOR` |
| | `STK_AAVE_ETH_BALANCER_POOL_V1` |
| | `STK_AAVE_ETH_BALANCER_POOL_V1_ORACLE` |
| ## Resources - [Smart Contracts](https://github.com/aave-dao/aave-umbrella) - [Frontend Implementation](https://github.com/aave-dao/aave-umbrella-ui) --- Source: https://aave.com/docs/aave-v3/horizon.md # Aave Horizon RWA Market Aave Horizon is an Aave Labs initiative: a licensed, separate instance of the Aave Protocol, initially forked from V3.3, that creates a market for _Real-World Assets (RWAs)_ for institutional and qualified participants. Users supply **permissioned**, tokenized RWAs as collateral and borrow **permissionless** stablecoins. Asset types and user roles are kept separate, so institutions stay compliant while accessing the capital efficiency and liquidity of _decentralized finance (DeFi)_. RWA collateral is **permissioned**: only qualified users allowlisted by the RWA issuers can supply it. Compliance is enforced at the asset level by the RWA token’s native smart contract, so only approved participants can interact with these regulated assets. The stablecoin liquidity pools for USDC, RLUSD, and GHO are **permissionless**, with no restrictions for liquidity providers. **Only users who supply permissioned RWA collateral can borrow** from the permissionless stablecoin pools. This lets institutions use regulated assets to access DeFi liquidity. ## Supplying RWA Collateral Participation starts by supplying tokenized RWAs as collateral, exclusively for users the RWA’s issuer has qualified and allowlisted. Qualification typically follows standard institutional onboarding: identity verification, compliance checks, and agreement to terms and conditions. Supplied RWAs are **collateral only** and cannot be borrowed by other participants. Suppliers receive aTokens representing the collateral position. These receipt tokens are **non-transferable**, so the collateral position stays with the original supplier. This prevents secondary-market trading of collateral positions and preserves the permissioning system. Collateral value comes from established pricing mechanisms that account for each RWA type’s characteristics. Risk parameters, including loan-to-value ratios and liquidation thresholds, follow the underlying asset’s risk profile and regulatory requirements. ## Borrowing Stablecoins The primary borrowable assets are permissionless stablecoins such as USDC, RLUSD, and GHO. Any participant can supply them to earn yield. Stablecoins cannot be used as collateral, which keeps the permissioned collateral side distinct from the permissionless liquidity side. Borrowing is therefore **exclusively available to users who have supplied and enabled RWA collateral**, so regulated, permissioned assets access permissionless liquidity. Borrowing follows standard Aave Protocol mechanics, with interest rates set by utilization curves and market dynamics. Borrowers must maintain adequate collateralization ratios under their RWA collateral’s risk parameters. The system continuously monitors these ratios and may trigger liquidation if positions become under-collateralized, with liquidation mechanisms adapted to RWA collateral. ## RWA Price Oracle Safeguards Unlike crypto-native assets priced by decentralized exchange markets, RWAs rely on a _Net Asset Value (NAV)_ reported directly by the issuer. This creates a critical risk: delayed, inaccurate, or malicious reporting. An operational error or malicious act could publish an incorrect NAV onchain and trigger faulty liquidations across the market. An emergency multisig can freeze the reserve, but only reactively, leaving a window where allowlisted liquidators could exploit a faulty price and cause irreparable harm to borrowers. Aave Horizon mitigates this with an automated safeguard at the oracle level. With Chainlink and LlamaRisk, upper and lower price bounds are configured for each RWA price feed at the _Decentralized Oracle Network (DON)_ level. When an issuer reports a new NAV, the Chainlink DON validates it against these bounds before publishing it onchain. Within the bounds, the update is accepted. Outside them, the DON **rejects the update** and the oracle keeps reporting the last valid price. This prevents a faulty price from reaching the protocol and eliminates erroneous liquidations. Any breach of the bounds also triggers a time-sensitive reaction from Aave Horizon’s emergency multisig, which prevents new loan originations and additional exposure until the root cause analysis is complete. ## Administrative Functions and Edge Case Management The market provides mechanisms for account recovery and management in exceptional circumstances, facilitated by the RWA issuers. These administrative functions are essential for institutional participation, giving resolution paths for complex scenarios in regulated environments. For example, if a user loses their private keys, the issuer can migrate the user’s entire collateral and borrow position to a new, secure wallet. This preserves market integrity while giving institutions operational flexibility. An issuer may also be legally required to secure a position. For example, issuers can prevent a user from increasing their borrow position while coordinating a resolution, preserving the market’s collateralization and compliance. The administrative framework is transparent and accountable, with clear governance determining how these powers are exercised. Institutions can trust their interests are protected while the protocol stays decentralized. For `RwaAToken` functions and roles, see the [tokenization documentation](./smart-contracts/tokenization#rwaatoken). For Aave Horizon RWA Market governance, see [access controls](../reference/access-controls). ## Integrations Aave Horizon is fully compatible with AaveKit API methods. Follow the [getting started](/aave-v3/getting-started/react) guides to integrate Aave programmatically and specify the Aave Horizon Pool address, as in the query examples below. ```tsx import { useAaveMarket, chainId, evmAddress } from "@aave/react"; function HorizonMarketData() { // Query Aave Horizon market data const { data: horizonMarketData, loading, error, } = useAaveMarket({ address: evmAddress("0xAe05Cd22df81871bc7cC2a04BeCfb516bFe332C8"), // Aave Horizon Pool address chainId: chainId(1), }); if (loading) return Loading…; if (error) return {error.message}; return {horizonMarketData?.name}; } ``` ```ts import { AaveClient, chainId, evmAddress } from "@aave/client"; import { market } from "@aave/client/actions"; const client = AaveClient.create(); // Query Aave Horizon market data const horizonMarketData = await market(client, { address: evmAddress("0xAe05Cd22df81871bc7cC2a04BeCfb516bFe332C8"), // Aave Horizon Pool address chainId: chainId(1), }); ``` ```graphql query HorizonMarketData { market( request: { address: "0xAe05Cd22df81871bc7cC2a04BeCfb516bFe332C8" # Aave Horizon Pool address chainId: 1 } ) { name chain { name chainId } address totalMarketSize totalAvailableLiquidity reserves { underlyingToken { symbol name address } supplyInfo { apy { formatted } canBeCollateral } borrowInfo { apy { formatted } } } } } ```