# Aave V4 Documentation (full) > Every Aave V4 page in one file. It covers Aave V4 only: other sections have their own files, listed at https://aave.com/docs/llms.txt. Source: https://aave.com/docs/aave-v4.md # Aave V4 Overview Aave V4 uses a _Hub & Spoke model_ for liquidity management: the Liquidity Hub consolidates protocol-wide liquidity and accounting, while Spokes implement modular borrowing with isolated risk. > [!NOTE] > This evolves Aave V3’s market-per-pool design, so governance can add features > or markets without migrating liquidity. ## Liquidity Hubs The Liquidity Hub (Hub) is the central liquidity source in Aave V4. It maintains oversight of Spokes, granting each a _credit line for borrowing_ and a _debit line for supplying_. The Hub enforces system-wide accounting and caps how much liquidity Spokes can draw or add. - Centralizes liquidity and accounting - Issues per-Spoke credit/debit limits - Enforces system-wide constraints - Provides emergency stop controls ## Hub Assets Hub Assets are the ERC-20 tokens registered in the Liquidity Hub. They form the shared liquidity that Spokes borrow from and supply to, enabling efficient reuse across Spokes. ## Spokes Spokes are modules that manage specific supply and borrowing use cases, asset types, or risk profiles. Users interact directly with Spokes, which route liquidity to and from the Hub. - Local controls (e.g., risk parameters, oracle interactions, emergency stops) - Independent accounting per Spoke - Modular: add or remove Spokes without affecting others ## Reserves Reserves define how a Hub Asset is supplied and borrowed within a specific Spoke. Each reserve has its own risk settings, while the Hub controls how much liquidity can flow to and from the reserve through credit and debit lines. ## Interest Rates Borrow and supply rates are determined by a utilization curve. _Utilization_ measures how much of an asset’s liquidity is currently borrowed, expressed as `borrowed / total liquidity`. Below an optimal usage ratio, the borrow rate increases gradually; above it, the rate increases more sharply. The supply rate is derived from borrower interest after protocol fees and reflects supply and demand for that asset. The curve is defined by a base rate, slopes below and above the optimal usage ratio, and the optimal usage ratio itself, configured per Hub Asset. _User Risk Premium_ represents an additional interest charge applied to a user’s borrowing cost based on the quality of their collateral. It is a percentage surcharge on top of the shared borrow rate for that asset, weighted by the collateral needed to cover the debt, and recalculated as the position changes. ## User Positions A user position is the combined view of what a user has supplied and borrowed within a Spoke. Positions are tracked per reserve internally, and surface as an aggregate view of a user’s activity on that Spoke. - **User Supplies**: the assets a user deposits into a Hub through the Spoke. They accrue interest over time and expand the Hub’s available liquidity. - **User Borrows**: the assets a user draws from a Hub through the Spoke. They create a debt balance that accrues interest until it is repaid. _Health factor_ reflects position solvency and indicates how close a position is to liquidation. It is calculated as eligible collateral value divided by debt value and **must stay above 1** to avoid liquidation. It increases when debt is repaid or collateral value rises, and decreases as interest accrues, collateral value falls, or new debt is taken. ## Liquidations Positions become eligible for liquidation when their health factor drops below 1.0. Aave V4 introduces a redesigned liquidation engine that improves capital efficiency and fairness compared to Aave V3. **Target Health Factor**: Instead of a fixed close factor, liquidators repay only enough debt to restore the position to a Target Health Factor set at the Spoke level. This prevents over-liquidation. **Variable Liquidation Bonus**: The bonus paid to liquidators scales with the position’s health factor. Lower health factors offer higher bonuses, creating a Dutch-auction style incentive that prioritizes the riskiest positions. **Dust Prevention**: If the remaining debt or collateral after liquidation would fall below $1,000, the liquidator must liquidate that debt or collateral in full, preventing small leftover balances from accumulating. --- ## Next Steps --- Source: https://aave.com/docs/aave-v4/getting-started/react.md # Aave V4 React Quickstart AaveKit React for Aave V4 is a collection of React hooks for building decentralized applications on top of Aave V4. ## Getting Started To get started, follow the steps below. ### 1. Install SDK First, install the latest AaveKit React packages using your package manager of choice. ```bash title="npm" npm install @aave/react@next ``` ```bash title="yarn" yarn add @aave/react@next ``` ```bash title="pnpm" pnpm add @aave/react@next ``` ### 2. Set Up 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 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. Here’s a basic example to fetch supported chains: ```tsx title="Example" import { useChains } from "@aave/react"; export function SupportedChains() { const { data: chains } = useChains(); return (

Supported Chains

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

{chain.name}

Chain ID: {chain.chainId}
))}
); } ``` ## Declarative Hooks AaveKit React declarative hooks execute on render with the given inputs, refresh when inputs change, and update after successful write operations; declarative hooks support two modes: loading state and React Suspense. Handle loading state manually in your component: ```tsx title="Loading State" import { useChains } from "@aave/react"; function ChainsList() { const { data, loading, error } = useChains(); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((chain) => (
{chain.name}
))}
); } ```
Let React handle loading states automatically through a [Suspense boundary](https://react.dev/reference/react/Suspense) by wrapping the component with a React `` component higher in the component tree. ```tsx title="With Suspense" import { useChains } from "@aave/react"; function ChainsList() { const { data } = useChains({ suspense: true, // Enable suspense mode }); return (
{data.map((chain) => (
{chain.name}
))}
); } ``` ```tsx title="Ancestor Component" import { Suspense } from "react"; function ChainsPage() { return ( Loading…}> ); } ``` You can also handle errors in a parent component by wrapping the component with an [Error boundary](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…}> ); } ```
### Pausable Reads AaveKit React read hooks support _pausing_, which defers data fetching until certain conditions are met. This is useful when: - **Waiting for user input** (e.g., wallet connection, user address) - **Conditional data loading** (e.g., only fetch when a user is authenticated) - **Dependent data** (e.g., fetch user data only after chain selection) Type safety is maintained by allowing nullish request parameters and returning a `paused` state, which explicitly signals when a hook is inactive and lets TypeScript precisely narrow types between paused and active states. ```tsx title="Pausable Loading State" import { useChains } from "@aave/react"; const { data, loading, error, paused } = useChains({ pause: !connected, }); // … // data: Chain[] | undefined // loading: boolean // error: UnexpectedError | undefined // paused: boolean if (paused) { // data: undefined // error: undefined // loading: boolean return null; } if (loading) { // data: undefined // error: undefined // loading: true return null; } if (error) { // data: undefined // error: UnexpectedError // loading: false return null; } // data: Chain[] (guaranteed to be defined) ``` ```tsx title="Pausable React Suspense" import { useChains } from "@aave/react"; const { data, paused } = useChains({ pause: !connected, suspense: true, }); // … // data: Chain[] | undefined // paused: boolean if (paused) { // data: undefined return null; } // data: Chain[] (guaranteed to be defined) ``` ### Reloading State Declarative hooks also expose a `reloading` state that indicates when data is being refreshed after the initial load. This is different from `loading`, which is only `true` during the first fetch. The `reloading` state becomes `true` when: - **Variables change** and the hook refetches with new parameters - **Polling triggers** a background refresh (if the hook is designed to poll) This lets you show a subtle refresh indicator while keeping the previous data visible, rather than replacing content with a loading spinner. ```tsx title="Loading State" import { useUserPositions } from "@aave/react"; const { data, loading, error, reloading } = useUserPositions({ user: userAddress, }); if (loading) { return ; } if (error) { return ; } // Show refresh indicator while keeping data visible return (
{reloading && }
); ``` ```tsx title="React Suspense" import { useUserPositions } from "@aave/react"; const { data, reloading } = useUserPositions({ user: userAddress, suspense: true, }); // Show refresh indicator while keeping data visible return (
{reloading && }
); ``` ## Imperative Hooks AaveKit React imperative hooks return an execute function and a state object. These are tailored for when you need explicit control, like event handlers or multi‑step flows. ```tsx const [execute, state] = useImperativeHook(); ``` > [!NOTE] > Read hooks with this pattern don’t watch for updates. Use the imperative > variant for on-demand fresh data, such as in an event handler. ### Execute Function The `execute` function takes the hook arguments and, when awaited, yields a `Result`. Use `isOk()` and `isErr()` to check the outcome and narrow the type: ```ts const result = await execute(); if (result.isOk()) { console.log("Result:", result.value); } else { console.error("Error:", result.error); } ``` See the [Result Objects](#result-objects) section for more information about the `Result` object. ### State Object The state object provides information about the operation status: ```ts const { called, data, error, loading } = state; ``` Where: - `called`: `true` once the hook has run at least once. - `data`: last successful result of type `T`, otherwise `undefined`. - `error`: error of type `E` if the operation failed, otherwise `undefined`. - `loading`: `true` while the operation is in progress, otherwise `false`. ## 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 AaveKit React provides transaction hooks 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 To send transactions, follow the steps below. #### 1. useSendTransaction First, use the provider‑specific `useSendTransaction` hook to send transactions with the connected wallet. ```tsx const [sendTransaction, { loading, error }] = useSendTransaction(/* args */); ``` It abstracts wallet differences and provides a consistent interface that interoperates with the other AaveKit React hooks. Import the `useSendTransaction` hook from the `@aave/react/viem` entry point and wire it up with 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 an ethers `Signer`. ```tsx title="Ethers" import { useSendTransaction } from "@aave/react/ethers"; import { ethers, type Signer } from "ethers"; import { useEffect, useState } from "react"; const provider = new ethers.BrowserProvider(window.ethereum); function MyComponent({ signer }: { signer: Signer }) { const [sendTransaction, sending] = useSendTransaction(signer); // Use with transaction hooks… } function App() { const [signer, setSigner] = useState(); useEffect(() => { provider.getSigner().then(setSigner); }, []); return signer ? : null; } ``` 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 wire it up with the `WalletClient` of Dynamic’s primary wallet. ```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(() => { const setupWallet = async () => { if (!httpClient || !wallets.length) return; const accounts = await fetchWalletAccounts({ wallet: wallets[0] }); const turnkeyAccount = await createAccount({ client: httpClient, organizationId: accounts[0].organizationId, signWith: accounts[0].address, }); setWalletClient( createWalletClient({ account: turnkeyAccount, chain: mainnet, transport: http(), }), ); }; setupWallet(); }, [httpClient, wallets, fetchWalletAccounts]); // Use with transaction hooks… } ``` #### 2. Transaction Hook Then, instantiate the specific transaction hook for the operation you want to perform. Call `sendTransaction` (from `useSendTransaction`) inside the simple‑transaction hook callback, as shown below. ```tsx title="Simple Transactions" const [sendTransaction, sending] = useSendTransaction(/* … */); const [execute, { loading, error }] = useSimpleTransaction((transaction) => sendTransaction(transaction), ); ``` You can bail out of the operation at any point by calling the `cancel(message)` function. ```ts title="Bail Out" const [execute, { loading, error }] = useSimpleTransaction( (transaction, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } return sendTransaction(transaction); }, ); ``` Call `sendTransaction` (from `useSendTransaction`) inside the complex transaction hook callback, as shown below. ```tsx title="Complex Transactions" const [sendTransaction, sending] = useSendTransaction(/* … */); const [signTypedData] = useSignTypedData(/* … */); const [execute, { loading, error }] = useComplexTransaction((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": // If token supports EIP-2612 permits, sign permit (recommended) if (plan.bySignature) { return signTypedData(plan.bySignature); } // Otherwise use traditional approval transaction return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` You can bail out of the operation at any point by calling the `cancel(message)` function. ```ts title="Bail Out" const [execute, { loading, error }] = useComplexTransaction( (plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }, ); ``` #### 3. Execute the Hook Finally, execute the hook. In your callback, call the `execute` function with the operation arguments and handle the result accordingly. ```tsx title="Simple Transactions" const result = await execute(/* args */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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; } return; } console.log(result.value.txHash); // TxHash ``` In your callback, call the `execute` function with the operation arguments and handle the result accordingly. ```tsx title="Complex Transactions" const result = await execute(/* args */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log(result.value.txHash); // TxHash ``` You can also take a declarative approach by using the loading and error state objects to drive your UI. ```tsx function MyComponent() { // … return (
{error &&

{error.message}

}
); } ``` You now know the standard approach for handling Aave transactions with AaveKit React. ### Sign Typed Data Some Aave operations require EIP-712 typed data signatures for the following: - **ERC-20 Permits**: Authorize exact amount transfers without separate approval transactions - **Swap Intents**: Sign swap orders for intent-based swaps > [!NOTE] > Permits are available for ERC-20 tokens that implement > [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612). As with `useSendTransaction`, instantiate the provider-specific `useSignTypedData` hook to sign typed data. Import the `useSignTypedData` hook from the `@aave/react/viem` entry point and wire it up with viem’s `WalletClient`. ```tsx title="Viem" import { useSignTypedData } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; function MyComponent() { const { data: walletClient } = useWalletClient(); const [signTypedData, signing] = useSignTypedData(walletClient); // Use with transaction hooks… } ``` > [!NOTE] > The example uses [wagmi](https://wagmi.sh/) to get the `WalletClient` from the > connected wallet. Import the `useSignTypedData` hook from the `@aave/react/ethers` entry point and wire it up with an ethers `Signer`. ```tsx title="Ethers" import { useSignTypedData } from "@aave/react/ethers"; import { ethers, type Signer } from "ethers"; import { useEffect, useState } from "react"; const provider = new ethers.BrowserProvider(window.ethereum); function MyComponent() { const [signer, setSigner] = useState(); const [signTypedData, signing] = useSignTypedData(signer); useEffect(() => { provider.getSigner().then(setSigner); }, []); // Use with transaction hooks… } ``` Import the `useSignTypedData` hook from the `@aave/react/privy` entry point. ```tsx title="Privy" import { useSignTypedData } from "@aave/react/privy"; function MyComponent() { const [signTypedData, signing] = useSignTypedData(); // Use with transaction hooks… } ``` Import the `useSignTypedData` hook from the `@aave/react/viem` entry point and wire it up with the `WalletClient` of Dynamic’s primary wallet. ```tsx title="Dynamic" import { useSignTypedData } 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 [signTypedData, signing] = useSignTypedData(walletClient); useEffect(() => { if (primaryWallet && isEthereumWallet(primaryWallet)) { primaryWallet.getWalletClient().then(setWalletClient); } }, [primaryWallet]); // Use with transaction hooks… } ``` Import the `useSignTypedData` hook from the `@aave/react/thirdweb` entry point. ```tsx title="thirdweb" import { useSignTypedData } from "@aave/react/thirdweb"; function MyComponent() { const [signTypedData, signing] = useSignTypedData(); // Use with transaction hooks… } ``` Import the `useSignTypedData` 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 { useSignTypedData } 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 [signTypedData, signing] = useSignTypedData(walletClient); useEffect(() => { const setupWallet = async () => { if (!httpClient || !wallets.length) return; const accounts = await fetchWalletAccounts({ wallet: wallets[0] }); const turnkeyAccount = await createAccount({ client: httpClient, organizationId: accounts[0].organizationId, signWith: accounts[0].address, }); setWalletClient( createWalletClient({ account: turnkeyAccount, chain: mainnet, transport: http(), }), ); }; setupWallet(); }, [httpClient, wallets, fetchWalletAccounts]); // Use with transaction hooks… } ``` Then, use the `signTypedData` function as described in the specific operation guide. ## Result Objects AaveKit handles errors with `Result`, which represents one of two states: - `Ok`: A successful result containing a value of type `T` - `Err`: A failure containing an error of type `E` ```ts title="Example" import { ok, err, Result } from "@aave/react"; function parseNumber(input: string): Result { return isNaN(Number(input)) ? err(new Error("Invalid number")) : ok(Number(input)); } ``` With a `Result`, use the `isOk()` and `isErr()` methods to check the outcome and narrow the type. ```ts const result = parseNumber("123"); if (result.isOk()) { console.log(result.value); // 123 } else { console.error(result.error); // Error } ``` This approach avoids reliance on `try/catch` blocks and promotes predictable, type-safe code by ensuring errors are handled explicitly. > [!NOTE] > AaveKit builds its `Result` object on > [NeverThrow](https://github.com/supermacro/neverthrow). `ResultAsync` is the async, thenable variant of `Result`. Awaiting it resolves to a `Result`. ```ts import { ResultAsync } from "@aave/react"; function fetchUser(id: number): ResultAsync<{ name: string }, Error> { return ResultAsync.fromPromise( fetch(`/api/users/${id}`).then((r) => r.json()), () => new Error("Not found"), ); } const result = await fetchUser(1); if (result.isOk()) { console.log(result.value); // { name: "John" } } else { console.error(result.error); // Error } ``` --- ## Next Steps --- Source: https://aave.com/docs/aave-v4/getting-started/typescript.md # Aave V4 TypeScript Quickstart AaveKit TypeScript for Aave V4 provides a type-safe, low-level API client for interacting with Aave V4. 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 data retrieval. ## 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@next ``` ```bash title="yarn" yarn add @aave/client@next ``` ```bash title="pnpm" pnpm add @aave/client@next ``` ### 2. Set Up 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 use the `@aave/client/actions` to interact with the Aave Protocol. Here’s a basic example to query supported chains: ```ts title="example.ts" import { ChainsFilter } from "@aave/client"; import { chains } from "@aave/client/actions"; import { client } from "./client"; // Fetch all chains supported by Aave const result = await chains(client, { query: { filter: ChainsFilter.ALL }, }); if (result.isOk()) { console.log("Chains:", result.value); } else { console.error("Error:", result.error); } ``` ## Server-Side Rendering `AaveClient` supports SSR hand-off through the `ssr` option. Create a server-side client, run your queries, serialize `client.extractData()`, then hydrate a browser client with that snapshot. ```ts title="server.ts" import { AaveClient, type SSRData, ChainsFilter } from "@aave/client"; import { chains } from "@aave/client/actions"; const client = AaveClient.create({ ssr: { isServer: true }, }); await chains(client, { query: { filter: ChainsFilter.ALL }, }); const initialState: SSRData = client.extractData(); // Serialize into the HTML: ``` ```ts title="client.ts" import { AaveClient, type SSRData } from "@aave/client"; declare global { interface Window { __AAVE_SSR_DATA__?: SSRData; } } export const client = AaveClient.create({ ssr: { isServer: false, initialState: window.__AAVE_SSR_DATA__, }, }); ``` If the snapshot arrives after the client is created, call `client.restoreData(initialState)` to hydrate the cache later. ## Display Configuration The optional `display` config transforms how assets are presented across queries. Transforms are applied after the cache, so the cache always stores untransformed data. ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create({ display: { // Show wrapped native tokens (e.g. WETH) as the native asset (e.g. ETH) showWrappedNativeReserveAsNative: true, // Per-asset overrides, keyed by chain ID and address assetOverrides: [ { chainId: 1, address: "0xAeBf0Bb9f57E89260d57f31AF34eB58657d96Ce0", display: { name: "PT USDe (May 2026)", symbol: "PT USDe", icon: "https://…" }, }, ], }, }); ``` - `showWrappedNativeReserveAsNative`: when `true`, wrapped native tokens are shown using the native asset’s `name`, `symbol`, and `icon` within reserve contexts (`Reserve`, `HubAsset`, `Asset`). Wallet balance, reward payout, and swap queries are unaffected. The underlying `isWrappedNativeToken` flag and token `address` are preserved. - `assetOverrides`: per-asset display overrides applied globally across all queries, keyed by `chainId` and `address`. Each entry takes a `display` object with optional `name`, `symbol`, and `icon`. > [!NOTE] > If both settings target the same token, `assetOverrides` takes precedence. ## Result Objects AaveKit handles errors with `Result`, which represents one of two states: - `Ok`: A successful result containing a value of type `T` - `Err`: A failure containing an error of type `E` ```ts title="Example" import { ok, err, Result } from "@aave/client"; function parseId(s: string): Result { if (/^\d+$/.test(s)) { return ok(Number(s)); } return err(new Error("ID must be a number")); } ``` With a `Result`, use the `isOk()` and `isErr()` methods to check the outcome and narrow the type. ```ts const result: Result = parseId("123"); if (result.isOk()) { console.log(result.value); // 123 } else { console.error(result.error); // Error } ``` This approach avoids reliance on `try/catch` blocks and promotes predictable, type-safe code by ensuring errors are handled explicitly. > [!NOTE] > AaveKit builds its `Result` object on > [NeverThrow](https://github.com/supermacro/neverthrow). `ResultAsync` is the async, thenable variant of `Result`. Awaiting it resolves to a `Result`. ```ts import { ResultAsync } from "@aave/client"; function fetchUser(id: number): ResultAsync<{ name: string }, Error> { return ResultAsync.fromPromise( fetch(`/api/users/${id}`).then((r) => r.json()), () => new Error("Not found"), ); } const result = await fetchUser(1); if (result.isOk()) { console.log(result.value); // { name: "John" } } else { console.error(result.error); // Error } ``` Result objects can be chained: ```ts title="Chaining" function divide(a: number, b: number): Result { return b === 0 ? err("Division by zero") : ok(a / b); } const result = parseId("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 if the result is an error: ```ts title="Default Value" const value = parseId("invalid").unwrapOr(0); // 0 ``` See the [NeverThrow documentation](https://github.com/supermacro/neverthrow) for more information. ## 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 = await 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(client, 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 "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } else { console.log(result.value.txHash); // TxHash } ``` You’ve sent the transaction. ### Sign Typed Data Some Aave operations require EIP-712 typed data signatures for the following: - **ERC-20 Permits**: Authorize exact amount transfers without separate approval transactions - **Swap Intents**: Sign swap orders for intent-based swaps > [!NOTE] > Permits are available for ERC-20 tokens that implement > [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612). Import the signing helpers for your wallet library. Import the `signTypedDataWith` or `permitWith` helpers from the `@aave/client/viem` entry point. ```tsx title="Viem" import { signTypedDataWith, permitWith } from "@aave/client/viem"; ``` Import the `signTypedDataWith` or `permitWith` helpers from the `@aave/client/ethers` entry point. ```tsx title="Ethers" import { signTypedDataWith, permitWith } from "@aave/client/ethers"; ``` Import the `signTypedDataWith` or `permitWith` helpers from the `@aave/client/privy` entry point. ```tsx title="Privy" import { signTypedDataWith, permitWith } from "@aave/client/privy"; ``` Import the `signTypedDataWith` or `permitWith` helpers from the `@aave/client/thirdweb` entry point. ```tsx title="thirdweb" import { signTypedDataWith, permitWith } from "@aave/client/thirdweb"; ``` Import the `signTypedDataWith` or `permitWith` helpers from the `@aave/client/viem` entry point. ```tsx title="Turnkey" import { signTypedDataWith, permitWith } from "@aave/client/viem"; ``` Then, use them as described in the specific operation guide. --- ## Next Steps --- Source: https://aave.com/docs/aave-v4/getting-started/graphql.md # Aave V4 GraphQL Quickstart AaveKit API is a GraphQL interface to query liquidity data and user positions and to prepare transactions. Use it for custom integrations and data analysis where the TypeScript SDK does not fit. ## Getting Started AaveKit API for Aave V4 is available at `https://api.v4.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 to query supported chains: ```bash curl -X POST https://api.v4.aave.com/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query Chains { chains(request: { query: { filter: ALL } }) { 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. Transaction 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! operations: [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. - `Erc20ApprovalRequired`: One or more ERC-20 approvals are required first, then the original transaction can be executed. - `PreContractActionRequired`: A pre-contract action 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 | Erc20ApprovalRequired | PreContractActionRequired | InsufficientBalanceError ``` ```graphql title="Erc20ApprovalRequired" type Erc20ApprovalRequired { approvals: [Erc20Approval!]! reason: String! requiredAmount: DecimalNumber! currentAllowance: DecimalNumber! originalTransaction: TransactionRequest! } ``` ```graphql title="Erc20Approval" type Erc20Approval { byTransaction: TransactionRequest! bySignature: PermitTypedData } ``` ```graphql title="PermitTypedData" type PermitTypedData { types: JSON! primaryType: String! domain: DomainData! message: JSON! signedAmount: BigDecimal! } ``` ```graphql title="PreContractActionRequired" type PreContractActionRequired { transaction: TransactionRequest! reason: String! originalTransaction: TransactionRequest! } ``` ```graphql title="InsufficientBalanceError" type InsufficientBalanceError { required: DecimalNumber! available: DecimalNumber! } ``` > [!NOTE] > **Multiple Approvals:** Some tokens, like USDT, don’t allow raising an > existing allowance. For these, the API returns two approvals: reset to 0, then > set the required amount. ## 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 operations 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 `operations` field. ```graphql title="Query" query { value: hasProcessedKnownTransaction( request: { operations: [SPOKE_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. This avoids race conditions with cached data. --- ## Scalars A non-exhaustive list of custom scalars used in the AaveKit API. A string representing binary data as a hex string. ```text 0x0000000000000000000000000000000000000000000000000000000000000020 ``` A string representing a big integer in decimal format. ```text 1000000000000000000000 ``` A string representing a decimal number with arbitrary precision. ```text 1.0000000000000000001 ``` A number representing a Chain ID. ```text 1 8453 42161 ``` A string representing an EVM address. ```text 0x0000000000000000000000000000000000000000 ``` A string representing an EVM transaction hash. ```text 0x0000000000000000000000000000000000000000000000000000000000000000 ``` A string representing a date and time. ```text 2021-01-01T00:00:00Z ``` ## Common Types Some of the common types used in the Aave Protocol GraphQL API. A `DecimalNumber` object represents a decimal value with arbitrary precision. ```graphql type DecimalNumber { """ The on-chain representation of `value`, stored as an integer. """ onChainValue: BigInt! """ The number of decimals defining how many fractional digits the number supports. """ decimals: Int! """ The normalized value computed as `onChainValue / 10^decimals`. """ value: BigDecimal! } ``` A `PercentNumber` object represents a percentage value. ```graphql type PercentNumber { """ The on-chain representation of the percentage, stored in basis points (bps). """ onChainValue: BigInt! """ The number of decimals defining the precision of `bps`. """ decimals: Int! """ The normalized percentage value where 1.0 represents 100%. """ value: BigDecimal! """ The human-friendly percentage value where 100.0 represents 100% """ normalized: 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! """ The RPC URL of the chain """ rpcUrl: String! """ The blockchain explorer URL """ explorerUrl: String! """ Whether this chain is a fork """ isFork: Boolean! """ Whether this is a testnet chain """ isTestnet: Boolean! """ The chain's native asset, or null on a chain with no native token """ nativeAsset: NativeAsset nativeWrappedToken: EvmAddress! @deprecated(reason: "Use nativeAsset { ... on WrappedNativeAsset { wrappedNativeTokenAddress } }.") nativeInfo: TokenInfo! @deprecated(reason: "Use nativeAsset { ... on WrappedNativeAsset { nativeToken } ... on SharedBalanceNativeAsset { nativeToken } }.") nativeGateway: EvmAddress! @deprecated(reason: "Use nativeAsset { ... on WrappedNativeAsset { gateway } }.") """ The signature gateway address """ signatureGateway: EvmAddress! } ``` A `TokenInfo` object contains basic metadata about a token. ```graphql type TokenInfo { """ The token info id """ id: TokenInfoId! """ The token name """ name: String! """ The token symbol """ symbol: String! """ The canonical token symbol """ canonicalSymbol: String! """ The token icon URL """ icon: String! """ The token decimals """ decimals: Int! """ The token categories """ categories: [TokenCategory!]! } ``` An `Erc20Token` object represents an ERC-20 token with its metadata and chain information. ```graphql type Erc20Token { """ The token contract address """ address: EvmAddress! """ The chain this token is deployed on """ chain: Chain! """ The token metadata """ info: TokenInfo! """ Whether this token is a wrapped native token (e.g., WETH) """ isWrappedNativeToken: Boolean! } ``` An `Erc20Amount` object represents an amount of an ERC-20 token. ```graphql type Erc20Amount { """ The amount """ amount: DecimalNumber! """ Get the fiat amount for this token amount """ exchange(currency: Currency! = USD): ExchangeAmount! """ Get the fiat rate for this token """ exchangeRate(currency: Currency! = USD): DecimalNumber! """ The token information """ token: Erc20Token! } ``` An `ExchangeAmount` object represents a monetary value in a fiat currency. ```graphql type ExchangeAmount { """ The numerical value """ value: BigDecimal! """ The currency name """ name: String! """ The currency symbol (e.g., $, €, £) """ symbol: String! """ The currency icon URL """ icon: String! """ The number of decimals for the currency """ decimals: Int! } ``` --- ## Next Steps --- Source: https://aave.com/docs/aave-v4/getting-started/solidity.md # Aave V4 Solidity Quickstart The Aave smart contract interfaces provide methods for interacting with Aave V4. They enable lending, borrowing, and collateral workflows inside custom integrations. We recommend using [Foundry](https://getfoundry.sh/) for Solidity development. ## Getting Started Start new projects from the [Foundry boilerplate](https://github.com/aave/aave-v4-foundry-template) for Aave V4. It includes a setup for deploying and testing contracts that integrate with the protocol. Included in the boilerplate are: - `/src`: A sample smart contract demonstrating how to fetch user positions. - `/script`: Deployment scripts for your contracts. - `/test`: Example tests for your contracts. - `foundry.toml`: A Foundry configuration file customized for Aave V4. Install or update [Foundry](https://getfoundry.sh/): ```bash curl -L https://foundry.paradigm.xyz | bash foundryup ``` Then, follow these steps to get started: ### 1. Clone the Repository Clone the boilerplate repository into a new project directory: ```bash git clone https://github.com/aave/aave-v4-foundry-template.git my-project cd my-project ``` ### 2. Install Dependencies Install the project dependencies: ```bash forge install ``` ### 3. Set Up Environment Create `.env` file from the `.env.example` template: ```bash cp .env.example .env ``` Then populate the required environment variables: ```text RPC_URL=https://… SPOKE_ADDRESS=0x… PRIVATE_KEY=0x… ``` ## Usage The project includes several Foundry commands designed to streamline your workflow: - `forge build`: Compiles the contracts. - `forge test`: Executes tests. - `forge script `: Deploys contracts using deployment scripts. - `forge clean`: Removes build artifacts from the project. - `forge fmt`: Formats the Solidity code. ## Example Deployment To deploy the example `ReserveUtilization` contract to the Spoke set in `SPOKE_ADDRESS`: ```bash source .env forge script script/Deploy_ReserveUtilization.s.sol:DeployReserveUtilization \ --rpc-url $RPC_URL \ --broadcast ``` ## Advanced ### Add to Existing Project If you have an existing Foundry project and want to add Aave V4 contracts, install the dependency: ```bash forge install aave/aave-v4 ``` Update `remappings.txt` for imports to resolve correctly: ```text aave-v4/=lib/aave-v4/ forge-std/=lib/forge-std/src/ ``` --- ## Next Steps --- Source: https://aave.com/docs/aave-v4/liquidity.md # Aave V4 Liquidity Model Aave V4 manages liquidity through Liquidity Hubs, Spokes, and Reserves. This page explains how capital flows between them and how new markets access existing liquidity. ## Liquidity Hubs Liquidity Hubs are the central settlement layer of Aave V4. Each Hub aggregates liquidity, manages credit lines, enforces risk parameters, and operates under governance controls. This design allows new markets to tap into established pools without fragmenting liquidity. Assets are held at the Liquidity Hub, which governs how Spokes can access and use them. Governance defines liquidity caps, credit allocations, and risk parameters for each supported asset. Different Hub types can be deployed for specific purposes (from conservative stablecoin liquidity to higher-yield, higher-risk configurations), each operating under its own governance model. ## Spokes Spokes are specialized smart contracts that connect to Hubs. They define user-facing logic such as collateral requirements, liquidation conditions, and oracle pricing while drawing on Hub liquidity. This keeps the complexity of user interactions isolated from the Hub layer. Credit lines govern Spoke access to Hub Assets, setting limits and conditions for borrowing. A Spoke may connect to multiple Hubs, giving it flexibility to tap different risk profiles or liquidity sources. Risk is isolated at the Spoke level: issues in one Spoke do not affect Hubs or other Spokes. ## Reserves Reserves are managed at the Spoke level and represent the accounting units for specific assets within each Spoke. They track deposits, borrows, repayments, and interest accrual while enforcing supply caps and user-specific configurations. Governance defines how much of the Hub’s underlying assets can be allocated to each Spoke reserve through credit lines, adjusting dynamically based on demand and risk conditions. --- Source: https://aave.com/docs/aave-v4/liquidity/hubs.md # Aave V4 Liquidity Hubs Liquidity Hubs hold the shared liquidity of Aave V4 and grant each Spoke a credit line for borrowing and a debit line for supplying. ## Hub Data Structure Hub data provides an aggregate view of a Liquidity Hub, including: - Identification: id, name, chain, address - Aggregated details: totalSupplied, totalBorrowed - System caps: totalSupplyCap, totalBorrowCap In Solidity, Hubs are represented by deployed contracts implementing the `IHub` interface, managed by governance. Unlike the SDK, there is no single onchain struct containing Hub metadata (name, address) nor aggregate summary information (e.g., total liquidity) as these are maintained offchain. Hubs manage two key relationships: Assets and Spokes. For more information about Hub Assets, see the [Hub Assets](#hub-assets) section below. For details on Spoke-Hub relationships and Spoke data structures, see the [Spoke Data Structure](/aave-v4/liquidity/spokes#spoke-data-structure) section. The following TypeScript interfaces and GraphQL fragments illustrate the core Hub type. ```ts title="Hub" interface Hub { __typename: "Hub"; id: HubId; address: EvmAddress; chain: Chain; name: string; summary: HubSummary; } ``` ```ts title="HubSummary" interface HubSummary { __typename: "HubSummary"; totalBorrowed: ExchangeAmountWithChange; totalBorrowCap: ExchangeAmount; totalSupplied: ExchangeAmountWithChange; totalSupplyCap: ExchangeAmount; utilizationRate: PercentNumber; } ``` ```ts title="ExchangeAmount" interface ExchangeAmount { __typename: "ExchangeAmount"; value: BigDecimal; name: string; symbol: string; icon: string; decimals: number; } ``` ```ts title="ExchangeAmountWithChange" interface ExchangeAmountWithChange { __typename: "ExchangeAmountWithChange"; current: ExchangeAmount; change: PercentNumber; } ``` ```ts title="PercentNumber" interface PercentNumber { __typename: "PercentNumber"; onChainValue: bigint; decimals: number; value: BigDecimal; normalized: BigDecimal; } ``` ```ts title="Chain" interface Chain { __typename: "Chain"; chainId: ChainId; name: string; icon: string; rpcUrl: string; explorerUrl: string; isTestnet: boolean; nativeWrappedToken: EvmAddress; nativeInfo: TokenInfo; nativeGateway: EvmAddress; signatureGateway: EvmAddress; } interface TokenInfo { __typename: "TokenInfo"; id: TokenInfoId; name: string; symbol: string; canonicalSymbol: string; icon: string; decimals: number; categories: TokenCategory[]; } ``` ```graphql title="Hub" fragment Hub on Hub { __typename id address chain { ...Chain } name summary { ...HubSummary } } ``` ```graphql title="HubSummary" fragment HubSummary on HubSummary { __typename totalBorrowed { ...ExchangeAmountWithChange } totalBorrowCap { ...ExchangeAmount } totalSupplied { ...ExchangeAmountWithChange } totalSupplyCap { ...ExchangeAmount } utilizationRate { ...PercentNumber } } ``` ```graphql title="ExchangeAmount" fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ``` ```graphql title="ExchangeAmountWithChange" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change { ...PercentNumber } } ``` ```graphql title="PercentNumber" fragment PercentNumber on PercentNumber { __typename onChainValue decimals value normalized } ``` ```graphql title="Chain" fragment Chain on Chain { __typename chainId name icon rpcUrl explorerUrl isTestnet nativeWrappedToken nativeInfo { ...TokenInfo } nativeGateway signatureGateway } fragment TokenInfo on TokenInfo { __typename id name symbol icon decimals categories } ``` ```solidity title="IHub Interface" interface IHub { function getAssetCount() external view returns (uint256); function getAsset(uint256 assetId) external view returns (Asset memory); function getAssetConfig(uint256 assetId) external view returns (AssetConfig memory); function getSpokeCount(uint256 assetId) external view returns (uint256); function getSpokeAddress(uint256 assetId, uint256 index) external view returns (address); function getSpoke(uint256 assetId, address spoke) external view returns (SpokeData memory); function getSpokeConfig(uint256 assetId, address spoke) external view returns (SpokeConfig memory); function isSpokeListed(uint256 assetId, address spoke) external view returns (bool); } ``` ## Listing Available Hubs Discover all available Aave Liquidity Hubs across supported networks. Use the `useHubs` hook in React, the `hubs` action in TypeScript, or the `hubs` query in GraphQL to fetch a list of Liquidity Hubs. ```tsx title="Loading State" import { type HubsRequest, useHubs } from "@aave/react"; function HubsList({ request }: { request: HubsRequest }) { const { data, loading, error } = useHubs(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((hub) => (

{hub.name}

Chain: {hub.chain.name}
))}
); } ``` ```tsx title="React Suspense" import { type HubsRequest, useHubs } from "@aave/react"; function HubsList({ request }: { request: HubsRequest }) { const { data } = useHubs({ ...request, suspense: true, }); return (
{data.map((hub) => (

{hub.name}

Chain: {hub.chain.name}
))}
); } ``` ```tsx title="Imperative Read" import { type HubsRequest, useHubsAction } from "@aave/react"; // … const [fetch, { called, data, error, loading }] = useHubsAction(); const handler = async (request: HubsRequest) => { const result = await fetch(request); if (result.isOk()) { console.log(result.value); // Hub[] } else { console.error(result.error); } }; ```
```ts title="By Chains" import { chainId } from "@aave/client"; import { hubs } from "@aave/client/actions"; import { client } from "./client"; const result = await hubs(client, { query: { chainIds: [chainId(1)], }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: Hub[] console.log(result.value); } ``` ```ts title="By Tokens" import { chainId, evmAddress } from "@aave/client"; import { hubs } from "@aave/client/actions"; import { client } from "./client"; const result = await hubs(client, { query: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }); ``` ```ts title="By Asset IDs" import { assetId } from "@aave/client"; import { hubs } from "@aave/client/actions"; import { client } from "./client"; const result = await hubs(client, { query: { assetIds: [assetId("SGVsbG8h"), assetId("V29ybGQh")], }, }); ``` ```ts title="Custom Currency" import { chainId, Currency } from "@aave/client"; import { hubs } from "@aave/client/actions"; import { client } from "./client"; const result = await hubs( client, { query: { chainIds: [chainId(1)], }, }, { currency: Currency.Eur }, ); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: HubsRequest!) { hubs(request: $request) { id address chain { ...Chain } name summary { ...HubSummary } } } ```
> [!NOTE] > `useHubsAction` doesn’t watch for updates. Use it for on-demand fresh data, > such as in an event handler. In React and GraphQL, see below for examples of `HubsRequest` objects. ```tsx title="By Chains" import { chainId } from "@aave/react"; const request: HubsRequest = { query: { chainIds: [chainId(1)], }, }; ``` ```tsx title="By Tokens" import { evmAddress, chainId } from "@aave/react"; const request: HubsRequest = { query: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }; ``` ```tsx title="By Asset IDs" import { assetId } from "@aave/react"; const request: HubsRequest = { query: { assetIds: [assetId("SGVsbG8h"), assetId("V29ybGQh")], }, }; ``` ```json title="By Chains" { "request": { "query": { "chainIds": [1] } } } ``` ```json title="By Tokens" { "request": { "query": { "tokens": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "chainId": 1 }, { "address": "0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f", "chainId": 1 } ] } } } ``` ```json title="By Asset IDs" { "request": { "query": { "assetIds": ["SGVsbG8h", "V29ybGQh"] } } } ``` ```graphql title="Custom Currency" query ($request: HubsRequest!) { hubs(request: $request) { id address chain { ...Chain } name summary(currency: EUR) { ...HubSummary } } } ``` In React, you can also specify a different currency for the data. ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, error, loading } = useHubs({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ### Deployed Hubs In Solidity, hubs are deployed and managed by governance. The following hubs are deployed on Ethereum Mainnet: | Name | Address | | --------- | -------------------------------------------- | | **Core Hub** | `0xCca852Bc40e560adC3b1Cc58CA5b55638ce826c9` | | **Plus Hub** | `0x06002e9c4412CB7814a791eA3666D905871E536A` | | **Prime Hub** | `0x943827DCA022D0F354a8a8c332dA1e5Eb9f9F931` | Once a hub address is known, access its assets and spokes using the methods documented in the [Hub Data Structure](#hub-data-structure) section above. ## Fetching a Single Hub Get detailed information about a specific Liquidity Hub. Use the `useHub` hook in React, the `hub` action in TypeScript, or the `hub` query in GraphQL to fetch a specific hub by ID or by address and chain. ```tsx title="Loading State" import { type HubRequest, useHub } from "@aave/react"; function HubDetails({ request }: { request: HubRequest }) { const { data, loading, error } = useHub(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (!data) return
Hub not found
; return (

{data.name}

Address: {data.address} Chain: {data.chain.name}
); } ``` ```tsx title="React Suspense" import { type HubRequest, useHub } from "@aave/react"; function HubDetails({ request }: { request: HubRequest }) { const { data } = useHub({ ...request, suspense: true, }); if (!data) return
Hub not found
; return (

{data.name}

Address: {data.address} Chain: {data.chain.name}
); } ```
```ts title="By Hub ID" import { hubId } from "@aave/client"; import { hub } from "@aave/client/actions"; import { client } from "./client"; const id = hubId("SGVsbG8h"); const result = await hub(client, { query: { hubId: id, }, }); if (result.isOk()) { console.log(result.value); // Hub | null - null if not found } else { console.error(result.error); } ``` ```ts title="By Hub Details" import { chainId, evmAddress } from "@aave/client"; import { hub } from "@aave/client/actions"; import { client } from "./client"; const result = await hub(client, { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; import { hub } from "@aave/client/actions"; import { client } from "./client"; const result = await hub( client, { query: , }, { currency: Currency.Eur }, ); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="By Hub ID" query { hub(request: { query: { hubId: "SGVsbG8h" } }) { id address chain { ...Chain } name summary { ...HubSummary } } } ``` ```graphql title="By Hub Details" query { hub(request: { query: { hubInput: { address: "0x123…", chainId: 1 } } }) { id address chain { ...Chain } name summary { ...HubSummary } } } ``` ```graphql title="Custom Currency" query { hub(request: { query: { hubId: "SGVsbG8h" } }) { id address chain { ...Chain } name summary(currency: EUR) { ...HubSummary } } } ```
In React, see below for examples of `HubRequest` objects. ```tsx title="By Hub ID" import { hubId } from "@aave/react"; const request: HubRequest = { query: { hubId: hubId(params.id), // HubId - typically from URL params }, }; ``` ```tsx title="By Hub Details" import { chainId, evmAddress } from "@aave/react"; const request: HubRequest = { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` In React, pass `timeWindow` or `currency` with the request; in TypeScript, pass them in the third options argument of `hub`. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, loading, error } = useHub({ query: { // your query criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, loading, error } = useHub({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ## Hub Summary History Fetch historical summary data for a specific hub over a specified time window. Use the `useHubSummaryHistory` hook in React, the `hubSummaryHistory` action in TypeScript, or the `hubSummaryHistory` query in GraphQL to fetch historical summary data for a hub. ```tsx title="Loading State" import { type HubSummaryHistoryRequest, useHubSummaryHistory, } from "@aave/react"; function HubHistory({ request }: { request: HubSummaryHistoryRequest }) { const { data, loading, error } = useHubSummaryHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (

Hub History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Deposits: {item.deposits.symbol} {item.deposits.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

Utilization: {item.utilizationRate.normalized.toFixed(2)}%
))}
); } ``` ```tsx title="React Suspense" import { type HubSummaryHistoryRequest, useHubSummaryHistory, } from "@aave/react"; function HubHistory({ request }: { request: HubSummaryHistoryRequest }) { const { data } = useHubSummaryHistory({ ...request, suspense: true, }); return (

Hub History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Deposits: {item.deposits.symbol} {item.deposits.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

))}
); } ```
```ts title="By Hub ID" import { hubSummaryHistory } from "@aave/client/actions"; import { hubId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await hubSummaryHistory(client, { query: { hubId: hubId(id) }, window: TimeWindow.LastWeek, }); if (result.isOk()) { console.log(result.value); // HubSummarySample[] } else { console.error(result.error); } ``` ```ts title="By Hub Details" import { hubSummaryHistory } from "@aave/client/actions"; import { chainId, evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await hubSummaryHistory(client, { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, window: TimeWindow.LastWeek, }); ``` ```graphql title="Query" query ($request: HubSummaryHistoryRequest!) { hubSummaryHistory(request: $request) { date deposits { ...ExchangeAmount } borrows { ...ExchangeAmount } availableLiquidity { ...ExchangeAmount } utilizationRate { ...PercentNumber } } } ```
- **React**: See below for examples of `HubSummaryHistoryRequest` objects. - **GraphQL**: Use the `query` and `window` fields to specify the hub and time period. ```tsx title="By Hub ID" import { hubId, TimeWindow } from "@aave/react"; const request: HubSummaryHistoryRequest = { query: { hubId: hubId(params.id) }, window: TimeWindow.LastWeek, }; ``` ```tsx title="By Hub Details" import { chainId, evmAddress, TimeWindow } from "@aave/react"; const request: HubSummaryHistoryRequest = { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, window: TimeWindow.LastWeek, }; ``` ```json title="By Hub ID" { "request": { "query": { "hubId": "SGVsbG8h" }, "window": "LAST_WEEK" } } ``` ```json title="By Hub Details" { "request": { "query": { "hubInput": { "address": "0x123…", "chainId": 1 } }, "window": "LAST_WEEK" } } ``` Specify the time window for the historical data. `window` accepts `TimeWindow.LastDay` (default), `LastWeek`, `LastMonth`, `LastSixMonths`, `LastYear` or `All` (GraphQL: `LAST_DAY`, `LAST_WEEK`, `LAST_MONTH`, `LAST_SIX_MONTHS`, `LAST_YEAR`, `ALL`). ```tsx title="Last Week" import { hubId, TimeWindow } from "@aave/react"; const request: HubSummaryHistoryRequest = { query: { hubId: hubId(params.id) }, window: TimeWindow.LastWeek, }; ``` ```ts title="Last Week" import { hubSummaryHistory } from "@aave/client/actions"; import { hubId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await hubSummaryHistory(client, { query: { hubId: hubId(id) }, window: TimeWindow.LastWeek, }); ``` ```json title="Last Week" { "request": { "query": { "hubId": "SGVsbG8h" }, "window": "LAST_WEEK" } } ``` You can also specify a different currency for the data. ```tsx title="Custom Currency" import { Currency, hubId, TimeWindow } from "@aave/react"; const { data, error, loading } = useHubSummaryHistory({ query: { hubId: hubId(params.id) }, window: TimeWindow.LastWeek, currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { hubSummaryHistory } from "@aave/client/actions"; import { hubId, TimeWindow, Currency } from "@aave/client"; import { client } from "./client"; const result = await hubSummaryHistory(client, { query: { hubId: hubId(id) }, window: TimeWindow.LastWeek, currency: Currency.Eur, }); ``` ```json title="Custom Currency" { "request": { "query": { "hubId": "SGVsbG8h" }, "window": "LAST_WEEK", "currency": "EUR" } } ``` ## Hub Spoke Configs Fetch per-asset configuration for a specific `(hub, spoke)` pair, including supply caps, borrow caps, operational status, and the risk premium threshold. The `HubSpokeConfig` type describes each config. ```ts title="HubSpokeConfig" interface HubSpokeConfig { __typename: "HubSpokeConfig"; hub: Hub; spoke: Spoke; asset: HubAsset; supplyCap: Erc20Amount; borrowCap: Erc20Amount; active: boolean; halted: boolean; riskPremiumThreshold: PercentNumber; } ``` ```graphql title="HubSpokeConfig" fragment HubSpokeConfig on HubSpokeConfig { __typename hub { ...Hub } spoke { ...Spoke } asset { ...HubAsset } supplyCap { ...Erc20Amount } borrowCap { ...Erc20Amount } active halted riskPremiumThreshold { ...PercentNumber } } ``` Use the `useHubSpokeConfigs` hook in React, the `hubSpokeConfigs` action in TypeScript, or the `hubSpokeConfigs` query in GraphQL to fetch all asset configs shared by a hub and spoke. ```tsx title="Loading State" import { type HubId, type SpokeId, useHubSpokeConfigs } from "@aave/react"; function HubSpokeConfigs({ hubId, spokeId }: { hubId: HubId; spokeId: SpokeId }) { const { data, loading, error } = useHubSpokeConfigs({ hubId, spokeId }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
    {data.map((config) => (
  • {config.asset.underlying.info.symbol}: {config.active ? "Active" : "Inactive"}
  • ))}
); } ``` ```tsx title="React Suspense" import { type HubId, type SpokeId, useHubSpokeConfigs } from "@aave/react"; function HubSpokeConfigs({ hubId, spokeId }: { hubId: HubId; spokeId: SpokeId }) { const { data } = useHubSpokeConfigs({ suspense: true, hubId, spokeId, }); return (
    {data.map((config) => (
  • {config.asset.underlying.info.symbol}: {config.active ? "Active" : "Inactive"}
  • ))}
); } ```
```ts title="Hub Spoke Configs" import { hubId, spokeId } from "@aave/client"; import { hubSpokeConfigs } from "@aave/client/actions"; import { client } from "./client"; const result = await hubSpokeConfigs(client, { hubId: hubId("SGVsbG8h"), spokeId: spokeId("SGVsbG8h"), }); if (result.isOk()) { console.log(result.value); // HubSpokeConfig[] } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="HubSpokeConfigs" query { hubSpokeConfigs(request: { hubId: "SGVsbG8h", spokeId: "SGVsbG8h" }) { hub { name } spoke { name } asset { underlying { info { symbol } } } supplyCap { amount { value } } borrowCap { amount { value } } active halted riskPremiumThreshold { value } } } ```
## Hub Assets Hub Assets are the ERC-20 tokens held by a given Hub. ### Hub Asset Data Structure Hub Asset data provides detailed information about each asset available on a Liquidity Hub, including: - Identification: id, onchainAssetId, underlying token details - Hub reference: the hub where this asset is available - Summary metrics: supplied/borrowed amounts, APY rates, utilization - Reserve coverage: total connected reserves and active reserves - Settings: fee receiver, liquidity fees, strategies - User state: user’s balance (when user is specified in request) ```ts title="HubAsset" interface HubAsset { __typename: "HubAsset"; id: HubAssetId; onchainAssetId: OnChainHubAssetId; hub: Hub; underlying: Erc20Token; summary: HubAssetSummary; settings: HubAssetSettings; userState: HubAssetUserState | null; } ``` ```ts title="HubAssetSummary" interface HubAssetSummary { __typename: "HubAssetSummary"; supplied: Erc20Amount; borrowed: Erc20Amount; availableLiquidity: Erc20Amount; supplyApy: PercentNumber; borrowApy: PercentNumber; netApy: PercentNumber; utilizationRate: PercentNumber; reservesCount: number; activeReservesCount: number; } ``` ```ts title="HubAssetSettings" interface HubAssetSettings { __typename: "HubAssetSettings"; feeReceiver: EvmAddress; liquidityFee: PercentNumber; irStrategy: EvmAddress; reinvestmentController: EvmAddress | null; optimalUtilizationRate: PercentNumber; baseBorrowRate: PercentNumber; slopeBelowOptimal: PercentNumber; slopeAboveOptimal: PercentNumber; } ``` ```ts title="HubAssetUserState" interface HubAssetUserState { __typename: "HubAssetUserState"; balance: Erc20Amount; } ``` ```graphql title="HubAsset" fragment HubAsset on HubAsset { __typename id onchainAssetId hub { ...Hub } underlying { ...Erc20Token } summary { ...HubAssetSummary } settings { ...HubAssetSettings } userState { ...HubAssetUserState } } ``` ```graphql title="HubAssetSummary" fragment HubAssetSummary on HubAssetSummary { __typename supplied { ...Erc20Amount } borrowed { ...Erc20Amount } availableLiquidity { ...Erc20Amount } supplyApy { ...PercentNumber } borrowApy { ...PercentNumber } netApy { ...PercentNumber } utilizationRate { ...PercentNumber } reservesCount activeReservesCount } ``` ```graphql title="HubAssetSettings" fragment HubAssetSettings on HubAssetSettings { __typename feeReceiver liquidityFee { ...PercentNumber } irStrategy reinvestmentController optimalUtilizationRate { ...PercentNumber } baseBorrowRate { ...PercentNumber } slopeBelowOptimal { ...PercentNumber } slopeAboveOptimal { ...PercentNumber } } ``` ```graphql title="HubAssetUserState" fragment HubAssetUserState on HubAssetUserState { __typename balance { ...Erc20Amount } } ``` ```solidity title="Asset Struct" struct Asset { uint120 liquidity; uint120 realizedFees; uint8 decimals; uint120 addedShares; uint120 swept; int200 premiumOffsetRay; uint120 drawnShares; uint120 premiumShares; uint16 liquidityFee; uint120 drawnIndex; uint96 drawnRate; uint40 lastUpdateTimestamp; address underlying; address irStrategy; address reinvestmentController; address feeReceiver; uint200 deficitRay; } ``` ```solidity title="AssetConfig Struct" struct AssetConfig { address feeReceiver; uint16 liquidityFee; address irStrategy; address reinvestmentController; } ``` ### Listing Hub Assets Discover all available assets on a Hub, including their liquidity metrics, APY rates, and user-specific data. Use the `useHubAssets` hook in React, the `hubAssets` action in TypeScript, or the `hubAssets` query in GraphQL to fetch assets for a specific hub. In Solidity, assets within the hub are assigned sequential `assetId` values starting from 0. For reference, here’s a complete function to retrieve all Hub Assets. ```tsx title="Loading State" import { type HubAssetsRequest, useHubAssets } from "@aave/react"; function HubAssetsList({ request }: { request: HubAssetsRequest }) { const { data, loading, error } = useHubAssets(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((asset) => (

{asset.underlying.info.name}

Hub: {asset.hub.name}
))}
); } ``` ```tsx title="React Suspense" import { type HubAssetsRequest, useHubAssets } from "@aave/react"; function HubAssetsList({ request }: { request: HubAssetsRequest }) { const { data } = useHubAssets({ ...request, suspense: true, }); return (
{data.map((asset) => (

{asset.underlying.info.name}

Hub: {asset.hub.name}
))}
); } ```
```ts title="By Hub ID" import { hubId } from "@aave/client"; import { hubAssets } from "@aave/client/actions"; import { client } from "./client"; const id = hubId("SGVsbG8h"); const result = await hubAssets(client, { query: { hubId: id, }, }); if (result.isOk()) { console.log(result.value); // HubAsset[] } else { console.error(result.error); } ``` ```ts title="By Hub Details" import { chainId, evmAddress } from "@aave/client"; import { hubAssets } from "@aave/client/actions"; import { client } from "./client"; const result = await hubAssets(client, { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; import { hubAssets } from "@aave/client/actions"; import { client } from "./client"; const result = await hubAssets( client, { query: { // your query criteria }, }, { currency: Currency.Eur, }, ); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="By Hub ID" query { hubAssets(request: { query: { hubId: "SGVsbG8h" } }) { id onchainAssetId hub { ...Hub } underlying { ...Erc20Token } summary { ...HubAssetSummary } settings { ...HubAssetSettings } userState { ...HubAssetUserState } } } ``` ```graphql title="By Hub Details" query { hubAssets( request: { query: { hubInput: { address: "0x123…", chainId: 1 } } } ) { id onchainAssetId hub { ...Hub } underlying { ...Erc20Token } summary { ...HubAssetSummary } settings { ...HubAssetSettings } userState { ...HubAssetUserState } } } ``` ```graphql title="Custom Currency" query { hubAssets(request: { query: { hubId: "SGVsbG8h" } }) { id onchainAssetId hub { ...Hub } underlying { ...Erc20Token } summary(currency: EUR) { ...HubAssetSummary } } } ``` ```graphql title="User State" query { hubAssets(request: { query: { hubId: "SGVsbG8h" }, user: "0x456…" }) { id onchainAssetId hub { ...Hub } underlying { ...Erc20Token } summary { ...HubAssetSummary } userState { ...HubAssetUserState } } } ``` ```solidity title="Get All Hub Assets" import { IHub } from "aave-v4/src/hub/interfaces/IHub.sol"; contract HubReader { function getHubAssets( address hubAddress ) external view returns (IHub.Asset[] memory) { IHub hub = IHub(hubAddress); uint256 assetCount = hub.getAssetCount(); IHub.Asset[] memory assets = new IHub.Asset[](assetCount); for (uint256 assetId = 0; assetId < assetCount; assetId++) { assets[assetId] = hub.getAsset(assetId); } return assets; } } ```
In React, see below for examples of `HubAssetsRequest` objects. ```tsx title="By Hub ID" const request: HubAssetsRequest = { query: { hubId: hub.id, // hub.id: HubId from component props or previous query }, }; ``` ```tsx title="By Hub Details" import { chainId, evmAddress } from "@aave/react"; const request: HubAssetsRequest = { query: { hubInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` In React and TypeScript, you can add a user address to return `HubAssetUserState` for each asset. ```tsx title="Hub Asset User State" import { evmAddress } from "@aave/react"; const request: HubAssetsRequest = { query: { // your query criteria }, user: evmAddress("0x456…"), }; ``` ```ts title="Hub Asset User State" import { evmAddress } from "@aave/client"; import { hubAssets } from "@aave/client/actions"; import { client } from "./client"; const result = await hubAssets(client, { query: { // your query criteria }, user: evmAddress("0x456…"), }); ``` In React, you can also specify a different currency for the data. ```tsx title="Custom Currency" import { Currency } from "@aave/react"; // … const { data, loading, error } = useHubAssets({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ### Interest Rate Model The interest rate model describes how supply and borrow rates change across the utilization range for a specific Hub Asset. Each data point includes the utilization rate, the corresponding borrow and supply rates, and the liquidity distance from the current state. ```ts title="HubAssetInterestRateModelPoint" interface HubAssetInterestRateModelPoint { __typename: "HubAssetInterestRateModelPoint"; utilizationRate: PercentNumber; borrowRate: PercentNumber; supplyRate: PercentNumber; liquidityDistance: Erc20Amount; } ``` ```graphql title="HubAssetInterestRateModelPoint" fragment HubAssetInterestRateModelPoint on HubAssetInterestRateModelPoint { __typename utilizationRate { ...PercentNumber } borrowRate { ...PercentNumber } supplyRate { ...PercentNumber } liquidityDistance { ...Erc20Amount } } ``` Fetch the full interest rate curve for a specific Hub Asset. Use the `useHubAssetInterestRateModel` hook to fetch the interest rate curve for a Hub Asset. ```tsx title="Loading State" import { useHubAssetInterestRateModel } from "@aave/react"; function InterestRateModel({ hubAssetId }: { hubAssetId: HubAssetId }) { const { data, loading, error } = useHubAssetInterestRateModel({ query: { hubAssetId }, }); if (loading) return Loading…; if (error) return Error: {error.message}; return (
{data?.map((point, i) => (
Utilization: {point.utilizationRate.normalized.toFixed(2)}% Borrow Rate: {point.borrowRate.normalized.toFixed(2)}% Supply Rate: {point.supplyRate.normalized.toFixed(2)}%
))}
); } ``` ```tsx title="React Suspense" import { useHubAssetInterestRateModel } from "@aave/react"; function InterestRateModel({ hubAssetId }: { hubAssetId: HubAssetId }) { const { data } = useHubAssetInterestRateModel({ suspense: true, query: { hubAssetId }, }); return (
{data.map((point, i) => (
Utilization: {point.utilizationRate.normalized.toFixed(2)}% Borrow Rate: {point.borrowRate.normalized.toFixed(2)}% Supply Rate: {point.supplyRate.normalized.toFixed(2)}%
))}
); } ```
Use the `hubAssetInterestRateModel` action to fetch the interest rate curve. ```ts title="By Hub Asset ID" import { type HubAssetId } from "@aave/client"; import { hubAssetInterestRateModel } from "@aave/client/actions"; import { client } from "./client"; // const hubAssetId: HubAssetId = "…"; // from a previous query const result = await hubAssetInterestRateModel(client, { query: { hubAssetId }, }); if (result.isOk()) { for (const point of result.value) { console.log( point.utilizationRate.value, point.borrowRate.value, point.supplyRate.value, ); } } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` Use the `hubAssetInterestRateModel` query to fetch the interest rate curve. ```graphql title="By Hub Asset ID" query { hubAssetInterestRateModel(request: { query: { hubAssetId: "…" } }) { points { utilizationRate { ...PercentNumber } borrowRate { ...PercentNumber } supplyRate { ...PercentNumber } liquidityDistance { ...Erc20Amount } } } } ```
--- Source: https://aave.com/docs/aave-v4/liquidity/assets.md # Aave V4 Assets Assets represent ERC-20 tokens that can be supplied or borrowed within Aave V4. ## Asset Data Structure Asset data describes a specific token in the protocol: - Token identification: id, address, symbol, name, decimals - Aggregate metrics: total supplied, total borrowed, caps, and available amounts - Reserve coverage: total number of reserves and how many are active - Current price: exchange valuation for a specific currency The following TypeScript interfaces illustrate the core Asset types: ```ts title="Asset" interface Asset { __typename: "Asset"; id: AssetId; token: Erc20Token; summary: AssetSummary; price: ExchangeAmountWithChange; } ``` ```ts title="AssetSummary" interface AssetSummary { __typename: "AssetSummary"; totalSupplyCap: AssetAmountWithChange; totalSupplied: AssetAmountWithChange; totalSuppliable: AssetAmountWithChange; totalBorrowCap: AssetAmountWithChange; totalBorrowed: AssetAmountWithChange; totalBorrowable: AssetAmountWithChange; reservesCount: number; activeReservesCount: number; averageSupplyApy: PercentNumber; averageBorrowApy: PercentNumber; } ``` ```ts title="Erc20Token" interface Erc20Token { __typename: "Erc20Token"; info: TokenInfo; address: EvmAddress; chain: Chain; isWrappedNativeToken: boolean; } ``` ```ts title="Others" interface DecimalNumberWithChange { __typename: "DecimalNumberWithChange"; current: DecimalNumber; change: PercentNumber; } interface ExchangeAmountWithChange { __typename: "ExchangeAmountWithChange"; current: ExchangeAmount; change: PercentNumber; } interface AssetAmountWithChange { __typename: "AssetAmountWithChange"; amount: DecimalNumberWithChange; exchange: ExchangeAmountWithChange; } ``` The following GraphQL fragments illustrate the core Asset types: ```graphql title="Asset" fragment Asset on Asset { __typename id token { ...Erc20Token } summary { ...AssetSummary } price { ...ExchangeAmountWithChange } } ``` ```graphql title="AssetSummary" fragment AssetSummary on AssetSummary { __typename totalSupplyCap { ...AssetAmountWithChange } totalSupplied { ...AssetAmountWithChange } totalSuppliable { ...AssetAmountWithChange } totalBorrowCap { ...AssetAmountWithChange } totalBorrowed { ...AssetAmountWithChange } totalBorrowable { ...AssetAmountWithChange } reservesCount activeReservesCount averageSupplyApy: supplyApy(metric: AVERAGE) { ...PercentNumber } averageBorrowApy: borrowApy(metric: AVERAGE) { ...PercentNumber } } ``` ```graphql title="Erc20Token" fragment Erc20Token on Erc20Token { __typename info { ...TokenInfo } address chain { ...Chain } isWrappedNativeToken } ``` ```graphql title="Others" fragment AssetAmountWithChange on AssetAmountWithChange { __typename amount { ...DecimalNumberWithChange } exchange(currency: $currency) { ...ExchangeAmountWithChange } } fragment DecimalNumberWithChange on DecimalNumberWithChange { __typename current { ...DecimalNumber } change(window: $timeWindow) { ...PercentNumber } } fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change(window: $timeWindow) { ...PercentNumber } } ``` ## Fetching Asset Information Query detailed information about a specific asset. Use the `useAsset` hook in React, the `asset` action in TypeScript, or the `asset` query in GraphQL to fetch asset information. ```tsx title="Loading State" import { type AssetRequest, useAsset } from "@aave/react"; function AssetDetails({ request }: { request: AssetRequest }) { const { data, loading, error } = useAsset(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (!data) return
Asset not found
; return (

{data.token.info.name}

Chain: {data.token.chain.name}
); } ``` ```tsx title="React Suspense" import { type AssetRequest, useAsset } from "@aave/react"; function AssetDetails({ request }: { request: AssetRequest }) { const { data } = useAsset({ ...request, suspense: true, }); if (!data) return
Asset not found
; return (

{data.token.info.name}

Chain: {data.token.chain.name}
); } ```
```ts title="By Token Details" import { chainId, evmAddress } from "@aave/client"; import { asset } from "@aave/client/actions"; import { client } from "./client"; const result = await asset(client, { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); if (result.isOk()) { console.log(result.value); // Asset | null - null if not found } else { console.error(result.error); } ``` ```ts title="By Asset ID" import { type AssetId } from "@aave/client"; import { asset } from "@aave/client/actions"; import { client } from "./client"; // const assetId: AssetId = "SGVsbG8h"; const result = await asset(client, { query: { assetId, }, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; import { asset } from "@aave/client/actions"; import { client } from "./client"; const result = await asset( client, { query: { // your query criteria }, }, { currency: Currency.Eur, }, ); ``` ```graphql title="Query" query ( $request: AssetRequest! $currency: Currency! = USD $timeWindow: TimeWindow! = LAST_DAY ) { value: asset(request: $request) { id token { ...Erc20Token } summary { ...AssetSummary } price(currency: $currency) { ...ExchangeAmountWithChange } } } ``` ```graphql title="AssetSummary" fragment AssetSummary on AssetSummary { __typename totalSupplyCap { ...AssetAmountWithChange } totalSupplied { ...AssetAmountWithChange } totalSuppliable { ...AssetAmountWithChange } totalBorrowCap { ...AssetAmountWithChange } totalBorrowed { ...AssetAmountWithChange } totalBorrowable { ...AssetAmountWithChange } reservesCount activeReservesCount averageSupplyApy: supplyApy(metric: AVERAGE) { ...PercentNumber } averageBorrowApy: borrowApy(metric: AVERAGE) { ...PercentNumber } } ``` ```graphql title="Erc20Token" fragment Erc20Token on Erc20Token { __typename info { ...TokenInfo } address chain { ...Chain } isWrappedNativeToken } ``` ```graphql title="Others" fragment AssetAmountWithChange on AssetAmountWithChange { __typename amount { ...DecimalNumberWithChange } exchange(currency: $currency) { ...ExchangeAmountWithChange } } fragment DecimalNumberWithChange on DecimalNumberWithChange { __typename current { ...DecimalNumber } change(window: $timeWindow) { ...PercentNumber } } fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change(window: $timeWindow) { ...PercentNumber } } fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ```
See below for examples of `AssetRequest` objects in React. In GraphQL, specify the asset ID or token address and chain ID. ```tsx title="By Token Details" import { chainId, evmAddress } from "@aave/react"; const request: AssetRequest = { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```tsx title="By Asset ID" import { assetId } from "@aave/react"; const request: AssetRequest = { query: { assetId: assetId(params.id), // AssetId - typically from URL params }, }; ``` ```json title="By Token Details" { "request": { "query": { "token": { "address": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "chainId": 1 } } } } ``` ```json title="By Asset ID" { "request": { "query": { "assetId": "SGVsbG8h" } } } ``` ```jsonc title="Custom Currency" { "request": { "query": { // your query criteria } }, "currency": "EUR" } ``` Finally, in React and TypeScript, you can specify a different time window or currency for the data. ```ts title="Custom Time Window" import { TimeWindow } from "@aave/react"; // … const { data, loading, error } = useAsset({ query: { // your query criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; // … const { data, loading, error } = useAsset({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ```ts title="Custom Time Window" import { TimeWindow } from "@aave/client"; import { asset } from "@aave/client/actions"; import { client } from "./client"; const result = await asset( client, { query: , }, { timeWindow: TimeWindow.LastWeek }, ); ``` ## Multichain Asset A multichain asset aggregates a single token across every chain where it is listed as a Hub Asset. Tokens are grouped by their _canonical symbol_ (the case-insensitive, alias-resolved symbol that identifies the same asset across chains), so you can show protocol-wide totals and APY ranges without querying each chain separately. ### Data Structure A multichain asset exposes the per-chain [`Asset`](#asset-data-structure) list alongside an aggregated summary. The following TypeScript interfaces illustrate the core multichain asset types: ```ts title="MultichainAsset" interface MultichainAsset { __typename: "MultichainAsset"; assets: Asset[]; summary: MultichainAssetSummary; } ``` ```ts title="MultichainAssetSummary" interface MultichainAssetSummary { __typename: "MultichainAssetSummary"; totalSupplied: ExchangeAmount; totalBorrowed: ExchangeAmount; totalSupplyCap: ExchangeAmount; totalBorrowCap: ExchangeAmount; totalAvailableLiquidity: ExchangeAmount; utilizationRate: PercentNumber; highestSupplyApy: PercentNumber; lowestSupplyApy: PercentNumber; averageSupplyApy: PercentNumber; highestBorrowApy: PercentNumber; lowestBorrowApy: PercentNumber; averageBorrowApy: PercentNumber; chainCount: number; reservesCount: number; activeReservesCount: number; } ``` The following GraphQL fragments illustrate the core multichain asset types: ```graphql title="MultichainAsset" fragment MultichainAsset on MultichainAsset { __typename assets { ...Asset } summary { ...MultichainAssetSummary } } ``` ```graphql title="MultichainAssetSummary" fragment MultichainAssetSummary on MultichainAssetSummary { __typename totalSupplied { ...ExchangeAmount } totalBorrowed { ...ExchangeAmount } totalSupplyCap { ...ExchangeAmount } totalBorrowCap { ...ExchangeAmount } totalAvailableLiquidity { ...ExchangeAmount } utilizationRate { ...PercentNumber } highestSupplyApy { ...PercentNumber } lowestSupplyApy { ...PercentNumber } averageSupplyApy { ...PercentNumber } highestBorrowApy { ...PercentNumber } lowestBorrowApy { ...PercentNumber } averageBorrowApy { ...PercentNumber } chainCount reservesCount activeReservesCount } ``` ### Fetching a Multichain Asset Select the token with exactly one of `symbol` or `tokenInfo`. Omit `chainIds` to aggregate across all chains, or pass a list to restrict the result. Use the `useMultichainAsset` hook in React, the `multichainAsset` action in TypeScript, or the `multichainAsset` query in GraphQL to fetch an asset aggregated across chains. ```tsx title="Loading State" import { useMultichainAsset } from "@aave/react"; function MultichainAssetSummary() { const { data, loading, error } = useMultichainAsset({ query: { symbol: "USDC" }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
Deployed on {data.summary.chainCount} chains

Total supplied: {data.summary.totalSupplied.value.toDisplayString(2)} {data.summary.totalSupplied.symbol}

); } ``` ```tsx title="React Suspense" import { useMultichainAsset } from "@aave/react"; function MultichainAssetSummary() { const { data } = useMultichainAsset({ query: { symbol: "USDC" }, suspense: true, }); return Deployed on {data.summary.chainCount} chains; } ```
```ts title="By Symbol" import { multichainAsset } from "@aave/client/actions"; import { client } from "./client"; const result = await multichainAsset(client, { query: { symbol: "USDC" }, }); if (result.isOk()) { console.log(result.value); // MultichainAsset } else { console.error(result.error); } ``` ```ts title="Restrict to Chains" import { chainId } from "@aave/client"; import { multichainAsset } from "@aave/client/actions"; import { client } from "./client"; const result = await multichainAsset(client, { query: { symbol: "USDC" }, chainIds: [chainId(1), chainId(43114)], }); ``` ```graphql title="Query" query ( $request: MultichainAssetRequest! $currency: Currency! = USD $timeWindow: TimeWindow! = LAST_DAY ) { value: multichainAsset(request: $request) { ...MultichainAsset } } ```
See below for examples of `MultichainAssetRequest` objects in React. In GraphQL, provide exactly one of `symbol` or `tokenInfo` in `query`, and optionally restrict the result with `chainIds`. ```tsx title="By Symbol" const request: MultichainAssetRequest = { query: { symbol: "USDC", }, }; ``` ```tsx title="By Token Info ID" const request: MultichainAssetRequest = { query: { tokenInfo: tokenInfo.id, // tokenInfo: TokenInfo }, }; ``` ```tsx title="Restrict to Chains" import { chainId } from "@aave/react"; const request: MultichainAssetRequest = { query: { symbol: "USDC", }, chainIds: [chainId(1), chainId(43114)], }; ``` ```json title="By Symbol" { "request": { "query": { "symbol": "USDC" } } } ``` ```json title="Restrict to Chains" { "request": { "query": { "symbol": "USDC" }, "chainIds": [1, 43114] } } ``` By default, Merkl rewards are included in the APY range. Pass `includeRewards: false` for protocol base rates only. ```tsx title="Protocol APYs Only" const request: MultichainAssetRequest = { query: { symbol: "USDC" }, includeRewards: false, }; ``` ```ts title="Protocol APYs Only" import { multichainAsset } from "@aave/client/actions"; import { client } from "./client"; const result = await multichainAsset(client, { query: { symbol: "USDC" }, includeRewards: false, }); ``` ```json title="Protocol APYs Only" { "request": { "query": { "symbol": "USDC" }, "includeRewards": false } } ``` ## Asset Price History Asset price history data provides time-series price information for an asset. Use the `useAssetPriceHistory` hook in React, the `assetPriceHistory` action in TypeScript, or the `assetPriceHistory` query in GraphQL to fetch historical price data. ```tsx title="Loading State" import { type AssetPriceHistoryRequest, useAssetPriceHistory, } from "@aave/react"; function AssetPrice({ request }: { request: AssetPriceHistoryRequest }) { const { data, loading, error } = useAssetPriceHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()}$ {sample.price.toFixed(2)}

))}
); } ``` ```tsx title="React Suspense" import { type AssetPriceHistoryRequest, useAssetPriceHistory, } from "@aave/react"; function AssetPrice({ request }: { request: AssetPriceHistoryRequest }) { const { data } = useAssetPriceHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()}$ {sample.price.toFixed(2)}

))}
); } ```
```ts title="By Asset ID" import { Currency, TimeWindow } from "@aave/client"; import { assetPriceHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetPriceHistory(client, { query: { assetId: asset.id, }, currency: Currency.Usd, window: TimeWindow.LastWeek, }); ``` ```ts title="By Token Details" import { chainId, evmAddress, Currency, TimeWindow } from "@aave/client"; import { assetPriceHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetPriceHistory(client, { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, currency: Currency.Usd, window: TimeWindow.LastWeek, }); ``` ```graphql title="Query" query ($request: AssetPriceHistoryRequest!) { value: assetPriceHistory(request: $request) { date price } } ```
See below for examples of `AssetPriceHistoryRequest` objects in React. In GraphQL, specify the asset ID or token, currency, and time window. ```tsx title="By Asset ID" const request: AssetPriceHistoryRequest = { query: { assetId: asset.id, }, }; ``` ```tsx title="By Token Details" import { chainId, evmAddress } from "@aave/react"; const request: AssetPriceHistoryRequest = { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```json title="By Asset ID" { "request": { "query": { "assetId": "SGVsbG8h" }, "currency": "USD", "window": "LAST_WEEK" } } ``` ```json title="By Token Details" { "request": { "query": { "token": { "address": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "chainId": 1 } }, "currency": "USD", "window": "LAST_WEEK" } } ``` Finally, in React, you can specify a different currency or time window for the data. ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, error, loading } = useAssetPriceHistory({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useAssetPriceHistory({ query: { // your query criteria }, window: TimeWindow.LastMonth, }); ``` ## Asset Supply History Asset supply history data provides time-series total supply information for an asset. Use the `useAssetSupplyHistory` hook in React, the `assetSupplyHistory` action in TypeScript, or the `assetSupplyHistory` query in GraphQL to fetch historical supply data. ```tsx title="Loading State" import { type AssetSupplyHistoryRequest, useAssetSupplyHistory, } from "@aave/react"; function AssetSupply({ request }: { request: AssetSupplyHistoryRequest }) { const { data, loading, error } = useAssetSupplyHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.amount.value.toDisplayString(2)}

))}
); } ``` ```tsx title="React Suspense" import { type AssetSupplyHistoryRequest, useAssetSupplyHistory, } from "@aave/react"; function AssetSupply({ request }: { request: AssetSupplyHistoryRequest }) { const { data } = useAssetSupplyHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.amount.value.toDisplayString(2)}

))}
); } ```
```ts title="By Asset ID" import { TimeWindow } from "@aave/client"; import { assetSupplyHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetSupplyHistory(client, { query: { assetId: asset.id, }, window: TimeWindow.LastWeek, }); ``` ```ts title="By Token Details" import { chainId, evmAddress, TimeWindow } from "@aave/client"; import { assetSupplyHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetSupplyHistory(client, { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, window: TimeWindow.LastWeek, }); ``` ```graphql title="Query" query ($request: AssetSupplyHistoryRequest!) { value: assetSupplyHistory(request: $request) { date amount { ...DecimalNumber } highestApy { ...PercentNumber } lowestApy { ...PercentNumber } averageApy { ...PercentNumber } breakdown { ...AssetSampleBreakdown } } } ``` ```graphql title="AssetSampleBreakdown" fragment AssetSampleBreakdown on AssetSampleBreakdown { __typename amount { ...DecimalNumber } apy { ...PercentNumber } hub { ...Hub } } ``` ```graphql title="Hub" fragment Hub on Hub { __typename id address chain { ...Chain } name } ```
See below for examples of `AssetSupplyHistoryRequest` objects in React. In GraphQL, specify the asset ID or token and time window. ```tsx title="By Asset ID" const request: AssetSupplyHistoryRequest = { query: { assetId: asset.id, }, }; ``` ```tsx title="By Token Details" import { chainId, evmAddress } from "@aave/react"; const request: AssetSupplyHistoryRequest = { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```json title="By Asset ID" { "request": { "query": { "assetId": "SGVsbG8h" }, "window": "LAST_WEEK" } } ``` ```json title="By Token Details" { "request": { "query": { "token": { "address": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "chainId": 1 } }, "window": "LAST_WEEK" } } ``` Finally, in React, you can specify a different time window for the data. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useAssetSupplyHistory({ query: { // your query criteria }, window: TimeWindow.LastMonth, }); ``` ## Asset Borrow History Asset borrow history data provides time-series total borrow information for an asset. Use the `useAssetBorrowHistory` hook in React, the `assetBorrowHistory` action in TypeScript, or the `assetBorrowHistory` query in GraphQL to fetch historical borrow data. ```tsx title="Loading State" import { type AssetBorrowHistoryRequest, useAssetBorrowHistory, } from "@aave/react"; function AssetBorrow({ request }: { request: AssetBorrowHistoryRequest }) { const { data, loading, error } = useAssetBorrowHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.amount.value.toDisplayString(2)}

))}
); } ``` ```tsx title="React Suspense" import { type AssetBorrowHistoryRequest, useAssetBorrowHistory, } from "@aave/react"; function AssetBorrow({ request }: { request: AssetBorrowHistoryRequest }) { const { data } = useAssetBorrowHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.amount.value.toDisplayString(2)}

))}
); } ```
```ts title="By Asset ID" import { TimeWindow } from "@aave/client"; import { assetBorrowHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetBorrowHistory(client, { query: { assetId: asset.id, }, window: TimeWindow.LastWeek, }); ``` ```ts title="By Token Details" import { chainId, evmAddress, TimeWindow } from "@aave/client"; import { assetBorrowHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await assetBorrowHistory(client, { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, window: TimeWindow.LastWeek, }); ``` ```graphql title="Query" query ($request: AssetBorrowHistoryRequest!) { value: assetBorrowHistory(request: $request) { date amount { ...DecimalNumber } highestApy { ...PercentNumber } lowestApy { ...PercentNumber } averageApy { ...PercentNumber } breakdown { ...AssetSampleBreakdown } } } ``` ```graphql title="AssetSampleBreakdown" fragment AssetSampleBreakdown on AssetSampleBreakdown { __typename amount { ...DecimalNumber } apy { ...PercentNumber } hub { ...Hub } } ``` ```graphql title="Hub" fragment Hub on Hub { __typename id address chain { ...Chain } name } ```
See below for examples of `AssetBorrowHistoryRequest` objects in React. In GraphQL, specify the asset ID or token and time window. ```tsx title="By Asset ID" const request: AssetBorrowHistoryRequest = { query: { assetId: asset.id, }, }; ``` ```tsx title="By Token Details" import { chainId, evmAddress } from "@aave/react"; const request: AssetBorrowHistoryRequest = { query: { token: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```json title="By Asset ID" { "request": { "query": { "assetId": "SGVsbG8h" }, "window": "LAST_WEEK" } } ``` ```json title="By Token Details" { "request": { "query": { "token": { "address": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "chainId": 1 } }, "window": "LAST_WEEK" } } ``` Finally, in React, you can specify a different time window for the data. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useAssetBorrowHistory({ query: { // your query criteria }, window: TimeWindow.LastMonth, }); ``` ## Protocol History Fetch protocol-wide historical data (deposits, borrows). Pass `chainIds` to scope the history to specific chains, or omit it to aggregate across all of them. Use the `useProtocolHistory` hook in React, the `protocolHistory` action in TypeScript, or the `protocolHistory` query in GraphQL to fetch protocol-wide historical data. ```tsx title="Loading State" import { type ProtocolHistoryRequest, useProtocolHistory } from "@aave/react"; function ProtocolHistory({ request }: { request: ProtocolHistoryRequest }) { const { data, loading, error } = useProtocolHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} Deposits {sample.deposits.symbol} {sample.deposits.value.toDisplayString(2)} Borrows {sample.borrows.symbol} {sample.borrows.value.toDisplayString(2)}

))}
); } ``` ```tsx title="React Suspense" import { type ProtocolHistoryRequest, useProtocolHistory } from "@aave/react"; function ProtocolHistory({ request }: { request: ProtocolHistoryRequest }) { const { data } = useProtocolHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} Deposits {sample.deposits.symbol} {sample.deposits.value.toDisplayString(2)} Borrows {sample.borrows.symbol} {sample.borrows.value.toDisplayString(2)}

))}
); } ```
```ts title="Protocol History" import { chainId, Currency, TimeWindow } from "@aave/client"; import { protocolHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await protocolHistory(client, { currency: Currency.Usd, window: TimeWindow.LastWeek, chainIds: [chainId(1), chainId(43114)], }); if (result.isOk()) { console.log(result.value); // ProtocolHistorySample[] } else { console.error(result.error); } ``` ```graphql title="Query" query ($request: ProtocolHistoryRequest!) { value: protocolHistory(request: $request) { date deposits { ...ExchangeAmount } borrows { ...ExchangeAmount } } } ``` ```graphql title="ExchangeAmount" fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ```
In GraphQL, specify currency and time window. ```json title="Protocol History Request" { "request": { "currency": "USD", "window": "LAST_WEEK", "chainIds": [1, 43114] } } ``` --- Source: https://aave.com/docs/aave-v4/liquidity/spokes.md # Aave V4 Spokes Spokes are the modules users interact with; each Spoke draws liquidity from one or more Liquidity Hubs. ## Spoke Data Structure Spoke data provide information about individual borrowing modules, including: - Identification: id, name, address, chain - Liquidation parameters: target health factor, max-bonus threshold, and bonus factor (`liquidationConfig`) - Summary metrics: supplied, borrowed, supply and borrow caps, connected Hubs, and unique assets The following TypeScript interfaces and GraphQL fragments illustrate the core Spoke type. In Solidity, Spokes are deployed contracts implementing the `ISpoke` interface, managed by governance, and the following structs illustrate the Spoke data. ```ts title="Spoke" interface Spoke { __typename: "Spoke"; id: SpokeId; name: string; address: EvmAddress; chain: Chain; liquidationConfig: SpokeLiquidationConfig | null; summary: SpokeSummary; connectedHubs: SpokeConnectedHub[]; } ``` ```ts title="SpokeLiquidationConfig" interface SpokeLiquidationConfig { __typename: "SpokeLiquidationConfig"; targetHealthFactor: BigDecimal; healthFactorForMaxBonus: BigDecimal; liquidationBonusFactor: PercentNumber; } ``` ```ts title="SpokeSummary" interface SpokeSummary { __typename: "SpokeSummary"; totalBorrowed: ExchangeAmount; totalBorrowCap: ExchangeAmount; totalSupplied: ExchangeAmount; totalSupplyCap: ExchangeAmount; uniqueAssets: number; connectedHubs: number; } ``` ```ts title="SpokeConnectedHub" interface SpokeConnectedHub { __typename: "SpokeConnectedHub"; hub: Hub; summary: SpokeConnectedHubSummary; } ``` ```ts title="SpokeConnectedHubSummary" interface SpokeConnectedHubSummary { __typename: "SpokeConnectedHubSummary"; totalBorrowed: ExchangeAmount; totalSupplied: ExchangeAmount; creditLine: ExchangeAmount; creditUsed: PercentNumber; } ``` ```ts title="Chain" interface Chain { __typename: "Chain"; chainId: ChainId; name: string; icon: string; rpcUrl: string; explorerUrl: string; isTestnet: boolean; nativeWrappedToken: EvmAddress; nativeInfo: TokenInfo; nativeGateway: EvmAddress; signatureGateway: EvmAddress; } ``` ```ts title="TokenInfo" interface TokenInfo { __typename: "TokenInfo"; id: TokenInfoId; name: string; symbol: string; canonicalSymbol: string; icon: string; decimals: number; categories: TokenCategory[]; } ``` ```graphql title="Spoke" fragment Spoke on Spoke { __typename id name address chain { ...Chain } liquidationConfig { ...SpokeLiquidationConfig } summary(currency: $currency) { ...SpokeSummary } connectedHubs(currency: $currency) { ...SpokeConnectedHub } } ``` ```graphql title="SpokeLiquidationConfig" fragment SpokeLiquidationConfig on SpokeLiquidationConfig { __typename targetHealthFactor healthFactorForMaxBonus liquidationBonusFactor { ...PercentNumber } } ``` ```graphql title="SpokeSummary" fragment SpokeSummary on SpokeSummary { __typename totalBorrowed { ...ExchangeAmount } totalBorrowCap { ...ExchangeAmount } totalSupplied { ...ExchangeAmount } totalSupplyCap { ...ExchangeAmount } uniqueAssets connectedHubs } ``` ```graphql title="SpokeConnectedHub" fragment SpokeConnectedHub on SpokeConnectedHub { __typename hub { ...Hub } summary { ...SpokeConnectedHubSummary } } ``` ```graphql title="SpokeConnectedHubSummary" fragment SpokeConnectedHubSummary on SpokeConnectedHubSummary { __typename totalBorrowed { ...ExchangeAmount } totalSupplied { ...ExchangeAmount } creditLine { ...ExchangeAmount } creditUsed { ...PercentNumber } } ``` ```graphql title="Chain" fragment Chain on Chain { __typename chainId name icon rpcUrl explorerUrl isTestnet nativeWrappedToken nativeInfo { ...TokenInfo } nativeGateway signatureGateway } ``` ```graphql title="TokenInfo" fragment TokenInfo on TokenInfo { __typename id name symbol icon decimals categories } ``` ```solidity title="SpokeData Struct" struct SpokeData { uint120 drawnShares; uint120 premiumShares; int200 premiumOffsetRay; uint120 addedShares; uint40 addCap; uint40 drawCap; uint24 riskPremiumThreshold; bool active; bool halted; uint200 deficitRay; } ``` ```solidity title="SpokeConfig Struct" struct SpokeConfig { uint40 addCap; uint40 drawCap; uint24 riskPremiumThreshold; bool active; bool halted; } ``` In Solidity, the relationship between Spokes and Hubs is tracked onchain within the Hub contract. Each Spoke can connect to multiple Hub Assets, maintaining separate `SpokeData` state for each asset. Spoke connections and config updates emit these events: ```solidity title="Spoke Events" event AddSpoke(uint256 indexed assetId, address indexed spoke); event UpdateSpokeConfig(uint256 indexed assetId, address indexed spoke, SpokeConfig config); ``` ## Listing Available Spokes Discover all available Aave Spokes across supported networks. Use the `useSpokes` hook in React, the `spokes` action in TypeScript, or the `spokes` query in GraphQL to fetch a list of available spokes. ```tsx title="Loading State" import { type SpokesRequest, useSpokes } from "@aave/react"; function SpokesList({ request }: { request: SpokesRequest }) { const { data, loading, error } = useSpokes(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((spoke) => (

{spoke.name}

Chain: {spoke.chain.name}
))}
); } ``` ```tsx title="React Suspense" import { type SpokesRequest, useSpokes } from "@aave/react"; function SpokesList({ request }: { request: SpokesRequest }) { const { data } = useSpokes({ ...request, suspense: true, }); return (
{data.map((spoke) => (

{spoke.name}

Chain: {spoke.chain.name}
))}
); } ```
```ts title="By Chains" import { chainId } from "@aave/client"; import { spokes } from "@aave/client/actions"; import { client } from "./client"; const result = await spokes(client, { query: { chainIds: [chainId(1)], }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: Spoke[] console.log(result.value); } ``` ```ts title="By Hub ID" import { spokes } from "@aave/client/actions"; import { client } from "./client"; // const hubId: HubId = "SGVsbG8h"; const result = await spokes(client, { query: { hubId, }, }); ``` ```ts title="By Hub Details" import { chainId, evmAddress } from "@aave/client"; import { spokes } from "@aave/client/actions"; import { client } from "./client"; const result = await spokes(client, { query: { hub: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```graphql title="By Chains" query { spokes(request: { query: { chainIds: [1] } }) { id name address chain { ...Chain } } } ``` ```graphql title="By Hub ID" query { spokes(request: { query: { hubId: "SGVsbG8h" } }) { id name address chain { ...Chain } } } ``` ```graphql title="By Hub Details" query { spokes(request: { query: { hub: { address: "0x123…", chainId: 1 } } }) { id name address chain { ...Chain } } } ```
In React, see below for examples of `SpokesRequest` objects. ```tsx title="By Chains" import { chainId } from "@aave/react"; const request: SpokesRequest = { query: { chainIds: [chainId(1)], }, }; ``` ```tsx title="By Hub ID" const request: SpokesRequest = { query: { hubId: hub.id, }, }; ``` ```tsx title="By Hub Details" import { chainId, evmAddress } from "@aave/react"; const request: SpokesRequest = { query: { hub: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ### Deployed Spokes In Solidity, Spokes are deployed and managed by governance. The following Spokes are deployed on Ethereum Mainnet: | Name | Address | | ----------------------- | -------------------------------------------- | | **Main Spoke** | `0x94e7A5dCbE816e498b89aB752661904E2F56c485` | | **Bluechip Spoke** | `0x973a023A77420ba610f06b3858aD991Df6d85A08` | | **Ethena Correlated Spoke** | `0x58131E79531caB1d52301228d1f7b842F26B9649` | | **Ethena Ecosystem Spoke** | `0xba1B3D55D249692b669A164024A838309B7508AF` | | **EtherFi eSpoke** | `0xbF10BDfE177dE0336aFD7fcCF80A904E15386219` | | **Forex Spoke** | `0xD8B93635b8C6d0fF98CbE90b5988E3F2d1Cd9da1` | | **Gold Spoke** | `0x65407b940966954b23dfA3caA5C0702bB42984DC` | | **Kelp eSpoke** | `0x3131FE68C4722e726fe6B2819ED68e514395B9a4` | | **Lido eSpoke** | `0xe1900480ac69f0B296841Cd01cC37546d92F35Cd` | | **Lombard BTC Spoke** | `0x7EC68b5695e803e98a21a9A05d744F28b0a7753D` | | **Treasury Spoke** | `0xB9B0b8616f6Bf6841972a52058132BE08d723155` | Spokes connected to a specific Hub can be discovered through the Hub’s Spoke events and methods. See the [Hub Data Structure](/aave-v4/liquidity/hubs#hub-data-structure) section for details on querying spoke relationships. ## Fetching a Single Spoke Fetch a specific Spoke by ID or by address and chain ID. Use the `useSpoke` hook in React, the `spoke` action in TypeScript, or the `spoke` query in GraphQL to fetch a specific spoke. ```tsx title="Loading State" import { type SpokeRequest, useSpoke } from "@aave/react"; function SpokeDetails({ request }: { request: SpokeRequest }) { const { data, loading, error } = useSpoke(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (!data) return
Spoke not found
; return (

{data.name}

Chain: {data.chain.name}
); } ``` ```tsx title="React Suspense" import { type SpokeRequest, useSpoke } from "@aave/react"; function SpokeDetails({ request }: { request: SpokeRequest }) { const { data } = useSpoke({ ...request, suspense: true, }); if (!data) return
Spoke not found
; return (

{data.name}

Chain: {data.chain.name}
); } ```
```ts title="By Spoke ID" import { spoke } from "@aave/client/actions"; import { client } from "./client"; // const spokeId: SpokeId = "SGVsbG8h"; const result = await spoke(client, { query: { spokeId, }, }); if (result.isOk()) { console.log(result.value); // Spoke | null - null if not found } else { console.error(result.error); } ``` ```ts title="By Spoke Details" import { chainId, evmAddress } from "@aave/client"; import { spoke } from "@aave/client/actions"; import { client } from "./client"; const result = await spoke(client, { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```graphql title="By Spoke ID" query { spoke(request: { query: { spokeId: "SGVsbG8h" } }) { id name address chain { ...Chain } } } ``` ```graphql title="By Spoke Details" query { spoke(request: { query: { spoke: { address: "0x123…", chainId: 1 } } }) { id name address chain { ...Chain } } } ```
In React, see below for examples of `SpokeRequest` objects. ```tsx title="By Spoke ID" import { spokeId } from "@aave/react"; const request: SpokeRequest = { query: { spokeId: spokeId(params.id), // SpokeId - typically from URL params }, }; ``` ```tsx title="By Spoke Details" import { chainId, evmAddress } from "@aave/react"; const request: SpokeRequest = { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ## Spoke Summary History Fetch historical deposits and borrows for a specific spoke over a chosen time window. Use the `useSpokeSummaryHistory` hook in React, the `spokeSummaryHistory` action in TypeScript, or the `spokeSummaryHistory` query in GraphQL to fetch historical data for a Spoke. ```tsx title="Loading State" import { type SpokeSummaryHistoryRequest, useSpokeSummaryHistory, } from "@aave/react"; function SpokeHistory({ request }: { request: SpokeSummaryHistoryRequest }) { const { data, loading, error } = useSpokeSummaryHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (

Spoke History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Deposits: {item.deposits.symbol} {item.deposits.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

))}
); } ``` ```tsx title="React Suspense" import { type SpokeSummaryHistoryRequest, useSpokeSummaryHistory, } from "@aave/react"; function SpokeHistory({ request }: { request: SpokeSummaryHistoryRequest }) { const { data } = useSpokeSummaryHistory({ ...request, suspense: true, }); return (

Spoke History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Deposits: {item.deposits.symbol} {item.deposits.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

))}
); } ```
```ts title="Spoke Summary History" import { Currency, spokeId, TimeWindow } from "@aave/client"; import { spokeSummaryHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await spokeSummaryHistory(client, { query: { spokeId: spokeId("SGVsbG8h") }, currency: Currency.Usd, window: TimeWindow.LastWeek, }); if (result.isOk()) { console.log(result.value); // SpokeSummarySample[] } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: SpokeSummaryHistoryRequest!) { spokeSummaryHistory(request: $request) { date deposits { ...ExchangeAmount } borrows { ...ExchangeAmount } } } ```
- **React**: See below for examples of `SpokeSummaryHistoryRequest` objects. - **GraphQL**: Use the `query`, `currency` and `window` fields to specify the Spoke and time period. ```tsx title="By Spoke ID" import { spokeId, TimeWindow } from "@aave/react"; const request: SpokeSummaryHistoryRequest = { query: { spokeId: spokeId(params.id) }, window: TimeWindow.LastWeek, }; ``` ```tsx title="By Spoke Details" import { chainId, evmAddress, TimeWindow } from "@aave/react"; const request: SpokeSummaryHistoryRequest = { query: { spokeInput: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, window: TimeWindow.LastWeek, }; ``` ```json title="By Spoke ID" { "request": { "query": { "spokeId": "SGVsbG8h" }, "currency": "USD", "window": "LAST_WEEK" } } ``` ```json title="By Spoke Details" { "request": { "query": { "spokeInput": { "address": "0x123…", "chainId": 1 } }, "currency": "USD", "window": "LAST_WEEK" } } ``` --- Source: https://aave.com/docs/aave-v4/liquidity/reserves.md # Aave V4 Reserves Reserves define how a Hub Asset is supplied and borrowed within a specific Spoke. ## Reserve Data Structure Reserve data describes each asset’s lending and borrowing conditions: - Identification: IDs, spoke, chain - Underlying token information - Supply information: APY, liquidity, caps, collateral configuration - Borrow information: APY, available liquidity, utilization rates, caps - Reserve configuration: collateral factor, liquidation bonus, liquidation fee, collateral risk - Reserve status: frozen, paused - User incentives: extra APY and borrow discounts (see [Incentive Programs](./incentives)) - User-specific state: balances, borrowable amounts, collateral usage (when user is specified in request) The following TypeScript interfaces illustrate the core Reserve type: ```ts title="Reserve" interface Reserve { __typename: "Reserve"; id: ReserveId; onChainId: OnChainReserveId; chain: Chain; spoke: Spoke; asset: HubAsset; summary: ReserveSummary; settings: ReserveSettings; status: ReserveStatus; canBorrow: boolean; canSupply: boolean; canUseAsCollateral: boolean; canSwapFrom: boolean; userState: ReserveUserState | null; } ``` ```ts title="ReserveSummary" interface ReserveSummary { __typename: "ReserveSummary"; supplied: Erc20Amount; borrowed: Erc20Amount; supplyApy: PercentNumber; borrowApy: PercentNumber; rewards: Reward[]; } ``` ```ts title="ReserveSettings" interface ReserveSettings { __typename: "ReserveSettings"; collateralFactor: PercentNumber; maxLiquidationBonus: PercentNumber; liquidationFee: PercentNumber; collateralRisk: PercentNumber; borrowable: boolean; collateral: boolean; suppliable: boolean; receiveSharesEnabled: boolean; latestDynamicConfigKey: DynamicConfigKey; borrowCap: Erc20Amount; supplyCap: Erc20Amount; } ``` ```ts title="ReserveStatus" interface ReserveStatus { __typename: "ReserveStatus"; frozen: boolean; paused: boolean; active: boolean; } ``` ```ts title="ReserveUserState" interface ReserveUserState { __typename: "ReserveUserState"; balance: Erc20Amount; suppliable: Erc20Amount; borrowable: Erc20Amount; borrowApy: PercentNumber; collateralFactor: PercentNumber; maxLiquidationBonus: PercentNumber; liquidationFee: PercentNumber; dynamicConfigKey: DynamicConfigKey; } ``` The following GraphQL fragments illustrate the core Reserve type: ```graphql title="Reserve" fragment Reserve on Reserve { __typename id onChainId spoke { ...Spoke } chain { ...Chain } summary { ...ReserveSummary } settings { ...ReserveSettings } status { ...ReserveStatus } canBorrow canSupply canUseAsCollateral canSwapFrom userState { ...ReserveUserState } asset { ...HubAsset } } ``` ```graphql title="ReserveSummary" fragment ReserveSummary on ReserveSummary { __typename supplied { ...Erc20Amount } borrowed { ...Erc20Amount } supplyApy { ...PercentNumber } borrowApy { ...PercentNumber } rewards { ...Reward } } ``` ```graphql title="ReserveSettings" fragment ReserveSettings on ReserveSettings { __typename collateralFactor { ...PercentNumber } maxLiquidationBonus { ...PercentNumber } liquidationFee { ...PercentNumber } collateralRisk { ...PercentNumber } borrowable collateral suppliable receiveSharesEnabled latestDynamicConfigKey borrowCap { ...Erc20Amount } supplyCap { ...Erc20Amount } } ``` ```graphql title="ReserveStatus" fragment ReserveStatus on ReserveStatus { __typename frozen paused active } ``` ```graphql title="ReserveUserState" fragment ReserveUserState on ReserveUserState { __typename balance { ...Erc20Amount } suppliable { ...Erc20Amount } borrowable { ...Erc20Amount } borrowApy { ...PercentNumber } collateralFactor { ...PercentNumber } maxLiquidationBonus { ...PercentNumber } liquidationFee { ...PercentNumber } dynamicConfigKey } ``` Reserves live inside the spoke contract and are exposed through the `ISpoke` interface. Each reserve stores links back to its Hub Asset plus configuration flags that control supply, borrow, and collateral behavior. Dynamic parameters such as collateral factor or liquidation bonus are kept in dedicated structs. ```solidity title="Reserve Struct" struct Reserve { address underlying; IHubBase hub; uint16 assetId; uint8 decimals; uint24 collateralRisk; ReserveFlags flags; uint32 dynamicConfigKey; } ``` ```solidity title="ReserveConfig Struct" struct ReserveConfig { uint24 collateralRisk; bool paused; bool frozen; bool borrowable; bool receiveSharesEnabled; } ``` ```solidity title="DynamicReserveConfig Struct" struct DynamicReserveConfig { uint16 collateralFactor; uint32 maxLiquidationBonus; uint16 liquidationFee; } ``` ## Listing Available Reserves Discover all available reserves given some criteria. Use the `useReserves` hook (or the imperative `useReservesAction` variant) in React, the `reserves` action in TypeScript, or the `reserves` query in GraphQL to fetch a list of reserves. In Solidity, reserves within a spoke are assigned sequential `reserveId` values. To retrieve all reserves within a spoke, first obtain the total reserve count and then loop through each `reserveId`. ```tsx title="Loading State" import { type ReservesRequest, useReserves } from "@aave/react"; function ReservesList({ request }: { request: ReservesRequest }) { const { data, loading, error } = useReserves(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((reserve) => (

{reserve.asset.underlying.info.name}

Spoke: {reserve.spoke.name}
))}
); } ``` ```tsx title="React Suspense" import { type ReservesRequest, useReserves } from "@aave/react"; function ReservesList({ request }: { request: ReservesRequest }) { const { data } = useReserves({ ...request, suspense: true, }); return (
{data.map((reserve) => (

{reserve.asset.underlying.info.name}

Spoke: {reserve.spoke.name}
))}
); } ``` ```tsx title="Imperative Read" import { type ReservesRequest, useReservesAction } from "@aave/react"; // … const [fetch, { called, data, error, loading }] = useReservesAction(); const handler = async (request: ReservesRequest) => { const result = await fetch(request); if (result.isOk()) { console.log(result.value); // Reserve[] } else { console.error(result.error); } }; ```
```ts title="Reserves" import { chainId } from "@aave/client"; import { reserves } from "@aave/client/actions"; import { client } from "./client"; const result = await reserves(client, { query: { chainIds: [chainId(1)], }, }); if (result.isOk()) { console.log(result.value); // Reserve[] } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: ReservesRequest!) { value: reserves(request: $request) { ...Reserve } } ``` ```solidity title="Get All Spoke Reserves" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; contract SpokeReader { function getSpokeReserves( address spokeAddress ) external view returns (ISpoke.Reserve[] memory) { ISpoke spoke = ISpoke(spokeAddress); uint256 reserveCount = spoke.getReserveCount(); ISpoke.Reserve[] memory reserves = new ISpoke.Reserve[](reserveCount); for (uint256 reserveId = 0; reserveId < reserveCount; reserveId++) { reserves[reserveId] = spoke.getReserve(reserveId); } return reserves; } } ```
> [!NOTE] > `useReservesAction` doesn’t watch for updates. Use it for on-demand fresh > data, such as in an event handler. You can query reserves by different criteria. In GraphQL, use the `query` field to select them. ```tsx title="By Chains" import { chainId } from "@aave/react"; const request: ReservesRequest = { query: { chainIds: [chainId(1)], }, }; ``` ```tsx title="By Tokens" import { evmAddress, chainId } from "@aave/react"; const request: ReservesRequest = { query: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }; ``` ```tsx title="By Spoke Token" import { evmAddress } from "@aave/react"; const request: ReservesRequest = { query: { spokeToken: { spoke: spoke.id, // spoke: Spoke token: evmAddress("0x123…"), }, }, }; ``` ```tsx title="By Hub Token" import { evmAddress, chainId } from "@aave/react"; const request: ReservesRequest = { query: { hubToken: { chainId: chainId(1), hub: evmAddress("0x456…"), token: evmAddress("0x123…"), }, }, }; ``` ```tsx title="By Hub ID" const request: ReservesRequest = { query: { hubId: hub.id, // hub: Hub }, }; ``` ```tsx title="By Hub Address" import { evmAddress, chainId } from "@aave/react"; const request: ReservesRequest = { query: { hub: { chainId: chainId(1), address: evmAddress("0x456…"), }, }, }; ``` ```tsx title="By Spoke ID" const request: ReservesRequest = { query: { spokeId: spoke.id, // spoke: Spoke }, }; ``` ```tsx title="By Spoke Address" import { evmAddress, chainId } from "@aave/react"; const request: ReservesRequest = { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```tsx title="By User Position" const request: ReservesRequest = { query: { userPositionId: position.id, // position: UserPosition }, }; ``` ```tsx title="By Categories" import { TokenCategory, chainId } from "@aave/react"; const request: ReservesRequest = { query: { chainTokenCategories: [ { chainId: chainId(1), categories: [TokenCategory.Stablecoin, TokenCategory.EthCorrelated], }, ], }, }; ``` ```tsx title="By Token Info" const request: ReservesRequest = { query: { tokenInfo: tokenInfo.id, // tokenInfo: TokenInfo }, }; ``` ```tsx title="By Symbol" import { chainId } from "@aave/react"; const request: ReservesRequest = { query: { symbolChainIds: { symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }; ``` ```ts title="By Chains" import { reserves } from "@aave/client/actions"; import { chainId } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { chainIds: [chainId(1)], }, }); if (result.isOk()) { console.log(result.value); // result.value: Reserve[] } else { console.error(result.error); } ``` ```ts title="By Tokens" import { reserves } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }); ``` ```ts title="By Spoke Token" import { reserves } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { spokeToken: { spoke: spoke.id, // spoke: Spoke token: evmAddress("0x123…"), }, }, }); ``` ```ts title="By Hub Token" import { reserves } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { hubToken: { chainId: chainId(1), hub: evmAddress("0x456…"), token: evmAddress("0x123…"), }, }, }); ``` ```ts title="By Hub ID" import { reserves } from "@aave/client/actions"; import { client } from "./client"; const result = await reserves(client, { query: { hubId: hub.id, // hub: Hub }, }); ``` ```ts title="By Hub Address" import { reserves } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { hub: { chainId: chainId(1), address: evmAddress("0x456…"), }, }, }); ``` ```ts title="By Spoke ID" import { reserves } from "@aave/client/actions"; import { client } from "./client"; const result = await reserves(client, { query: { spokeId: spoke.id, // spoke: Spoke }, }); ``` ```ts title="By Spoke Address" import { reserves } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```ts title="By User Position" import { reserves } from "@aave/client/actions"; import { client } from "./client"; const result = await reserves(client, { query: { userPositionId: position.id, // position: UserPosition }, }); ``` ```ts title="By Categories" import { reserves } from "@aave/client/actions"; import { TokenCategory, chainId } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { chainTokenCategories: [ { chainId: chainId(1), categories: [TokenCategory.Stablecoin, TokenCategory.EthCorrelated], }, ], }, }); ``` ```ts title="By Token Info" import { reserves } from "@aave/client/actions"; import { client } from "./client"; const result = await reserves(client, { query: { tokenInfo: tokenInfo.id, // tokenInfo: TokenInfo }, }); ``` ```ts title="By Symbol" import { reserves } from "@aave/client/actions"; import { chainId } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { symbolChainIds: { symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```json title="By Chains" { "request": { "query": { "chainIds": [1] } } } ``` ```json title="By Tokens" { "request": { "query": { "tokens": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "chainId": 1 }, { "address": "0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f", "chainId": 1 } ] } } } ``` ```json title="By Spoke Token" { "request": { "query": { "spokeToken": { "spoke": "SGVsbG8h", "token": "0x123…" } } } } ``` ```json title="By Hub Token" { "request": { "query": { "hubToken": { "chainId": 1, "hub": "0x456…", "token": "0x123…" } } } } ``` ```json title="By Hub ID" { "request": { "query": { "hubId": "SGVsbG8h" } } } ``` ```json title="By Hub Address" { "request": { "query": { "hub": { "chainId": 1, "address": "0x456…" } } } } ``` ```json title="By Spoke ID" { "request": { "query": { "spokeId": "SGVsbG8h" } } } ``` ```json title="By Spoke Address" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } } } } ``` ```json title="By User Position" { "request": { "query": { "userPositionId": "SGVsbG8h" } } } ``` ```json title="By Categories" { "request": { "query": { "chainTokenCategories": [ { "chainId": 1, "categories": ["STABLECOIN", "ETH_CORRELATED"] } ] } } } ``` ```json title="By Token Info" { "request": { "query": { "tokenInfo": "SGVsbG8h" } } } ``` ```json title="By Symbol" { "request": { "query": { "symbolChainIds": { "symbol": "USDC", "chainIds": [1, 43114] } } } } ``` Filter reserves by supply, borrow, or collateral. ```tsx title="Supply Reserves" import { ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, }; ``` ```tsx title="Collateral Reserves" import { ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Collateral, }; ``` ```tsx title="Borrow Reserves" import { ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, }; ``` ```ts title="Supply Reserves" import { reserves } from "@aave/client/actions"; import { ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, }); ``` ```ts title="Collateral Reserves" import { reserves } from "@aave/client/actions"; import { ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Collateral, }); ``` ```ts title="Borrow Reserves" import { reserves } from "@aave/client/actions"; import { ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, }); ``` ```json title="Supply Reserves" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "SUPPLY" } } ``` ```json title="Collateral Reserves" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "COLLATERAL" } } ``` ```json title="Borrow Reserves" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "BORROW" } } ``` Add a user address to return `ReserveUserState` for each reserve. ```tsx title="Reserves User State" import { evmAddress } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, user: evmAddress("0x456…"), }; ``` ```ts title="Reserves User State" import { reserves } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, user: evmAddress("0x456…"), }); ``` ```json title="With User" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "user": "0x456…" } } ``` Sort reserves by asset name, user balance, APYs, collateral factor, or available amounts. ```tsx title="Asset Name" import { OrderDirection } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }; ``` ```tsx title="User Balance" import { evmAddress, OrderDirection } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, orderBy: { userBalance: OrderDirection.Asc }, user: evmAddress("0x456…"), }; ``` ```tsx title="Supply APY" import { OrderDirection, ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, orderBy: { supplyApy: OrderDirection.Desc }, }; ``` ```tsx title="Borrow APY" import { OrderDirection, ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, orderBy: { borrowApy: OrderDirection.Asc }, }; ``` ```tsx title="Collateral Factor" import { OrderDirection } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, orderBy: { collateralFactor: OrderDirection.Desc }, }; ``` ```tsx title="Supply Available" import { OrderDirection, ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, orderBy: { supplyAvailable: OrderDirection.Desc }, }; ``` ```tsx title="Borrow Available" import { OrderDirection, ReservesRequestFilter } from "@aave/react"; // … const request: ReservesRequest = { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, orderBy: { borrowAvailable: OrderDirection.Desc }, }; ``` ```ts title="Asset Name" import { reserves } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }); ``` ```ts title="User Balance" import { reserves } from "@aave/client/actions"; import { evmAddress, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, orderBy: { userBalance: OrderDirection.Asc }, user: evmAddress("0x456…"), }); ``` ```ts title="Supply APY" import { reserves } from "@aave/client/actions"; import { OrderDirection, ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, orderBy: { supplyApy: OrderDirection.Desc }, }); ``` ```ts title="Borrow APY" import { reserves } from "@aave/client/actions"; import { OrderDirection, ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, orderBy: { borrowApy: OrderDirection.Asc }, }); ``` ```ts title="Collateral Factor" import { reserves } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, orderBy: { collateralFactor: OrderDirection.Desc }, }); ``` ```ts title="Supply Available" import { reserves } from "@aave/client/actions"; import { OrderDirection, ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Supply, orderBy: { supplyAvailable: OrderDirection.Desc }, }); ``` ```ts title="Borrow Available" import { reserves } from "@aave/client/actions"; import { OrderDirection, ReservesRequestFilter } from "@aave/client"; import { client } from "./client"; const result = await reserves(client, { query: { // your query criteria }, filter: ReservesRequestFilter.Borrow, orderBy: { borrowAvailable: OrderDirection.Desc }, }); ``` ```json title="AssetName" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "orderBy": { "assetName": "ASC" } } } ``` ```json title="User Balance" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "user": "0x456…", "orderBy": { "userBalance": "ASC" } } } ``` ```json title="Supply APY" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "SUPPLY", "orderBy": { "supplyApy": "DESC" } } } ``` ```json title="Borrow APY" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "BORROW", "orderBy": { "borrowApy": "ASC" } } } ``` ```json title="Collateral Factor" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "orderBy": { "collateralFactor": "DESC" } } } ``` ```json title="Supply Available" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "SUPPLY", "orderBy": { "supplyAvailable": "DESC" } } } ``` ```json title="Borrow Available" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "filter": "BORROW", "orderBy": { "borrowAvailable": "DESC" } } } ``` In React and TypeScript, specify a different currency to return fiat amounts in. ```tsx title="Declarative Read" import { Currency } from "@aave/react"; // … const { data, error, loading } = useReserves({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ```tsx title="Imperative Read" import { Currency } from "@aave/react"; const [fetch, { called, data, error, loading }] = useReservesAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { reserves } from "@aave/client/actions"; import { Currency } from "@aave/client"; import { client } from "./client"; const result = await reserves( client, { // your request }, { currency: Currency.Eur, }, ); ``` ## Fetching a Single Reserve Get detailed information about a specific reserve. Use the `useReserve` hook in React, the `reserve` action in TypeScript, or the `reserve` query in GraphQL to fetch a specific reserve. ```tsx title="Loading State" import { type ReserveRequest, useReserve } from "@aave/react"; function ReserveDetails({ request }: { request: ReserveRequest }) { const { data, loading, error } = useReserve(request); if (loading) return Loading reserve…; if (error) return Error: {error.message}; if (!data) return Reserve not found; return (

Reserve ID: {data.id}

Supply APY: {data.summary.supplyApy.normalized.toFixed(2)}% Borrow APY: {data.summary.borrowApy.normalized.toFixed(2)}%
); } ``` ```tsx title="React Suspense" import { type ReserveRequest, useReserve } from "@aave/react"; function ReserveDetails({ request }: { request: ReserveRequest }) { const { data } = useReserve({ ...request, suspense: true, }); if (!data) return Reserve not found; return (

Reserve ID: {data.id}

Supply APY: {data.summary.supplyApy.normalized.toFixed(2)}% Borrow APY: {data.summary.borrowApy.normalized.toFixed(2)}%
); } ```
```ts title="Reserve" import { reserveId } from "@aave/client"; import { reserve } from "@aave/client/actions"; import { client } from "./client"; const result = await reserve(client, { query: { reserveId: reserveId("SGVsbG8h"), }, }); if (result.isOk()) { console.log(result.value); // Reserve | null } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: ReserveRequest!) { value: reserve(request: $request) { ...Reserve } } ```
See below for examples of `ReserveRequest` objects. ```tsx title="By OnChain ID" import { chainId, evmAddress, type OnChainReserveId } from "@aave/react"; const request: ReserveRequest = { query: { reserveInput: { chainId: chainId(1), spoke: evmAddress("0x123…"), onChainId: "1" as OnChainReserveId, }, }, }; ``` ```tsx title="By Reserve ID" import { ReserveId } from "@aave/react"; const request: ReserveRequest = { query: { reserveId: "SGVsbG8h" as ReserveId, }, }; ``` ```tsx title="With User State" import { evmAddress } from "@aave/react"; const request: ReserveRequest = { query: { // your query criteria }, user: evmAddress("0x456…"), }; ``` ```ts title="By OnChain ID" import { reserve } from "@aave/client/actions"; import { chainId, evmAddress, type OnChainReserveId } from "@aave/client"; import { client } from "./client"; const result = await reserve(client, { query: { reserveInput: { chainId: chainId(1), spoke: evmAddress("0x123…"), onChainId: "1" as OnChainReserveId, }, }, }); if (result.isOk()) { console.log(result.value); // Reserve | null - null if not found } else { console.error(result.error); } ``` ```ts title="By Reserve ID" import { reserve } from "@aave/client/actions"; import { type ReserveId } from "@aave/client"; import { client } from "./client"; // const id: ReserveId = "SGVsbG8h"; const result = await reserve(client, { query: { reserveId: id }, }); ``` ```ts title="With User State" import { reserve } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await reserve(client, { query: { // your query criteria }, user: evmAddress("0x456…"), }); ``` ```json title="By OnChain ID" { "request": { "query": { "reserveInput": { "chainId": 1, "spoke": "0x123…", "onChainId": "1" } } } } ``` ```json title="By Reserve ID" { "request": { "query": { "reserveId": "SGVsbG8h" } } } ``` ```json title="With User State" { "request": { "query": { "reserveId": "SGVsbG8h" }, "user": "0x456…" } } ``` Finally, in React, you can specify a different time window or currency for the data. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, loading, error } = useReserve({ query: { // your query criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, loading, error } = useReserve({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ## Borrow APY History Fetch historical borrow APY data for a specific reserve. By default, Merkl rewards are included in the returned rates; pass `includeRewards: false` for protocol base rates only. Use the `useBorrowApyHistory` hook in React, the `borrowApyHistory` action in TypeScript, or the `borrowApyHistory` query in GraphQL to fetch historical borrow APY data. ```tsx title="Loading State" import { type BorrowApyHistoryRequest, useBorrowApyHistory } from "@aave/react"; function BorrowApy({ request }: { request: BorrowApyHistoryRequest }) { const { data, loading, error } = useBorrowApyHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.avgRate.normalized.toFixed(2)}%

))}
); } ``` ```tsx title="React Suspense" import { type BorrowApyHistoryRequest, useBorrowApyHistory } from "@aave/react"; function BorrowApy({ request }: { request: BorrowApyHistoryRequest }) { const { data } = useBorrowApyHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.avgRate.normalized.toFixed(2)}%

))}
); } ```
```graphql title="Query" query ($request: BorrowApyHistoryRequest!) { borrowApyHistory(request: $request) { date avgRate { onChainValue decimals value normalized } } } ```
See below for examples of `BorrowApyHistoryRequest` objects. ```tsx title="By Reserve ID" import { TimeWindow } from "@aave/react"; const request: BorrowApyHistoryRequest = { reserve: reserve.id, window: TimeWindow.LastDay, }; ``` ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const request: BorrowApyHistoryRequest = { reserve: reserve.id, window: TimeWindow.LastWeek, }; ``` ```tsx title="Protocol Rates Only" const request: BorrowApyHistoryRequest = { reserve: reserve.id, includeRewards: false, // exclude Merkl rewards from the rates }; ``` ```ts title="By Reserve ID" import { borrowApyHistory } from "@aave/client/actions"; import { TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await borrowApyHistory(client, { reserve: reserve.id, window: TimeWindow.LastDay, }); if (result.isOk()) { console.log(result.value); // ApySample[] } else { console.error(result.error); } ``` ```ts title="Custom Time Window" import { borrowApyHistory } from "@aave/client/actions"; import { TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await borrowApyHistory(client, { reserve: reserve.id, window: TimeWindow.LastWeek, }); ``` ```ts title="Protocol Rates Only" import { borrowApyHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await borrowApyHistory(client, { reserve: reserve.id, includeRewards: false, // exclude Merkl rewards from the rates }); ``` ```json title="By Reserve ID" { "request": { "reserve": "SGVsbG8h", "window": "LAST_DAY" } } ``` ```json title="Custom Time Window" { "request": { "reserve": "SGVsbG8h", "window": "LAST_WEEK" } } ``` ```json title="Protocol Rates Only" { "request": { "reserve": "SGVsbG8h", "includeRewards": false } } ``` ## Supply APY History Fetch historical supply APY data for a specific reserve. By default, Merkl rewards are included in the returned rates; pass `includeRewards: false` for protocol base rates only. Use the `useSupplyApyHistory` hook in React, the `supplyApyHistory` action in TypeScript, or the `supplyApyHistory` query in GraphQL to fetch historical supply APY data. ```tsx title="Loading State" import { type SupplyApyHistoryRequest, useSupplyApyHistory } from "@aave/react"; function SupplyApy({ request }: { request: SupplyApyHistoryRequest }) { const { data, loading, error } = useSupplyApyHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.avgRate.normalized.toFixed(2)}%

))}
); } ``` ```tsx title="React Suspense" import { type SupplyApyHistoryRequest, useSupplyApyHistory } from "@aave/react"; function SupplyApy({ request }: { request: SupplyApyHistoryRequest }) { const { data } = useSupplyApyHistory({ ...request, suspense: true, }); return (
{data.map((sample) => (

{sample.date.toLocaleDateString()} {sample.avgRate.normalized.toFixed(2)}%

))}
); } ```
```graphql title="Query" query ($request: SupplyApyHistoryRequest!) { supplyApyHistory(request: $request) { date avgRate { onChainValue decimals value normalized } } } ```
See below for examples of `SupplyApyHistoryRequest` objects. ```tsx title="By Reserve ID" import { TimeWindow } from "@aave/react"; const request: SupplyApyHistoryRequest = { reserve: reserve.id, window: TimeWindow.LastDay, }; ``` ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const request: SupplyApyHistoryRequest = { reserve: reserve.id, window: TimeWindow.LastWeek, }; ``` ```tsx title="Protocol Rates Only" const request: SupplyApyHistoryRequest = { reserve: reserve.id, includeRewards: false, // exclude Merkl rewards from the rates }; ``` ```ts title="By Reserve ID" import { supplyApyHistory } from "@aave/client/actions"; import { TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await supplyApyHistory(client, { reserve: reserve.id, window: TimeWindow.LastDay, }); if (result.isOk()) { console.log(result.value); // ApySample[] } else { console.error(result.error); } ``` ```ts title="Custom Time Window" import { supplyApyHistory } from "@aave/client/actions"; import { TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await supplyApyHistory(client, { reserve: reserve.id, window: TimeWindow.LastWeek, }); ``` ```ts title="Protocol Rates Only" import { supplyApyHistory } from "@aave/client/actions"; import { client } from "./client"; const result = await supplyApyHistory(client, { reserve: reserve.id, includeRewards: false, // exclude Merkl rewards from the rates }); ``` ```json title="By Reserve ID" { "request": { "reserve": "SGVsbG8h", "window": "LAST_DAY" } } ``` ```json title="Custom Time Window" { "request": { "reserve": "SGVsbG8h", "window": "LAST_WEEK" } } ``` ```json title="Protocol Rates Only" { "request": { "reserve": "SGVsbG8h", "includeRewards": false } } ``` ## Reserve Holders Fetch a paginated list of the top holders for a specific reserve, filtered by suppliers or borrowers. Use the `useReserveHolders` hook in React, the `reserveHolders` action in TypeScript, or the `reserveHolders` query in GraphQL to fetch holders for a specific reserve. ```tsx title="Loading State" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; function ReserveHoldersList({ reserveId }: { reserveId: string }) { const { data, loading, error } = useReserveHolders({ reserve: { reserveId }, filter: ReserveHoldersFilter.Supplied, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.items.map((holder) => (
{holder.address}

{holder.amount.amount.value.toFixed(4)} {holder.amount.token.info.symbol}

{holder.weight.normalized.toFixed(4)}%
))}
); } ``` ```tsx title="React Suspense" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; function ReserveHoldersList({ reserveId }: { reserveId: string }) { const { data } = useReserveHolders({ reserve: { reserveId }, filter: ReserveHoldersFilter.Supplied, suspense: true, }); return (
{data.items.map((holder) => (
{holder.address}

{holder.amount.amount.value.toFixed(4)} {holder.amount.token.info.symbol}

))}
); } ```
```graphql title="Query" query ($request: PaginatedReserveHoldersRequest!) { reserveHolders(request: $request) { items { address amount { ...Erc20Amount } weight { ...PercentNumber } } pageInfo { next prev } } } ```
Filter by `ReserveHoldersFilter.Supplied` (default) or `ReserveHoldersFilter.Borrowed`. In GraphQL, provide these as query variables. ```tsx title="Supplied Holders" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; const { data } = useReserveHolders({ reserve: { reserveId: reserve.id }, filter: ReserveHoldersFilter.Supplied, }); ``` ```tsx title="Borrowed Holders" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; const { data } = useReserveHolders({ reserve: { reserveId: reserve.id }, filter: ReserveHoldersFilter.Borrowed, }); ``` ```ts title="Supplied Holders" import { ReserveHoldersFilter, reserveId } from "@aave/client"; import { reserveHolders } from "@aave/client/actions"; import { client } from "./client"; const result = await reserveHolders(client, { reserve: { reserveId: reserveId("SGVsbG8h") }, filter: ReserveHoldersFilter.Supplied, }); if (result.isOk()) { console.log(result.value.items); // ReserveHolder[] } else { console.error(result.error); } ``` ```ts title="Borrowed Holders" import { ReserveHoldersFilter, reserveId } from "@aave/client"; import { reserveHolders } from "@aave/client/actions"; import { client } from "./client"; const result = await reserveHolders(client, { reserve: { reserveId: reserveId("SGVsbG8h") }, filter: ReserveHoldersFilter.Borrowed, }); ``` ```json title="Supplied Holders" { "request": { "reserve": { "reserveId": "SGVsbG8h" }, "filter": "SUPPLIED" } } ``` ```json title="Borrowed Holders" { "request": { "reserve": { "reserveId": "SGVsbG8h" }, "filter": "BORROWED" } } ``` Results are paginated. Use `pageSize` (`PageSize.Ten` by default, or `PageSize.Fifty`) and pass `pageInfo.next` as `cursor` to fetch the next page. ```tsx title="Pagination" import { PageSize, useReserveHolders } from "@aave/react"; const { data } = useReserveHolders({ reserve: { reserveId: reserve.id }, pageSize: PageSize.Fifty, cursor: previousPage.pageInfo.next, }); ``` ```ts title="Pagination" import { PageSize, reserveId } from "@aave/client"; import { reserveHolders } from "@aave/client/actions"; import { client } from "./client"; const result = await reserveHolders(client, { reserve: { reserveId: reserveId("SGVsbG8h") }, pageSize: PageSize.Fifty, cursor: previousPage.pageInfo.next, }); ``` ```json title="Pagination" { "request": { "reserve": { "reserveId": "SGVsbG8h" }, "pageSize": "FIFTY", "cursor": "…" } } ``` --- Source: https://aave.com/docs/aave-v4/liquidity/chains.md # Aave V4 Supported Chains Chains are the blockchain networks where Aave V4 is deployed. ## Chain Data Structure Chain data provides information about blockchain networks supported by Aave V4, including: - Identification: name, chain ID, icon URL - Configuration: explorer URL, whether it is a testnet - Native token details: native token metadata, wrapped token address, and gateway The following TypeScript interface illustrates the core Chain type: ```ts title="Chain" interface Chain { __typename: "Chain"; chainId: ChainId; name: string; icon: string; rpcUrl: string; explorerUrl: string; isTestnet: boolean; isFork: boolean; nativeAsset: NativeAsset | null; // Deprecated: use nativeAsset nativeWrappedToken: EvmAddress; nativeInfo: TokenInfo; nativeGateway: EvmAddress; signatureGateway: EvmAddress; } ``` ```ts title="NativeAsset" type NativeAsset = WrappedNativeAsset | SharedBalanceNativeAsset; interface WrappedNativeAsset { __typename: "WrappedNativeAsset"; nativeToken: TokenInfo; wrappedNativeTokenAddress: EvmAddress; gateway: EvmAddress | null; } interface SharedBalanceNativeAsset { __typename: "SharedBalanceNativeAsset"; nativeToken: TokenInfo; erc20Address: EvmAddress; } ``` ```ts title="TokenInfo" interface TokenInfo { __typename: "TokenInfo"; id: TokenInfoId; name: string; symbol: string; // Case-folded, alias-resolved symbol grouping this token // with the same asset on other chains. canonicalSymbol: string; icon: string; decimals: number; categories: TokenCategory[]; } ``` ```ts title="TokenCategory" enum TokenCategory { Stablecoin = "STABLECOIN", EthCorrelated = "ETH_CORRELATED", } ``` The following GraphQL fragments illustrate the core Chain type: ```graphql title="Chain" fragment Chain on Chain { __typename chainId name icon rpcUrl explorerUrl isTestnet isFork nativeAsset { ...NativeAsset } # Deprecated: use nativeAsset nativeWrappedToken nativeInfo { ...TokenInfo } nativeGateway signatureGateway } ``` ```graphql title="NativeAsset" fragment NativeAsset on NativeAsset { __typename ... on WrappedNativeAsset { nativeToken { ...TokenInfo } wrappedNativeTokenAddress gateway } ... on SharedBalanceNativeAsset { nativeToken { ...TokenInfo } erc20Address } } ``` ```graphql title="TokenInfo" fragment TokenInfo on TokenInfo { __typename id name symbol canonicalSymbol icon decimals categories } ``` ## Listing Supported Chains Discover all blockchain networks supported by Aave V4. Use the `useChains` hook in React, the `chains` action in TypeScript, or the `chains` query in GraphQL to fetch a list of supported chains. ```tsx title="Loading State" import { type ChainsRequest, useChains } from "@aave/react"; function ChainsList({ request }: { request: ChainsRequest }) { const { data, loading, error } = useChains(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((chain) => (

{chain.name}

Chain ID: {chain.chainId}
))}
); } ``` ```tsx title="React Suspense" import { type ChainsRequest, useChains } from "@aave/react"; function ChainsList({ request }: { request: ChainsRequest }) { const { data } = useChains({ ...request, suspense: true, }); return (
{data.map((chain) => (

{chain.name}

Chain ID: {chain.chainId}
))}
); } ```
```ts title="By Filter" import { ChainsFilter } from "@aave/client"; import { chains } from "@aave/client/actions"; import { client } from "./client"; const result = await chains(client, { query: { filter: ChainsFilter.ALL }, }); if (result.isOk()) { console.log(result.value); // Chain[] } else { console.error(result.error); } ``` ```ts title="By Chain IDs" import { chainId } from "@aave/client"; import { chains } from "@aave/client/actions"; import { client } from "./client"; const result = await chains(client, { query: { chainIds: [chainId(1), chainId(137)] }, }); if (result.isOk()) { console.log(result.value); // Chain[] } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: ChainsRequest!) { chains(request: $request) { chainId name icon explorerUrl isTestnet nativeWrappedToken nativeInfo { name symbol icon decimals } nativeGateway signatureGateway } } ```
See below for examples of `ChainsRequest` objects in React and query variables in GraphQL. ```tsx title="By Filter" import { ChainsFilter, type ChainsRequest } from "@aave/react"; const request: ChainsRequest = { query: { filter: ChainsFilter.ALL }, }; ``` ```tsx title="By Chain IDs" import { chainId, type ChainsRequest } from "@aave/react"; const request: ChainsRequest = { query: { chainIds: [chainId(1), chainId(137)] }, }; ``` ```jsonc title="By Filter" { "request": { "query": { "filter": "ALL" // or "MAINNET_ONLY" or "TESTNET_ONLY" } } } ``` ```json title="By Chain IDs" { "request": { "query": { "chainIds": [1, 137] } } } ``` In React and TypeScript, `ChainsFilter` is one of: - `ChainsFilter.ALL`: all chains - `ChainsFilter.MAINNET_ONLY`: mainnets only - `ChainsFilter.TESTNET_ONLY`: testnets only ## Fetching a Single Chain Get detailed information about a specific blockchain network by its chain ID. Use the `useChain` hook in React, the `chain` action in TypeScript, or the `chain` query in GraphQL to fetch a specific chain. ```tsx title="Loading State" import { type ChainRequest, useChain } from "@aave/react"; function ChainDetails({ request }: { request: ChainRequest }) { const { data, loading, error } = useChain(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (!data) return
Chain not found
; return (

{data.name}

Chain ID: {data.chainId}
); } ``` ```tsx title="React Suspense" import { type ChainRequest, useChain } from "@aave/react"; function ChainDetails({ request }: { request: ChainRequest }) { const { data } = useChain({ ...request, suspense: true, }); if (!data) return
Chain not found
; return (

{data.name}

Chain ID: {data.chainId}
); } ```
```ts title="Example" import { chainId } from "@aave/client"; import { chain } from "@aave/client/actions"; import { client } from "./client"; const result = await chain(client, { chainId: chainId(1), }); if (result.isOk()) { console.log(result.value); // Chain | null } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: ChainRequest!) { chain(request: $request) { chainId name icon explorerUrl isTestnet nativeWrappedToken nativeInfo { name symbol icon decimals } nativeGateway signatureGateway } } ```
See below for an example of a `ChainRequest` object in React and query variables in GraphQL. ```tsx title="Example" import { chainId, type ChainRequest } from "@aave/react"; const request: ChainRequest = { chainId: chainId(1), }; ``` ```json title="Variables" { "request": { "chainId": 1 } } ``` --- Source: https://aave.com/docs/aave-v4/liquidity/incentives.md # Aave V4 Incentive Programs Aave V4 reserves may offer additional incentives beyond base lending rates. These incentives are distributed through [Merkl](https://merkl.xyz/), a decentralized incentive distribution platform, or through _Points programs_ that reward users with points multipliers. ## Reward Types Potential rewards are available in the `rewards` array of the [Reserve Summary](./reserves#reserve-data-structure). ```ts title="Reserve" interface Reserve { // … summary: { rewards: Reward[]; // … }; } type Reward = | MerklSupplyReward | MerklBorrowReward | SupplyPointsReward | BorrowPointsReward; ``` ```graphql title="Reserve" fragment Reserve on Reserve { # … summary { rewards { ... on MerklSupplyReward { ...MerklSupplyReward } ... on MerklBorrowReward { ...MerklBorrowReward } ... on SupplyPointsReward { ...SupplyPoints } ... on BorrowPointsReward { ...BorrowPoints } } # … } } ``` ### Supply Rewards Supply rewards can be present on suppliable reserves. #### Merkl Supply Rewards Merkl supply rewards represent an _extra APY_ on top of the base reserve supply APY. The accrued extra interest is paid in the specified payout token when the incentive campaign reaches its maturity. ```ts title="MerklSupplyReward" interface MerklSupplyReward { __typename: "MerklSupplyReward"; id: string; startDate: Date; endDate: Date; extraApy: PercentNumber; payoutToken: Erc20Token; criteria: MerklCriteria[]; userEligible: boolean; } ``` ```graphql title="MerklSupplyReward" fragment MerklSupplyReward on MerklSupplyReward { __typename id startDate endDate extraApy { ...PercentNumber } payoutToken { ...Erc20Token } criteria { ...MerklCriteria } userEligible } ``` Where: - `extraApy`: the additional APY earned on top of the base supply APY - `payoutToken`: the token used to pay the extra interest accrued from the reward - `criteria`: [eligibility requirements](#eligibility-criteria) for earning the reward #### Points Supply Rewards Some reserves participate in Points programs. Users who supply into these reserves accrue points over time proportional to their position size. ```ts title="SupplyPointsReward" interface SupplyPointsReward { __typename: "SupplyPointsReward"; id: string; program: PointsProgram; name: string; startDate: Date; endDate: Date | null; multiplier: number; criteria: PointsCriteria[]; userEligible: boolean; } ``` ```graphql title="SupplyPoints" fragment SupplyPoints on SupplyPointsReward { __typename id program { ...PointsProgram } name startDate endDate multiplier criteria { ...PointsCriteria } userEligible } ``` Where: - `program`: the [Points program](#points-program) issuing the reward - `multiplier`: boost factor on the base points accrual rate - `criteria`: [eligibility requirements](#eligibility-criteria) for earning the reward ### Borrow Rewards Borrow rewards can be present on borrowable reserves. #### Merkl Borrow Rewards Merkl borrow rewards represent an _APY discount_ on the user’s borrow rate (which includes their [Risk Premium](../positions/conditions#user-risk-premium)). The accrued interest discount is paid in the specified payout token when the incentive campaign reaches its maturity. ```ts title="MerklBorrowReward" interface MerklBorrowReward { __typename: "MerklBorrowReward"; id: string; startDate: Date; endDate: Date; discountApy: PercentNumber; payoutToken: Erc20Token; criteria: MerklCriteria[]; userEligible: boolean; } ``` ```graphql title="MerklBorrowReward" fragment MerklBorrowReward on MerklBorrowReward { __typename id startDate endDate discountApy { ...PercentNumber } payoutToken { ...Erc20Token } criteria { ...MerklCriteria } userEligible } ``` Where: - `discountApy`: the APY discount applied to the user’s borrow rate - `payoutToken`: the token used to pay the reward - `criteria`: [eligibility requirements](#eligibility-criteria) for earning the reward #### Points Borrow Rewards Similarly, borrowing from certain reserves can accrue points in a Points program. ```ts title="BorrowPointsReward" interface BorrowPointsReward { __typename: "BorrowPointsReward"; id: string; program: PointsProgram; name: string; startDate: Date; endDate: Date | null; multiplier: number; criteria: PointsCriteria[]; userEligible: boolean; } ``` ```graphql title="BorrowPoints" fragment BorrowPoints on BorrowPointsReward { __typename id program { ...PointsProgram } name startDate endDate multiplier criteria { ...PointsCriteria } userEligible } ``` Where: - `program`: the [Points program](#points-program) issuing the reward - `multiplier`: boost factor on the base points accrual rate - `criteria`: [eligibility requirements](#eligibility-criteria) for earning the reward ### Points Program A `PointsProgram` represents a loyalty or incentive system. Users accumulate points over time based on their supply or borrow position. The `externalUrl` links to the program’s website where users can view their accumulated points. ```ts title="PointsProgram" interface PointsProgram { __typename: "PointsProgram"; id: string; name: string; externalUrl: string | null; iconUrl: string | null; } ``` ```graphql title="PointsProgram" fragment PointsProgram on PointsProgram { __typename id name externalUrl iconUrl } ``` ### Eligibility Criteria Each reward may have eligibility criteria that users must meet. Both Merkl and Points criteria share the same shape (`id`, `text`, `userPassed`) but use distinct GraphQL types. ```ts title="MerklCriteria" // Merkl rewards use MerklCriteria interface MerklCriteria { __typename: "MerklGenericCriteria"; id: string; text: string; userPassed: boolean; } // Points rewards use PointsCriteria interface PointsCriteria { __typename: "PointsGenericCriteria"; id: string; text: string; userPassed: boolean; } ``` ```graphql title="MerklCriteria" fragment MerklCriteria on MerklCriteria { ... on MerklGenericCriteria { __typename id text userPassed } } fragment PointsCriteria on PointsCriteria { ... on PointsGenericCriteria { __typename id text userPassed } } ``` ## Matured Rewards Rewards become claimable when their incentive campaign reaches maturity. Campaigns are often renewed upon reaching their end date, so users should check for new reward opportunities periodically. ### Claimable Rewards Fetch the user’s matured rewards that are ready to claim. Use the `useUserClaimableRewards` hook (or the imperative `useUserClaimableRewardsAction` variant) in React, the `userClaimableRewards` action in TypeScript, or the `userClaimableRewards` query in GraphQL to fetch all rewards the user can claim. ```tsx title="Loading State" import { chainId, useUserClaimableRewards, type EvmAddress, } from "@aave/react"; function ClaimableRewards({ user }: { user: EvmAddress }) { const { data, loading, error } = useUserClaimableRewards({ user, chainIds: [chainId(1)], }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (data.length === 0) return
No claimable rewards
; return (
{data.map((reward) => (
Amount: {reward.claimable.amount.value.toFixed(2)} Claim until: {reward.claimUntil.toLocaleDateString()}
))}
); } ``` ```tsx title="React Suspense" import { chainId, useUserClaimableRewards, type EvmAddress, } from "@aave/react"; function ClaimableRewards({ user }: { user: EvmAddress }) { const { data } = useUserClaimableRewards({ user, chainIds: [chainId(1)], suspense: true, }); if (data.length === 0) return
No claimable rewards
; return (
{data.map((reward) => (
Amount: {reward.claimable.amount.value.toFixed(2)} Claim until: {reward.claimUntil.toLocaleDateString()}
))}
); } ``` ```tsx title="Imperative Read" import { chainId, useUserClaimableRewardsAction, type EvmAddress, } from "@aave/react"; // … const [fetch, { called, data, error, loading }] = useUserClaimableRewardsAction(); const handler = async (user: EvmAddress) => { const result = await fetch({ user, chainIds: [chainId(1)], }); if (result.isOk()) { console.log(result.value); // UserClaimableReward[] } else { console.error(result.error); } }; ```
```ts title="Claimable Rewards" import { userClaimableRewards } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userClaimableRewards(client, { user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainIds: [chainId(1)], }); if (result.isErr()) { console.error("claimable rewards error:", result.error); } else { // result.value: UserClaimableReward[] console.log(result.value); } ``` ```graphql title="Query" query { userClaimableRewards( request: { user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", chainIds: [1] } ) { __typename ... on UserMerklClaimableReward { id claimChainId claimable { token { address info { symbol decimals } chain { chainId } } amount { value decimals onChainValue } exchange(currency: USD) { value symbol } } startDate endDate claimUntil } } } ```
> [!NOTE] > `useUserClaimableRewardsAction` doesn’t watch for updates. Use it for > on-demand fresh data, such as in an event handler. An empty array means the user has no claimable rewards. The `UserMerklClaimableReward` type contains details about each claimable reward: ```ts title="UserMerklClaimableReward" interface UserMerklClaimableReward { __typename: "UserMerklClaimableReward"; id: RewardId; claimChainId: ChainId; claimable: Erc20Amount; startDate: Date; endDate: Date; claimUntil: Date; } ``` ```graphql title="UserMerklClaimableReward" fragment UserMerklClaimableReward on UserMerklClaimableReward { __typename id claimChainId claimable { ...Erc20Amount } startDate endDate claimUntil } ``` Where: - `id`: unique identifier for the reward (used when claiming) - `claimChainId`: the chain on which the reward is claimed - `claimable`: the claimable token amount - `startDate`: when the reward period started - `endDate`: when the reward period ended - `claimUntil`: deadline to claim the reward ### Claim Rewards Once you have claimable rewards, collect them individually or all at once in a single transaction. > [!NOTE] > Claimed rewards can stay in the claimable list until Merkl reports them as > claimed, which can take a while. To claim rewards with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Claim Flow Then, in React, use the `useClaimRewards` hook to prepare the claim operation. ```tsx title="Basic Usage" import { useClaimRewards } from "@aave/react"; const [claim, { loading, error }] = useClaimRewards((transaction) => sendTransaction(transaction), ); ``` ```tsx title="Update Component State" import { useClaimRewards } from "@aave/react"; import { useState } from "react"; const [status, setStatus] = useState(""); const [claim, { loading, error }] = useClaimRewards((transaction) => { setStatus("Please sign the claim transaction in your wallet"); return sendTransaction(transaction).andTee(() => setStatus("Claiming…")); }); ``` ```tsx title="Cancel Flow" import { useClaimRewards } from "@aave/react"; const [claim, { loading, error }] = useClaimRewards( (transaction, { cancel }) => { if (window.confirm("Are you sure you want to claim?") === false) { return cancel("User cancelled the operation"); } return sendTransaction(transaction); }, ); ``` #### 3. Execute the Claim Operation Then, execute the claim operation with the reward IDs from the claimable rewards. - **TypeScript**: Use the `claimRewards` action. - **GraphQL**: Use the `claimRewards` query. ```tsx title="Claim Rewards" import { chainId, useUserClaimableRewards, evmAddress, } from "@aave/react"; const { data: claimableRewards } = useUserClaimableRewards({ user: evmAddress(wallet.account.address), chainIds: [chainId(1)], suspense: true, }); const execute = async () => { if (claimableRewards.length > 0) { const result = await claim({ ids: claimableRewards.map((reward) => reward.id), user: evmAddress(wallet.account.address), chainId: chainId(1), }); // … } }; ``` ```ts title="Claim Rewards" import { userClaimableRewards, claimRewards } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userClaimableRewards(client, { user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainIds: [chainId(1)], }).andThen((rewards) => claimRewards(client, { ids: rewards.map((reward) => reward.id), user: evmAddress("0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234"), chainId: chainId(1), }), ); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { claimRewards( request: { ids: ["reward-id-1", "reward-id-2"] user: "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234" chainId: 1 } ) { to from data value chainId } } ``` #### 4. Process the Transaction Request In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transaction, and await indexing with `client.waitForTransaction`. ```ts title="Viem" import { userClaimableRewards, claimRewards } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await userClaimableRewards(client, { user: evmAddress(wallet.account.address), chainIds: [chainId(1)], }) .andThen((rewards) => claimRewards(client, { ids: rewards.map((reward) => reward.id), user: evmAddress(wallet.account.address), chainId: chainId(1), }), ) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```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(), }); ``` In GraphQL, send the returned transaction using the wallet associated with the `from` address. ```json title="Response" { "data": { "claimRewards": { "to": "0x1234567890abcdef1234567890abcdef12345678", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x…", "value": "0", "chainId": 1 } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await claim(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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; } return; } console.log("Rewards claimed successfully with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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("Rewards claimed successfully with hash:", result.value.txHash); } ``` --- Source: https://aave.com/docs/aave-v4/positions.md # Aave V4 User Positions A User Position represents the complete financial state of a user within a specific Spoke, tracking User Supplies and User Borrows alongside key risk metrics such as health factor and Risk Premium. Unlike V3, where user positions were per-market, V4 positions are per-Spoke, allowing users to manage different strategies and risk profiles independently. > [!NOTE] > A _User Account_ (or _User_) is a single Ethereum address that has used the > protocol, either an _Externally Owned Account (EOA)_ or a smart contract. ## User Supplies User Supplies represent assets that a user has deposited into a Spoke’s Reserve. Each supply position: - **Accrues yield** automatically through share-based accounting that appreciates over time - **May be enabled as collateral** (if the reserve supports it) to provide borrowing power based on the reserve’s Collateral Factor - **Affects the Risk Premium** when enabled as collateral: riskier collateral assets increase the overall risk profile of the position - **Can be withdrawn** at any time, provided the position’s health factor remains above 1.0 > [!NOTE] > The above applies to standard Hub and Spoke behavior. Tailored implementations > may vary. ## User Borrows User Borrows represent assets that a user has borrowed from a Spoke’s Reserve. Each borrow position: - **Accumulates interest** based on the asset’s borrow rate, increasing debt over time - **Requires collateral backing** according to the Collateral Factor of each collateral asset - **Impacts the health factor** as part of the total debt value - **Can be repaid** partially or fully at any time to reduce debt and free up collateral > [!NOTE] > The above applies to standard Hub and Spoke behavior. Tailored implementations > may vary. ## Health Factor The _health factor_ is the core safety metric that determines a user position’s liquidation risk. It measures the stability of a user position: The health factor value determines the position’s safety status: - **Above 1.0**: The position is safe from liquidation - **Below 1.0**: The position becomes eligible for liquidation. Liquidators repay only enough debt to restore the position to a healthy state - **Changes dynamically** as asset prices fluctuate and interest accrues on both supplies and borrows - **Can be improved** by supplying more collateral or repaying part of the borrowed amount - **Determines available actions**: new borrows or collateral withdrawals are blocked if they would reduce the health factor below 1.0 ### Example If a user supplies $10,000 in ETH as collateral with an 80% Collateral Factor and borrows $6,000 in GHO, the health factor would be 1.333. ## User Risk Premium User Risk Premium represents the additional interest charge applied to borrowing based on the quality of a user’s collateral. It determines how much extra a user pays on top of the base borrow rate for any borrowed asset within a Spoke. - **Based on Collateral Risk**: a percentage value from 0% (highest quality) to 1000% (maximum risk) that reflects how risky an asset is when used as collateral - **Weighted by collateral amounts**: calculated using only the collateral needed to cover total debt, starting with the safest assets - **Updated dynamically**: recalculated when users withdraw, borrow, or through ad-hoc refresh. - **Lower is better**: users with safer collateral pay lower interest rates For example, a 0% User Risk Premium means paying only the base rate, while 50% means paying 50% more (7.5% total if base rate is 5%). ## Cross-Spoke Strategies Aave V4’s modular design lets users manage positions across multiple Spokes. ### Spoke Isolation Each Spoke maintains independent risk parameters and liquidation logic. This means: - Positions in different Spokes do not affect each other’s health factors - A user can hold conservative positions in one Spoke and aggressive positions in another ### Multi-Hub Access Advanced Spokes can access multiple Hubs, enabling strategies such as: - Collateralizing assets from one Hub to borrow from another - Accessing different yield opportunities across Hub configurations - Optimizing liquidity and rates across the entire protocol --- Source: https://aave.com/docs/aave-v4/positions/fetch.md # Fetch Open Positions on Aave V4 Each user position captures a user’s activity within a Spoke, simplifying health and performance tracking. ## User Positions ### User Position Data Structure User position data describes a user’s lending and borrowing activity on a specific spoke: - Identification: id, user, spoke, creation timestamp - Position balances: supplied amounts, collateral amounts, debt amounts, net balances - Yield information: supply APY, borrow APY, net APY, net interests - Risk metrics: health factor, user risk premium breakdown, liquidation price, maximum and remaining borrowing power - Performance data: net balance percentage changes over time The following TypeScript interfaces illustrate the core UserPosition type: ```ts title="UserPosition" interface UserPosition { __typename: "UserPosition"; id: UserPositionId; user: EvmAddress; createdAt: Date; spoke: Spoke; totalSupplied: ExchangeAmountWithChange; totalCollateral: ExchangeAmountWithChange; totalDebt: ExchangeAmountWithChange; netBalance: ExchangeAmountWithChange; netCollateral: ExchangeAmountWithChange; netApy: PercentNumber; netSupplyApy: PercentNumberWithChange; netBorrowApy: PercentNumberWithChange; netAccruedInterest: ExchangeAmount; healthFactor: HealthFactorWithChange; riskPremium: UserPositionRiskPremium | null; liquidationPrice: ExchangeAmount | null; maxBorrowingPower: ExchangeAmount; remainingBorrowingPower: ExchangeAmount; canUpdateDynamicConfig: boolean; netBalancePercentChange: PercentNumber; averageCollateralFactor: PercentNumber; } ``` ```ts title="UserPositionRiskPremium" interface UserPositionRiskPremium { __typename: "UserPositionRiskPremium"; current: PercentNumber; latest: PercentNumber; breakdown: UserRiskPremiumBreakdownItem[]; } interface UserRiskPremiumBreakdownItem { __typename: "UserRiskPremiumBreakdownItem"; token: Erc20Token; currentRiskPremiumWeight: PercentNumber; latestRiskPremiumWeight: PercentNumber; collateral: PercentNumber; } ``` ```ts title="HealthFactorWithChange" interface HealthFactorWithChange { __typename: "HealthFactorWithChange"; current: BigDecimal | null; change: PercentNumber; } ``` ```ts title="Others" interface ExchangeAmountWithChange { __typename: "ExchangeAmountWithChange"; current: ExchangeAmount; change: PercentNumber; } interface ExchangeAmount { __typename: "ExchangeAmount"; value: BigDecimal; name: string; symbol: string; icon: string; decimals: number; } interface PercentNumberWithChange { __typename: "PercentNumberWithChange"; current: PercentNumber; change: PercentNumber; } ``` The following GraphQL fragments illustrate the core UserPosition type: ```graphql title="UserPosition" fragment UserPosition on UserPosition { __typename id user createdAt spoke { ...Spoke } totalSupplied { ...ExchangeAmountWithChange } totalCollateral { ...ExchangeAmountWithChange } totalDebt { ...ExchangeAmountWithChange } netBalance { ...ExchangeAmountWithChange } netCollateral { ...ExchangeAmountWithChange } netAccruedInterest { ...ExchangeAmount } netApy { ...PercentNumber } netSupplyApy { ...PercentNumberWithChange } netBorrowApy { ...PercentNumberWithChange } healthFactor { ...HealthFactorWithChange } riskPremium { ...UserPositionRiskPremium } liquidationPrice { ...ExchangeAmount } maxBorrowingPower { ...ExchangeAmount } remainingBorrowingPower { ...ExchangeAmount } canUpdateDynamicConfig netBalancePercentChange { ...PercentNumber } averageCollateralFactor { ...PercentNumber } } ``` ```graphql title="UserPositionRiskPremium" fragment UserPositionRiskPremium on UserPositionRiskPremium { __typename current { ...PercentNumber } latest { ...PercentNumber } breakdown { ...UserRiskPremiumBreakdownItem } } fragment UserRiskPremiumBreakdownItem on UserRiskPremiumBreakdownItem { __typename token { ...Erc20Token } currentRiskPremiumWeight { ...PercentNumber } latestRiskPremiumWeight { ...PercentNumber } collateral { ...PercentNumber } } ``` ```graphql title="HealthFactorWithChange" fragment HealthFactorWithChange on HealthFactorWithChange { __typename current change { ...PercentNumber } } ``` ```graphql title="Others" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change { ...PercentNumber } } fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } fragment PercentNumberWithChange on PercentNumberWithChange { __typename current { ...PercentNumber } change { ...PercentNumber } } ``` A user’s position lives inside the spoke contract. The `ISpoke` interface exposes the user’s share balances and risk metrics. ```solidity title="UserPosition Struct" struct UserPosition { uint120 drawnShares; uint120 premiumShares; int200 premiumOffsetRay; uint120 suppliedShares; uint24 dynamicConfigKey; } ``` ```solidity title="UserAccountData Struct" struct UserAccountData { uint256 riskPremium; uint256 avgCollateralFactor; uint256 healthFactor; uint256 totalCollateralValue; uint256 totalDebtValue; uint256 activeCollateralCount; uint256 borrowedCount; } ``` See the [Spoke Data Structure](../liquidity/spokes#spoke-data-structure) for more details. ### Listing User Positions Fetch all user positions with filtering and ordering options. Use the `useUserPositions` hook in React, the `userPositions` action in TypeScript, or the `userPositions` query in GraphQL to fetch positions for a given user address. In TypeScript, the examples also show how to filter by chains or tokens. ```tsx title="Loading State" import { type UserPositionsRequest, useUserPositions } from "@aave/react"; function UserPositionsList({ request }: { request: UserPositionsRequest }) { const { data, loading, error } = useUserPositions(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((position) => (

Position on {position.spoke.name}

Chain: {position.spoke.chain.name}
))}
); } ``` ```tsx title="React Suspense" import { type UserPositionsRequest, useUserPositions } from "@aave/react"; function UserPositionsList({ request }: { request: UserPositionsRequest }) { const { data } = useUserPositions({ ...request, suspense: true, }); return (
{data.map((position) => (

Position on {position.spoke.name}

Chain: {position.spoke.chain.name}
))}
); } ```
```ts title="By Chains" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, }); if (result.isOk()) { console.log(result.value); // UserPosition[] } else { console.error(result.error); } ``` ```ts title="By Tokens" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }); ``` ```graphql title="Query" query ( $request: UserPositionsRequest! $currency: Currency! = USD $window: TimeWindow! = LAST_DAY ) { userPositions(request: $request) { id user createdAt spoke { ...Spoke } totalSupplied(currency: $currency) { ...ExchangeAmountWithChange } totalCollateral(currency: $currency) { ...ExchangeAmountWithChange } totalDebt(currency: $currency) { ...ExchangeAmountWithChange } netBalance(currency: $currency) { ...ExchangeAmountWithChange } netCollateral(currency: $currency) { ...ExchangeAmountWithChange } netApy { ...PercentNumber } netSupplyApy { ...PercentNumberWithChange } netBorrowApy { ...PercentNumberWithChange } healthFactor { ...HealthFactorWithChange } riskPremium { ...UserPositionRiskPremium } liquidationPrice(currency: $currency) { ...ExchangeAmount } maxBorrowingPower(currency: $currency) { ...ExchangeAmount } remainingBorrowingPower(currency: $currency) { ...ExchangeAmount } canUpdateDynamicConfig netBalancePercentChange(window: $window) { ...PercentNumber } averageCollateralFactor { ...PercentNumber } } } ``` ```graphql title="HealthFactorWithChange" fragment HealthFactorWithChange on HealthFactorWithChange { __typename current change(window: $window) { ...PercentNumber } } ``` ```graphql title="ExchangeAmountWithChange" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change(window: $window) { ...PercentNumber } } fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ``` ```graphql title="PercentNumberWithChange" fragment PercentNumberWithChange on PercentNumberWithChange { __typename current { ...PercentNumber } change(window: $window) { ...PercentNumber } } ```
In React and GraphQL, you can filter positions by the following criteria: ```tsx title="By Chains" import { evmAddress, chainId } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)], }, }; ``` ```tsx title="By Tokens" import { evmAddress, chainId } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { tokens: [ { address: evmAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), // USDC chainId: chainId(1), }, { address: evmAddress("0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f"), // GHO chainId: chainId(1), }, ], }, }; ``` ```json title="By Chains" { "request": { "user": "0x456…", "filter": { "chainIds": [1] } } } ``` ```jsonc title="By Tokens" { "request": { "user": "0x456…", "filter": { "tokens": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC "chainId": 1 }, { "address": "0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f", // GHO "chainId": 1 } ] } } } ``` And you can sort positions as follows: ```tsx title="By Balance" import { evmAddress, OrderDirection, type UserPositionsRequest } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { balance: OrderDirection.Asc }, }; ``` ```tsx title="By Net APY" import { evmAddress, OrderDirection, type UserPositionsRequest } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { netApy: OrderDirection.Asc }, }; ``` ```tsx title="By Health Factor" import { evmAddress, OrderDirection, type UserPositionsRequest } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { healthFactor: OrderDirection.Asc }, }; ``` ```tsx title="By Net Collateral" import { evmAddress, OrderDirection, type UserPositionsRequest } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { netCollateral: OrderDirection.Asc }, }; ``` ```tsx title="By Creation Date" import { evmAddress, OrderDirection, type UserPositionsRequest } from "@aave/react"; const request: UserPositionsRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { created: OrderDirection.Asc }, }; ``` ```ts title="By Balance" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, orderBy: { balance: OrderDirection.Asc }, }); ``` ```ts title="By Net APY" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, orderBy: { netApy: OrderDirection.Asc }, }); ``` ```ts title="By Health Factor" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, orderBy: { healthFactor: OrderDirection.Asc }, }); ``` ```ts title="By Net Collateral" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, orderBy: { netCollateral: OrderDirection.Asc }, }); ``` ```ts title="By Creation Date" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userPositions(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, orderBy: { created: OrderDirection.Asc }, }); ``` ```json title="By Balance" { "request": { "user": "0x456…", "filter": { "chainIds": [1] }, "orderBy": { "balance": "ASC" } } } ``` ```json title="By Net APY" { "request": { "user": "0x456…", "filter": { "chainIds": [1] }, "orderBy": { "netApy": "ASC" } } } ``` ```json title="By Health Factor" { "request": { "user": "0x456…", "filter": { "chainIds": [1] }, "orderBy": { "healthFactor": "ASC" } } } ``` ```json title="By Net Collateral" { "request": { "user": "0x456…", "filter": { "chainIds": [1] }, "orderBy": { "netCollateral": "ASC" } } } ``` ```json title="By Creation Date" { "request": { "user": "0x456…", "filter": { "chainIds": [1] }, "orderBy": { "created": "ASC" } } } ``` Finally, you can specify a different time window or currency for the data. ```tsx title="Custom Time Window" import { evmAddress, TimeWindow } from "@aave/react"; const { data, error, loading } = useUserPositions({ user: evmAddress("0x456…"), filter: { // your filter criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { evmAddress, Currency } from "@aave/react"; const { data, error, loading } = useUserPositions({ user: evmAddress("0x456…"), filter: { // your filter criteria }, currency: Currency.Eur, }); ``` ```ts title="Custom Time Window" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userPositions( client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, }, { timeWindow: TimeWindow.LastWeek, } ); ``` ```ts title="Custom Currency" import { userPositions } from "@aave/client/actions"; import { evmAddress, chainId, Currency } from "@aave/client"; import { client } from "./client"; const result = await userPositions( client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)] }, }, { currency: Currency.Eur, } ); ``` ```json title="Custom Currency" { "request": { "user": "0x456…", "filter": { "chainIds": [1] } }, "currency": "EUR" } ``` ```json title="Custom Time Window" { "request": { "user": "0x456…", "filter": { "chainIds": [1] } }, "window": "LAST_WEEK" } ``` In Solidity, to fetch user positions onchain, iterate through each reserve listed on the spoke and fetch the record for the target user. ```solidity title="Get User Positions" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function getUserPositions( address spokeAddress, address user ) external view returns (ISpoke.UserPosition[] memory) { ISpoke spoke = ISpoke(spokeAddress); uint256 reserveCount = spoke.getReserveCount(); ISpoke.UserPosition[] memory positions = new ISpoke.UserPosition[](reserveCount); for (uint256 reserveId = 0; reserveId < reserveCount; reserveId++) { positions[reserveId] = spoke.getUserPosition(reserveId, user); } return positions; } ``` In Solidity, you can also pull aggregate risk metrics directly: ```solidity title="Get User Account Summary" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function getUserAccountSummary( address spokeAddress, address user ) external view returns (ISpoke.UserAccountData memory) { ISpoke spoke = ISpoke(spokeAddress); return spoke.getUserAccountData(user); } ``` ### Fetching a Single Position Fetch a specific user position. Use the `useUserPosition` hook in React, the `userPosition` action in TypeScript, or the `userPosition` query in GraphQL to fetch a specific user position. In TypeScript, the examples also show how to query by user and spoke or by position ID, and how to specify a different time window or currency. ```tsx title="Loading State" import { type UserPositionRequest, useUserPosition } from "@aave/react"; function UserPositionDetail({ request }: { request: UserPositionRequest }) { const { data, loading, error } = useUserPosition(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; if (!data) return
Position not found
; return (

Position {data.id}

Net Balance: {data.netBalance.current.value.toDisplayString(2)} Health Factor: {data.healthFactor.current?.toFixed(2) ?? "N/A"}
); } ``` ```tsx title="React Suspense" import { type UserPositionRequest, useUserPosition } from "@aave/react"; function UserPositionDetail({ request }: { request: UserPositionRequest }) { const { data } = useUserPosition({ ...request, suspense: true, }); if (!data) return
Position not found
; return (

Position {data.id}

Net Balance: {data.netBalance.current.value.toDisplayString(2)} Health Factor: {data.healthFactor.current?.toFixed(2) ?? "N/A"}
); } ```
```ts title="By User & Spoke" import { userPosition } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userPosition(client, { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, }, }); if (result.isOk()) { console.log(result.value); // UserPosition | null } else { console.error(result.error); } ``` ```ts title="By Position ID" import { userPosition } from "@aave/client/actions"; import { userPositionId } from "@aave/client"; import { client } from "./client"; const id = userPositionId("SGVsbG8h"); const result = await userPosition(client, { id }); ``` ```ts title="Custom Time Window" import { userPosition } from "@aave/client/actions"; import { TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userPosition( client, { // your query criteria }, { timeWindow: TimeWindow.LastWeek, } ); ``` ```ts title="Custom Currency" import { userPosition } from "@aave/client/actions"; import { Currency } from "@aave/client"; import { client } from "./client"; const result = await userPosition( client, { // your query criteria }, { currency: Currency.Eur, } ); ``` ```graphql title="Query" query ( $request: UserPositionRequest! $currency: Currency! = USD $window: TimeWindow! = LAST_DAY ) { userPosition(request: $request) { id user createdAt spoke { ...Spoke } totalSupplied(currency: $currency) { ...ExchangeAmountWithChange } totalCollateral(currency: $currency) { ...ExchangeAmountWithChange } totalDebt(currency: $currency) { ...ExchangeAmountWithChange } netBalance(currency: $currency) { ...ExchangeAmountWithChange } netCollateral(currency: $currency) { ...ExchangeAmountWithChange } netApy { ...PercentNumber } netSupplyApy { ...PercentNumberWithChange } netBorrowApy { ...PercentNumberWithChange } healthFactor { ...HealthFactorWithChange } riskPremium { ...UserPositionRiskPremium } liquidationPrice(currency: $currency) { ...ExchangeAmount } maxBorrowingPower(currency: $currency) { ...ExchangeAmount } remainingBorrowingPower(currency: $currency) { ...ExchangeAmount } canUpdateDynamicConfig netBalancePercentChange(window: $window) { ...PercentNumber } averageCollateralFactor { ...PercentNumber } } } ``` ```graphql title="HealthFactorWithChange" fragment HealthFactorWithChange on HealthFactorWithChange { __typename current change(window: $window) { ...PercentNumber } } ``` ```graphql title="ExchangeAmountWithChange" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change(window: $window) { ...PercentNumber } } fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ``` ```graphql title="PercentNumberWithChange" fragment PercentNumberWithChange on PercentNumberWithChange { __typename current { ...PercentNumber } change(window: $window) { ...PercentNumber } } ```
Query by user and spoke or by position ID. - **React**: See below for examples of `UserPositionRequest` objects. - **GraphQL**: Use the `request` field; the examples also show how to specify a different currency or time window. ```tsx title="By Position ID" import { userPositionId } from "@aave/react"; const request: UserPositionRequest = { id: userPositionId(params.id), // UserPositionId - typically from URL params }; ``` ```tsx title="By User & Spoke" import { evmAddress } from "@aave/react"; const request: UserPositionRequest = { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, }, }; ``` ```json title="By User & Spoke" { "request": { "userSpoke": { "user": "0x456…", "spoke": "SGVsbG8h" } } } ``` ```json title="By Position ID" { "request": { "id": "SGVsbG8h" } } ``` ```jsonc title="Custom Currency" { "request": { // your query criteria }, "currency": "EUR" } ``` ```jsonc title="Custom Time Window" { "request": { // your query criteria }, "window": "LAST_WEEK" } ``` In React, you can also specify a different time window or currency for the data. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useUserPosition({ // your query criteria timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, error, loading } = useUserPosition({ // your query criteria currency: Currency.Eur, }); ``` In Solidity, positions are identified by the spoke’s `reserveId` and the user address onchain. To inspect a single position, call `getUserPosition` on the spoke with the reserve ID and user address. ```solidity title="Get Single User Position" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function getUserPosition( address spokeAddress, uint256 reserveId, address user ) external view returns ( ISpoke.UserPosition memory position, bool isBorrowing, bool usingAsCollateral ) { ISpoke spoke = ISpoke(spokeAddress); position = spoke.getUserPosition(reserveId, user); (usingAsCollateral, isBorrowing) = spoke.getUserReserveStatus(reserveId, user); return (position, isBorrowing, usingAsCollateral); } ``` ## User Supplies ### User Supply Data Structure User supply data provides detailed information about individual user supplies within a spoke, including: - Reserve details: token information, supply APY, lending limits - Position amounts: current balance, principal, earned interest, and withdrawable amounts - Collateral status: whether the supply is used as collateral - Performance metrics: earned interest over time The following TypeScript interfaces illustrate the UserSupplyItem type: ```ts title="UserSupplyItem" interface UserSupplyItem { __typename: "UserSupplyItem"; id: UserSupplyItemId; reserve: Reserve; principal: Erc20Amount; balance: Erc20Amount; withdrawable: Erc20Amount; interest: Erc20Amount; isCollateral: boolean; } ``` The following GraphQL fragments illustrate the UserSupplyItem type: ```graphql title="UserSupplyItem" fragment UserSupplyItem on UserSupplyItem { __typename id reserve { ...Reserve } principal { ...Erc20Amount } balance { ...Erc20Amount } withdrawable { ...Erc20Amount } interest { ...Erc20Amount } isCollateral } ``` See the [Reserve Data Structure](../liquidity/reserves#reserve-data-structure) for more details. ### Fetching User Supplies Fetch user supplies within a specific spoke. Use the `useUserSupplies` hook in React, the `userSupplies` action in TypeScript, or the `userSupplies` query in GraphQL to fetch user supplies for a user. In TypeScript, the examples also show the supported fetch criteria. ```tsx title="Loading State" import { type UserSuppliesRequest, useUserSupplies } from "@aave/react"; function UserSuppliesList({ request }: { request: UserSuppliesRequest }) { const { data, loading, error } = useUserSupplies(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((supply) => (

{supply.reserve.asset.underlying.info.name}

Amount: {supply.withdrawable.amount.value.toDisplayString(2)}
))}
); } ``` ```tsx title="React Suspense" import { type UserSuppliesRequest, useUserSupplies } from "@aave/react"; function UserSuppliesList({ request }: { request: UserSuppliesRequest }) { const { data } = useUserSupplies({ ...request, suspense: true, }); return (
{data.map((supply) => (

{supply.reserve.asset.underlying.info.name}

Amount: {supply.withdrawable.amount.value.toDisplayString(2)}
))}
); } ```
```ts title="By Position ID" import { userSupplies } from "@aave/client/actions"; import { client } from "./client"; const result = await userSupplies(client, { query: { userPositionId: position.id, // position: UserPosition }, }); if (result.isOk()) { console.log(result.value); // UserSupplyItem[] } else { console.error(result.error); } ``` ```ts title="By Spoke" import { userSupplies } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, // spoke: Spoke }, }, }); ``` ```ts title="By Chain IDs" import { userSupplies } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { userChains: { user: evmAddress("0x456…"), chainIds: [chainId(1)], }, }, }); ``` ```ts title="By Hub" import { userSupplies } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { userHub: { user: evmAddress("0x456…"), hub: { id: hub.id, // hub: Hub }, }, }, }); ``` ```ts title="By Symbol Across Chains" import { userSupplies } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { userSymbol: { user: evmAddress("0x456…"), symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }); ``` ```graphql title="Query" query ($request: UserSuppliesRequest!, $currency: Currency! = USD) { userSupplies(request: $request) { id reserve { ...Reserve } principal { ...Erc20Amount } balance { ...Erc20Amount } withdrawable { ...Erc20Amount } interest { ...Erc20Amount } isCollateral } } ``` ```graphql title="Erc20Amount" fragment Erc20Amount on Erc20Amount { __typename amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } token { ...Erc20Token } } ```
See below for examples of fetch criteria. - **React**: These are `UserSuppliesRequest` objects. - **GraphQL**: Use the `query` field to specify the fetch criteria. ```tsx title="By Position ID" const request: UserSuppliesRequest = { query: { userPositionId: position.id, // position: UserPosition }, }; ``` ```tsx title="By Spoke" import { evmAddress } from "@aave/react"; const request: UserSuppliesRequest = { query: { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, // spoke: Spoke }, }, }; ``` ```tsx title="By Chain IDs" import { evmAddress, chainId } from "@aave/react"; const request: UserSuppliesRequest = { query: { userChains: { user: evmAddress("0x456…"), chainIds: [chainId(1)], }, }, }; ``` ```tsx title="By Hub" import { evmAddress } from "@aave/react"; const request: UserSuppliesRequest = { query: { userHub: { user: evmAddress("0x456…"), hub: { id: hub.id, // hub: Hub }, }, }, }; ``` ```tsx title="By Symbol Across Chains" import { chainId, evmAddress } from "@aave/react"; const request: UserSuppliesRequest = { query: { userSymbol: { user: evmAddress("0x456…"), symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }; ``` ```json title="By Position ID" { "request": { "query": { "userPositionId": "SGVsbG8h" } } } ``` ```json title="By Spoke" { "request": { "query": { "userSpoke": { "user": "0x456…", "spoke": "SGVsbG8h" } } } } ``` ```json title="By Chain IDs" { "request": { "query": { "userChains": { "user": "0x456…", "chainIds": [1] } } } } ``` ```json title="By Hub" { "request": { "query": { "userHub": { "user": "0x456…", "hub": { "id": "SGVsbG8h" } } } } } ``` ```json title="By Symbol Across Chains" { "request": { "query": { "userSymbol": { "user": "0x456…", "symbol": "USDC", "chainIds": [1, 43114] } } } } ``` Sort user supplies by asset name, amount, or supply APY. ```tsx title="By Asset Name" import { OrderDirection } from "@aave/react"; const request: UserSuppliesRequest = { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }; ``` ```tsx title="By Amount" import { OrderDirection } from "@aave/react"; const request: UserSuppliesRequest = { query: { // your query criteria }, orderBy: { amount: OrderDirection.Desc }, }; ``` ```tsx title="By APY" import { OrderDirection } from "@aave/react"; const request: UserSuppliesRequest = { query: { // your query criteria }, orderBy: { apy: OrderDirection.Desc }, }; ``` ```ts title="By Asset Name" import { userSupplies } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }); ``` ```ts title="By Amount" import { userSupplies } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { // your query criteria }, orderBy: { amount: OrderDirection.Desc }, }); ``` ```ts title="By APY" import { userSupplies } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { // your query criteria }, orderBy: { apy: OrderDirection.Desc }, }); ``` ```jsonc title="By Asset Name" { "request": { "query": { // your query criteria }, "orderBy": { "assetName": "ASC" } } } ``` ```jsonc title="By Amount" { "request": { "query": { // your query criteria }, "orderBy": { "amount": "DESC" } } } ``` ```jsonc title="By APY" { "request": { "query": { // your query criteria }, "orderBy": { "apy": "DESC" } } } ``` Include zero-value entries for all other supply reserves available on the same spoke, typically ordered by descending amount. ```tsx title="Include Zero Balances" import { OrderDirection } from "@aave/react"; const request: UserSuppliesRequest = { query: { // your query criteria }, includeZeroBalances: true, orderBy: { amount: OrderDirection.Desc }, }; ``` ```ts title="Include Zero Balances" import { userSupplies } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userSupplies(client, { query: { // your query criteria }, includeZeroBalances: true, orderBy: { amount: OrderDirection.Desc }, }); ``` ```jsonc title="Include Zero Balances" { "request": { "query": { // your query criteria }, "includeZeroBalances": true, "orderBy": { "amount": "DESC" } } } ``` Finally, you can specify a different currency for displaying fiat amounts. In React, you can also specify a different time window. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useUserSupplies({ query: { // your query criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, error, loading } = useUserSupplies({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { userSupplies } from "@aave/client/actions"; import { Currency } from "@aave/client"; import { client } from "./client"; const result = await userSupplies( client, { query: { // your query criteria }, }, { currency: Currency.Eur, } ); ``` ```jsonc title="Custom Currency" { "request": { "query": { // your query criteria } }, "currency": "EUR" } ``` In Solidity, supply balances are exposed per reserve on the spoke. Loop through all reserves and inspect `suppliedShares` for the target user, converting them to asset amounts using the hub’s exchange rate. Here’s a complete example: ```solidity title="Get User Supplies" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; struct UserSupply { uint256 reserveId; address underlying; uint256 suppliedAmount; bool isCollateral; } function getUserSupplies( address spokeAddress, address user ) external view returns (UserSupply[] memory) { ISpoke spoke = ISpoke(spokeAddress); uint256 reserveCount = spoke.getReserveCount(); UserSupply[] memory supplies = new UserSupply[](reserveCount); uint256 supplyCount = 0; for (uint256 reserveId = 0; reserveId < reserveCount; reserveId++) { ISpoke.UserPosition memory position = spoke.getUserPosition(reserveId, user); if (position.suppliedShares > 0) { ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); (bool isCollateral, ) = spoke.getUserReserveStatus(reserveId, user); supplies[supplyCount] = UserSupply({ reserveId: reserveId, underlying: reserve.underlying, suppliedAmount: reserve.hub.previewRemoveByShares(reserve.assetId, position.suppliedShares), isCollateral: isCollateral }); supplyCount++; } } UserSupply[] memory result = new UserSupply[](supplyCount); for (uint256 i = 0; i < supplyCount; i++) { result[i] = supplies[i]; } return result; } ``` User positions store balances as shares. Use the hub’s `previewRemoveByShares` to convert shares to the underlying asset amount, accounting for accrued interest. ## User Borrows ### User Borrow Data Structure User borrow data provides detailed information about individual borrow positions within a spoke, including: - Reserve details: token information, borrow APY, borrowing limits - Position amounts: principal and current debt, with token details - Performance metrics: accrued interest The following TypeScript interfaces illustrate the UserBorrowItem type: ```ts title="UserBorrowItem" interface UserBorrowItem { __typename: "UserBorrowItem"; id: UserBorrowItemId; reserve: Reserve; principal: Erc20Amount; debt: Erc20Amount; interest: Erc20Amount; } ``` The following GraphQL fragments illustrate the UserBorrowItem type: ```graphql title="UserBorrowItem" fragment UserBorrowItem on UserBorrowItem { __typename id reserve { ...Reserve } principal { ...Erc20Amount } debt { ...Erc20Amount } interest { ...Erc20Amount } } ``` See the [Reserve Data Structure](../liquidity/reserves#reserve-data-structure) for more details. ### Fetching User Borrows Fetch user borrows within a specific spoke. Use the `useUserBorrows` hook in React, the `userBorrows` action in TypeScript, or the `userBorrows` query in GraphQL to fetch borrow positions for a user. In TypeScript, the examples also show the supported fetch criteria. ```tsx title="Loading State" import { type UserBorrowsRequest, useUserBorrows } from "@aave/react"; function UserBorrowsList({ request }: { request: UserBorrowsRequest }) { const { data, loading, error } = useUserBorrows(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((borrow) => (

{borrow.reserve.asset.underlying.info.name}

Amount: {borrow.debt.amount.value.toDisplayString(2)}
))}
); } ``` ```tsx title="React Suspense" import { type UserBorrowsRequest, useUserBorrows } from "@aave/react"; function UserBorrowsList({ request }: { request: UserBorrowsRequest }) { const { data } = useUserBorrows({ ...request, suspense: true, }); return (
{data.map((borrow) => (

{borrow.reserve.asset.underlying.info.name}

Amount: {borrow.debt.amount.value.toDisplayString(2)}
))}
); } ```
```ts title="By Position ID" import { userBorrows } from "@aave/client/actions"; import { client } from "./client"; const result = await userBorrows(client, { query: { userPositionId: position.id, // position: UserPosition }, }); if (result.isOk()) { console.log(result.value); // UserBorrowItem[] } else { console.error(result.error); } ``` ```ts title="By Spoke" import { userBorrows } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, // spoke: Spoke }, }, }); ``` ```ts title="By Chain IDs" import { userBorrows } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { userChains: { user: evmAddress("0x456…"), chainIds: [chainId(1)], }, }, }); ``` ```ts title="By Hub" import { userBorrows } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { userHub: { user: evmAddress("0x456…"), hub: { id: hub.id, // hub: Hub }, }, }, }); ``` ```ts title="By Symbol Across Chains" import { userBorrows } from "@aave/client/actions"; import { chainId, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { userSymbol: { user: evmAddress("0x456…"), symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }); ``` ```graphql title="Query" query ($request: UserBorrowsRequest!, $currency: Currency! = USD) { userBorrows(request: $request) { id reserve { ...Reserve } principal { ...Erc20Amount } debt { ...Erc20Amount } interest { ...Erc20Amount } } } ``` ```graphql title="Erc20Amount" fragment Erc20Amount on Erc20Amount { __typename amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } token { ...Erc20Token } } ```
See below for examples of fetch criteria. - **React**: These are `UserBorrowsRequest` objects. - **GraphQL**: Use the `query` field to specify the fetch criteria. ```tsx title="By Position ID" const request: UserBorrowsRequest = { query: { userPositionId: position.id, // position: UserPosition }, }; ``` ```tsx title="By Spoke" import { evmAddress } from "@aave/react"; const request: UserBorrowsRequest = { query: { userSpoke: { user: evmAddress("0x456…"), spoke: spoke.id, // spoke: Spoke }, }, }; ``` ```tsx title="By Chain IDs" import { evmAddress, chainId } from "@aave/react"; const request: UserBorrowsRequest = { query: { userChains: { user: evmAddress("0x456…"), chainIds: [chainId(1)], }, }, }; ``` ```tsx title="By Hub" import { evmAddress } from "@aave/react"; const request: UserBorrowsRequest = { query: { userHub: { user: evmAddress("0x456…"), hub: { id: hub.id, // hub: Hub }, }, }, }; ``` ```tsx title="By Symbol Across Chains" import { chainId, evmAddress } from "@aave/react"; const request: UserBorrowsRequest = { query: { userSymbol: { user: evmAddress("0x456…"), symbol: "USDC", chainIds: [chainId(1), chainId(43114)], // optional; omit to match all chains }, }, }; ``` ```json title="By Position ID" { "request": { "query": { "userPositionId": "SGVsbG8h" } } } ``` ```json title="By Spoke" { "request": { "query": { "userSpoke": { "user": "0x456…", "spoke": "SGVsbG8h" } } } } ``` ```json title="By Chain IDs" { "request": { "query": { "userChains": { "user": "0x456…", "chainIds": [1] } } } } ``` ```json title="By Hub" { "request": { "query": { "userHub": { "user": "0x456…", "hub": { "id": "SGVsbG8h" } } } } } ``` ```json title="By Symbol Across Chains" { "request": { "query": { "userSymbol": { "user": "0x456…", "symbol": "USDC", "chainIds": [1, 43114] } } } } ``` Sort user borrows by asset name, amount, or borrow APY. ```tsx title="By Asset Name" import { OrderDirection } from "@aave/react"; const request: UserBorrowsRequest = { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }; ``` ```tsx title="By Amount" import { OrderDirection } from "@aave/react"; const request: UserBorrowsRequest = { query: { // your query criteria }, orderBy: { amount: OrderDirection.Desc }, }; ``` ```tsx title="By APY" import { OrderDirection } from "@aave/react"; const request: UserBorrowsRequest = { query: { // your query criteria }, orderBy: { apy: OrderDirection.Desc }, }; ``` ```ts title="By Asset Name" import { userBorrows } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { // your query criteria }, orderBy: { assetName: OrderDirection.Asc }, }); ``` ```ts title="By Amount" import { userBorrows } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { // your query criteria }, orderBy: { amount: OrderDirection.Desc }, }); ``` ```ts title="By APY" import { userBorrows } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { // your query criteria }, orderBy: { apy: OrderDirection.Desc }, }); ``` ```jsonc title="By Asset Name" { "request": { "query": { // your query criteria }, "orderBy": { "assetName": "ASC" } } } ``` ```jsonc title="By Amount" { "request": { "query": { // your query criteria }, "orderBy": { "amount": "DESC" } } } ``` ```jsonc title="By APY" { "request": { "query": { // your query criteria }, "orderBy": { "apy": "DESC" } } } ``` Include zero-value entries for all other borrow reserves available on the same spoke, typically ordered by descending amount. ```tsx title="Include Zero Balances" import { OrderDirection } from "@aave/react"; const request: UserBorrowsRequest = { query: { // your query criteria }, includeZeroBalances: true, orderBy: { amount: OrderDirection.Desc }, }; ``` ```ts title="Include Zero Balances" import { userBorrows } from "@aave/client/actions"; import { OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBorrows(client, { query: { // your query criteria }, includeZeroBalances: true, orderBy: { amount: OrderDirection.Desc }, }); ``` ```jsonc title="Include Zero Balances" { "request": { "query": { // your query criteria }, "includeZeroBalances": true, "orderBy": { "amount": "DESC" } } } ``` Finally, you can specify a different currency for displaying fiat amounts. In React, you can also specify a different time window. ```tsx title="Custom Time Window" import { TimeWindow } from "@aave/react"; const { data, error, loading } = useUserBorrows({ query: { // your query criteria }, timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { Currency } from "@aave/react"; const { data, error, loading } = useUserBorrows({ query: { // your query criteria }, currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { userBorrows } from "@aave/client/actions"; import { Currency } from "@aave/client"; import { client } from "./client"; const result = await userBorrows( client, { query: { // your query criteria }, }, { currency: Currency.Eur, } ); ``` ```jsonc title="Custom Currency" { "request": { "query": { // your query criteria } }, "currency": "EUR" } ``` In Solidity, borrow balances are exposed per reserve on the spoke. Loop through all reserves and read each borrowed reserve’s total debt for the target user with `getUserTotalDebt`. Here’s a complete example: ```solidity title="Get User Borrows" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; struct UserBorrow { uint256 reserveId; address underlying; uint256 borrowedAmount; } function getUserBorrows( address spokeAddress, address user ) external view returns (UserBorrow[] memory) { ISpoke spoke = ISpoke(spokeAddress); uint256 reserveCount = spoke.getReserveCount(); UserBorrow[] memory borrows = new UserBorrow[](reserveCount); uint256 borrowCount = 0; for (uint256 reserveId = 0; reserveId < reserveCount; reserveId++) { ISpoke.UserPosition memory position = spoke.getUserPosition(reserveId, user); if (position.drawnShares > 0) { borrows[borrowCount] = UserBorrow({ reserveId: reserveId, underlying: spoke.getReserve(reserveId).underlying, borrowedAmount: spoke.getUserTotalDebt(reserveId, user) }); borrowCount++; } } UserBorrow[] memory result = new UserBorrow[](borrowCount); for (uint256 i = 0; i < borrowCount; i++) { result[i] = borrows[i]; } return result; } ``` Use the Spoke’s `getUserTotalDebt` to get the drawn plus premium debt in asset units, including accrued interest. ## User Summary ### User Summary Data Structure User summary data describes a user’s aggregated activity across all positions: - Position count: total number of positions held by the user - Portfolio totals: supplied amounts, collateral amounts, debt amounts, net balances - Yield information: calculated net APY across all positions - Risk metrics: lowest health factor across all positions - Performance data: net accrued interest across all positions The following TypeScript interfaces illustrate the UserSummary type: ```ts title="UserSummary" interface UserSummary { __typename: "UserSummary"; totalPositions: number; netBalance: ExchangeAmountWithChange; totalCollateral: ExchangeAmount; totalSupplied: ExchangeAmount; totalDebt: ExchangeAmount; netApy: PercentNumber; netAccruedInterest: ExchangeAmount; lowestHealthFactor: BigDecimal | null; } ``` ```ts title="ExchangeAmountWithChange" interface ExchangeAmountWithChange { __typename: "ExchangeAmountWithChange"; current: ExchangeAmount; change: PercentNumber; } ``` The following GraphQL fragments illustrate the UserSummary type: ```graphql title="UserSummary" fragment UserSummary on UserSummary { __typename totalPositions netBalance { ...ExchangeAmountWithChange } totalCollateral { ...ExchangeAmount } totalSupplied { ...ExchangeAmount } totalDebt { ...ExchangeAmount } netApy { ...PercentNumber } netAccruedInterest { ...ExchangeAmount } lowestHealthFactor } ``` ```graphql title="ExchangeAmountWithChange" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change { ...PercentNumber } } ``` ### Fetching User Summary Fetch a financial summary for a user across all their positions. Use the `useUserSummary` hook in React, the `userSummary` action in TypeScript, or the `userSummary` query in GraphQL to fetch the financial summary for a user. In TypeScript, the examples also show how to filter the summary. ```tsx title="Loading State" import { type UserSummaryRequest, useUserSummary } from "@aave/react"; function UserSummaryDisplay({ request }: { request: UserSummaryRequest }) { const { data, loading, error } = useUserSummary(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (

Financial Summary

Total Positions: {data.totalPositions}

Net Balance: {data.netBalance.current.symbol} {data.netBalance.current.value.toDisplayString(2)}

Total Supplied: {data.totalSupplied.symbol} {data.totalSupplied.value.toDisplayString(2)}

Total Debt: {data.totalDebt.symbol} {data.totalDebt.value.toDisplayString(2)}

Net APY: {data.netApy.normalized.toFixed(2)}%
); } ``` ```tsx title="React Suspense" import { type UserSummaryRequest, useUserSummary } from "@aave/react"; function UserSummaryDisplay({ request }: { request: UserSummaryRequest }) { const { data } = useUserSummary({ ...request, suspense: true, }); return (

Financial Summary

Total Positions: {data.totalPositions}

Net Balance: {data.netBalance.current.symbol} {data.netBalance.current.value.toDisplayString(2)}

Total Supplied: {data.totalSupplied.symbol} {data.totalSupplied.value.toDisplayString(2)}

Total Debt: {data.totalDebt.symbol} {data.totalDebt.value.toDisplayString(2)}

Net APY: {data.netApy.normalized.toFixed(2)}%
); } ```
```ts title="Basic Usage" import { userSummary } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSummary(client, { user: evmAddress("0x456…"), }); if (result.isOk()) { console.log(result.value); // UserSummary } else { console.error(result.error); } ``` ```ts title="Filter by Spoke ID" import { userSummary } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSummary(client, { user: evmAddress("0x456…"), filter: { spokeId: spoke.id, }, }); ``` ```ts title="Filter by Chains" import { userSummary } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userSummary(client, { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)], }, }); ``` ```ts title="Filter by Position ID" import { userSummary } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userSummary(client, { user: evmAddress("0x456…"), filter: { userPositionId: position.id, }, }); ``` ```ts title="Filter by Spoke Details" import { userSummary } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userSummary(client, { user: evmAddress("0x456…"), filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```graphql title="Query" query ( $request: UserSummaryRequest! $currency: Currency! = USD $window: TimeWindow! = LAST_DAY ) { userSummary(request: $request) { totalPositions netBalance(currency: $currency) { ...ExchangeAmountWithChange } totalCollateral(currency: $currency) { ...ExchangeAmount } totalSupplied(currency: $currency) { ...ExchangeAmount } totalDebt(currency: $currency) { ...ExchangeAmount } netApy { ...PercentNumber } netAccruedInterest(currency: $currency) { ...ExchangeAmount } lowestHealthFactor } } ``` ```graphql title="ExchangeAmountWithChange" fragment ExchangeAmountWithChange on ExchangeAmountWithChange { __typename current { ...ExchangeAmount } change(window: $window) { ...PercentNumber } } ```
- **React**: See below for examples of `UserSummaryRequest` objects. - **GraphQL**: Use the `user` field to specify the user. ```tsx title="Basic Usage" import { evmAddress } from "@aave/react"; const request: UserSummaryRequest = { user: evmAddress("0x456…"), }; ``` ```tsx title="Filter by Spoke ID" import { evmAddress } from "@aave/react"; const request: UserSummaryRequest = { user: evmAddress("0x456…"), filter: { spokeId: spoke.id, }, }; ``` ```tsx title="Filter by Chains" import { evmAddress, chainId } from "@aave/react"; const request: UserSummaryRequest = { user: evmAddress("0x456…"), filter: { chainIds: [chainId(1)], }, }; ``` ```tsx title="Filter by Position ID" import { evmAddress } from "@aave/react"; const request: UserSummaryRequest = { user: evmAddress("0x456…"), filter: { userPositionId: position.id, }, }; ``` ```tsx title="Filter by Spoke Details" import { evmAddress, chainId } from "@aave/react"; const request: UserSummaryRequest = { user: evmAddress("0x456…"), filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```json title="Basic Request" { "request": { "user": "0x456…" } } ``` In GraphQL, filter the summary by specific spokes or chains using the `filter` field. ```json title="Filter by Spoke ID" { "request": { "user": "0x456…", "filter": { "spokeId": "SGVsbG8h" } } } ``` ```json title="Filter by Chains" { "request": { "user": "0x456…", "filter": { "chainIds": [1] } } } ``` ```json title="Filter by Position ID" { "request": { "user": "0x456…", "filter": { "userPositionId": "SGVsbG8h" } } } ``` ```json title="Filter by Spoke Details" { "request": { "user": "0x456…", "filter": { "spoke": { "address": "0x123…", "chainId": 1 } } } } ``` Finally, you can specify a different time window or currency for the data. ```tsx title="Custom Time Window" import { evmAddress, TimeWindow } from "@aave/react"; const { data, error, loading } = useUserSummary({ user: evmAddress("0x456…"), timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { evmAddress, Currency, useUserSummary } from "@aave/react"; const { data, error, loading } = useUserSummary({ user: evmAddress("0x456…"), currency: Currency.Eur, }); ``` ```ts title="Custom Time Window" import { userSummary } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummary( client, { user: evmAddress("0x456…"), }, { timeWindow: TimeWindow.LastWeek, } ); ``` ```ts title="Custom Currency" import { userSummary } from "@aave/client/actions"; import { evmAddress, Currency } from "@aave/client"; import { client } from "./client"; const result = await userSummary( client, { user: evmAddress("0x456…"), }, { currency: Currency.Eur, } ); ``` ```jsonc title="Custom Currency" { "request": { // your query criteria }, "currency": "EUR" } ``` ```jsonc title="Custom Time Window" { "request": { // your query criteria }, "window": "LAST_WEEK" } ``` ## User Summary History ### User Summary History Data Structure User summary history data provides detailed information about a user’s activity changes over time, including: - Historical snapshots: portfolio state at different points in time - Portfolio metrics: net balance, borrows, supplies at each snapshot - Risk metrics: health factor changes over time The following TypeScript interfaces illustrate the UserSummaryHistoryItem type: ```ts title="UserSummaryHistoryItem" interface UserSummaryHistoryItem { __typename: "UserSummaryHistoryItem"; netBalance: ExchangeAmount; borrows: ExchangeAmount; supplies: ExchangeAmount; healthFactor: BigDecimal | null; date: Date; } ``` The following GraphQL fragments illustrate the UserSummaryHistoryItem type: ```graphql title="UserSummaryHistoryItem" fragment UserSummaryHistoryItem on UserSummaryHistoryItem { __typename netBalance { ...ExchangeAmount } borrows { ...ExchangeAmount } supplies { ...ExchangeAmount } healthFactor date } ``` ### Fetching User Summary History Fetch historical financial data for a user over a specified time window. Use the `useUserSummaryHistory` hook in React, the `userSummaryHistory` action in TypeScript, or the `userSummaryHistory` query in GraphQL to fetch historical financial data for a user. In TypeScript, the examples also show how to set the time window. ```tsx title="Loading State" import { type UserSummaryHistoryRequest, useUserSummaryHistory, } from "@aave/react"; function UserSummaryHistory({ request, }: { request: UserSummaryHistoryRequest; }) { const { data, loading, error } = useUserSummaryHistory(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (

Financial History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Net Balance: {item.netBalance.symbol} {item.netBalance.value.toDisplayString(2)}

Supplies: {item.supplies.symbol} {item.supplies.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

))}
); } ``` ```tsx title="React Suspense" import { type UserSummaryHistoryRequest, useUserSummaryHistory, } from "@aave/react"; function UserSummaryHistory({ request, }: { request: UserSummaryHistoryRequest; }) { const { data } = useUserSummaryHistory({ ...request, suspense: true, }); return (

Financial History

{data.map((item) => (
Date: {item.date.toLocaleDateString()}

Net Balance: {item.netBalance.symbol} {item.netBalance.value.toDisplayString(2)}

Supplies: {item.supplies.symbol} {item.supplies.value.toDisplayString(2)}

Borrows: {item.borrows.symbol} {item.borrows.value.toDisplayString(2)}

))}
); } ```
```ts title="Last Day" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastDay, }); if (result.isOk()) { console.log(result.value); // UserSummaryHistoryItem[] } else { console.error(result.error); } ``` ```ts title="Last Week" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, }); ``` ```ts title="Last Month" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastMonth, }); ``` ```graphql title="Query" query ($request: UserSummaryHistoryRequest!, $currency: Currency! = USD) { userSummaryHistory(request: $request) { netBalance(currency: $currency) { ...ExchangeAmount } borrows(currency: $currency) { ...ExchangeAmount } supplies(currency: $currency) { ...ExchangeAmount } healthFactor date } } ```
- **React**: See below for examples of `UserSummaryHistoryRequest` objects. - **GraphQL**: Use the `user` and `window` fields to specify the user and time period. ```tsx title="Last Day" import { evmAddress, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastDay, }; ``` ```tsx title="Last Week" import { evmAddress, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, }; ``` ```tsx title="Last Month" import { evmAddress, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastMonth, }; ``` ```json title="Last Day" { "request": { "user": "0x456…", "window": "LAST_DAY" } } ``` ```json title="Last Week" { "request": { "user": "0x456…", "window": "LAST_WEEK" } } ``` ```json title="Last Month" { "request": { "user": "0x456…", "window": "LAST_MONTH" } } ``` Filter the history by specific spokes or chains. In GraphQL, use the `filter` field. ```tsx title="Filter by Spoke ID" import { evmAddress, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { spokeId: spoke.id, }, }; ``` ```tsx title="Filter by Chains" import { evmAddress, chainId, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { chainIds: [chainId(1)], }, }; ``` ```tsx title="Filter by Position ID" import { evmAddress, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { userPositionId: position.id, }, }; ``` ```tsx title="Filter by Spoke Details" import { evmAddress, chainId, TimeWindow } from "@aave/react"; const request: UserSummaryHistoryRequest = { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```ts title="Filter by Spoke ID" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { spokeId: spoke.id, }, }); ``` ```ts title="Filter by Chains" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, chainId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { chainIds: [chainId(1)], }, }); ``` ```ts title="Filter by Position ID" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { userPositionId: position.id, }, }); ``` ```ts title="Filter by Spoke Details" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, chainId, TimeWindow } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory(client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```json title="Filter by Spoke ID" { "request": { "user": "0x456…", "window": "LAST_WEEK", "filter": { "spokeId": "SGVsbG8h" } } } ``` ```json title="Filter by Chains" { "request": { "user": "0x456…", "window": "LAST_WEEK", "filter": { "chainIds": [1] } } } ``` ```json title="Filter by Position ID" { "request": { "user": "0x456…", "window": "LAST_WEEK", "filter": { "userPositionId": "SGVsbG8h" } } } ``` ```json title="Filter by Spoke Details" { "request": { "user": "0x456…", "window": "LAST_WEEK", "filter": { "spoke": { "address": "0x123…", "chainId": 1 } } } } ``` Finally, you can specify a different currency for displaying fiat amounts. ```tsx title="Custom Currency" import { Currency, evmAddress, TimeWindow } from "@aave/react"; const { data, error, loading } = useUserSummaryHistory({ user: evmAddress("0x456…"), window: TimeWindow.LastWeek, currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { userSummaryHistory } from "@aave/client/actions"; import { evmAddress, TimeWindow, Currency } from "@aave/client"; import { client } from "./client"; const result = await userSummaryHistory( client, { user: evmAddress("0x456…"), window: TimeWindow.LastWeek, }, { currency: Currency.Eur, } ); ``` ```jsonc title="Custom Currency" { "request": { // your query criteria }, "currency": "EUR" } ``` --- Source: https://aave.com/docs/aave-v4/positions/supply.md # Supply Assets on Aave V4 Supplying assets to Aave V4 allows you to: - Receive reserve shares representing your deposit - Earn variable supply APY on your reserve shares - Use reserve shares as collateral for borrowing - Withdraw assets and earnings anytime > [!NOTE] > Supplying collateral while you have open debt can raise your health factor. ## Supply Assets Supplying assets to Aave can be broken down into the following steps: 1. Identify the Reserve 2. Preview the impact of the supply operation (optional) 3. Supply the assets ### Identify the Reserve The first step is to [filter the supply reserves](../liquidity/reserves#listing-available-reserves) to those marked with `canSupply: true`. ```tsx title="Reserves List" const reserves: Reserve[] = [ { id: "SGVsbG8h", onChainId: "42", canSupply: true, settings: { supplyCap: { amount: { value: BigDecimal(2000000000.0) }, // 2B USDC // … }, // … }, // … }, { id: "V29ybGQh", onChainId: "43", canSupply: false, // cannot supply to this reserve settings: { supplyCap: { amount: { value: BigDecimal(1000000000.0) }, // 1B USDC // … }, // … }, // … }, // … ]; ``` > [!NOTE] > `canSupply` means the reserve is active: not frozen, not paused, and below its > supply cap. From the remaining reserves, choose one that meets these criteria: - **Collateral Enabled**: The reserve can be used as collateral (`canUseAsCollateral`) if you plan to borrow against it. - **Suppliable Amount**: The `userState.suppliable` value is sufficient for the amount you want to supply. ```tsx title="Example Reserve Data" const reserve: Reserve = { id: "SGVsbG8h", onChainId: "42", canSupply: true, canUseAsCollateral: true, chain: { chainId: 1, name: "Ethereum", }, spoke: { address: "0x123…", // … }, status: { frozen: false, paused: false, }, settings: { supplyCap: { amount: { value: BigDecimal(2000000000.0) }, // 2B USDC // … }, // … }, userState: { suppliable: { amount: { onChainValue: "1000000000", decimals: 6, value: BigDecimal(1000.0), // Can supply up to 1,000 USDC }, // … }, // … }, // … }; ``` > [!NOTE] > Include a user address when fetching reserve data, or `userState` will be > `null`. ### Preview Supply with AaveKit Preview the impact of a supply operation before committing to it. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of the supply operation on the user’s position. ```tsx title="Loading State" import { type SupplyRequest, usePreview } from "@aave/react"; function SupplyPreview({ request }: { request: SupplyRequest }) { const { data, error, loading } = usePreview({ action: { supply: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type SupplyRequest, usePreview } from "@aave/react"; function SupplyPreview({ request }: { request: SupplyRequest }) { const { data, error, loading } = usePreview({ action: { supply: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: SupplyRequest) => { const result = await preview({ action: { supply: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Supply ERC-20" import { preview } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await preview(client, { action: { supply: { sender: evmAddress("0x123…"), reserve: reserve.id, amount: { erc20: { value: bigDecimal(100), // 100 tokens }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```ts title="Enable Collateral" const result = await preview(client, { action: { supply: { sender: evmAddress("0x123…"), reserve: reserve.id, amount: { erc20: { value: bigDecimal(100), }, }, enableCollateral: true, }, }, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } reserveRates { supplyApy { ...PercentNumberVariation } borrowApy { ...PercentNumberVariation } } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: See below for examples of `SupplyRequest` objects. - **GraphQL**: You can preview different supply operations using the `action` field. ```ts title="Supply ERC-20" const request: SupplyRequest = { sender: evmAddress("0x123…"), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // USDC }, }, }; ``` ```ts title="Enable Collateral" const request: SupplyRequest = { sender: evmAddress("0x123…"), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // USDC }, }, enableCollateral: true, }; ``` ```json title="Supply ERC-20" { "request": { "action": { "supply": { "sender": "0x123…", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "100" } } } } } } ``` ```json title="Enable Collateral" { "request": { "action": { "supply": { "sender": "0x123…", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "100" } }, "enableCollateral": true } } } } ``` The `PreviewUserPosition` shows the impact of the supply operation by comparing current and after states, with the table below outlining key fields and how to interpret them. You can also specify a different currency to return fiat amounts in. ```ts title="usePreview" import { Currency } from "@aave/react"; const { data, error, loading } = usePreview({ action: { supply: request, }, currency: Currency.Eur, }); ``` ```ts title="usePreviewAction" import { Currency } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; const result = await preview( client, { action: { supply: { // your supply action }, }, }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "action": { "supply": { // … } } }, "currency": "EUR" } ``` ### Preview Supply with Solidity Start with the spoke address and on-chain reserve ID identified: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; ``` And an amount to supply: ```solidity title="Amount to Supply" uint256 amountToSupply = 42e6; // 42 USDC ``` Follow these steps to preview the impact of a supply operation on the user’s position. #### 1. Get Current Account Data First, retrieve the user’s current account data from the Spoke contract. ```solidity title="Get Account Data" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); ``` #### 2. Calculate New Collateral Value Then, retrieve the reserve data and asset price from the oracle to calculate the USD value of the new supply, and add it to the current total collateral. ```solidity title="New Collateral Value" address oracleAddress = spoke.ORACLE(); ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(oracleAddress).getReservePrice(reserveId); uint256 supplyValue = amountToSupply * assetPrice * 10 ** (18 - reserve.decimals); uint256 newTotalCollateralValue = currentData.totalCollateralValue + supplyValue; ``` #### 3. Get Collateral Factor Then, retrieve the user’s position configuration to get the collateral factor for the reserve. ```solidity title="Get Collateral Factor" uint32 dynamicConfigKey = spoke.getUserPosition(reserveId, user).dynamicConfigKey; ISpoke.DynamicReserveConfig memory config = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey); uint256 collateralFactor = config.collateralFactor; ``` #### 4. Compute New Health Factor Finally, calculate the new health factor by incorporating the new supply’s collateral value and factor into the weighted sum. This assumes the supply is enabled as collateral. ```solidity title="Compute New Health Factor" import { Math } from "aave-v4/src/dependencies/openzeppelin/Math.sol"; uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 newSupplyWeightedValue = (supplyValue * collateralFactor) / 10000; uint256 newWeightedSum = currentWeightedSum + newSupplyWeightedValue; uint256 newHealthFactor = currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); ``` #### Complete Preview Example Here’s a complete example that calculates the health factor before a supply operation: ```solidity title="Complete Health Factor Preview" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; import { Math } from "aave-v4/src/dependencies/openzeppelin/Math.sol"; function previewSupplyHealthFactor( address spokeAddress, uint256 reserveId, uint256 amountToSupply, address user ) external view returns (uint256) { ISpoke spoke = ISpoke(spokeAddress); IAaveOracle oracle = IAaveOracle(spoke.ORACLE()); // Step 1: Get Current Account Data ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); // Step 2: Calculate New Collateral Value ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = oracle.getReservePrice(reserveId); uint256 supplyValue = amountToSupply * assetPrice * 10 ** (18 - reserve.decimals); // Step 3: Get Collateral Factor uint32 dynamicConfigKey = spoke.getUserPosition(reserveId, user).dynamicConfigKey; uint256 collateralFactor = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey).collateralFactor; // Step 4: Compute New Health Factor uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 newWeightedSum = currentWeightedSum + (supplyValue * collateralFactor) / 10000; return currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); } ``` ### Step-by-Step with AaveKit Supply assets to the selected reserve. Supplying ERC-20 tokens requires token approval. You can choose between two approaches: - **Transaction-based approval**: Sends a separate ERC-20 `approve()` transaction before the supply transaction (2 transactions total). - **Permit-based approval**: Signs an [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) permit to approve and supply in a single transaction. More gas-efficient, but requires the token to support permits. To supply assets to an Aave reserve with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the hooks for the [wallet library of your choice](../getting-started/react#integrations): - `useSendTransaction`: used to send ERC-20 approval and supply transactions - `useSignTypedData`: used to sign ERC-20 permits when available ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` #### 2. Define the Supply Flow Then, in React, use the `useSupply` hook to prepare the supply operation. ```tsx title="Basic Usage" import { useSupply } from "@aave/react"; const [supply, { loading, error }] = useSupply((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": // If token supports EIP-2612 permits, sign permit (recommended) if (plan.bySignature) { return signTypedData(plan.bySignature); } // use traditional approval transaction return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useSupply } from "@aave/react"; const [status, setStatus] = useState(""); const [supply, { loading, error }] = useSupply((plan) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please sign the Supply transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Supplying…")); case "Erc20Approval": if (plan.bySignature) { setStatus("Please sign the Permit approval in your wallet"); return signTypedData(plan.bySignature); } setStatus("Please sign the Approval transaction in your wallet"); return sendTransaction(plan.byTransaction).andTee(() => setStatus("Approving…"), ); case "PreContractActionRequired": setStatus("Please sign the Pre-Contract Action in your wallet"); return sendTransaction(plan.transaction).andTee(() => setStatus("Processing…"), ); } }); ``` ```tsx title="Cancel Flow" import { useSupply } from "@aave/react"; const [supply, { loading, error }] = useSupply((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` In the `Erc20Approval` case, the `bySignature` field is only available if the token supports EIP-2612 permits. > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the hook calls your callback twice: reset to 0, then set the new value. > `bySignature` is `null` for these. #### 3. Execute the Supply Operation Then, execute the supply operation. - **TypeScript**: Use the `supply` action to prepare the supply execution plan. - **GraphQL**: Use the `supply` query to prepare the supply execution plan. ```tsx title="Supply ERC-20" import { bigDecimal, evmAddress } from "@aave/react"; const execute = async () => { const result = await supply({ sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // 42 USDC }, }, }); // … }; ``` ```ts title="Enable Collateral" const execute = async () => { const result = await supply({ sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // 42 USDC }, }, enableCollateral: true, }); // … }; ``` ```ts title="Transaction-based" import { supply } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await supply(client, { sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // 42 USDC }, }, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: SupplyRequest!) { supply(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on Erc20ApprovalRequired { reason requiredAmount { ...DecimalNumber } currentAllowance { ...DecimalNumber } approvals { byTransaction { ...TransactionRequest } bySignature { ...PermitTypedData } } originalTransaction { ...TransactionRequest } } ... on PreContractActionRequired { reason transaction { ...TransactionRequest } originalTransaction { ...TransactionRequest } } ... on InsufficientBalanceError { required { ...DecimalNumber } available { ...DecimalNumber } } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` ```graphql title="PermitTypedData" fragment PermitTypedData on PermitTypedData { types primaryType domain { name version chainId verifyingContract } message } ``` In TypeScript, to handle ERC-20 permit-based approval, wrap the `supply` call with `permitWith` for the [wallet library of your choice](../getting-started/typescript#integrations). ```ts title="Permit-based (Viem)" import { supply } from "@aave/client/actions"; import { permitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await permitWith(wallet, (permitSig) => supply(client, { sender: evmAddress(wallet.account.address), reserve: reserve.id, amount: { erc20: { value: bigDecimal(42), // 42 USDC permitSig, }, }, }), ); // … ``` ```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(), }); ``` In TypeScript, the `permitWith` helper: 1. Calls the `supply` action without a permit signature 2. If the response is `Erc20ApprovalRequired` with permit signature available, signs the permit and calls `supply` again with the signature to get an updated execution plan 3. Otherwise, returns the execution plan unchanged (no permit needed or token doesn’t support permits) > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > `permitWith` skips the permit and the next step handles both approvals. In GraphQL, below are some examples of `SupplyRequest` objects. ```json title="Basic Usage" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "42" } } } } ``` ```json title="Enable Collateral" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "42" } }, "enableCollateral": true } } ``` ```jsonc title="Permit-based Approval" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "42", "permitSig": { "deadline": 1700000000, // use approvals[0].bySignature.message.deadline "value": "0xabcdef…" } } } } } ``` #### 4. Process the Supply Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. ```ts title="Transaction-based" 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); ``` ```ts title="Permit-based" import { supply } from "@aave/client/actions"; import { permitWith, sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await permitWith(wallet, (permitSig) => supply(client, { // … }), ) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` > [!NOTE] > `sendWith` handles all required approvals, including the allowance reset for > tokens like USDT. In GraphQL, if the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```json title="TransactionRequest" { "data": { "supply": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x852a56a5…", "value": "0", "chainId": 1, "operations": ["SPOKE_SUPPLY"] } } } ``` If the response is `Erc20ApprovalRequired`, you have two options: **Transaction-based approval** 1. Send each transaction in the `approvals` array in sequence 2. Then send `originalTransaction` **Permit-based approval** > [!NOTE] > This is available only when `approvals` contains a single `Erc20Approval` > item. 1. Sign the `approvals[0].bySignature` typed data with the sender’s account. 2. Call the `supply` query again with the permit signature (see the `Permit-based Approval` example above) 3. The response will be a `TransactionRequest` you can then send directly ```jsonc title="Single Approval" { "data": { "supply": { "__typename": "Erc20ApprovalRequired", "reason": "Insufficient allowance for ERC-20 token transfer", "requiredAmount": { "value": "42.000000", "decimals": 6 }, "currentAllowance": { "value": "0.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "bySignature": { "types": , "primaryType": "Permit", "domain": , "message": } } ], "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x852a56a5…", "value": "0", "chainId": 1, "operations": ["SPOKE_SUPPLY"] } } } } ``` ```json title="With Approval Reset (USDT-like)" { "data": { "supply": { "__typename": "Erc20ApprovalRequired", "reason": "Token requires allowance reset before new approval", "requiredAmount": { "value": "42.000000", "decimals": 6 }, "currentAllowance": { "value": "10.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…0", "value": "0", "chainId": 1, "operations": null }, "bySignature": null }, { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…42", "value": "0", "chainId": 1, "operations": null }, "bySignature": null } ], "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x852a56a5…", "value": "0", "chainId": 1, "operations": ["SPOKE_SUPPLY"] } } } } ``` > [!NOTE] > With multiple approvals in `Erc20ApprovalRequired`, send each `byTransaction` > in order, then `originalTransaction`. For [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the first resets the allowance to 0 and the second sets the required amount. If the response is `PreContractActionRequired`, you must first send the `transaction` request, then send the `originalTransaction`. ```json title="PreContractActionRequired" { "data": { "supply": { "__typename": "PreContractActionRequired", "reason": "Native gateway needs approval", "transaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x852a56a5…", "value": "0", "chainId": 1, "operations": ["SPOKE_SUPPLY"] } } } } ``` 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.000000", "decimals": 6 }, "available": { "value": "15.500000", "decimals": 6 } } } } ``` #### 5. Handle the Supply Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await supply(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Supply successful with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Supply successful with hash:", result.value.txHash); } ``` ### Step-by-Step with Solidity Use the same identifiers and amount to supply used to preview the supply operation: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; uint256 amountToSupply = 42e6; // 42 USDC ``` Complete the supply process with the following steps: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Approve Token Transfer Then, retrieve the reserve from the spoke and approve the Spoke to transfer the specified amount of ERC-20 tokens. ```solidity title="Approve Token Transfer" import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); IERC20 token = IERC20(reserve.underlying); token.approve(spokeAddress, amountToSupply); ``` #### 3. Supply Tokens Finally, call the `supply` function on the Spoke contract, specifying the reserve ID, amount, and the address to credit the supply shares to. ```solidity title="Supply" spoke.supply( reserveId, amountToSupply, msg.sender ); ``` #### Complete Supply Example Here’s a complete example that executes the full supply flow: ```solidity title="Complete Supply Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; function supplyToReserve( address spokeAddress, uint256 reserveId, uint256 amountToSupply, address onBehalfOf ) external { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Pull tokens from the caller and approve the Spoke IERC20 token = IERC20(spoke.getReserve(reserveId).underlying); token.transferFrom(msg.sender, address(this), amountToSupply); token.approve(spokeAddress, amountToSupply); // Step 2: Supply tokens spoke.supply(reserveId, amountToSupply, onBehalfOf); } ``` The contract must be an active [Position Manager](./managers) approved by `onBehalfOf`, otherwise `supply` reverts. ## Collateral Management Manage how user supplies are used as collateral for borrowing. The process can be broken down into three steps: 1. Identify the supply position 2. Preview the impact of changing collateral status 3. Toggle the collateral status ### Identify the Supply Position First, identify the supply position you want to modify from the user’s [supply positions](./fetch#user-supplies). ```ts title="UserSupplyItem" const supplyPosition: UserSupplyItem = { reserve: { id: "SGVsbG8h", onChainId: "42", chain: { chainId: 1, name: "Ethereum", }, spoke: { address: "0x123…", // … }, canUseAsCollateral: true, // … }, isCollateral: false, balance: { amount: { value: BigDecimal(46.2), }, // … }, principal: { amount: { value: BigDecimal(42.0), }, // … }, interest: { amount: { value: BigDecimal(4.2), }, // … }, }; ``` The reserve must have `canUseAsCollateral: true` to be used as collateral. ### Preview Changes with AaveKit Preview the impact of changing collateral status before executing the transaction. > [!WARNING] > Disabling collateral can lower your health factor and put the position at risk > of liquidation. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of collateral status changes on the user’s position. ```tsx title="Loading State" import { type SetUserSuppliesAsCollateralRequest, usePreview, } from "@aave/react"; function CollateralPreview({ request, }: { request: SetUserSuppliesAsCollateralRequest; }) { const { data, error, loading } = usePreview({ action: { setUserSuppliesAsCollateral: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type SetUserSuppliesAsCollateralRequest, usePreview, } from "@aave/react"; function CollateralPreview({ request, }: { request: SetUserSuppliesAsCollateralRequest; }) { const { data, error, loading } = usePreview({ action: { setUserSuppliesAsCollateral: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: SetUserSuppliesAsCollateralRequest) => { const result = await preview({ action: { setUserSuppliesAsCollateral: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Preview" import { preview } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; const result = await preview(client, { action: { setUserSuppliesAsCollateral: { sender: evmAddress("0x123…"), // User's address changes: [ { reserve: supplyPosition.reserve.id, enableCollateral: true, // false to disable collateral }, ], }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: The `SetUserSuppliesAsCollateralRequest` can be as follows. - **GraphQL**: The `PreviewRequest` can be as follows. ```ts title="Single Change" const request: SetUserSuppliesAsCollateralRequest = { sender: evmAddress("0x123…"), // User's address changes: [ { reserve: supplyPosition.reserve.id, enableCollateral: true, // false to disable collateral }, ], }; ``` ```ts title="Multiple Changes" const request: SetUserSuppliesAsCollateralRequest = { sender: evmAddress("0x123…"), // User's address changes: [ { reserve: supplyPositions[0].reserve.id, enableCollateral: true, }, { reserve: supplyPositions[1].reserve.id, enableCollateral: true, }, ], }; ``` ```json title="Toggle Collateral" { "request": { "action": { "setUserSuppliesAsCollateral": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "changes": [ { "reserve": "SGVsbG8h", "enableCollateral": true } ] } } } } ``` The `PreviewUserPosition` shows the impact of the collateral status change by comparing current and after states, with the table below outlining key fields and how to interpret them. You can also specify a different currency to return fiat amounts in. ```ts title="usePreview" import { Currency } from "@aave/react"; const { data, error, loading } = usePreview({ action: { setUserSuppliesAsCollateral: request, }, currency: Currency.Eur, }); ``` ```ts title="usePreviewAction" import { Currency } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; const result = await preview( client, { action: { setUserSuppliesAsCollateral: , }, }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "action": { "setUserSuppliesAsCollateral": { // … } } }, "currency": "EUR" } ``` ### Preview Changes with Solidity Start with the spoke address and on-chain reserve ID identified: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; ``` Follow the steps below to preview the impact of enabling or disabling collateral on the user’s position. #### 1. Get Current Account Data First, retrieve the user’s current account data from the Spoke contract. ```solidity title="Get Account Data" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; import { Math } from "aave-v4/src/dependencies/openzeppelin/Math.sol"; ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); ``` #### 2. Calculate Supply Position Value Then, retrieve the user’s supply position and calculate its USD value using the oracle. ```solidity title="Supply Position Value" ISpoke.UserPosition memory userPosition = spoke.getUserPosition(reserveId, user); ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); address oracleAddress = spoke.ORACLE(); uint256 assetPrice = IAaveOracle(oracleAddress).getReservePrice(reserveId); uint256 suppliedAssets = spoke.getUserSuppliedAssets(reserveId, user); uint256 supplyValue = suppliedAssets * assetPrice * 10 ** (18 - reserve.decimals); ``` #### 3. Compute New Health Factor Finally, calculate the new health factor based on whether collateral is being enabled or disabled. ```solidity title="Enable Collateral" uint32 dynamicConfigKey = reserve.dynamicConfigKey; ISpoke.DynamicReserveConfig memory config = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey); uint256 collateralFactor = config.collateralFactor; uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 newSupplyWeightedValue = (supplyValue * collateralFactor) / 10000; uint256 newWeightedSum = currentWeightedSum + newSupplyWeightedValue; uint256 newHealthFactor = currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); ``` ```solidity title="Disable Collateral" uint32 dynamicConfigKey = userPosition.dynamicConfigKey; ISpoke.DynamicReserveConfig memory config = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey); uint256 collateralFactor = config.collateralFactor; uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 removedWeightedValue = (supplyValue * collateralFactor) / 10000; uint256 newWeightedSum = currentWeightedSum - removedWeightedValue; uint256 newHealthFactor = currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); ``` ### Toggle Collateral with AaveKit Toggle the collateral status of any supplied asset using the following steps. > [!WARNING] > Enabling collateral updates the asset’s Dynamic Config (Collateral Factor, > Liquidation Fee, Max Liquidation Bonus). Disabling it increases risk and also > updates the User Risk Premium of the whole position (see [User Position > Conditions](./conditions)). To enable or disable a supplied asset as collateral with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Collateral Management Flow Then, in React, use the `useSetUserSuppliesAsCollateral` hook to prepare the transaction request. ```tsx title="Basic Usage" import { useSetUserSuppliesAsCollateral } from "@aave/react"; const [setAsCollateral, { loading, error }] = useSetUserSuppliesAsCollateral( (transaction) => sendTransaction(transaction), ); ``` ```tsx title="Update Component State" import { useSetUserSuppliesAsCollateral } from "@aave/react"; const [status, setStatus] = useState(""); const [setAsCollateral, { loading, error }] = useSetUserSuppliesAsCollateral( (transaction) => { setStatus("Please sign the transaction in your wallet"); return sendTransaction(transaction).andTee(() => setStatus("Setting collateral…"), ); }, ); ``` ```tsx title="Cancel Flow" import { useSetUserSuppliesAsCollateral } from "@aave/react"; const [setAsCollateral, { loading, error }] = useSetUserSuppliesAsCollateral( (transaction, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } return sendTransaction(transaction); }, ); ``` #### 3. Execute the Transaction Then, update the collateral status. - **TypeScript**: Use the `setUserSuppliesAsCollateral` action to prepare the transaction request. - **GraphQL**: Use the `setUserSuppliesAsCollateral` query to prepare the transaction request. ```tsx title="Set Collateral" import { evmAddress } from "@aave/react"; const execute = async () => { const result = await setAsCollateral({ sender: evmAddress(wallet.account.address), // User's address changes: [ { reserve: supplyPosition.reserve.id, enableCollateral: true, }, ], }); }; // … ``` ```ts title="Set Collateral" import { setUserSuppliesAsCollateral } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await setUserSuppliesAsCollateral(client, { sender: evmAddress(wallet.account.address), // User's address changes: [ { reserve: supplyPosition.reserve.id, enableCollateral: true, }, ], }); // … ``` ```graphql title="Query" query ($request: SetUserSuppliesAsCollateralRequest!) { setUserSuppliesAsCollateral(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` In GraphQL, below is an example of a `SetUserSuppliesAsCollateralRequest` object. ```json title="Basic Usage" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "changes": [ { "reserve": "SGVsbG8h", "enableCollateral": true } ] } } ``` #### 4. Process the Collateral Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transaction, and await indexing with `client.waitForTransaction`. ```ts title="Viem" import { setUserSuppliesAsCollateral } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await setUserSuppliesAsCollateral(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```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(), }); ``` In GraphQL, the API returns a `TransactionRequest`, which you can send directly with the wallet tied to the `from` address. ```json title="TransactionRequest" { "data": { "setUserSuppliesAsCollateral": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x9e35c533…", "value": "0", "chainId": 1, "operations": ["SPOKE_SET_USER_USING_AS_COLLATERAL"] } } } ``` #### 5. Handle the Collateral Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await setAsCollateral(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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; } return; } console.log("Collateral updated successfully with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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("Collateral updated successfully with hash:", result.value.txHash); } ``` ### Toggle Collateral with Solidity To enable or disable a supplied asset as collateral, call `setUsingAsCollateral` on the Spoke contract. ```solidity title="Enable Collateral" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUsingAsCollateral( reserveId, true, msg.sender ); ``` ```solidity title="Disable Collateral" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUsingAsCollateral( reserveId, false, msg.sender ); ``` --- ## Advanced Usage ### Network Fee > [!NOTE] > This experimental React hook only works with Viem or Wagmi integrations. ```tsx title="PreviewAction" import { type PreviewAction } from "@aave/react"; const action: PreviewAction = { supply: { sender: evmAddress("0x123…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { value: bigDecimal(42), // USDC }, }, }, }; ``` ### Native Tokens with AaveKit When the Reserve’s underlying token is the wrapped version of the chain’s native token (e.g., WETH on Ethereum), you can supply the asset as the chain’s native token using the Native Token Gateway. Use the `reserve.asset.underlying.isWrappedNativeToken` flag to determine if the underlying token is a wrapped native token. The Native Token Gateway address is available from the chain details. ```ts title="WETH Reserve" const reserve: Reserve = { id: "SGVsbG8h", onChainId: "42", canSupply: true, canUseAsCollateral: true, asset: { underlying: { address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", info: { name: "Wrapped Ether", symbol: "WETH", decimals: 18, // … }, isWrappedNativeToken: true, // … }, // … }, settings: { supplyCap: { amount: { value: BigDecimal(2000000000.0) }, // 2B WETH // … }, // … }, spoke: { address: "0x123…", // … }, chain: { chainId: 1, name: "Ethereum", nativeGateway: "0xabc…", }, // … }; ``` Specify the amount in the `amount` field as a `native` value. ```tsx title="Supply Native" const execute = async () => { const result = await supply({ sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { native: bigDecimal(42), // 42 ETH }, }); // … }; ``` ```ts title="Supply Native" const result = await supply(client, { sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { native: bigDecimal(42), // 42 ETH }, }); // … ``` ```jsonc title="Supply Native" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": "42" // 42 ETH } } } ``` ### Native Tokens with Solidity Start with the spoke address, reserve ID, and native gateway address identified: ```solidity title="Native Token Gateway" address spokeAddress = 0x123…; uint256 reserveId = 42; address nativeGateway = 0xabc…; ``` Follow the steps below to supply native tokens (e.g., ETH) to a wrapped native token reserve (e.g., WETH). #### 1. Approve the Gateway First, approve the Native Token Gateway as your position manager. This is a one-time setup step. ```solidity title="Approve Gateway" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(nativeGateway, true); ``` #### 2. Supply Native Tokens Then, call `supplyNative` on the gateway, sending the native token amount via `msg.value`. ```solidity title="Supply Native" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); gateway.supplyNative{value: amountToSupply}(spokeAddress, reserveId, amountToSupply); ``` The gateway wraps the native token (ETH → WETH), approves the spoke, and calls `spoke.supply` on your behalf. #### Complete Native Token Example Here’s a complete example for supplying native tokens. This helper acts on the contract’s own position. To supply for a user’s wallet, the user calls `setUserPositionManager` and the gateway directly. ```solidity title="Complete Native Supply Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; function supplyNativeToken( address spokeAddress, address nativeGateway, uint256 reserveId, uint256 amountToSupply ) external payable { require(msg.value == amountToSupply, "Incorrect ETH amount"); ISpoke spoke = ISpoke(spokeAddress); // Step 1: Approve gateway as position manager (one-time setup) if (!spoke.isPositionManager(address(this), nativeGateway)) { spoke.setUserPositionManager(nativeGateway, true); } // Step 2: Supply native tokens via gateway INativeTokenGateway(nativeGateway).supplyNative{value: amountToSupply}(spokeAddress, reserveId, amountToSupply); } ``` --- Source: https://aave.com/docs/aave-v4/positions/borrow.md # Borrow Assets on Aave V4 Borrowing assets from Aave V4 allows you to: - Access liquidity without selling your assets - Leverage your positions with borrowed capital - Repay borrowed assets at any time to close your position > [!WARNING] > Borrowing lowers your health factor. Keep enough collateral and watch the > health factor, especially in volatile markets, to avoid liquidation. ## Borrow Assets Borrowing on Aave V4 takes place at the spoke level, and users can only borrow against collateral supplied to that same spoke. Borrowing can be broken down into the following steps: 1. Identify the Reserve to borrow from 2. Preview the impact of the borrow operation 3. Borrow the assets ### Identify the Reserve The first step is to filter the borrow reserves on the same spoke as the collateral to those marked with `canBorrow: true`. ```tsx title="Reserves List" const reserves: Reserve[] = [ { id: "SGVsbG8h", onChainId: "42", canBorrow: true, settings: { borrowCap: { amount: { value: BigDecimal(1000000000.0) }, // 1B USDC // … }, // … }, status: { frozen: false, paused: false, }, spoke: { address: "0x123…", // … }, // … }, { id: "V29ybGQh", onChainId: "43", canBorrow: false, // cannot borrow from this reserve settings: { borrowCap: { amount: { value: BigDecimal(500000000.0) }, // 500M DAI // … }, // … }, status: { frozen: true, // reserve is frozen paused: false, }, spoke: { address: "0x123…", // … }, // … }, // … ]; ``` > [!NOTE] > `canBorrow` means the reserve is active: not frozen, not paused, and below its > borrow cap. From the remaining borrowable reserves, select the one that: - **Best matches the desired token** with a sufficient borrowable amount. This already accounts for the combined collateral factors (LTV ratios) of the position’s collateral - **Offers the lowest borrow APY**: the effective borrow APY combines the reserve’s borrow APY with the [Risk Premium](../positions#user-risk-premium) tied to the position’s collateral ```tsx title="Reserve" const reserve: Reserve = { id: "SGVsbG8h", onChainId: "42", canBorrow: true, chain: { chainId: 1, name: "Ethereum", }, spoke: { address: "0x123…", // … }, asset: { underlying: { address: "0xa0b86a33e6e2ad05ad6c9ac3b6e5e5f6e7b6c1b2", // USDC }, // … }, userState: { borrowApy: { normalized: BigDecimal(3.73), // 3.73% APY // … }, borrowable: { amount: { value: BigDecimal(10000.0), // 10,000 USDC }, // … }, // … }, }; ``` > [!NOTE] > Include a user address when fetching reserve data, or `userState` will be > `null`. ### Preview Borrow with AaveKit Preview the impact of a borrow operation before committing to it. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of the borrow operation on the user’s position. ```tsx title="Loading State" import { type BorrowRequest, usePreview } from "@aave/react"; function BorrowPreview({ request }: { request: BorrowRequest }) { const { data, error, loading } = usePreview({ action: { borrow: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type BorrowRequest, usePreview } from "@aave/react"; function BorrowPreview({ request }: { request: BorrowRequest }) { const { data, error, loading } = usePreview({ action: { borrow: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type BorrowRequest, usePreviewAction } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: BorrowRequest) => { const result = await preview({ action: { borrow: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Preview" import { preview } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; const result = await preview(client, { action: { borrow: { sender: evmAddress("0x789…"), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(1000), // 1000 USDC }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } reserveRates { supplyApy { ...PercentNumberVariation } borrowApy { ...PercentNumberVariation } } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: The `BorrowRequest` can be as follows. - **GraphQL**: The `PreviewRequest` can be as follows. ```ts title="Borrow ERC-20" const request: BorrowRequest = { sender: evmAddress("0x789…"), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(1000), // 1000 USDC }, }, }; ``` ```json title="Borrow ERC-20" { "request": { "action": { "borrow": { "sender": "0x789…", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "1000" } } } } } } ``` The `PreviewUserPosition` shows the impact of the borrow operation by comparing current and after states, with the table below outlining key fields and how to interpret them. You can also specify a different currency to return fiat amounts in. ```ts title="usePreview" import { Currency } from "@aave/react"; const { data, error, loading } = usePreview({ action: { borrow: request, }, currency: Currency.Eur, }); ``` ```ts title="usePreviewAction" import { Currency } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; const result = await preview( client, { action: { borrow: , }, }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "action": { "borrow": { // … } } }, "currency": "EUR" } ``` ### Preview Borrow with Solidity Start with the spoke address and on-chain reserve ID identified: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; ``` And an amount to borrow: ```solidity title="Amount to Borrow" uint256 amountToBorrow = 42e6; // 42 USDC ``` Follow the steps below to preview the impact of a borrow operation on the user’s position. #### 1. Get Current Account Data First, retrieve the user’s current account data from the Spoke contract. ```solidity title="Get Account Data" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); ``` #### 2. Calculate New Debt Value Then, retrieve the reserve data and asset price from the oracle to calculate the USD value of the new borrow, and add it to the current total debt. ```solidity title="New Debt Value" address oracleAddress = spoke.ORACLE(); ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(oracleAddress).getReservePrice(reserveId); uint256 borrowValue = amountToBorrow * assetPrice * 10 ** (18 - reserve.decimals); uint256 newTotalDebtValue = currentData.totalDebtValueRay / 1e27 + borrowValue; ``` #### 3. Compute New Health Factor Finally, calculate the new health factor by incorporating the new debt value. ```solidity title="Compute New Health Factor" uint256 newHealthFactor = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / newTotalDebtValue; // WAD, 1e18 = 1.00 ``` #### Complete Preview Example Here’s a complete Solidity example that calculates the health factor before a borrow operation: ```solidity title="Complete Health Factor Preview" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; function previewBorrowHealthFactor( address spokeAddress, uint256 reserveId, uint256 amountToBorrow, address user ) external view returns (uint256) { ISpoke spoke = ISpoke(spokeAddress); IAaveOracle oracle = IAaveOracle(spoke.ORACLE()); // Step 1: Get Current Account Data ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); // Step 2: Calculate New Debt Value ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = oracle.getReservePrice(reserveId); uint256 borrowValue = amountToBorrow * assetPrice * 10 ** (18 - reserve.decimals); uint256 newTotalDebtValue = currentData.totalDebtValueRay / 1e27 + borrowValue; // Step 3: Compute New Health Factor return (currentData.totalCollateralValue * currentData.avgCollateralFactor) / newTotalDebtValue; // WAD, 1e18 = 1.00 } ``` ### Step-by-Step with AaveKit Borrow assets from the selected reserve. > [!WARNING] > Borrowing increases risk and updates the Dynamic Config, which updates the > position’s User Risk Premium. See [User Position Conditions](./conditions). To borrow assets from an Aave reserve with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Borrow Flow Then, in React, use the `useBorrow` hook to prepare the borrow operation. ```tsx title="Basic Usage" import { useBorrow } from "@aave/react"; const [borrow, { loading, error }] = useBorrow((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useBorrow } from "@aave/react"; const [status, setStatus] = useState(""); const [borrow, { loading, error }] = useBorrow((plan) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please sign the Borrow transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Borrowing…")); case "PreContractActionRequired": setStatus("Please sign the Pre-Contract Action in your wallet"); return sendTransaction(plan.transaction).andTee(() => setStatus("Processing…"), ); } }); ``` ```tsx title="Cancel Flow" import { useBorrow } from "@aave/react"; const [borrow, { loading, error }] = useBorrow((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` #### 3. Execute the Borrow Operation Then, execute the desired borrow operation. - **TypeScript**: Use the `borrow` action to prepare the borrow execution plan. - **GraphQL**: Use the `borrow` query to prepare the borrow execution plan. ```tsx title="Borrow ERC-20" import { bigDecimal, evmAddress } from "@aave/react"; const execute = async () => { const result = await borrow({ sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(100), // 100 USDC }, }, }); // … }; ``` ```ts title="Borrow ERC-20" import { borrow } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await borrow(client, { sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(100), // 100 USDC }, }, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: BorrowRequest!) { borrow(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on PreContractActionRequired { reason transaction { ...TransactionRequest } originalTransaction { ...TransactionRequest } } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` In GraphQL, below is an example of a `BorrowRequest` object. ```json title="Variables" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": "100" } } } } ``` #### 4. Process the Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. ```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); ``` ```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(), }); ``` In GraphQL, if the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```json title="TransactionRequest" { "data": { "borrow": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xd6bda0c0…", "value": "0", "chainId": 1, "operations": ["SPOKE_BORROW"] } } } ``` If the response is a `PreContractActionRequired`, you must first send the `transaction` request. Once it succeeds, you can then send the `originalTransaction`. ```json title="PreContractActionRequired" { "data": { "borrow": { "__typename": "PreContractActionRequired", "reason": "Authorize the native wrapping gateway to operate on behalf of the user", "transaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xd6bda0c0…", "value": "0", "chainId": 1, "operations": ["SPOKE_BORROW"] } } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await borrow(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Borrow successful with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Borrow successful with hash:", result.value.txHash); ``` ### Step-by-Step with Solidity Use the same identifiers and amount to borrow used to preview the borrow operation: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; uint256 amountToBorrow = 42e6; // 42 USDC ``` Complete the borrow process with the following steps: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Borrow Assets Then, call the `borrow` function on the Spoke contract, specifying the reserve ID, amount to borrow, and the `onBehalfOf` address (the position owner). The borrowed tokens are sent to the caller (`msg.sender`). ```solidity title="Borrow" spoke.borrow( reserveId, amountToBorrow, msg.sender ); ``` #### Complete Borrow Example Here’s a complete Solidity example that executes the borrow operation: ```solidity title="Complete Borrow Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function borrowFromReserve( address spokeAddress, uint256 reserveId, uint256 amountToBorrow, address onBehalfOf ) external { // Borrow assets from reserve ISpoke(spokeAddress).borrow(reserveId, amountToBorrow, onBehalfOf); } ``` --- ## Advanced Usage ### Network Fee > [!NOTE] > This experimental React hook only works with Viem or Wagmi integrations. ```tsx title="PreviewAction" import { type PreviewAction } from "@aave/react"; const action: PreviewAction = { borrow: { sender: evmAddress("0x789…"), // User's address reserve: reserve.id, amount: { erc20: { value: bigDecimal(1000), // 1000 USDC }, }, }, }; ``` ### Native Tokens with AaveKit When the Reserve’s underlying token is the wrapped version of the chain’s native token (e.g., WETH on Ethereum), you can borrow the asset as the chain’s native token using the Native Token Gateway. Use the `asset.underlying.isWrappedNativeToken` flag to determine if the underlying token is a wrapped native token. The Native Token Gateway address is available from the chain details. ```ts title="WETH Reserve" const reserve: Reserve = { id: "SGVsbG8h", onChainId: "42", canBorrow: true, canSupply: true, canUseAsCollateral: true, asset: { underlying: { address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", info: { name: "Wrapped Ether", symbol: "WETH", decimals: 18, // … }, isWrappedNativeToken: true, // … }, // … }, settings: { borrowCap: { amount: { value: BigDecimal(1000000000.0) }, // 1B WETH // … }, supplyCap: { amount: { value: BigDecimal(2000000000.0) }, // 2B WETH // … }, // … }, spoke: { address: "0x123…", // … }, chain: { chainId: 1, name: "Ethereum", nativeGateway: "0xabc…", }, // … }; ``` Specify the amount in the `amount` field as a `native` value. ```tsx title="Borrow Native" const execute = async () => { const result = await borrow({ sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { native: bigDecimal(1), // 1 ETH }, }); // … }; ``` ```ts title="Borrow Native" const result = await borrow(client, { sender: evmAddress(wallet.account.address), // User's address reserve: reserve.id, amount: { native: bigDecimal(1), // 1 ETH }, }); // … ``` ```jsonc title="Borrow Native" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": "1" // 1 ETH } } } ``` ### Native Tokens with Solidity Start with the spoke address, reserve ID, and native gateway address identified: ```solidity title="Native Token Gateway" address spokeAddress = 0x123…; uint256 reserveId = 42; address nativeGateway = 0xabc…; ``` Follow the steps below to borrow native tokens (e.g., ETH) from a wrapped native token reserve (e.g., WETH). #### 1. Approve the Gateway First, approve the Native Token Gateway as your position manager. This is a one-time setup step. ```solidity title="Approve Gateway" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(nativeGateway, true); ``` #### 2. Borrow Native Tokens Then, call `borrowNative` on the gateway to borrow and unwrap the tokens. ```solidity title="Borrow Native" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); gateway.borrowNative(spokeAddress, reserveId, amountToBorrow); ``` The gateway calls `spoke.borrow` on your behalf, unwraps the token (WETH → ETH), and sends the native token to the caller (`msg.sender`). #### Complete Native Token Example Here’s a complete Solidity example for borrowing native tokens. This helper acts on the contract’s own position. The gateway sends the native tokens to the contract, so it needs a `receive()` function. To borrow for a user’s wallet, the user calls `setUserPositionManager` and the gateway directly. ```solidity title="Complete Native Borrow Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; function borrowNativeToken( address spokeAddress, address nativeGateway, uint256 reserveId, uint256 amountToBorrow ) external { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Approve gateway as position manager (one-time setup) if (!spoke.isPositionManager(address(this), nativeGateway)) { spoke.setUserPositionManager(nativeGateway, true); } // Step 2: Borrow native tokens via gateway INativeTokenGateway(nativeGateway).borrowNative(spokeAddress, reserveId, amountToBorrow); } receive() external payable {} ``` --- Source: https://aave.com/docs/aave-v4/positions/repay.md # Repay Loans on Aave V4 Repaying borrowed assets allows you to: - Reduce or eliminate your debt position - Improve your position’s health factor and reduce liquidation risk - Free up collateral for withdrawal or additional borrowing - Close your borrow position entirely when repaying the full amount ## Repay Loans Repaying a loan can be broken down into the following steps: 1. Identify the borrow position to repay 2. Preview the impact of the repay operation 3. Repay the borrowed assets ### Identify the Borrow Position Given a list of the user’s [borrow positions](./fetch#user-borrows), identify the position (token) you want to reduce and choose the repayment amount (partial or full). > [!NOTE] > You can’t repay while the reserve is paused. For example, let’s say you have identified the following `UserBorrowItem` object. ```tsx title="Example UserBorrowItem" const borrowPosition: UserBorrowItem = { reserve: { id: "SGVsbG8h", onChainId: "42", chain: { chainId: 1, name: "Ethereum", }, spoke: { address: "0x123…", // … }, asset: { underlying: { address: "0xa0b86a33e6e2ad05ad6c9ac3b6e5e5f6e7b6c1b2", // USDC }, // … }, status: { paused: false, }, // … other reserve properties }, debt: { amount: { value: BigDecimal(512.023456), // ~512 USDC debt // … }, // … }, // … }; ``` ### Preview Repay with AaveKit Preview the impact of a repay operation before committing to it. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of the repay operation on the user’s position. ```tsx title="Loading State" import { type RepayRequest, usePreview } from "@aave/react"; function RepayPreview({ request }: { request: RepayRequest }) { const { data, error, loading } = usePreview({ action: { repay: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type RepayRequest, usePreview } from "@aave/react"; function RepayPreview({ request }: { request: RepayRequest }) { const { data, error, loading } = usePreview({ action: { repay: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type RepayRequest, usePreviewAction } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: RepayRequest) => { const result = await preview({ action: { repay: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Repay Specific Amount" import { preview } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; const result = await preview(client, { action: { repay: { sender: evmAddress("0x789…"), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), // 250 USDC }, }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```ts title="Repay Maximum Amount" import { preview } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; const result = await preview(client, { action: { repay: { sender: evmAddress("0x789…"), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { max: true, // Repay the full debt amount }, }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: The `RepayRequest` can be as follows. - **GraphQL**: The `PreviewRequest` can be as follows. ```ts title="Repay Specific Amount" const request: RepayRequest = { sender: evmAddress("0x789…"), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), // 250 USDC }, }, }, }; ``` ```tsx title="Repay Maximum Amount" const request: RepayRequest = { sender: evmAddress("0x789…"), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { max: true, // Repay the full debt amount }, }, }, }; ``` ```json title="Repay Specific Amount" { "request": { "action": { "repay": { "sender": "0x789…", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": { "exact": "250" } } } } } } } ``` ```json title="Repay Maximum Amount" { "request": { "action": { "repay": { "sender": "0x789…", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": { "max": true } } } } } } } ``` The `PreviewUserPosition` shows the impact of the repay operation by comparing current and after states, with the table below outlining key fields and how to interpret them. You can also specify a different currency to return fiat amounts in. ```ts title="usePreview" import { Currency } from "@aave/react"; const { data, error, loading } = usePreview({ action: { repay: request, }, currency: Currency.Eur, }); ``` ```ts title="usePreviewAction" import { Currency } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; const result = await preview( client, { action: { repay: , }, }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "action": { "repay": { // … } } }, "currency": "EUR" } ``` ### Preview Repay with Solidity Start with the spoke address and on-chain reserve ID identified: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; ``` And an amount to repay: ```solidity title="Amount to Repay" uint256 amountToRepay = 42e6; // 42 USDC ``` Follow the steps below to preview the impact of a repay operation on the user’s position. #### 1. Get Current Account Data First, retrieve the user’s current account data from the Spoke contract. ```solidity title="Get Account Data" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); ``` #### 2. Calculate Repay Value Then, retrieve the reserve data and asset price from the oracle to calculate the USD value of the repayment amount. ```solidity title="Repay Value" address oracleAddress = spoke.ORACLE(); ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(oracleAddress).getReservePrice(reserveId); uint256 repayValue = amountToRepay * assetPrice * 10 ** (18 - reserve.decimals); ``` #### 3. Compute New Health Factor Finally, calculate the new health factor by reducing the total debt value. ```solidity title="Compute New Health Factor" uint256 totalDebtValue = currentData.totalDebtValueRay / 1e27; if (repayValue >= totalDebtValue) return type(uint256).max; uint256 newHealthFactor = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / (totalDebtValue - repayValue); // WAD ``` #### Complete Preview Example Here’s a complete Solidity example that calculates the health factor before a repay operation: ```solidity title="Complete Health Factor Preview" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; function previewRepayHealthFactor( address spokeAddress, uint256 reserveId, uint256 amountToRepay, address user ) external view returns (uint256) { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Get current account data ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); // Step 2: Calculate repay value ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(spoke.ORACLE()).getReservePrice(reserveId); uint256 repayValue = amountToRepay * assetPrice * 10 ** (18 - reserve.decimals); // Step 3: Compute new health factor uint256 totalDebtValue = currentData.totalDebtValueRay / 1e27; if (repayValue >= totalDebtValue) return type(uint256).max; return (currentData.totalCollateralValue * currentData.avgCollateralFactor) / (totalDebtValue - repayValue); // WAD } ``` ### Step-by-Step with AaveKit Repay the selected borrow position. Repaying ERC-20 tokens requires token approval. You can choose between two approaches: - **Transaction-based approval**: Sends a separate ERC-20 `approve()` transaction before the repay transaction (2 transactions total). - **Permit-based approval**: Signs an [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) permit to approve and repay in a single transaction. More gas-efficient, but requires the token to support permits. To repay a loan with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the hooks for the [wallet library of your choice](../getting-started/react#integrations): - `useSendTransaction`: used to send ERC-20 approval and repay transactions - `useSignTypedData`: used to sign ERC-20 permits when available ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` #### 2. Define the Repay Flow Then, in React, use the `useRepay` hook to prepare the repay operation. ```tsx title="Basic Usage" import { useRepay } from "@aave/react"; const [repay, { loading, error }] = useRepay((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": // If token supports EIP-2612 permits, sign permit (recommended) if (plan.bySignature) { return signTypedData(plan.bySignature); } // Otherwise use traditional approval transaction return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useRepay } from "@aave/react"; const [status, setStatus] = useState(""); const [repay, { loading, error }] = useRepay((plan) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please sign the Repay transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Repaying…")); case "Erc20Approval": if (plan.bySignature) { setStatus("Please sign the Permit approval in your wallet"); return signTypedData(plan.bySignature); } setStatus("Please sign the Approval transaction in your wallet"); return sendTransaction(plan.byTransaction).andTee(() => setStatus("Approving…"), ); case "PreContractActionRequired": setStatus("Please sign the Pre-Contract Action in your wallet"); return sendTransaction(plan.transaction).andTee(() => setStatus("Processing…"), ); } }); ``` ```tsx title="Cancel Flow" import { useRepay } from "@aave/react"; const [repay, { loading, error }] = useRepay((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` In the `Erc20Approval` case, the `bySignature` field is only available if the token supports EIP-2612 permits. > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the hook calls your callback twice: reset to 0, then set the new value. > `bySignature` is `null` for these. #### 3. Execute the Repay Operation Then, execute the desired repay operation. - **TypeScript**: Use the `repay` action to prepare the repay execution plan. - **GraphQL**: Use the `repay` query to prepare the repay execution plan. ```tsx title="Repay Specific Amount" import { bigDecimal, evmAddress } from "@aave/react"; const execute = async () => { const result = await repay({ sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), // Repay 250 USDC }, }, }, }); // … }; ``` ```tsx title="Repay Maximum Amount" import { evmAddress } from "@aave/react"; const execute = async () => { const result = await repay({ sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { max: true, // Repay the full debt amount }, }, }, }); // … }; ``` ```ts title="Transaction-based" import { repay } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await repay(client, { sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), // Repay 250 USDC }, }, }, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: RepayRequest!) { repay(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on Erc20ApprovalRequired { reason requiredAmount { ...DecimalNumber } currentAllowance { ...DecimalNumber } approvals { byTransaction { ...TransactionRequest } bySignature { ...PermitTypedData } } originalTransaction { ...TransactionRequest } } ... on PreContractActionRequired { reason transaction { ...TransactionRequest } originalTransaction { ...TransactionRequest } } ... on InsufficientBalanceError { required { ...DecimalNumber } available { ...DecimalNumber } } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` ```graphql title="PermitTypedData" fragment PermitTypedData on PermitTypedData { types primaryType domain { name version chainId verifyingContract } message signedAmount } ``` In GraphQL, below are some examples of `RepayRequest` objects. ```json title="Repay Specific Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": { "exact": "250" } } } } } ``` ```json title="Repay Maximum Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": { "max": true } } } } } ``` ```jsonc title="Permit-based Approval" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "value": { "exact": "250" }, "permit": { "permitSig": { "deadline": 1700000000, // use approvals[0].bySignature.message.deadline "value": "0xabcdef…" }, "signedAmount": "250.000000" // use approvals[0].bySignature.signedAmount } } } } } ``` In TypeScript, to handle ERC-20 permit-based approval, first get the execution plan, sign the permit typed data when available, then call `repay` again with both the signature and signed amount. Unlike supply, repay also needs the `signedAmount` from the permit typed data, so `permitWith` cannot be used here. ```ts title="Permit-based (Viem)" import { repay } from "@aave/client/actions"; import { signTypedDataWith } from "@aave/client/viem"; import { bigDecimal, evmAddress, okAsync } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { sender: evmAddress(wallet.account.address), reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), // Repay 250 USDC }, }, }, }) .andThen((plan) => { if ( plan.__typename !== "Erc20ApprovalRequired" || plan.approvals.length !== 1 || !plan.approvals[0].bySignature ) { return okAsync(plan); } const permitTypedData = plan.approvals[0].bySignature; return signTypedDataWith(wallet, permitTypedData).andThen((signature) => repay(client, { sender: evmAddress(wallet.account.address), reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250), }, permit: { permitSig: { deadline: permitTypedData.message.deadline as number, value: signature, }, signedAmount: permitTypedData.signedAmount, }, }, }, }), ); }); // … ``` ```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(), }); ``` The permit-based repay flow: 1. Call `repay` without a permit 2. If the response is `Erc20ApprovalRequired` with a single `approvals[0].bySignature`, sign it 3. Call `repay` again with `amount.erc20.permit.permitSig` and `amount.erc20.permit.signedAmount` 4. Otherwise, keep the original execution plan (no permit needed or token doesn’t support permits) > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > permits aren’t available and the execution plan uses transaction-based > approvals. #### 4. Process the Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. ```ts title="Transaction-based" 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); ``` ```ts title="Permit-based" import { repay } from "@aave/client/actions"; import { sendWith, signTypedDataWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await repay(client, { sender: evmAddress(wallet.account.address), reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250) }, }, }, }) .andThen((plan) => { if ( plan.__typename !== "Erc20ApprovalRequired" || plan.approvals.length !== 1 || !plan.approvals[0].bySignature ) { return sendWith(wallet, plan); } const permitTypedData = plan.approvals[0].bySignature; return signTypedDataWith(wallet, permitTypedData) .andThen((signature) => repay(client, { sender: evmAddress(wallet.account.address), reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(250) }, permit: { permitSig: { deadline: permitTypedData.message.deadline as number, value: signature, }, signedAmount: permitTypedData.signedAmount, }, }, }, }), ) .andThen(sendWith(wallet)); }) .andThen(client.waitForTransaction); ``` > [!NOTE] > `sendWith` handles all required approvals, including the allowance reset for > tokens like USDT. In GraphQL, if the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```json title="TransactionRequest" { "data": { "repay": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xb1e8f8ef…", "value": "0", "chainId": 1, "operations": ["SPOKE_REPAY"] } } } ``` If the response is `Erc20ApprovalRequired`, you have two options: **Transaction-based approval** 1. Send each transaction in the `approvals` array in sequence 2. Then send `originalTransaction` **Permit-based approval** > [!NOTE] > This is available only when `approvals` contains a single `Erc20Approval` > item. 1. Sign the `approvals[0].bySignature` typed data with the sender’s account. 2. Call the `repay` query again with both the permit signature and `signedAmount` (see the `Permit-based Approval` example above) 3. The response will be a `TransactionRequest` you can then send directly ```jsonc title="Single Approval" { "data": { "repay": { "__typename": "Erc20ApprovalRequired", "reason": "Insufficient allowance for ERC-20 token transfer", "requiredAmount": { "value": "250.000000", "decimals": 6 }, "currentAllowance": { "value": "0.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "bySignature": { "types": , "primaryType": "Permit", "domain": , "message": , "signedAmount": "250.000000" } } ], "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xb1e8f8ef…", "value": "0", "chainId": 1, "operations": ["SPOKE_REPAY"] } } } } ``` ```json title="With Approval Reset (USDT-like)" { "data": { "repay": { "__typename": "Erc20ApprovalRequired", "reason": "Token requires allowance reset before new approval", "requiredAmount": { "value": "250.000000", "decimals": 6 }, "currentAllowance": { "value": "100.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…0", "value": "0", "chainId": 1, "operations": null }, "bySignature": null }, { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…250", "value": "0", "chainId": 1, "operations": null }, "bySignature": null } ], "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xb1e8f8ef…", "value": "0", "chainId": 1, "operations": ["SPOKE_REPAY"] } } } } ``` > [!NOTE] > With multiple approvals in `Erc20ApprovalRequired`, send each `byTransaction` > in order, then `originalTransaction`. For [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the first resets the allowance to 0 and the second sets the required amount. If the response is `PreContractActionRequired`, you must first send the `transaction` request, then send the `originalTransaction`. ```json title="PreContractActionRequired" { "data": { "repay": { "__typename": "PreContractActionRequired", "reason": "Authorize the native wrapping gateway to operate on behalf of the user", "transaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0xb1e8f8ef…", "value": "0", "chainId": 1, "operations": ["SPOKE_REPAY"] } } } } ``` If the response is an `InsufficientBalanceError`, inform the user that they don’t have enough tokens to repay the requested amount. ```json title="InsufficientBalanceError" { "data": { "repay": { "__typename": "InsufficientBalanceError", "required": { "value": "250.000000", "decimals": 6 }, "available": { "value": "150.500000", "decimals": 6 } } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await repay(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Repay successful with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Repay successful with hash:", result.value.txHash); } ``` ### Step-by-Step with Solidity Use the same identifiers and amount to repay used to preview the repay operation: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; uint256 amountToRepay = 42e6; // 42 USDC ``` Complete the repay process with the following steps: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Approve Token Transfer Then, approve the Spoke to transfer the specified amount of ERC-20 tokens. ```solidity title="Approve Token Transfer" import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; IERC20 token = IERC20(spoke.getReserve(reserveId).underlying); token.approve(spokeAddress, amountToRepay); ``` #### 3. Repay Tokens Finally, call the `repay` function on the Spoke contract, specifying the reserve ID, amount, and the user address. ```solidity title="Repay Specific Amount" spoke.repay( reserveId, amountToRepay, msg.sender ); ``` ```solidity title="Repay Maximum Amount" spoke.repay( reserveId, type(uint256).max, // Repay the full debt amount msg.sender ); ``` #### Complete Repay Example Here’s a complete Solidity example that executes the full repay flow: ```solidity title="Complete Repay Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; function repayDebt( address spokeAddress, uint256 reserveId, uint256 amountToRepay, address onBehalfOf ) external { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Pull tokens from the caller and approve the Spoke IERC20 token = IERC20(spoke.getReserve(reserveId).underlying); token.transferFrom(msg.sender, address(this), amountToRepay); token.approve(spokeAddress, amountToRepay); // Step 2: Repay debt spoke.repay(reserveId, amountToRepay, onBehalfOf); } ``` The contract must be an active [Position Manager](./managers) approved by `onBehalfOf`, otherwise `repay` reverts. --- ## Advanced Usage ### Network Fee > [!NOTE] > This experimental React hook only works with Viem or Wagmi integrations. ```tsx title="PreviewAction" import { type PreviewAction } from "@aave/react"; const action: PreviewAction = { repay: { sender: evmAddress("0x123…"), // User's address reserve: borrowPosition.reserve.id, amount: { erc20: { value: { exact: bigDecimal(42) }, // 42 USDC }, }, }, }; ``` ### Native Tokens with AaveKit When the Reserve’s underlying token is the wrapped version of the chain’s native token (e.g., WETH on Ethereum), you can repay the debt using the chain’s native token with the Native Token Gateway. Use the `reserve.asset.underlying.isWrappedNativeToken` flag to determine if the underlying token is a wrapped native token. The Native Token Gateway address is available from the chain details. ```ts title="WETH Borrow Position" const borrowPosition: UserBorrowItem = { reserve: { id: "SGVsbG8h", onChainId: "42", asset: { underlying: { address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", info: { name: "Wrapped Ether", symbol: "WETH", decimals: 18, // … }, isWrappedNativeToken: true, // … }, // … }, spoke: { address: "0x123…", // … }, chain: { chainId: 1, name: "Ethereum", nativeGateway: "0xabc…", }, // … }, // … }; ``` Specify the amount in the `amount` field as a `native` value. ```tsx title="Repay Specific Amount" const execute = async () => { const result = await repay({ sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { native: { exact: bigDecimal(1), // Repay 1 ETH }, }, }); // … }; ``` ```tsx title="Repay Maximum Amount" const execute = async () => { const result = await repay({ sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { native: { max: true, // Repay the full debt amount }, }, }); // … }; ``` ```ts title="Repay Specific Amount" const result = await repay(client, { sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { native: { exact: bigDecimal(1), // Repay 1 ETH }, }, }); // … ``` ```ts title="Repay Maximum Amount" const result = await repay(client, { sender: evmAddress(wallet.account.address), // User's address reserve: borrowPosition.reserve.id, amount: { native: { max: true, // Repay the full debt amount }, }, }); // … ``` ```json title="Repay Specific Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": { "exact": "1" } } } } ``` ```json title="Repay Maximum Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": { "max": true } } } } ``` ### Native Tokens with Solidity Start with the spoke address, reserve ID, and native gateway address identified: ```solidity title="Native Token Gateway" address spokeAddress = 0x123…; uint256 reserveId = 42; address nativeGateway = 0xabc…; ``` Follow the steps below to repay debt with native tokens (e.g., ETH) for a wrapped native token reserve (e.g., WETH). #### 1. Approve the Gateway First, approve the Native Token Gateway as your position manager. This is a one-time setup step. ```solidity title="Approve Gateway" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(nativeGateway, true); ``` #### 2. Repay Native Tokens Then, call `repayNative` on the gateway, sending the native token amount via `msg.value`. ```solidity title="Repay Specific Amount" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); gateway.repayNative{value: amountToRepay}(spokeAddress, reserveId, amountToRepay); ``` ```solidity title="Repay Full Debt" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); uint256 repayAmount = spoke.getUserTotalDebt(reserveId, msg.sender) * 10_001 / 10_000; // buffer for accrued interest gateway.repayNative{value: repayAmount}(spokeAddress, reserveId, repayAmount); ``` The gateway wraps the native token (ETH → WETH), approves the Spoke, and calls `spoke.repay` on your behalf. Any amount above the current debt is refunded to you. #### Complete Native Token Example Here’s a complete Solidity example that executes the native token repay flow. This helper acts on the contract’s own position. To repay for a user’s wallet, the user calls `setUserPositionManager` and the gateway directly. ```solidity title="Complete Native Repay Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; function repayNativeToken( address spokeAddress, address nativeGateway, uint256 reserveId, uint256 amountToRepay ) external payable { require(msg.value == amountToRepay, "Incorrect ETH amount"); ISpoke spoke = ISpoke(spokeAddress); // Step 1: Approve gateway as position manager (one-time setup) if (!spoke.isPositionManager(address(this), nativeGateway)) { spoke.setUserPositionManager(nativeGateway, true); } // Step 2: Repay native tokens via gateway INativeTokenGateway(nativeGateway).repayNative{value: amountToRepay}(spokeAddress, reserveId, amountToRepay); } ``` --- Source: https://aave.com/docs/aave-v4/positions/withdraw.md # Withdraw Assets on Aave V4 Withdrawing assets from Aave V4 allows you to: - Access your supplied assets and earned interest - Reduce or fully exit a supply position > [!WARNING] > Withdrawing collateral while you have open debt lowers your health factor and > can put the position at risk of liquidation. ## Withdraw Assets Withdrawing can be broken down into the following steps: 1. Identify the supply position to withdraw from 2. Preview the impact of the withdraw operation 3. Withdraw the assets ### Identify the Supply Position Given a list of the user’s [supply positions](./fetch#user-supplies), identify the supply position matching the token you want to withdraw and with a withdrawable amount that covers your needs. > [!NOTE] > You can’t withdraw while the reserve is paused. For example, let’s say you have identified the following `UserSupplyItem` object. ```tsx title="Example UserSupplyItem" const supplyPosition: UserSupplyItem = { reserve: { id: "SGVsbG8h", onChainId: "42", chain: { chainId: 1, name: "Ethereum", }, spoke: { address: "0x123…", // … }, asset: { underlying: { address: "0xa0b86a33e6e2ad05ad6c9ac3b6e5e5f6e7b6c1b2", // USDC }, // … }, status: { paused: false, }, // … other reserve properties }, isCollateral: true, balance: { amount: { value: BigDecimal(1042.5), // principal + accrued interest // … }, // … }, withdrawable: { amount: { value: BigDecimal(1000.0), // withdrawable now, capped by available liquidity // … }, // … }, // … }; ``` Keep in mind that if the asset is used as collateral (`isCollateral: true`), withdrawing may: - Reduce your borrowing capacity and lower the position’s health factor, increasing the risk of liquidation. - Raise the [User Risk Premium](./conditions#user-risk-premium), and with it the borrow APY of open borrow positions on the same Spoke, if the remaining collateral has a higher `reserve.settings.collateralRisk`. ### Preview Withdraw with AaveKit Preview the impact of a withdraw operation before committing to it. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of the withdraw operation on the user’s position. ```tsx title="Loading State" import { type WithdrawRequest, usePreview } from "@aave/react"; function WithdrawPreview({ request }: { request: WithdrawRequest }) { const { data, error, loading } = usePreview({ action: { withdraw: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type WithdrawRequest, usePreview } from "@aave/react"; function WithdrawPreview({ request }: { request: WithdrawRequest }) { const { data, error, loading } = usePreview({ action: { withdraw: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type WithdrawRequest, usePreviewAction } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: WithdrawRequest) => { const result = await preview({ action: { withdraw: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Withdraw Specific Amount" import { preview } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; const result = await preview(client, { action: { withdraw: { sender: evmAddress("0x789…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { exact: bigDecimal(500), // 500 USDC }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```ts title="Withdraw Maximum Amount" import { preview } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; const result = await preview(client, { action: { withdraw: { sender: evmAddress("0x789…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { max: true, // Withdraw everything (principal + interest) }, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: The `WithdrawRequest` can be as follows. - **GraphQL**: The `PreviewRequest` can be as follows. ```ts title="Withdraw Specific Amount" const request: WithdrawRequest = { sender: evmAddress("0x789…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { exact: bigDecimal(500), // 500 USDC }, }, }; ``` ```tsx title="Withdraw Maximum Amount" const request: WithdrawRequest = { sender: evmAddress("0x789…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { max: true, // Withdraw everything (principal + interest) }, }, }; ``` ```json title="Withdraw Specific Amount" { "request": { "action": { "withdraw": { "sender": "0x789…", "reserve": "SGVsbG8h", "amount": { "erc20": { "exact": "500" } } } } } } ``` ```json title="Withdraw Maximum Amount" { "request": { "action": { "withdraw": { "sender": "0x789…", "reserve": "SGVsbG8h", "amount": { "erc20": { "max": true } } } } } } ``` The `PreviewUserPosition` shows the impact of the withdraw operation by comparing current and after states, with the table below outlining key fields and how to interpret them. You can also specify a different currency to return fiat amounts in. ```tsx title="usePreview" import { Currency } from "@aave/react"; const { data, error, loading } = usePreview({ action: { withdraw: request, }, currency: Currency.Eur, }); ``` ```tsx title="usePreviewAction" import { Currency } from "@aave/react"; const [preview, { called, data, error, loading }] = usePreviewAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; const result = await preview( client, { action: { withdraw: , }, }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "action": { "withdraw": { // … } } }, "currency": "EUR" } ``` ### Preview Withdraw with Solidity Start with the spoke address and on-chain reserve ID identified: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; ``` And an amount to withdraw: ```solidity title="Amount to Withdraw" uint256 amountToWithdraw = 42e6; // 42 USDC ``` Follow the steps below to preview the impact of a withdraw operation on the user’s position. #### 1. Get Current Account Data First, retrieve the user’s current account data from the Spoke contract. ```solidity title="Get Account Data" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { Math } from "aave-v4/src/dependencies/openzeppelin/Math.sol"; ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); ``` #### 2. Calculate Withdraw Value Then, retrieve the reserve data and asset price from the oracle to calculate the USD value of the withdrawal amount. ```solidity title="Withdraw Value" address oracleAddress = spoke.ORACLE(); ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(oracleAddress).getReservePrice(reserveId); uint256 withdrawValue = amountToWithdraw * assetPrice * 10 ** (18 - reserve.decimals); ``` #### 3. Compute New Health Factor Finally, calculate the new health factor by removing the withdrawn collateral value and factor. ```solidity title="Compute New Health Factor" ISpoke.UserPosition memory userPosition = spoke.getUserPosition(reserveId, user); uint32 dynamicConfigKey = userPosition.dynamicConfigKey; ISpoke.DynamicReserveConfig memory config = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey); uint256 collateralFactor = config.collateralFactor; uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 removedWeightedValue = (withdrawValue * collateralFactor) / 10000; uint256 newWeightedSum = currentWeightedSum - removedWeightedValue; uint256 newHealthFactor = currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); ``` #### Complete Preview Example Here’s a complete Solidity example that calculates the health factor before a withdraw operation: ```solidity title="Complete Health Factor Preview" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; import { Math } from "aave-v4/src/dependencies/openzeppelin/Math.sol"; function previewWithdrawHealthFactor( address spokeAddress, uint256 reserveId, uint256 amountToWithdraw, address user ) external view returns (uint256) { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Get current account data ISpoke.UserAccountData memory currentData = spoke.getUserAccountData(user); // Step 2: Calculate withdraw value ISpoke.Reserve memory reserve = spoke.getReserve(reserveId); uint256 assetPrice = IAaveOracle(spoke.ORACLE()).getReservePrice(reserveId); uint256 withdrawValue = amountToWithdraw * assetPrice * 10 ** (18 - reserve.decimals); // Step 3: Compute new health factor uint32 dynamicConfigKey = spoke.getUserPosition(reserveId, user).dynamicConfigKey; uint256 collateralFactor = spoke.getDynamicReserveConfig(reserveId, dynamicConfigKey).collateralFactor; uint256 currentWeightedSum = (currentData.totalCollateralValue * currentData.avgCollateralFactor) / 1e18; uint256 newWeightedSum = currentWeightedSum - (withdrawValue * collateralFactor) / 10000; return currentData.totalDebtValueRay == 0 ? type(uint256).max : Math.mulDiv(newWeightedSum * 1e18, 1e27, currentData.totalDebtValueRay); } ``` ### Step-by-Step with AaveKit Withdraw assets from the selected supply position. > [!WARNING] > Withdrawing collateral with open debt increases risk and updates the [Dynamic > Config](./conditions#dynamic-risk-configuration), which updates the position’s > [User Risk Premium](./conditions#user-risk-premium). To withdraw assets from an Aave supply position with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Withdraw Flow Then, in React, use the `useWithdraw` hook to prepare the withdraw operation. ```tsx title="Basic Usage" import { useWithdraw } from "@aave/react"; const [withdraw, { loading, error }] = useWithdraw((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useWithdraw } from "@aave/react"; const [status, setStatus] = useState(""); const [withdraw, { loading, error }] = useWithdraw((plan) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please sign the Withdraw transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Withdrawing…")); case "PreContractActionRequired": setStatus("Please sign the Pre-Contract Action in your wallet"); return sendTransaction(plan.transaction).andTee(() => setStatus("Processing…"), ); } }); ``` ```tsx title="Cancel Flow" import { useWithdraw } from "@aave/react"; const [withdraw, { loading, error }] = useWithdraw((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); ``` #### 3. Execute the Withdraw Operation Then, execute the desired withdraw operation. - **TypeScript**: Use the `withdraw` action to prepare the withdraw execution plan. - **GraphQL**: Use the `withdraw` query to prepare the withdraw execution plan. ```tsx title="Withdraw Specific Amount" import { bigDecimal, evmAddress } from "@aave/react"; const execute = async () => { const result = await withdraw({ sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { exact: bigDecimal(500), // Withdraw 500 USDC }, }, }); // … }; ``` ```tsx title="Withdraw Maximum Amount" import { evmAddress } from "@aave/react"; const execute = async () => { const result = await withdraw({ sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { max: true, // Withdraw everything (principal + interest) }, }, }); // … }; ``` ```ts title="Withdraw Specific Amount" import { withdraw } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await withdraw(client, { sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { exact: bigDecimal(500), // Withdraw 500 USDC }, }, }); // … ``` ```ts title="Withdraw Maximum Amount" import { withdraw } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await withdraw(client, { sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { max: true, // Withdraw everything (principal + interest) }, }, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: WithdrawRequest!) { withdraw(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on PreContractActionRequired { reason transaction { ...TransactionRequest } originalTransaction { ...TransactionRequest } } ... on InsufficientBalanceError { required { ...DecimalNumber } available { ...DecimalNumber } } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` In GraphQL, below are some examples of `WithdrawRequest` objects. ```json title="Withdraw Specific Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "exact": "500" } } } } ``` ```json title="Withdraw Maximum Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "erc20": { "max": true } } } } ``` #### 4. Process the Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. ```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); ``` ```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(), }); ``` In GraphQL, if the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```json title="TransactionRequest" { "data": { "withdraw": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x0ad58d2f…", "value": "0", "chainId": 1, "operations": ["SPOKE_WITHDRAW"] } } } ``` If the response is a `PreContractActionRequired`, you must first send the `transaction` request. Once it succeeds, you can then send the `originalTransaction`. ```json title="PreContractActionRequired" { "data": { "withdraw": { "__typename": "PreContractActionRequired", "reason": "Authorize the native wrapping gateway to operate on behalf of the user", "transaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "originalTransaction": { "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x0ad58d2f…", "value": "0", "chainId": 1, "operations": ["SPOKE_WITHDRAW"] } } } } ``` 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": "500.000000", "decimals": 6 }, "available": { "value": "250.500000", "decimals": 6 } } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await withdraw(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error(`Invalid withdrawal amount: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Withdraw successful with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error(`Invalid withdrawal amount: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Withdraw successful with hash:", result.value.txHash); } ``` ### Step-by-Step with Solidity Use the same identifiers and amount to withdraw used to preview the withdraw operation: ```solidity title="Target Reserve" address spokeAddress = 0x123…; uint256 reserveId = 42; uint256 amountToWithdraw = 42e6; // 42 USDC ``` Complete the withdraw process with the following steps: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Withdraw Assets Finally, call the `withdraw` function on the Spoke contract, specifying the reserve ID, amount, and the `onBehalfOf` address (the position owner). The withdrawn assets are sent to `msg.sender`. ```solidity title="Withdraw" spoke.withdraw( reserveId, amountToWithdraw, msg.sender ); ``` #### Complete Withdraw Example Here’s a complete Solidity example that executes the full withdraw flow: ```solidity title="Complete Withdraw Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function withdrawFromReserve( address spokeAddress, uint256 reserveId, uint256 amountToWithdraw, address onBehalfOf ) external { ISpoke(spokeAddress).withdraw(reserveId, amountToWithdraw, onBehalfOf); } ``` --- ## Advanced Usage ### Network Fee > [!NOTE] > This experimental React hook only works with Viem or Wagmi integrations. ```tsx title="PreviewAction" import { type PreviewAction } from "@aave/react"; const action: PreviewAction = { withdraw: { sender: evmAddress("0x123…"), // User's address reserve: supplyPosition.reserve.id, amount: { erc20: { exact: bigDecimal(42), // USDC }, }, }, }; ``` ### Native Tokens with AaveKit When the Reserve’s underlying token is the wrapped version of the chain’s native token (e.g., WETH on Ethereum), you can withdraw the asset as the chain’s native token using the Native Token Gateway. Use the `reserve.asset.underlying.isWrappedNativeToken` flag to determine if the underlying token is a wrapped native token. The Native Token Gateway address is available from the chain details. ```ts title="WETH Supply Position" const supplyPosition: UserSupplyItem = { reserve: { id: "SGVsbG8h", onChainId: "42", asset: { underlying: { address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", info: { name: "Wrapped Ether", symbol: "WETH", decimals: 18, // … }, isWrappedNativeToken: true, // … }, // … }, spoke: { address: "0x123…", // … }, chain: { chainId: 1, name: "Ethereum", nativeGateway: "0xabc…", }, // … }, balance: { amount: { value: BigDecimal(1.25), // … }, // … }, // … }; ``` Specify the amount in the `amount` field as a `native` value. ```tsx title="Withdraw Specific Amount" const execute = async () => { const result = await withdraw({ sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { native: { exact: bigDecimal(1), // Withdraw 1 ETH }, }, }); // … }; ``` ```tsx title="Withdraw Maximum Amount" const execute = async () => { const result = await withdraw({ sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { native: { max: true, // Withdraw everything }, }, }); // … }; ``` ```ts title="Withdraw Specific Amount" const result = await withdraw(client, { sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { native: { exact: bigDecimal(1), // Withdraw 1 ETH }, }, }); // … ``` ```ts title="Withdraw Maximum Amount" const result = await withdraw(client, { sender: evmAddress(wallet.account.address), // User's address reserve: supplyPosition.reserve.id, amount: { native: { max: true, // Withdraw everything }, }, }); // … ``` ```json title="Withdraw Specific Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": { "exact": "1" } } } } ``` ```json title="Withdraw Maximum Amount" { "request": { "sender": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "reserve": "SGVsbG8h", "amount": { "native": { "max": true } } } } ``` ### Native Tokens with Solidity Start with the spoke address, reserve ID, and native gateway address identified: ```solidity title="Native Token Gateway" address spokeAddress = 0x123…; uint256 reserveId = 42; address nativeGateway = 0xabc…; ``` Follow the steps below to withdraw native tokens (e.g., ETH) from an existing supply position in a wrapped native token reserve (e.g., WETH). #### 1. Approve the Gateway First, approve the Native Token Gateway as your position manager. This is a one-time setup step. ```solidity title="Approve Gateway" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(nativeGateway, true); ``` #### 2. Withdraw Native Tokens Then, call `withdrawNative` on the gateway to withdraw and unwrap the tokens. ```solidity title="Withdraw Specific Amount" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); gateway.withdrawNative(spokeAddress, reserveId, amountToWithdraw); ``` ```solidity title="Withdraw Maximum Amount" import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; INativeTokenGateway gateway = INativeTokenGateway(nativeGateway); gateway.withdrawNative(spokeAddress, reserveId, type(uint256).max); ``` The gateway calls `spoke.withdraw` on your behalf, unwraps the token (WETH → ETH), and sends the native token to the caller. #### Complete Native Token Example Here’s a complete Solidity example that executes the native token withdraw flow. This helper acts on the contract’s own position. The gateway sends the native tokens to the contract, so it needs a `receive()` function. To withdraw for a user’s wallet, the user calls `setUserPositionManager` and the gateway directly. ```solidity title="Complete Native Withdraw Flow" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { INativeTokenGateway } from "aave-v4/src/position-manager/interfaces/INativeTokenGateway.sol"; function withdrawNativeToken( address spokeAddress, address nativeGateway, uint256 reserveId, uint256 amountToWithdraw ) external { ISpoke spoke = ISpoke(spokeAddress); // Step 1: Approve gateway as position manager (one-time setup) if (!spoke.isPositionManager(address(this), nativeGateway)) { spoke.setUserPositionManager(nativeGateway, true); } // Step 2: Withdraw native tokens via gateway INativeTokenGateway(nativeGateway).withdrawNative(spokeAddress, reserveId, amountToWithdraw); } receive() external payable {} ``` --- Source: https://aave.com/docs/aave-v4/positions/conditions.md # Aave V4 Position Conditions User positions track two risk conditions: Dynamic Risk Configuration and User Risk Premium. ## Dynamic Risk Configuration Dynamic Risk Configuration, or _Dynamic Config_ for short, snapshots the per-reserve collateral parameters (Collateral Factor, Max Liquidation Bonus, and Liquidation Fee) active when the position first became risk-bearing, i.e. when the user initially borrowed against collateral. It updates when the user performs risk-increasing actions: borrowing, withdrawing collateral, or disabling collateral (updates all reserves' snapshots), or enabling collateral (updates only that reserve’s snapshot). It can also be updated manually, and always refreshes the User Risk Premium. The Dynamic Config values used on first borrow or after an update (implicit or explicit) are exposed on the `Reserve` object under the `settings` field: ```ts title="Live Dynamic Config" const reserve: Reserve = { __typename: "Reserve", id: "SGVsbG8h", settings: { __typename: "ReserveSettings", collateralFactor: { normalized: BigDecimal(80), // 80% // … }, maxLiquidationBonus: { normalized: BigDecimal(10), // 10% // … }, // protocol fee liquidationFee: { normalized: BigDecimal(1), // 1% // … }, // … latestDynamicConfigKey: "1234567890", }, // … }; ``` The snapshotted values are exposed under the Reserve’s `userState` field: the Collateral Factor applies to reserves linked by `UserSupplyItem` when used as collateral, while the Max Liquidation Bonus and Liquidation Fee apply to reserves linked by `UserBorrowItem`. ```ts title="UserBorrowItem" const borrowItem: UserBorrowItem = { __typename: "UserBorrowItem", id: "aGVsbG8=", reserve: { __typename: "Reserve", id: "SGVsbG8h", userState: { __typename: "ReserveUserState", maxLiquidationBonus: { normalized: BigDecimal(10), // 10% // … }, // protocol fee liquidationFee: { normalized: BigDecimal(1), // 1% // … }, // … dynamicConfigKey: "1234567889", }, // … }, // … }; ``` ```ts title="UserSupplyItem" const supplyItem: UserSupplyItem = { __typename: "UserSupplyItem", id: "aGVsbG8=", isCollateral: true, reserve: { __typename: "Reserve", id: "SGVsbG8h", userState: { __typename: "ReserveUserState", collateralFactor: { normalized: BigDecimal(80), // 80% // … }, // … dynamicConfigKey: "1234567889", }, // … }, // … }; ``` ## User Risk Premium User Risk Premium reflects the current risk profile of the collateral assets. In practice, it acts as a multiplier: a percentage applied on top of each reserve’s base borrow rate. Lower is better. > [!NOTE] > Riskier collateral raises the User Risk Premium and the borrow rate. > Higher-quality collateral lowers both. It updates when the user performs actions that affect collateralization (borrowing, withdrawing collateral, enabling or disabling collateral), when the Dynamic Risk Configuration changes, or when explicitly triggered. You can keep track of the User Risk Premium for a position by checking the `riskPremium.current` field in the [User Position](./fetch#listing-user-positions) response. ```ts title="User Risk Premium" const userPosition: UserPosition = { __typename: "UserPosition", id: "aGVsbG8", user: "0x456…", riskPremium: { current: { normalized: BigDecimal(50), // 50% // … }, latest: { normalized: BigDecimal(50), // 50% - same as current // … }, breakdown: [ // … ], }, spoke: { id: "SGVsbG8h", address: "0x123…", chain: { chainId: 1, name: "Ethereum", // … }, // … }, // … }; ``` > [!NOTE] > In this example, a 50% User Risk Premium on a 5% base borrow rate means the > user pays 7.5% (5% × 1.5). The `riskPremium.breakdown` field contains the [User Risk Premium Breakdown](#user-risk-premium-breakdown) for the user position collaterals. ### User Risk Premium Breakdown The User Risk Premium Breakdown shows each collateral asset in a user position, including what percentage of total collateral it represents and its weight in the overall User Risk Premium. ```ts title="User Risk Premium Breakdown" const breakdown: UserRiskPremiumBreakdownItem[] = [ { __typename: "UserRiskPremiumBreakdownItem", token: { __typename: "Erc20Token", address: "0x456…", info: { name: "USD Coin", symbol: "USDC", decimals: 6, }, }, currentRiskPremiumWeight: { __typename: "PercentNumber", normalized: BigDecimal(50), // 50% // … }, latestRiskPremiumWeight: { __typename: "PercentNumber", normalized: BigDecimal(45), // 45% // … }, collateral: { __typename: "PercentNumber", normalized: BigDecimal(30), // 30% // … }, }, // … ]; ``` Where: - `currentRiskPremiumWeight` represents the current contribution of this collateral asset to the overall User Risk Premium. - `latestRiskPremiumWeight` represents the contribution if the User Risk Premium were to be updated. - `collateral` represents this asset’s share of the position’s total collateral value. As mentioned above, the breakdown is available in the `riskPremium.breakdown` field of [user positions](./fetch#user-position-data-structure), or you can use the standalone query explained below. Use the `useUserRiskPremiumBreakdown` hook in React, the `userRiskPremiumBreakdown` action in TypeScript, or the `userRiskPremiumBreakdown` query in GraphQL to fetch the breakdown for a specific user position. ```tsx title="Loading State" import { type UserRiskPremiumBreakdownRequest, useUserRiskPremiumBreakdown, } from "@aave/react"; function UserRiskPremiumBreakdown({ request, }: { request: UserRiskPremiumBreakdownRequest; }) { const { data, loading, error } = useUserRiskPremiumBreakdown(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (
{data.map((item) => (
{item.token.info.symbol}

Current Weight: {item.currentRiskPremiumWeight.normalized.toFixed(2)}%

Latest Weight: {item.latestRiskPremiumWeight.normalized.toFixed(2)}%

Collateral: {item.collateral.normalized.toFixed(2)}%
))}
); } ``` ```tsx title="React Suspense" import { type UserRiskPremiumBreakdownRequest, useUserRiskPremiumBreakdown, } from "@aave/react"; function UserRiskPremiumBreakdown({ request, }: { request: UserRiskPremiumBreakdownRequest; }) { const { data } = useUserRiskPremiumBreakdown({ ...request, suspense: true, }); return (
{data.map((item) => (
{item.token.info.symbol}

Current Weight: {item.currentRiskPremiumWeight.normalized.toFixed(2)}%

Latest Weight: {item.latestRiskPremiumWeight.normalized.toFixed(2)}%

Collateral: {item.collateral.normalized.toFixed(2)}%
))}
); } ```
```ts title="By User Position ID" import { userRiskPremiumBreakdown } from "@aave/client/actions"; import { evmAddress, userPositionId } from "@aave/client"; import { client } from "./client"; const result = await userRiskPremiumBreakdown(client, { user: evmAddress("0x742d35cc…"), query: { userPositionId: userPositionId(params.id), // UserPositionId - typically from route params }, }); if (result.isOk()) { console.log(result.value); // UserRiskPremiumBreakdownItem[] } else { console.error(result.error); } ``` ```ts title="By User and Spoke" import { userRiskPremiumBreakdown } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await userRiskPremiumBreakdown(client, { user: evmAddress("0x742d35cc…"), query: { userSpoke: { user: evmAddress("0x742d35cc…"), spoke: spoke.id, // spoke: Spoke }, }, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: UserRiskPremiumBreakdownRequest!) { userRiskPremiumBreakdown(request: $request) { token { ...Erc20Token } currentRiskPremiumWeight { ...PercentNumber } latestRiskPremiumWeight { ...PercentNumber } collateral { ...PercentNumber } } } ``` ```graphql title="Erc20Token" fragment Erc20Token on Erc20Token { address info { ...TokenInfo } chain { ...Chain } } fragment TokenInfo on TokenInfo { id name symbol icon decimals } fragment Chain on Chain { name chainId icon } ``` ```graphql title="PercentNumber" fragment PercentNumber on PercentNumber { onChainValue decimals value normalized } ```
- **React**: You can query by user position ID or by user spoke. - **GraphQL**: Use the following variables: ```tsx title="By User Position ID" const request: UserRiskPremiumBreakdownRequest = { user: evmAddress("0x742d35cc…"), query: { userPositionId: userPositionId(params.id), // UserPositionId - typically from URL params }, }; ``` ```tsx title="By User and Spoke" const request: UserRiskPremiumBreakdownRequest = { user: evmAddress("0x742d35cc…"), query: { userSpoke: { user: evmAddress("0x742d35cc…"), spoke: spoke.id, // spoke: Spoke }, }, }; ``` ```json title="By User Position ID" { "request": { "user": "0x742d35cc…", "query": { "userPositionId": "aGVsbG8" } } } ``` ```json title="By User and Spoke" { "request": { "user": "0x742d35cc…", "query": { "userSpoke": { "user": "0x742d35cc…", "spoke": "SGVsbG8h" } } } } ``` ## Update Conditions As protocol configurations evolve through governance votes, a user position’s conditions may improve. Updating user position conditions can be broken down into the following steps: 1. Identify eligible positions 2. Preview the impact of the update (optional) 3. Update the position conditions ### Identify Eligible Positions You can identify positions that qualify for updates by checking if the `riskPremium.latest` is lower than `riskPremium.current` (indicating a better risk premium is available) or the `canUpdateDynamicConfig` field (true when dynamic config can be updated) in the [user’s positions](./fetch#listing-user-positions). ```ts title="Eligible User Position" const userPosition: UserPosition = { __typename: "UserPosition", id: "aGVsbG8", user: "0x456…", riskPremium: { current: { normalized: BigDecimal(50), // 50% // … }, latest: { normalized: BigDecimal(25), // 25% - lower is better // … }, breakdown: [ // … ], }, spoke: { id: "SGVsbG8h", address: "0x123…", chain: { chainId: 1, name: "Ethereum", // … }, // … }, canUpdateDynamicConfig: true, // … }; ``` ### Preview the Impact Preview the impact of updating the user position conditions before committing to it. Use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query in GraphQL to preview the impact of updating the user position conditions. ```tsx title="Loading State" import { type UpdateUserPositionConditionsRequest, usePreview, } from "@aave/react"; function UserPositionConditionsPreview({ request, }: { request: UpdateUserPositionConditionsRequest; }) { const { data, error, loading } = usePreview({ action: { updateUserPositionConditions: request, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type UpdateUserPositionConditionsRequest, usePreview, } from "@aave/react"; function UserPositionConditionsPreview({ request, }: { request: UpdateUserPositionConditionsRequest; }) { const { data, error, loading } = usePreview({ action: { updateUserPositionConditions: request, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (request: UpdateUserPositionConditionsRequest) => { const result = await preview({ action: { updateUserPositionConditions: request, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Update User Risk Premium" import { preview } from "@aave/client/actions"; import { UserPositionConditionsUpdate } from "@aave/client"; import { client } from "./client"; const result = await preview(client, { action: { updateUserPositionConditions: { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.JustRiskPremium, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } ``` ```ts title="Update All Dynamic Config" const result = await preview(client, { action: { updateUserPositionConditions: { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.AllDynamicConfig, }, }, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ``` ```graphql title="HealthFactorResult" fragment HealthFactorResult on HealthFactorResult { __typename ... on HealthFactorVariation { ...HealthFactorVariation } ... on HealthFactorError { ...HealthFactorError } } fragment HealthFactorVariation on HealthFactorVariation { __typename current after } fragment HealthFactorError on HealthFactorError { __typename reason current after } ``` ```graphql title="UserPositionConditionVariation" fragment UserPositionConditionVariation on UserPositionConditionVariation { __typename ... on CollateralFactorVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on LiquidationFeeVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } ... on MaxLiquidationBonusVariation { reserveId token { ...Erc20Token } current { ...PercentNumber } after { ...PercentNumber } } } ``` ```graphql title="Others" fragment PercentNumberVariation on PercentNumberVariation { __typename current { ...PercentNumber } after { ...PercentNumber } } fragment ExchangeAmountVariation on ExchangeAmountVariation { __typename current { ...ExchangeAmount } after { ...ExchangeAmount } } ```
- **React**: See below for examples of `UpdateUserPositionConditionsRequest` objects. - **GraphQL**: You can preview different update operations using the `update` field. ```ts title="Update User Risk Premium" const request: UpdateUserPositionConditionsRequest = { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.JustRiskPremium, }; ``` ```ts title="Update All Dynamic Config" const request: UpdateUserPositionConditionsRequest = { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.AllDynamicConfig, }; ``` ```json title="Update User Risk Premium" { "request": { "action": { "updateUserPositionConditions": { "userPositionId": "aGVsbG8", "update": "JUST_RISK_PREMIUM" } } } } ``` ```json title="Update All Dynamic Config" { "request": { "action": { "updateUserPositionConditions": { "userPositionId": "aGVsbG8", "update": "ALL_DYNAMIC_CONFIG" } } } } ``` > [!WARNING] > Updating Dynamic Config also updates the User Risk Premium. The `PreviewUserPosition` shows the impact of updating the position conditions by comparing current and after states, with the table below outlining key fields and how to interpret them. ### Step-by-Step with AaveKit Update the selected user position conditions. To update user position conditions with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Update Flow Then, in React, use the `useUpdateUserPositionConditions` hook to prepare the transaction request. ```tsx title="Basic Usage" import { useUpdateUserPositionConditions } from "@aave/react"; const [updateConditions, { loading, error }] = useUpdateUserPositionConditions( (transaction) => sendTransaction(transaction), ); ``` ```tsx title="Update Component State" import { useUpdateUserPositionConditions } from "@aave/react"; const [status, setStatus] = useState(""); const [updateConditions, { loading, error }] = useUpdateUserPositionConditions( (transaction) => { setStatus("Please sign the transaction in your wallet"); return sendTransaction(transaction).andTee(() => setStatus("Updating position conditions…"), ); }, ); ``` ```tsx title="Cancel Flow" import { useUpdateUserPositionConditions } from "@aave/react"; const [updateConditions, { loading, error }] = useUpdateUserPositionConditions( (transaction, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } return sendTransaction(transaction); }, ); ``` #### 3. Execute the Transaction Then, execute the transaction. - **TypeScript**: Use the `updateUserPositionConditions` action to prepare the transaction request. - **GraphQL**: Use the `updateUserPositionConditions` query to prepare the transaction request. ```tsx title="Update User Risk Premium" import { UserPositionConditionsUpdate, type UserPosition } from "@aave/react"; const execute = async (userPosition: UserPosition) => { const result = await updateConditions({ userPositionId: userPosition.id, update: UserPositionConditionsUpdate.JustRiskPremium, }); }; ``` ```tsx title="Update All Dynamic Config" import { UserPositionConditionsUpdate, type UserPosition } from "@aave/react"; const execute = async (userPosition: UserPosition) => { const result = await updateConditions({ userPositionId: userPosition.id, update: UserPositionConditionsUpdate.AllDynamicConfig, }); }; ``` ```ts title="Update User Risk Premium" import { updateUserPositionConditions } from "@aave/client/actions"; import { UserPositionConditionsUpdate } from "@aave/client"; // const userPosition: UserPosition = … const result = await updateUserPositionConditions(client, { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.JustRiskPremium, }); ``` ```ts title="Update All Dynamic Config" import { updateUserPositionConditions } from "@aave/client/actions"; import { UserPositionConditionsUpdate } from "@aave/client"; const result = await updateUserPositionConditions(client, { userPositionId: userPosition.id, update: UserPositionConditionsUpdate.AllDynamicConfig, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: UpdateUserPositionConditionsRequest!) { updateUserPositionConditions(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` In GraphQL, use the following variables: ```json title="Update User Risk Premium" { "request": { "userPositionId": "aGVsbG8", "update": "JUST_RISK_PREMIUM" } } ``` ```json title="Update All Dynamic Config" { "request": { "userPositionId": "aGVsbG8", "update": "ALL_DYNAMIC_CONFIG" } } ``` #### 4. Process the Transaction Request In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transaction, and await indexing with `client.waitForTransaction`. ```ts title="Viem" import { updateUserPositionConditions } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await updateUserPositionConditions(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```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(), }); ``` In GraphQL, the API returns a `TransactionRequest`, which you can send directly with the wallet tied to the `from` address. ```json title="TransactionRequest" { "data": { "updateUserPositionConditions": { "__typename": "TransactionRequest", "to": "0x94e7a5dcbe816e498b89ab752661904e2f56c485", "from": "0x742d35cc6e5c4ce3b69a2a8c7c8e5f7e9a0b1234", "data": "0x91c46d09…", "value": "0", "chainId": 1, "operations": ["SPOKE_UPDATE_USER_RISK_PREMIUM"] } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async () => { const result = await updateConditions(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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; } return; } console.log( "Position conditions updated successfully with hash:", result.value.txHash, ); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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( "Position conditions updated successfully with hash:", result.value.txHash, ); } ``` ### Step-by-Step with Solidity To update user position conditions onchain, follow these steps after identifying the `spokeAddress`: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Update User Position Conditions Then, call `updateUserRiskPremium` to update only the User Risk Premium, or `updateUserDynamicConfig` to update all Dynamic Config and the User Risk Premium. ```solidity title="Update Risk Premium" spoke.updateUserRiskPremium(msg.sender); ``` ```solidity title="Update All Dynamic Config" spoke.updateUserDynamicConfig(msg.sender); ``` --- ## Advanced Usage ### Network Fee > [!NOTE] > This experimental React hook only works with Viem or Wagmi integrations. ```tsx title="PreviewAction" import { type PreviewAction, UserPositionConditionsUpdate } from "@aave/react"; const action: PreviewAction = { updateUserPositionConditions: { userPositionId: userPosition.id, // from UserPosition update: UserPositionConditionsUpdate.AllDynamicConfig, }, }; ``` --- Source: https://aave.com/docs/aave-v4/positions/swaps/supply.md # Swap Supply Asset Swapping supply assets combines withdraw, swap, and re-supply into one step. > [!WARNING] > Position swaps now run on the Order API. Update your code: > - `preparePositionSwap` → `prepareOrder` > - `swap` → `submitOrder` > - React: `useSupplySwap` → `useSupplySwapOrder` > - React: `useBorrowSwap` → `useBorrowSwapOrder` > - React: `useRepayWithSupply` → `useRepayWithSupplyOrder` This feature leverages [CoW Protocol](https://cow.fi/) for swap execution. Users sign an intent and solvers execute it through batch auctions with [MEV protection](https://ethereum.org/en/developers/docs/mev/). Most flows need no transaction; if an approval or the `submitOrder` result returns a transaction request, the user sends it and pays gas. > [!NOTE] > See [Fees](../../tools/swaps#fees) for swap costs. Common scenarios: | Scenario | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | **Liquidation Risk Reduction** | User wants to swap volatile collateral to stable assets to reduce liquidation risk | | **Better Rates** | User wants to switch supply position to a reserve with better rates (regardless of being used as collateral or not) | | **Replenish Collateral** | User wants to use a non-collateral supply to replenish a collateral position to gain more borrowing power at the same risk level | | **Better Risk Premium** | User wants to consolidate collateral to a less risky asset (lower Collateral Risk) to reduce the risk premium on borrows | Swapping supply assets can be broken down into the following steps: 1. Identify the supply position to swap from 2. Choose the target reserve to swap onto 3. Choose between market order and limit order 4. Execute the swap operation ## Identify the Supply Position Identify the supply position among the user’s [supply positions](../fetch#user-supplies) where `reserve.canSwapFrom: true`. ```tsx title="UserSupplyItem" const supplyPosition: UserSupplyItem = { id: "aGVsbG8", reserve: { id: "SGVsbG8h", canSwapFrom: true, chain: { chainId: 1, name: "Ethereum", }, spoke: { id: "aGVsbG8", // … }, // … }, isCollateral: true, balance: { amount: { value: BigDecimal(1.5), exchange: { value: BigDecimal(5000.0), // … }, // … }, // … }, withdrawable: { amount: { value: BigDecimal(0.03), exchange: { value: BigDecimal(100.0), // … }, // … }, // … }, // … }; ``` > [!NOTE] > `reserve.canSwapFrom` means the reserve isn’t paused and has flash loans > enabled, which the swap needs. ## Identify the Target Reserve Choose the target [reserve](../../liquidity/reserves#listing-available-reserves) where `canSupply: true`. The target reserve must be on the **same spoke** as the source supply position. > [!NOTE] > As in a regular supply, `canSupply` means the reserve isn’t frozen, isn’t > paused and is below its supply cap. ```tsx title="Target Reserve" const targetReserve: Reserve = { id: "V29ybGQh", canSupply: true, canUseAsCollateral: true, spoke: { id: "aGVsbG8", // … }, asset: { underlying: { address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", info: { name: "USD Coin", symbol: "USDC", decimals: 6, // … }, // … }, // … }, summary: { supplyApy: { normalized: BigDecimal(4.5), // 4.5% APY // … }, // … }, userState: { suppliable: { exchange: { value: BigDecimal(1245.67), name: "USD", symbol: "$", // … }, // … }, }, // … }; ``` Consider the following factors when selecting a target reserve: - **Token**: Check `asset.underlying` for the token of the new supply position - **Collateral**: Verify `canUseAsCollateral` if collateral is needed - **Capacity**: Review `userState.suppliable` for sufficient supply capacity - **Rate**: Compare `summary.supplyApy` for favorable APY ## Market or Limit Order You decide whether to use a market order or a limit order. ### Market Orders Market orders execute at current rates. ```ts title="TypeScript" const request: SupplySwapQuoteRequest = { market: { sellPosition: supplyPosition.id, buyReserve: targetReserve.id, enableCollateral: supplyPosition.isCollateral && targetReserve.canUseAsCollateral, amount: bigDecimal(0.03), user: evmAddress("0x123…"), // selectedSlippage: bigDecimal(1), // Optional: override suggested slippage }, }; ``` ```json title="GraphQL Variables" { "request": { "market": { "sellPosition": "aGVsbG8", "buyReserve": "V29ybGQh", "enableCollateral": true, "amount": "0.03", "user": "0x123…" } } } ``` The request takes the following parameters: - `sellPosition`: The current supply position to swap from - `buyReserve`: The target reserve to swap to - `enableCollateral`: Whether to enable the new position as collateral - `amount`: The amount of the current position to swap - `user`: The user’s address - `selectedSlippage`: Optional slippage tolerance to use instead of the suggested slippage ### Limit Orders Limit orders execute when your price condition is met. ```ts title="TypeScript" const request: SupplySwapQuoteRequest = { limit: { currentPosition: supplyPosition.id, currentAmount: bigDecimal(0.03), newReserve: targetReserve.id, newAmount: bigDecimal(105), // Desired amount to receive enableCollateral: supplyPosition.isCollateral && targetReserve.canUseAsCollateral, user: evmAddress("0x123…"), kind: SupplySwapKind.Current, // deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // Optional: custom expiry }, }; ``` ```json title="GraphQL Variables" { "request": { "limit": { "currentPosition": "aGVsbG8", "currentAmount": "0.03", "newReserve": "V29ybGQh", "newAmount": "105", "enableCollateral": true, "user": "0x123…", "kind": "CURRENT" } } } ``` The request takes the following parameters: - `currentPosition`: The current supply position to swap from - `currentAmount`: The amount of the current position to swap - `newReserve`: The target reserve to swap to - `newAmount`: The desired amount to receive in the new position - `enableCollateral`: Whether to enable the new position as collateral - `user`: The user’s address - `kind`: Current (default) or New, determines which amount is honored - `deadline`: Optional deadline as DateTime; if not provided, uses default expiry With both amounts specified, the `kind` parameter determines which amount takes priority: | Kind | User specifies… | What happens with the order | | ------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------ | | **Current** | The exact _current_ amount and a minimum _new_ amount | Order fulfilled when new position price allows desired exchange within current limit | | **New** | The exact _new_ amount and a maximum _current_ usage | Order fulfilled when current position price allows achieving the desired new amount | The `enableCollateral` flag controls the destination supply’s collateral status: `true` enables it as collateral; `false` keeps the existing status (or non-collateral for a new position). The examples assume the target reserve allows collateral and mirror the source’s collateral state; adjust to fit your scenario. ## Step-by-Step with AaveKit To execute a supply swap with AaveKit, follow these steps. ### 1. Get a Quote First, use the `useSupplySwapQuote` hook (or the imperative `useSupplySwapQuoteAction` variant) in React, the `supplySwapQuote` action in TypeScript, or the `supplySwapQuote` query in GraphQL to get pricing information for the swap. ```tsx title="Loading State" import { type SupplySwapQuoteRequest, useSupplySwapQuote } from "@aave/react"; function SwapQuote({ request }: { request: SupplySwapQuoteRequest }) { const { data, loading, error } = useSupplySwapQuote(request); if (loading) return Loading…; if (error) { if (error.name === "ValidationError") { switch (error.cause.__typename) { case "InsufficientLiquidityError": return Not enough liquidity for this swap; } } return {error.message}; } // data: SwapQuote return (
You will receive: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="React Suspense" import { type SupplySwapQuoteRequest, useSupplySwapQuote } from "@aave/react"; function SwapQuote({ request }: { request: SupplySwapQuoteRequest }) { const { data } = useSupplySwapQuote({ ...request, suspense: true, }); // data: SwapQuote return (
You will receive: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="Imperative Read" import { type SupplySwapQuoteRequest, useSupplySwapQuoteAction, } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useSupplySwapQuoteAction(); const handler = async (request: SupplySwapQuoteRequest) => { const result = await getQuote(request); if (result.isOk()) { // result.value: SwapQuote console.log(result.value); } else { console.error(result.error); } }; ```
```ts title="Get Quote" import { supplySwapQuote } from "@aave/client/actions"; import { client } from "./client"; // … const result = await supplySwapQuote(client, request); if (result.isErr()) { console.error(result.error); return; } // result.value.quote: SwapQuote ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: SupplySwapQuoteRequest!, $currency: Currency!) { supplySwapQuote(request: $request) { __typename ... on PositionSwapByIntentApprovalsRequired { quote { ...SwapQuote } approvals { ...PositionSwapApproval } } ... on InsufficientLiquidityError { reason } } } ``` ```graphql title="PositionSwapApproval" fragment PositionSwapApproval on PositionSwapApproval { __typename ... on PositionSwapAdapterContractApproval { bySignature { ...SwapTypedData } } ... on PositionSwapPositionManagerApproval { byTransaction { ...TransactionRequest } bySignature { ...SwapTypedData } } ... on PositionSwapSetCollateralApproval { bySignature { ...SwapTypedData } } } ```
In React and TypeScript, you can specify a different currency to return fiat amounts in. ```ts title="useSupplySwapQuote" import { Currency } from "@aave/react"; const { data, error, loading } = useSupplySwapQuote({ ...request, currency: Currency.Eur, }); ``` ```ts title="useSupplySwapQuoteAction" import { Currency } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useSupplySwapQuoteAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; // … const result = await supplySwapQuote(client, request, { currency: Currency.Eur, }); ``` In React and TypeScript, the quote is returned as a `SwapQuote`. In GraphQL, the response can be either: - `PositionSwapByIntentApprovalsRequired`: The quote was successful, but the user needs to sign approvals before executing the swap. - `InsufficientLiquidityError`: There’s not enough liquidity for the requested swap amount. The `PositionSwapByIntentApprovalsRequired` contains the `SwapQuote` with pricing details and the `PositionSwapApproval` list of required approvals to sign before executing the swap. ### 2. Preview the Impact Then, use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query with the `quoteId` from the previous step in GraphQL to preview the impact of the swap operation on the user’s position. In TypeScript and GraphQL, this step is optional. ```tsx title="Loading State" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { supplySwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { supplySwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type SwapQuote, usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (quote: SwapQuote) => { const result = await preview({ action: { supplySwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Preview Swap" import { preview } from "@aave/client/actions"; import { client } from "./client"; // … const result = await supplySwapQuote(client, request).andThen( ({ approvals, quote }) => preview(client, { action: { supplySwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }), ); if (result.isErr()) { console.error(result.error); return; } // result.value: PreviewUserPosition ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ```
In GraphQL, pass the `quoteId` in the `supplySwap.fromQuote` field: ```json title="Variables" { "request": { "action": { "supplySwap": { "fromQuote": { "quoteId": "" } } } }, "currency": "USD" } ``` The `PreviewUserPosition` shows the impact of the swap operation by comparing current and after states, with the table below outlining key fields and how to interpret them. ### 3. Configure Wallet Integration Then, in React, instantiate the hooks for the [wallet library of your choice](../../getting-started/react#integrations): - `useSignTypedData`: used to sign the approvals and the order typed data - `useSendTransaction`: used to send the order transaction when the Order API returns one ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` ### 4. Define the Swap Flow Then, in React, use the `useSupplySwapOrder` hook to handle the operation. It fetches the quote, collects the approval signatures, and prepares, signs, and submits the order. ```tsx title="Basic Usage" import { useSupplySwapOrder } from "@aave/react"; const [swapSupply, { loading, error }] = useSupplySwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useState } from "react"; import { useSupplySwapOrder } from "@aave/react"; const [status, setStatus] = useState(""); const [swapSupply, { loading, error }] = useSupplySwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": setStatus("Sign the swap adapter approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapPositionManagerApproval": setStatus("Sign the swap position manager approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapSetCollateralApproval": setStatus("Sign the set collateral approval in your wallet"); return signTypedData(plan.bySignature); case "OrderTypedData": setStatus("Sign the swap order in your wallet"); return signTypedData(plan); case "OrderTransactionRequest": setStatus("Send the swap transaction in your wallet"); return sendTransaction(plan.transaction); } }); ``` ```tsx title="Cancel Flow" import { useSupplySwapOrder } from "@aave/react"; const [swapSupply, { loading, error }] = useSupplySwapOrder((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` The operation involves up to 4 signatures: - **Swap adapter contract approval**: A one-time-use contract that encapsulates the swap logic. This signature ensures the contract is used only once for this specific swap operation. - **Swap position manager approval**: Authorizes a dedicated [Position Manager](../managers) to operate on the user’s position. - **Set collateral approval**: Enables the destination asset as collateral, needed only when it is not yet enabled as collateral. - **Swap order**: The order typed data returned by `prepareOrder`, signed after the approvals. ### 5. Sign Approvals In TypeScript, use `signTypedDataWith` for the [wallet library of your choice](../../getting-started/typescript#sign-typed-data) to sign the swap approvals. ```ts title="signApprovals.ts" import { type PositionSwapByIntentApprovalsRequired, type PrepareOrderRequest, type ResultAsync, type SignTypedDataError, okAsync, } from "@aave/client"; import { signTypedDataWith } from "@aave/client/viem"; import { wallet } from "./wallet"; export function signApprovals({ approvals, quote, }: PositionSwapByIntentApprovalsRequired): ResultAsync< PrepareOrderRequest, SignTypedDataError > { return approvals.reduce( (acc, approval) => acc.andThen((request) => signTypedDataWith(wallet, approval.bySignature).map((signature) => { switch (approval.__typename) { case "PositionSwapAdapterContractApproval": return { ...request, adapterContractSignature: signature }; case "PositionSwapPositionManagerApproval": return { ...request, positionManagerSignature: signature }; case "PositionSwapSetCollateralApproval": return { ...request, setCollateralSignature: signature }; } }), ), okAsync({ quoteId: quote.orderQuoteId, adapterContractSignature: null, positionManagerSignature: null, setCollateralSignature: null, }), ); } ``` ```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(), }); ``` In GraphQL, handle the required approvals from the quote response before proceeding: - `PositionSwapAdapterContractApproval`: Sign the `bySignature` typed data to authorize the swap adapter contract. - `PositionSwapPositionManagerApproval`: Either send the `byTransaction` request or sign the `bySignature` typed data to authorize the position manager. - `PositionSwapSetCollateralApproval`: Sign the `bySignature` typed data to enable the destination asset as collateral. Pass it as `setCollateralSignature` when preparing the order. ### 6. Prepare the Order - **TypeScript**: Use the `prepareOrder` action to prepare the order. - **GraphQL**: Use the `prepareOrder` query with the quote’s `orderQuoteId` and the signed approvals. ```ts title="Prepare Order" import { prepareOrder } from "@aave/client/actions"; import { signApprovals } from "./signApprovals"; // … const result = await supplySwapQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)); if (result.isErr()) { console.error(result.error); return; } // result.value: PreparedOrder ``` ```graphql title="Query" query ($request: PrepareOrderRequest!) { prepareOrder(request: $request) { __typename ... on PreparedOrder { ...PreparedOrder } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="PreparedOrder" fragment PreparedOrder on PreparedOrder { __typename newQuoteId data { ...OrderTypedData } } ``` ```graphql title="OrderTypedData" fragment OrderTypedData on OrderTypedData { __typename types primaryType domain { ...DomainData } message } ``` With the `orderQuoteId` from the last quote response and the signed approvals, construct the request as follows: ```json title="All Approvals by Signature" { "request": { "quoteId": "", "adapterContractSignature": "0x…", "positionManagerSignature": "0x…", "setCollateralSignature": "0x…" } } ``` ```json title="Position Manager Approval by Transaction" { "request": { "quoteId": "", "adapterContractSignature": "0x…" } } ``` ```json title="No Approvals Needed" { "request": { "quoteId": "" } } ``` If the response is a `PreparedOrder`, sign the `data` typed data and submit the order. If it’s an `InsufficientBalanceError`, inform the user about the insufficient balance. ### 7. Execute the Swap Then, execute the swap for the given quote. - **TypeScript**: Sign the order typed data and submit it with the `submitOrder` action. If the response is an `OrderTransactionRequest`, send the transaction with `sendWith`. - **GraphQL**: Use the `submitOrder` mutation with the new quote ID and the signed order from the previous step. ```tsx title="Execute" const execute = async (quote: SwapQuote) => { const result = await swapSupply({ fromQuote: { quoteId: quote.quoteId, }, }); if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); }; ``` ```ts title="Execute Swap" import { okAsync } from "@aave/client"; import { prepareOrder, submitOrder, supplySwapQuote } from "@aave/client/actions"; import { sendWith, signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { signApprovals } from "./signApprovals"; import { wallet } from "./wallet"; const result = await supplySwapQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)) .andThen(({ newQuoteId, data }) => signTypedDataWith(wallet, data).andThen((signature) => submitOrder(client, { bySignature: { quoteId: newQuoteId, signature } }), ), ) .andThen((plan) => { switch (plan.__typename) { case "OrderTransactionRequest": return sendWith(wallet, plan.transaction).map(() => plan.orderReceipt); case "OrderReceipt": return okAsync(plan); } }); // … ``` ```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="Mutation" mutation ($request: SubmitOrderRequest!) { submitOrder(request: $request) { __typename ... on OrderTransactionRequest { ...OrderTransactionRequest } ... on OrderReceipt { ...OrderReceipt } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="OrderTransactionRequest" fragment OrderTransactionRequest on OrderTransactionRequest { __typename transaction { ...TransactionRequest } orderReceipt { ...OrderReceipt } } ``` ```graphql title="OrderReceipt" fragment OrderReceipt on OrderReceipt { __typename orderId } ``` In GraphQL, pass the `newQuoteId` from the `prepareOrder` response and the signed order as variables: ```json title="Variables" { "request": { "bySignature": { "quoteId": "", "signature": "0x…" } } } ``` ### 8. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": return; case "SigningError": console.error(`Failed to sign: ${result.error.message}`); break; case "TimeoutError": console.error(`Timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Failed: ${result.error.message}`); break; case "ValidationError": switch (result.error.cause.__typename) { case "InsufficientBalanceError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "InsufficientLiquidityError": console.error(`Insufficient liquidity: ${result.error.cause.reason}`); break; } break; case "UnexpectedError": console.error(result.error.message); break; } return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` ```ts title="Handle Result" // … if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` In GraphQL, process the response based on the `__typename`: - `OrderReceipt`: The order was placed. Use the `orderId` to track its status. - `OrderTransactionRequest`: Send the `transaction` request, then track the order using `orderReceipt.orderId`. - `InsufficientBalanceError`: Inform the user about the insufficient balance. You placed your first supply swap order. Keep track of its status in the [Monitor Swap Status](../../tools/swaps#monitor-swap-status) section. --- Source: https://aave.com/docs/aave-v4/positions/swaps/borrow.md # Swap Borrow Asset Swapping borrow assets combines repay, swap, and re-borrow into one step. > [!WARNING] > Position swaps now run on the Order API. Update your code: > - `preparePositionSwap` → `prepareOrder` > - `swap` → `submitOrder` > - React: `useSupplySwap` → `useSupplySwapOrder` > - React: `useBorrowSwap` → `useBorrowSwapOrder` > - React: `useRepayWithSupply` → `useRepayWithSupplyOrder` This feature leverages [CoW Protocol](https://cow.fi/) for swap execution. Users sign an intent and solvers execute it through batch auctions with [MEV protection](https://ethereum.org/en/developers/docs/mev/). Most flows need no transaction; if an approval or the `submitOrder` result returns a transaction request, the user sends it and pays gas. > [!NOTE] > See [Fees](../../tools/swaps#fees) for swap costs. Common scenarios: | Scenario | Description | | --------------------- | --------------------------------------------------------------------------------------------------------- | | **Rate Optimization** | User wants to switch debt from a high-interest token to a lower-interest one (e.g., USDC → GHO) | | **Risk Management** | User wants to match their debt currency to their income or collateral to reduce currency exposure | | **Liquidation Avoidance** | User wants to swap volatile debt (e.g., ETH-denominated) to stable debt (e.g., USDC) to avoid liquidation | Swapping borrow assets can be broken down into the following steps: 1. Identify the borrow position to swap from 2. Choose the target reserve to swap onto 3. Choose between market order and limit order 4. Execute the swap operation ## Identify the Borrow Position Identify the borrow position among the user’s [borrow positions](../fetch#fetching-user-borrows) where `reserve.canSwapFrom: true`. ```tsx title="UserBorrowItem" const borrowPosition: UserBorrowItem = { id: "Ym9ycm93", reserve: { id: "SGVsbG8h", canSwapFrom: true, chain: { chainId: 1, name: "Ethereum", }, spoke: { id: "aGVsbG8", // … }, // … }, debt: { amount: { value: BigDecimal(1000.0), exchange: { value: BigDecimal(1000.0), // … }, // … }, // … }, principal: { amount: { value: BigDecimal(950.0), // … }, // … }, interest: { amount: { value: BigDecimal(50.0), // … }, // … }, // … }; ``` > [!NOTE] > `reserve.canSwapFrom` means the reserve isn’t paused and has flash loans > enabled, which the swap needs. ## Identify the Target Borrow Reserve Choose the target [reserve](../../liquidity/reserves#listing-available-reserves) where `canBorrow: true`. The target reserve must be on the **same spoke** as the source borrow position. > [!NOTE] > As in a regular borrow, `canBorrow` means the reserve isn’t frozen, isn’t > paused and is below its borrow cap. ```tsx title="Target Reserve" const targetReserve: Reserve = { id: "V29ybGQh", canBorrow: true, spoke: { id: "aGVsbG8", // … }, asset: { underlying: { address: "0x40d16fc0246ad3160ccc09b8d0d3a2cd28ae6c2f", info: { name: "GHO", symbol: "GHO", decimals: 18, // … }, // … }, // … }, summary: { borrowApy: { normalized: BigDecimal(2.5), // 2.5% APY // … }, // … }, userState: { borrowable: { exchange: { value: BigDecimal(5000.0), name: "USD", symbol: "$", // … }, // … }, }, // … }; ``` Consider the following factors when selecting a target reserve: - **Token**: Check `asset.underlying` for the token of the new debt position - **Capacity**: Review `userState.borrowable` for sufficient borrow capacity - **Rate**: Compare `summary.borrowApy` for favorable borrowing rates ## Market or Limit Order You decide whether to use a market order or a limit order. ### Market Orders Market orders execute at current rates. ```ts title="TypeScript" const request: BorrowSwapQuoteRequest = { market: { debtPosition: borrowPosition.id, buyReserve: targetReserve.id, amount: bigDecimal(1000), user: evmAddress("0x123…"), // selectedSlippage: bigDecimal(1), // Optional: override suggested slippage }, }; ``` ```json title="GraphQL Variables" { "request": { "market": { "debtPosition": "Ym9ycm93", "buyReserve": "V29ybGQh", "amount": "1000", "user": "0x123…" } } } ``` The request takes the following parameters: - `debtPosition`: The current borrow position to swap from - `buyReserve`: The target reserve to swap to - `amount`: The amount of the current debt to swap - `user`: The user’s address - `selectedSlippage`: Optional slippage tolerance to use instead of the suggested slippage ### Limit Orders Limit orders execute when your price condition is met. ```ts title="TypeScript" const request: BorrowSwapQuoteRequest = { limit: { currentPosition: borrowPosition.id, currentAmount: bigDecimal(1000), newReserve: targetReserve.id, newAmount: bigDecimal(1050), // Desired amount of new debt user: evmAddress("0x123…"), kind: BorrowSwapKind.Current, // deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // Optional: custom expiry }, }; ``` ```json title="GraphQL Variables" { "request": { "limit": { "currentPosition": "Ym9ycm93", "currentAmount": "1000", "newReserve": "V29ybGQh", "newAmount": "1050", "user": "0x123…", "kind": "CURRENT" } } } ``` The request takes the following parameters: - `currentPosition`: The current borrow position to swap from - `currentAmount`: The amount of the current debt to repay - `newReserve`: The target reserve to swap to - `newAmount`: The desired amount of new debt to take on - `user`: The user’s address - `kind`: Current (default) or New, determines which amount is honored - `deadline`: Optional deadline as DateTime; if not provided, uses default expiry With both amounts specified, the `kind` parameter determines which amount takes priority: | Kind | User specifies… | What happens with the order | | ------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | **Current** | The exact _current_ debt repaid and a maximum _new_ debt amount | Order fulfilled when the full current debt can be repaid without exceeding the new debt | | **New** | The exact _new_ debt amount and a minimum _current_ debt repaid | Order fulfilled when the new debt repays at least the specified current debt | ## Step-by-Step with AaveKit To execute a borrow swap with AaveKit, follow these steps. ### 1. Get a Quote First, use the `useBorrowSwapQuote` hook (or the imperative `useBorrowSwapQuoteAction` variant) in React, the `borrowSwapQuote` action in TypeScript, or the `borrowSwapQuote` query in GraphQL to get pricing information for the swap. ```tsx title="Loading State" import { type BorrowSwapQuoteRequest, useBorrowSwapQuote } from "@aave/react"; function SwapQuote({ request }: { request: BorrowSwapQuoteRequest }) { const { data, loading, error } = useBorrowSwapQuote(request); if (loading) return Loading…; if (error) { if (error.name === "ValidationError") { switch (error.cause.__typename) { case "InsufficientLiquidityError": return Not enough liquidity for this swap; } } return {error.message}; } // data: SwapQuote return (
New debt amount: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="React Suspense" import { type BorrowSwapQuoteRequest, useBorrowSwapQuote } from "@aave/react"; function SwapQuote({ request }: { request: BorrowSwapQuoteRequest }) { const { data } = useBorrowSwapQuote({ ...request, suspense: true, }); // data: SwapQuote return (
New debt amount: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="Imperative Read" import { type BorrowSwapQuoteRequest, useBorrowSwapQuoteAction, } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useBorrowSwapQuoteAction(); const handler = async (request: BorrowSwapQuoteRequest) => { const result = await getQuote(request); if (result.isOk()) { // result.value: SwapQuote console.log(result.value); } else { console.error(result.error); } }; ```
```ts title="Get Quote" import { borrowSwapQuote } from "@aave/client/actions"; import { client } from "./client"; // … const result = await borrowSwapQuote(client, request); if (result.isErr()) { console.error(result.error); return; } // result.value.quote: SwapQuote ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: BorrowSwapQuoteRequest!, $currency: Currency!) { borrowSwapQuote(request: $request) { __typename ... on PositionSwapByIntentApprovalsRequired { quote { ...SwapQuote } approvals { ...PositionSwapApproval } } ... on InsufficientLiquidityError { reason } } } ``` ```graphql title="PositionSwapApproval" fragment PositionSwapApproval on PositionSwapApproval { __typename ... on PositionSwapAdapterContractApproval { bySignature { ...SwapTypedData } } ... on PositionSwapPositionManagerApproval { byTransaction { ...TransactionRequest } bySignature { ...SwapTypedData } } ... on PositionSwapSetCollateralApproval { bySignature { ...SwapTypedData } } } ```
In React and TypeScript, you can specify a different currency to return fiat amounts in. ```ts title="useBorrowSwapQuote" import { Currency } from "@aave/react"; const { data, error, loading } = useBorrowSwapQuote({ ...request, currency: Currency.Eur, }); ``` ```ts title="useBorrowSwapQuoteAction" import { Currency } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useBorrowSwapQuoteAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; // … const result = await borrowSwapQuote(client, request, { currency: Currency.Eur, }); ``` In React and TypeScript, the quote is returned as a `SwapQuote`. In GraphQL, the response can be either: - `PositionSwapByIntentApprovalsRequired`: The quote was successful, but the user needs to sign approvals before executing the swap. - `InsufficientLiquidityError`: There’s not enough liquidity for the requested swap amount. The `PositionSwapByIntentApprovalsRequired` contains the `SwapQuote` with pricing details and the `PositionSwapApproval` list of required approvals to sign before executing the swap. ### 2. Preview the Impact Then, use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query with the `quoteId` from the previous step in GraphQL to preview the impact of the swap operation on the user’s position. In TypeScript and GraphQL, this step is optional. ```tsx title="Loading State" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { borrowSwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { borrowSwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type SwapQuote, usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (quote: SwapQuote) => { const result = await preview({ action: { borrowSwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Preview Swap" import { preview } from "@aave/client/actions"; import { client } from "./client"; // … const result = await borrowSwapQuote(client, request).andThen( ({ approvals, quote }) => preview(client, { action: { borrowSwap: { fromQuote: { quoteId: quote.quoteId, }, }, }, }), ); if (result.isErr()) { console.error(result.error); return; } // result.value: PreviewUserPosition ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ```
In GraphQL, pass the `quoteId` in the `borrowSwap.fromQuote` field: ```json title="Variables" { "request": { "action": { "borrowSwap": { "fromQuote": { "quoteId": "" } } } }, "currency": "USD" } ``` The `PreviewUserPosition` shows the impact of the swap operation by comparing current and after states, with the table below outlining key fields and how to interpret them. ### 3. Configure Wallet Integration Then, in React, instantiate the hooks for the [wallet library of your choice](../../getting-started/react#integrations): - `useSignTypedData`: used to sign the approvals and the order typed data - `useSendTransaction`: used to send the order transaction when the Order API returns one ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` ### 4. Define the Swap Flow Then, in React, use the `useBorrowSwapOrder` hook to handle the operation. It fetches the quote, collects the approval signatures, and prepares, signs, and submits the order. ```tsx title="Basic Usage" import { useBorrowSwapOrder } from "@aave/react"; const [swapBorrow, { loading, error }] = useBorrowSwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useState } from "react"; import { useBorrowSwapOrder } from "@aave/react"; const [status, setStatus] = useState(""); const [swapBorrow, { loading, error }] = useBorrowSwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": setStatus("Sign the swap adapter approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapPositionManagerApproval": setStatus("Sign the swap position manager approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapSetCollateralApproval": setStatus("Sign the set collateral approval in your wallet"); return signTypedData(plan.bySignature); case "OrderTypedData": setStatus("Sign the swap order in your wallet"); return signTypedData(plan); case "OrderTransactionRequest": setStatus("Send the swap transaction in your wallet"); return sendTransaction(plan.transaction); } }); ``` ```tsx title="Cancel Flow" import { useBorrowSwapOrder } from "@aave/react"; const [swapBorrow, { loading, error }] = useBorrowSwapOrder((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` The operation involves up to 3 signatures: - **Swap adapter contract approval**: A one-time-use contract that encapsulates the swap logic. This signature ensures the contract is used only once for this specific swap operation. - **Swap position manager approval**: Authorizes a dedicated [Position Manager](../managers) to operate on the user’s position. - **Swap order**: The order typed data returned by `prepareOrder`, signed after the approvals. ### 5. Sign Approvals In TypeScript, use `signTypedDataWith` for the [wallet library of your choice](../../getting-started/typescript#sign-typed-data) to sign the swap approvals. ```ts title="signApprovals.ts" import { type PositionSwapByIntentApprovalsRequired, type PrepareOrderRequest, type ResultAsync, type SignTypedDataError, okAsync, } from "@aave/client"; import { signTypedDataWith } from "@aave/client/viem"; import { wallet } from "./wallet"; export function signApprovals({ approvals, quote, }: PositionSwapByIntentApprovalsRequired): ResultAsync< PrepareOrderRequest, SignTypedDataError > { return approvals.reduce( (acc, approval) => acc.andThen((request) => signTypedDataWith(wallet, approval.bySignature).map((signature) => { switch (approval.__typename) { case "PositionSwapAdapterContractApproval": return { ...request, adapterContractSignature: signature }; case "PositionSwapPositionManagerApproval": return { ...request, positionManagerSignature: signature }; case "PositionSwapSetCollateralApproval": return { ...request, setCollateralSignature: signature }; } }), ), okAsync({ quoteId: quote.orderQuoteId, adapterContractSignature: null, positionManagerSignature: null, setCollateralSignature: null, }), ); } ``` ```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(), }); ``` In GraphQL, handle the required approvals from the quote response before proceeding: - `PositionSwapAdapterContractApproval`: Sign the `bySignature` typed data to authorize the swap adapter contract. - `PositionSwapPositionManagerApproval`: Either send the `byTransaction` request or sign the `bySignature` typed data to authorize the position manager. ### 6. Prepare the Order - **TypeScript**: Use the `prepareOrder` action to prepare the order. - **GraphQL**: Use the `prepareOrder` query with the quote’s `orderQuoteId` and the signed approvals. ```ts title="Prepare Order" import { prepareOrder } from "@aave/client/actions"; import { signApprovals } from "./signApprovals"; // … const result = await borrowSwapQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)); if (result.isErr()) { console.error(result.error); return; } // result.value: PreparedOrder ``` ```graphql title="Query" query ($request: PrepareOrderRequest!) { prepareOrder(request: $request) { __typename ... on PreparedOrder { ...PreparedOrder } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="PreparedOrder" fragment PreparedOrder on PreparedOrder { __typename newQuoteId data { ...OrderTypedData } } ``` ```graphql title="OrderTypedData" fragment OrderTypedData on OrderTypedData { __typename types primaryType domain { ...DomainData } message } ``` With the `orderQuoteId` from the last quote response and the signed approvals, construct the request as follows: ```json title="Both Approvals by Signature" { "request": { "quoteId": "", "adapterContractSignature": "0x…", "positionManagerSignature": "0x…" } } ``` ```json title="Position Manager Approval by Transaction" { "request": { "quoteId": "", "adapterContractSignature": "0x…" } } ``` ```json title="No Approvals Needed" { "request": { "quoteId": "" } } ``` If the response is a `PreparedOrder`, sign the `data` typed data and submit the order. If it’s an `InsufficientBalanceError`, inform the user about the insufficient balance. ### 7. Execute the Swap Then, execute the swap for the given quote. - **TypeScript**: Sign the order typed data and submit it with the `submitOrder` action. If the response is an `OrderTransactionRequest`, send the transaction with `sendWith`. - **GraphQL**: Use the `submitOrder` mutation with the new quote ID and the signed order from the previous step. ```tsx title="Execute" const execute = async (quote: SwapQuote) => { const result = await swapBorrow({ fromQuote: { quoteId: quote.quoteId, }, }); if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); }; ``` ```ts title="Execute Swap" import { okAsync } from "@aave/client"; import { prepareOrder, submitOrder, borrowSwapQuote } from "@aave/client/actions"; import { sendWith, signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { signApprovals } from "./signApprovals"; import { wallet } from "./wallet"; const result = await borrowSwapQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)) .andThen(({ newQuoteId, data }) => signTypedDataWith(wallet, data).andThen((signature) => submitOrder(client, { bySignature: { quoteId: newQuoteId, signature } }), ), ) .andThen((plan) => { switch (plan.__typename) { case "OrderTransactionRequest": return sendWith(wallet, plan.transaction).map(() => plan.orderReceipt); case "OrderReceipt": return okAsync(plan); } }); // … ``` ```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="Mutation" mutation ($request: SubmitOrderRequest!) { submitOrder(request: $request) { __typename ... on OrderTransactionRequest { ...OrderTransactionRequest } ... on OrderReceipt { ...OrderReceipt } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="OrderTransactionRequest" fragment OrderTransactionRequest on OrderTransactionRequest { __typename transaction { ...TransactionRequest } orderReceipt { ...OrderReceipt } } ``` ```graphql title="OrderReceipt" fragment OrderReceipt on OrderReceipt { __typename orderId } ``` In GraphQL, pass the `newQuoteId` from the `prepareOrder` response and the signed order as variables: ```json title="Variables" { "request": { "bySignature": { "quoteId": "", "signature": "0x…" } } } ``` ### 8. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": return; case "SigningError": console.error(`Failed to sign: ${result.error.message}`); break; case "TimeoutError": console.error(`Timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Failed: ${result.error.message}`); break; case "ValidationError": switch (result.error.cause.__typename) { case "InsufficientBalanceError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "InsufficientLiquidityError": console.error(`Insufficient liquidity: ${result.error.cause.reason}`); break; } break; case "UnexpectedError": console.error(result.error.message); break; } return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` ```ts title="Handle Result" // … if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` In GraphQL, process the response based on the `__typename`: - `OrderReceipt`: The order was placed. Use the `orderId` to track its status. - `OrderTransactionRequest`: Send the `transaction` request, then track the order using `orderReceipt.orderId`. - `InsufficientBalanceError`: Inform the user about the insufficient balance. You placed your first borrow swap order. Keep track of its status in the [Monitor Swap Status](../../tools/swaps#monitor-swap-status) section. --- Source: https://aave.com/docs/aave-v4/positions/swaps/repay.md # Repay with Supply Repay with supply combines withdraw, swap, and repay into one step. > [!WARNING] > Position swaps now run on the Order API. Update your code: > - `preparePositionSwap` → `prepareOrder` > - `swap` → `submitOrder` > - React: `useSupplySwap` → `useSupplySwapOrder` > - React: `useBorrowSwap` → `useBorrowSwapOrder` > - React: `useRepayWithSupply` → `useRepayWithSupplyOrder` This feature leverages [CoW Protocol](https://cow.fi/) for swap execution. Users sign an intent and solvers execute it through batch auctions with [MEV protection](https://ethereum.org/en/developers/docs/mev/). Most flows need no transaction; if an approval or the `submitOrder` result returns a transaction request, the user sends it and pays gas. > [!NOTE] > See [Fees](../../tools/swaps#fees) for swap costs. Common scenarios: | Scenario | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------ | | **Avoid Liquidation** | User wants to improve [Health Factor](../../positions#health-factor) by repaying debt using their supply | | **Rebalance Positions** | User wants to consolidate stablecoin exposure by using idle supply to pay off debt in a different stablecoin | | **Reduce Debt Exposure** | User wants to reduce debt load by converting non-collateral supply into debt repayment | > [!WARNING] > Repaying with supply lowers your supplied balance. If that asset is > collateral, check that the position stays healthy. Repay with supply can be broken down into the following steps: 1. Identify the supply position to use for repayment 2. Identify the borrow position to repay 3. Choose between market order and limit order 4. Execute the swap operation ## Identify the Supply Position to Repay With Identify the supply position among the user’s [supply positions](../fetch#fetching-user-supplies) where `reserve.canSwapFrom: true`. ```tsx title="UserSupplyItem" const supplyPosition: UserSupplyItem = { id: "c3VwcGx5", reserve: { id: "SGVsbG8h", canSwapFrom: true, chain: { chainId: 1, name: "Ethereum", }, spoke: { id: "aGVsbG8", // … }, // … }, isCollateral: true, balance: { amount: { value: BigDecimal(5000.0), exchange: { value: BigDecimal(5000.0), // … }, // … }, // … }, principal: { amount: { value: BigDecimal(4800.0), // … }, // … }, interest: { amount: { value: BigDecimal(200.0), // … }, // … }, // … }; ``` > [!NOTE] > `reserve.canSwapFrom` means the reserve isn’t paused and has flash loans > enabled, which the swap needs. ## Identify the Borrow Position to Repay Identify the borrow position among the user’s [borrow positions](../fetch#fetching-user-borrows) to repay. ```tsx title="UserBorrowItem" const borrowPosition: UserBorrowItem = { id: "Ym9ycm93", reserve: { id: "V29ybGQh", spoke: { id: "aGVsbG8", // … }, // … }, debt: { amount: { value: BigDecimal(1000.0), exchange: { value: BigDecimal(1000.0), // … }, // … }, // … }, principal: { amount: { value: BigDecimal(950.0), // … }, // … }, interest: { amount: { value: BigDecimal(50.0), // … }, // … }, // … }; ``` > [!NOTE] > The supply and borrow positions must be on the **same spoke**. The supply > position’s asset is swapped to repay the debt. ## Market or Limit Order You decide whether to use a market order or a limit order. ### Market Orders Market orders execute at current rates. ```ts title="TypeScript" const request: RepayWithSupplyQuoteRequest = { market: { debtPosition: borrowPosition.id, repayWithReserve: supplyPosition.reserve.id, amount: bigDecimal(1000), user: evmAddress("0x123…"), // kind: RepayWithSupplyKind.Repay, // Optional: specify repay or supply priority // selectedSlippage: bigDecimal(1), // Optional: override suggested slippage }, }; ``` ```jsonc title="GraphQL Variables" { "request": { "market": { "debtPosition": "Ym9ycm93", "repayWithReserve": "SGVsbG8h", "amount": "1000", "user": "0x123…", "kind": "REPAY" // Optional: "REPAY" or "SUPPLY" } } } ``` The request takes the following parameters: - `debtPosition`: The borrow position with debt to repay - `repayWithReserve`: The reserve of the supply position to use for repayment - `amount`: The swap amount, interpreted based on `kind` - `user`: The user’s address - `kind`: Repay (default) or Supply, determines how `amount` is interpreted - `selectedSlippage`: Optional slippage tolerance to use instead of the suggested slippage Since only one amount is provided, the `kind` parameter determines how it’s interpreted: | Kind | User inputs… | System calculates… | | --------------- | ---------------------------- | ----------------------------------- | | **Repay (default)** | The debt amount to _repay_ | The supply amount needed | | **Supply** | The supply amount to _use_ | The debt amount that will be repaid | ### Limit Orders Limit orders execute when your price condition is met. ```ts title="TypeScript" const request: RepayWithSupplyQuoteRequest = { limit: { repayPosition: borrowPosition.id, repayAmount: bigDecimal(1000), supplyPosition: supplyPosition.id, supplyAmount: bigDecimal(1050), // Amount of supply to use user: evmAddress("0x123…"), kind: RepayWithSupplyKind.Repay, // deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // Optional: custom expiry }, }; ``` ```json title="GraphQL Variables" { "request": { "limit": { "repayPosition": "Ym9ycm93", "repayAmount": "1000", "supplyPosition": "c3VwcGx5", "supplyAmount": "1050", "user": "0x123…", "kind": "REPAY" } } } ``` The request takes the following parameters: - `repayPosition`: The borrow position with debt to repay - `repayAmount`: The amount of debt to repay - `supplyPosition`: The supply position to use for repayment - `supplyAmount`: The amount of supply to use - `user`: The user’s address - `kind`: Repay (default) or Supply, determines which amount is honored - `deadline`: Optional deadline as DateTime; if not provided, uses default expiry With both amounts specified, the `kind` parameter determines which amount takes priority: | Kind | User specifies… | What happens with the order | | ------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------- | | **Repay** | The exact _repay_ amount and a maximum _supply_ usage | Order fulfilled when supply price allows full debt repayment within supply limit | | **Supply** | The exact _supply_ to use and a minimum _repay_ amount | Order fulfilled when enough debt can be repaid using the specified supply amount | ## Step-by-Step with AaveKit To execute a repay with supply swap with AaveKit, follow these steps. ### 1. Get a Quote First, use the `useRepayWithSupplyQuote` hook (or the imperative `useRepayWithSupplyQuoteAction` variant) in React, the `repayWithSupplyQuote` action in TypeScript, or the `repayWithSupplyQuote` query in GraphQL to get pricing information for the swap. ```tsx title="Loading State" import { type RepayWithSupplyQuoteRequest, useRepayWithSupplyQuote, } from "@aave/react"; function SwapQuote({ request }: { request: RepayWithSupplyQuoteRequest }) { const { data, loading, error } = useRepayWithSupplyQuote(request); if (loading) return Loading…; if (error) { if (error.name === "ValidationError") { switch (error.cause.__typename) { case "InsufficientLiquidityError": return Not enough liquidity for this swap; } } return {error.message}; } // data: SwapQuote return (
Repay amount: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="React Suspense" import { type RepayWithSupplyQuoteRequest, useRepayWithSupplyQuote, } from "@aave/react"; function SwapQuote({ request }: { request: RepayWithSupplyQuoteRequest }) { const { data } = useRepayWithSupplyQuote({ ...request, suspense: true, }); // data: SwapQuote return (
Repay amount: {data.finalBuy.amount.value.toDisplayString()} Partner fee: {data.costs.partnerFee.amount.value.toDisplayString()} Slippage: {data.suggestedSlippage.normalized}%
); } ``` ```tsx title="Imperative Read" import { type RepayWithSupplyQuoteRequest, useRepayWithSupplyQuoteAction, } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useRepayWithSupplyQuoteAction(); const handler = async (request: RepayWithSupplyQuoteRequest) => { const result = await getQuote(request); if (result.isOk()) { // result.value: SwapQuote console.log(result.value); } else { console.error(result.error); } }; ```
```ts title="Get Quote" import { repayWithSupplyQuote } from "@aave/client/actions"; import { client } from "./client"; // … const result = await repayWithSupplyQuote(client, request); if (result.isErr()) { console.error(result.error); return; } // result.value.quote: SwapQuote ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: RepayWithSupplyQuoteRequest!, $currency: Currency!) { repayWithSupplyQuote(request: $request) { __typename ... on PositionSwapByIntentApprovalsRequired { quote { ...SwapQuote } approvals { ...PositionSwapApproval } } ... on InsufficientLiquidityError { reason } } } ``` ```graphql title="PositionSwapApproval" fragment PositionSwapApproval on PositionSwapApproval { __typename ... on PositionSwapAdapterContractApproval { bySignature { ...SwapTypedData } } ... on PositionSwapPositionManagerApproval { byTransaction { ...TransactionRequest } bySignature { ...SwapTypedData } } ... on PositionSwapSetCollateralApproval { bySignature { ...SwapTypedData } } } ```
In React and TypeScript, you can specify a different currency to return fiat amounts in. ```ts title="useRepayWithSupplyQuote" import { Currency } from "@aave/react"; const { data, error, loading } = useRepayWithSupplyQuote({ ...request, currency: Currency.Eur, }); ``` ```ts title="useRepayWithSupplyQuoteAction" import { Currency } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useRepayWithSupplyQuoteAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; // … const result = await repayWithSupplyQuote(client, request, { currency: Currency.Eur, }); ``` In React and TypeScript, the quote is returned as a `SwapQuote`. In GraphQL, the response can be either: - `PositionSwapByIntentApprovalsRequired`: The quote was successful, but the user needs to sign approvals before executing the swap. - `InsufficientLiquidityError`: There’s not enough liquidity for the requested swap amount. The `PositionSwapByIntentApprovalsRequired` contains the `SwapQuote` with pricing details and the `PositionSwapApproval` list of required approvals to sign before executing the swap. ### 2. Preview the Impact Then, use the `usePreview` hook (or the imperative `usePreviewAction` variant) in React, the `preview` action in TypeScript, or the `preview` query with the `quoteId` from the previous step in GraphQL to preview the impact of the swap operation on the user’s position. In TypeScript and GraphQL, this step is optional. ```tsx title="Loading State" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { repayWithSupply: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type SwapQuote, usePreview } from "@aave/react"; function SwapPreview({ quote }: { quote: SwapQuote }) { const { data, error, loading } = usePreview({ action: { repayWithSupply: { fromQuote: { quoteId: quote.quoteId, }, }, }, suspense: true, }); // data: PreviewUserPosition return (

Health Factor:

From: {data.healthFactor.current?.toFixed(2) ?? "N/A"} To: {data.healthFactor.after?.toFixed(2) ?? "N/A"}

User Risk Premium:

From: {data.riskPremium.current.normalized.toFixed(2)}% To: {data.riskPremium.after.normalized.toFixed(2)}%

Net APY:

From: {data.netApy.current.normalized.toFixed(2)}% To: {data.netApy.after.normalized.toFixed(2)}%

Net Collateral:

From: {data.netCollateral.current.value.toDisplayString(2)} To: {data.netCollateral.after.value.toDisplayString(2)}

Max Borrowing Power:

From: {data.maxBorrowingPower.current.value.toDisplayString(2)} To: {data.maxBorrowingPower.after.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type SwapQuote, usePreviewAction } from "@aave/react"; // … const [preview, { called, data, error, loading }] = usePreviewAction(); const handler = async (quote: SwapQuote) => { const result = await preview({ action: { repayWithSupply: { fromQuote: { quoteId: quote.quoteId, }, }, }, }); if (result.isOk()) { console.log(result.value); // PreviewUserPosition } else { console.error(result.error); } }; ```
```ts title="Preview Swap" import { preview } from "@aave/client/actions"; import { client } from "./client"; // … const result = await repayWithSupplyQuote(client, request).andThen( ({ approvals, quote }) => preview(client, { action: { repayWithSupply: { fromQuote: { quoteId: quote.quoteId, }, }, }, }), ); if (result.isErr()) { console.error(result.error); return; } // result.value: PreviewUserPosition ``` ```graphql title="Query" query ($request: PreviewRequest!, $currency: Currency = USD) { preview(request: $request) { __typename id healthFactor { ...HealthFactorResult } netApy { ...PercentNumberVariation } riskPremium { ...PercentNumberVariation } netCollateral(currency: $currency) { ...ExchangeAmountVariation } netBalance(currency: $currency) { ...ExchangeAmountVariation } projectedEarnings { ...ExchangeAmountVariation } maxBorrowingPower { ...ExchangeAmountVariation } remainingBorrowingPower { ...ExchangeAmountVariation } otherConditions { ...UserPositionConditionVariation } } } ```
In GraphQL, pass the `quoteId` in the `repayWithSupply.fromQuote` field: ```json title="Variables" { "request": { "action": { "repayWithSupply": { "fromQuote": { "quoteId": "" } } } }, "currency": "USD" } ``` The `PreviewUserPosition` shows the impact of the swap operation by comparing current and after states, with the table below outlining key fields and how to interpret them. ### 3. Configure Wallet Integration Then, in React, instantiate the hooks for the [wallet library of your choice](../../getting-started/react#integrations): - `useSignTypedData`: used to sign the approvals and the order typed data - `useSendTransaction`: used to send the order transaction when the Order API returns one ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` ### 4. Define the Swap Flow Then, in React, use the `useRepayWithSupplyOrder` hook to handle the operation. It fetches the quote, collects the approval signatures, and prepares, signs, and submits the order. ```tsx title="Basic Usage" import { useRepayWithSupplyOrder } from "@aave/react"; const [repayWithSupply, { loading, error }] = useRepayWithSupplyOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` ```tsx title="Update Component State" import { useState } from "react"; import { useRepayWithSupplyOrder } from "@aave/react"; const [status, setStatus] = useState(""); const [repayWithSupply, { loading, error }] = useRepayWithSupplyOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": setStatus("Sign the swap adapter approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapPositionManagerApproval": setStatus("Sign the swap position manager approval in your wallet"); return signTypedData(plan.bySignature); case "PositionSwapSetCollateralApproval": setStatus("Sign the set collateral approval in your wallet"); return signTypedData(plan.bySignature); case "OrderTypedData": setStatus("Sign the swap order in your wallet"); return signTypedData(plan); case "OrderTransactionRequest": setStatus("Send the swap transaction in your wallet"); return sendTransaction(plan.transaction); } }); ``` ```tsx title="Cancel Flow" import { useRepayWithSupplyOrder } from "@aave/react"; const [repayWithSupply, { loading, error }] = useRepayWithSupplyOrder((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); ``` The operation involves up to 3 signatures: - **Swap adapter contract approval**: A one-time-use contract that encapsulates the swap logic. This signature ensures the contract is used only once for this specific swap operation. - **Swap position manager approval**: Authorizes a dedicated [Position Manager](../managers) to operate on the user’s position. - **Swap order**: The order typed data returned by `prepareOrder`, signed after the approvals. ### 5. Sign Approvals In TypeScript, use `signTypedDataWith` for the [wallet library of your choice](../../getting-started/typescript#sign-typed-data) to sign the swap approvals. ```ts title="signApprovals.ts" import { type PositionSwapByIntentApprovalsRequired, type PrepareOrderRequest, type ResultAsync, type SignTypedDataError, okAsync, } from "@aave/client"; import { signTypedDataWith } from "@aave/client/viem"; import { wallet } from "./wallet"; export function signApprovals({ approvals, quote, }: PositionSwapByIntentApprovalsRequired): ResultAsync< PrepareOrderRequest, SignTypedDataError > { return approvals.reduce( (acc, approval) => acc.andThen((request) => signTypedDataWith(wallet, approval.bySignature).map((signature) => { switch (approval.__typename) { case "PositionSwapAdapterContractApproval": return { ...request, adapterContractSignature: signature }; case "PositionSwapPositionManagerApproval": return { ...request, positionManagerSignature: signature }; case "PositionSwapSetCollateralApproval": return { ...request, setCollateralSignature: signature }; } }), ), okAsync({ quoteId: quote.orderQuoteId, adapterContractSignature: null, positionManagerSignature: null, setCollateralSignature: null, }), ); } ``` ```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(), }); ``` In GraphQL, handle the required approvals from the quote response before proceeding: - `PositionSwapAdapterContractApproval`: Sign the `bySignature` typed data to authorize the swap adapter contract. - `PositionSwapPositionManagerApproval`: Either send the `byTransaction` request or sign the `bySignature` typed data to authorize the position manager. ### 6. Prepare the Order - **TypeScript**: Use the `prepareOrder` action to prepare the order. - **GraphQL**: Use the `prepareOrder` query with the quote’s `orderQuoteId` and the signed approvals. ```ts title="Prepare Order" import { prepareOrder } from "@aave/client/actions"; import { signApprovals } from "./signApprovals"; // … const result = await repayWithSupplyQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)); if (result.isErr()) { console.error(result.error); return; } // result.value: PreparedOrder ``` ```graphql title="Query" query ($request: PrepareOrderRequest!) { prepareOrder(request: $request) { __typename ... on PreparedOrder { ...PreparedOrder } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="PreparedOrder" fragment PreparedOrder on PreparedOrder { __typename newQuoteId data { ...OrderTypedData } } ``` ```graphql title="OrderTypedData" fragment OrderTypedData on OrderTypedData { __typename types primaryType domain { ...DomainData } message } ``` With the `orderQuoteId` from the last quote response and the signed approvals, construct the request as follows: ```json title="Both Approvals by Signature" { "request": { "quoteId": "", "adapterContractSignature": "0x…", "positionManagerSignature": "0x…" } } ``` ```json title="Position Manager Approval by Transaction" { "request": { "quoteId": "", "adapterContractSignature": "0x…" } } ``` ```json title="No Approvals Needed" { "request": { "quoteId": "" } } ``` If the response is a `PreparedOrder`, sign the `data` typed data and submit the order. If it’s an `InsufficientBalanceError`, inform the user about the insufficient balance. ### 7. Execute the Swap Then, execute the swap for the given quote. - **TypeScript**: Sign the order typed data and submit it with the `submitOrder` action. If the response is an `OrderTransactionRequest`, send the transaction with `sendWith`. - **GraphQL**: Use the `submitOrder` mutation with the new quote ID and the signed order from the previous step. ```tsx title="Execute" const execute = async (quote: SwapQuote) => { const result = await repayWithSupply({ fromQuote: { quoteId: quote.quoteId, }, }); if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); }; ``` ```ts title="Execute Swap" import { okAsync } from "@aave/client"; import { prepareOrder, submitOrder, repayWithSupplyQuote } from "@aave/client/actions"; import { sendWith, signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { signApprovals } from "./signApprovals"; import { wallet } from "./wallet"; const result = await repayWithSupplyQuote(client, request) .andThen(signApprovals) .andThen((request) => prepareOrder(client, request)) .andThen(({ newQuoteId, data }) => signTypedDataWith(wallet, data).andThen((signature) => submitOrder(client, { bySignature: { quoteId: newQuoteId, signature } }), ), ) .andThen((plan) => { switch (plan.__typename) { case "OrderTransactionRequest": return sendWith(wallet, plan.transaction).map(() => plan.orderReceipt); case "OrderReceipt": return okAsync(plan); } }); // … ``` ```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="Mutation" mutation ($request: SubmitOrderRequest!) { submitOrder(request: $request) { __typename ... on OrderTransactionRequest { ...OrderTransactionRequest } ... on OrderReceipt { ...OrderReceipt } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="OrderTransactionRequest" fragment OrderTransactionRequest on OrderTransactionRequest { __typename transaction { ...TransactionRequest } orderReceipt { ...OrderReceipt } } ``` ```graphql title="OrderReceipt" fragment OrderReceipt on OrderReceipt { __typename orderId } ``` In GraphQL, pass the `newQuoteId` from the `prepareOrder` response and the signed order as variables: ```json title="Variables" { "request": { "bySignature": { "quoteId": "", "signature": "0x…" } } } ``` ### 8. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": return; case "SigningError": console.error(`Failed to sign: ${result.error.message}`); break; case "TimeoutError": console.error(`Timed out: ${result.error.message}`); break; case "TransactionError": console.error(`Failed: ${result.error.message}`); break; case "ValidationError": switch (result.error.cause.__typename) { case "InsufficientBalanceError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "InsufficientLiquidityError": console.error(`Insufficient liquidity: ${result.error.cause.reason}`); break; } break; case "UnexpectedError": console.error(result.error.message); break; } return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` ```ts title="Handle Result" // … if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` In GraphQL, process the response based on the `__typename`: - `OrderReceipt`: The order was placed. Use the `orderId` to track its status. - `OrderTransactionRequest`: Send the `transaction` request, then track the order using `orderReceipt.orderId`. - `InsufficientBalanceError`: Inform the user about the insufficient balance. You placed your first repay with supply order. Keep track of its status in the [Monitor Swap Status](../../tools/swaps#monitor-swap-status) section. --- Source: https://aave.com/docs/aave-v4/positions/managers.md # Aave V4 Position Managers Position managers are smart contracts users can authorize to manage their positions, enabling automated actions like supplying, withdrawing, borrowing, and repaying, while maintaining full user control. They unlock use cases such as: - **Automated strategies**: leverage management, yield optimization, and rebalancing - **Vault protocols**: external protocols that aggregate and manage user positions - **Risk management**: automated liquidation protection and position adjustments - **Account abstraction**: smart contract wallets managing DeFi positions > [!NOTE] > Position managers can only act for users who authorized them, and users can > revoke access at any time. ## How They Work 1. **Registration**: Position managers are registered with a spoke through governance before users can enable them. 2. **Authorization**: Users explicitly enable selected managers to act on their behalf for a given position. 3. **Delegated Operations**: Authorized managers can execute position operations on behalf of users. 4. **Revocation**: Users can disable a manager at any time to revoke its access. Each position manager is identified by its contract address and may include optional off-chain metadata, such as a name, for easier discovery. ## Built-in Position Managers Since registration requires governance approval, custom contracts cannot register themselves as position managers. Instead, Aave V4 ships with built-in position managers that collectively expose every operation a position manager can perform. They come in two groups: gateways and delegation managers. ### Gateways - `NativeTokenGateway`: enables native token support (e.g., supply and borrow ETH) - `SignatureGateway`: enables [ERC-20 Permits](https://eips.ethereum.org/EIPS/eip-2612); see [Supply](./supply#step-by-step-with-aavekit) and [Repay](./repay#step-by-step-with-aavekit) for examples Both contracts are automatically registered on every new spoke, and their addresses are available for convenience in the [spoke’s](../liquidity/spokes) `chain` field: ```ts title="Spoke Highlight" interface Spoke { __typename: "Spoke"; name: string; address: EvmAddress; chain: { __typename: "Chain"; // … nativeGateway: EvmAddress; signatureGateway: EvmAddress; }; } ``` ```graphql title="Spoke Highlight" fragment Spoke on Spoke { __typename name address chain { # … nativeGateway signatureGateway } } ``` AaveKit automatically handles user authorization of these built-in position managers as part of each operation. For example, when a user supplies native tokens (e.g., ETH): 1. AaveKit returns a `PreContractActionRequired` plan whose `transaction` authorizes the `NativeTokenGateway` to act on the user’s behalf on the spoke. 2. The subsequent transaction sends ETH to the gateway. 3. The gateway wraps the ETH into WETH and supplies it to the WETH reserve in the spoke on the user’s behalf. This process happens automatically for other operations like borrowing, withdrawing, or repaying with native tokens, as well as when using ERC-20 permits to supply or repay. The SDK manages these flows transparently. Users never need to interact with position managers directly. ### Delegation Managers Three additional managers let external contracts (vaults, automation bots, or your own flash loan contract) execute position operations on behalf of users without registering as position managers themselves: - `GiverPositionManager`: supplies and repays on behalf of a user (`supplyOnBehalfOf`, `repayOnBehalfOf`). The caller provides the funds, so no per-reserve allowance is required. - `TakerPositionManager`: withdraws and borrows on behalf of a user (`withdrawOnBehalfOf`, `borrowOnBehalfOf`), sending the funds to the caller. Gated by per-reserve allowances the user grants with `approveWithdraw`/`approveBorrow`, either onchain or via EIP-712 signatures. - `ConfigPositionManager`: updates position configuration on behalf of a user (e.g., `setUsingAsCollateralOnBehalfOf`). Gated by permissions the user delegates per action type. To integrate a custom contract, route position operations through these managers instead of calling the spoke directly: 1. The user [authorizes](#step-by-step-with-aavekit) the built-in manager on the spoke. 2. For taker and config operations, the user grants your contract an allowance or permission on the manager. 3. Your contract calls the manager’s `…OnBehalfOf` methods to modify the user’s position. For example, a flash loan contract opening a leveraged position for a user: ```solidity title="Leverage via Built-in Managers" import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; import { IGiverPositionManager } from "aave-v4/src/position-manager/interfaces/IGiverPositionManager.sol"; import { ITakerPositionManager } from "aave-v4/src/position-manager/interfaces/ITakerPositionManager.sol"; // IGiverPositionManager giver = … // ITakerPositionManager taker = … // address collateralAsset = … // Prerequisites (sent by the user, once per spoke): // - spoke.setUserPositionManager(address(giver), true) // - spoke.setUserPositionManager(address(taker), true) // - taker.approveBorrow(spoke, debtReserveId, address(this), borrowAmount) function openLeveragedPosition( address spoke, uint256 collateralReserveId, uint256 collateralAmount, uint256 debtReserveId, uint256 borrowAmount, address user ) external { // Supply collateral to the user's position, funded by this contract IERC20(collateralAsset).approve(address(giver), collateralAmount); giver.supplyOnBehalfOf(spoke, collateralReserveId, collateralAmount, user); // Borrow against it, consuming the allowance granted by the user taker.borrowOnBehalfOf(spoke, debtReserveId, borrowAmount, user); } ``` The production deployments on Ethereum are: | Contract | Address | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | `GiverPositionManager` | [`0x17A54b8d6D9C68e7fa1C7112AC998EA1BA51d11e`](https://etherscan.io/address/0x17A54b8d6D9C68e7fa1C7112AC998EA1BA51d11e) | | `TakerPositionManager` | [`0x6c044c0D3801499bCAbfAd458B70880bc518e9F7`](https://etherscan.io/address/0x6c044c0D3801499bCAbfAd458B70880bc518e9F7) | | `ConfigPositionManager` | [`0x51305839CE822a7b4b12AA7D86eA7005052d575c`](https://etherscan.io/address/0x51305839CE822a7b4b12AA7D86eA7005052d575c) | The contracts live in [`aave-v4/src/position-manager`](https://github.com/aave/aave-v4/tree/v0.5.11/src/position-manager), and deployed addresses are listed under `AaveV4EthereumPositionManagers` in the [Aave Address Book](https://github.com/aave-dao/aave-address-book/blob/main/src/AaveV4Ethereum.sol). ## Available Position Managers Get all available position managers for a specific spoke. Use the paginated `useSpokePositionManagers` hook in React, the paginated `spokePositionManagers` action in TypeScript, or the `spokePositionManagers` query in GraphQL to fetch position managers for a spoke. ```tsx title="Loading State" import { type SpokePositionManagersRequest, useSpokePositionManagers, } from "@aave/react"; function SpokePositionManagersList({ request, }: { request: SpokePositionManagersRequest; }) { const { data, loading, error } = useSpokePositionManagers(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PaginatedSpokePositionManagerResult return (

Position Managers

{data.items.map((manager) => (

{manager.name}

Address: {manager.address} Status: {manager.active ? "Active" : "Inactive"}
))}
); } ``` ```tsx title="React Suspense" import { type SpokePositionManagersRequest, useSpokePositionManagers, } from "@aave/react"; function SpokePositionManagersList({ request, }: { request: SpokePositionManagersRequest; }) { const { data } = useSpokePositionManagers({ ...request, suspense: true, }); // data: PaginatedSpokePositionManagerResult return (

Position Managers

{data.items.map((manager) => (

{manager.name}

Address: {manager.address} Status: {manager.active ? "Active" : "Inactive"}
))}
); } ```
```ts title="Basic Usage" import { spokePositionManagers } from "@aave/client/actions"; import { client } from "./client"; // const spoke: Spoke = … const result = await spokePositionManagers(client, { spoke: spoke.id, }); if (result.isOk()) { // result.value: PaginatedSpokePositionManagerResult result.value.items.forEach((manager) => { console.log(`${manager.name}: ${manager.active ? "Active" : "Inactive"}`); }); } else { console.error(result.error); } ``` ```ts title="Include Inactive" const result = await spokePositionManagers(client, { spoke: spoke.id, includeInactive: true, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Basic Query" query ($request: SpokePositionManagersRequest!) { spokePositionManagers(request: $request) { items { name address active } pageInfo { next prev } } } ```
The following examples show `useSpokePositionManagers` usage in React and `SpokePositionManagersRequest` variables in GraphQL. ```tsx title="Basic Usage" const { data, loading, error } = useSpokePositionManagers({ spoke: spoke.id, }); ``` ```tsx title="Include Inactive" const { data, loading, error } = useSpokePositionManagers({ spoke: spoke.id, includeInactive: true, }); ``` ```json title="Basic Usage" { "request": { "spoke": "SGVsbG8h", "pageSize": "TEN" } } ``` ```json title="Include Inactive" { "request": { "spoke": "SGVsbG8h", "pageSize": "TEN", "includeInactive": true } } ``` ## User’s Position Managers with AaveKit Get all position managers that a specific user has enabled within a spoke. Use the paginated `useSpokeUserPositionManagers` hook in React, the paginated `spokeUserPositionManagers` action in TypeScript, or the `spokeUserPositionManagers` query in GraphQL to fetch position managers enabled by a user. ```tsx title="Loading State" import { type EvmAddress, type SpokeId, useSpokeUserPositionManagers, } from "@aave/react"; function UserPositionManagersList({ spoke, user, }: { spoke: SpokeId; user: EvmAddress; }) { const { data, loading, error } = useSpokeUserPositionManagers({ spoke, user, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PaginatedSpokeUserPositionManagerResult return (

User Position Managers

{data.items.map((manager) => (

{manager.name}

Address: {manager.address} Approved: {manager.approvedOn.toLocaleDateString()} Status: {manager.active ? "Active" : "Inactive"}
))}
); } ``` ```tsx title="React Suspense" import { type EvmAddress, type SpokeId, useSpokeUserPositionManagers, } from "@aave/react"; function UserPositionManagersList({ spoke, user, }: { spoke: SpokeId; user: EvmAddress; }) { const { data } = useSpokeUserPositionManagers({ spoke, user, suspense: true, }); // data: PaginatedSpokeUserPositionManagerResult return (

User Position Managers

{data.items.map((manager) => (

{manager.name}

Address: {manager.address} Approved: {manager.approvedOn.toLocaleDateString()} Status: {manager.active ? "Active" : "Inactive"}
))}
); } ```
```ts title="Basic Usage" import { spokeUserPositionManagers } from "@aave/client/actions"; import { client } from "./client"; // const spoke: Spoke = … // const user: EvmAddress = … const result = await spokeUserPositionManagers(client, { spoke: spoke.id, user, }); if (result.isOk()) { // result.value: PaginatedSpokeUserPositionManagerResult result.value.items.forEach((manager) => { console.log( `${manager.name}: approved on ${manager.approvedOn} (${ manager.active ? "Active" : "Inactive" })`, ); }); } else { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Basic Query" query ($request: SpokeUserPositionManagersRequest!) { spokeUserPositionManagers(request: $request) { items { name address approvedOn active } pageInfo { next prev } } } ```
In GraphQL, below is an example of a `SpokeUserPositionManagersRequest` object. ```json title="SpokeUserPositionManagersRequest" { "request": { "spoke": "SGVsbG8h", "user": "0x456…", "pageSize": "TEN" } } ``` ## User’s Position Managers with Solidity User position managers are not enumerable onchain. However, you can check if a user has approved a specific position manager: ```solidity title="Check Position Manager Approval" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function isPositionManagerApproved( address spokeAddress, address userAddress, address managerAddress ) external view returns (bool) { ISpoke spoke = ISpoke(spokeAddress); return spoke.isPositionManager(userAddress, managerAddress); } ``` This method checks both that the position manager is active and that the user has approved it. ## Authorize a Position Manager ### Step-by-Step with AaveKit Authorize or revoke a position manager to act on behalf of a user within a spoke. To enable or disable a position manager with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the `useSendTransaction` hook for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); ``` #### 2. Define the Position Manager Flow Then, in React, use the `useSetSpokeUserPositionManager` hook to prepare the transaction request. ```tsx title="Basic Usage" import { useSetSpokeUserPositionManager } from "@aave/react"; const [setPositionManager, { loading, error }] = useSetSpokeUserPositionManager( (transaction) => sendTransaction(transaction), ); ``` ```tsx title="Update Component State" import { useSetSpokeUserPositionManager } from "@aave/react"; const [status, setStatus] = useState(""); const [setPositionManager, { loading, error }] = useSetSpokeUserPositionManager( (transaction) => { setStatus("Please sign the transaction in your wallet"); return sendTransaction(transaction).andTee(() => setStatus("Enabling position manager…"), ); }, ); ``` ```tsx title="Cancel Flow" import { useSetSpokeUserPositionManager } from "@aave/react"; const [setPositionManager, { loading, error }] = useSetSpokeUserPositionManager( (transaction, { cancel }) => { if (window.confirm("Enable this position manager?") === false) { return cancel("User cancelled the operation"); } return sendTransaction(transaction); }, ); ``` #### 3. Enable or Disable the Position Manager Then, enable or disable the position manager. - **TypeScript**: Use the `setSpokeUserPositionManager` action to prepare the transaction request. - **GraphQL**: Use the `setSpokeUserPositionManager` query to prepare the transaction request. ```tsx title="Enable Manager" import { type EvmAddress, type SpokeId } from "@aave/react"; const execute = async ( spoke: SpokeId, manager: EvmAddress, user: EvmAddress, ) => { const result = await setPositionManager({ spoke, manager, approve: true, // true to enable, false to disable user, }); }; // … ``` ```ts title="Enable Manager" import { evmAddress } from "@aave/client"; import { setSpokeUserPositionManager } from "@aave/client/actions"; import { client } from "./client"; // const spoke: Spoke = … const result = await setSpokeUserPositionManager(client, { spoke: spoke.id, manager: evmAddress("0x456…"), // Position manager address approve: true, // true to enable, false to disable user: evmAddress("0x789…"), // User granting permission }); // … ``` ```graphql title="Query" query ($request: SetSpokeUserPositionManagerRequest!) { setSpokeUserPositionManager(request: $request) { to from data value chainId operations } } ``` In GraphQL, below is an example of a `SetSpokeUserPositionManagerRequest` object. ```json title="Basic Usage" { "request": { "spoke": "SGVsbG8h", "manager": "0x456…", "approve": true, "user": "0x789…" } } ``` #### 4. Send the Transaction In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transaction, and await indexing with `client.waitForTransaction`. ```ts title="Viem" import { setSpokeUserPositionManager } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await setSpokeUserPositionManager(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```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(), }); ``` In GraphQL, the API returns a `TransactionRequest`, which you can send directly with the wallet tied to the `from` address. ```json title="TransactionRequest" { "data": { "setSpokeUserPositionManager": { "to": "0x123…", "from": "0x789…", "data": "0xabcd…", "value": "0", "chainId": 1, "operations": ["SPOKE_SET_USER_POSITION_MANAGER"] } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async (/* … */) => { const result = await setPositionManager(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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; } return; } console.log("Position manager updated with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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("Position manager updated with hash:", result.value.txHash); } ``` ### Step-by-Step with Solidity To authorize or revoke a position manager onchain, call `setUserPositionManager` on the Spoke contract. ```solidity title="Enable Position Manager" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(managerAddress, true); ``` ```solidity title="Disable Position Manager" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(managerAddress, false); ``` This is useful for smart contract wallets, account abstraction implementations, and automated vault protocols that need to authorize position managers programmatically. #### Complete Example Here’s a complete Solidity example for authorizing or revoking a position manager: ```solidity title="Authorize Position Manager" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function authorizePositionManager( address spokeAddress, address managerAddress, bool approve ) external { ISpoke spoke = ISpoke(spokeAddress); spoke.setUserPositionManager(managerAddress, approve); } ``` --- Source: https://aave.com/docs/aave-v4/positions/liquidations.md # Aave V4 Liquidations Liquidate unhealthy positions to earn liquidation bonuses and help maintain protocol stability. ## Identify Target Position First, identify a position with a health factor below 1.0 that is eligible for liquidation. ```ts title="User Position" const position: UserPosition = { __typename: "UserPosition", id: "aGVsbG8", user: "0x456…", healthFactor: { value: BigDecimal(0.85), // Below 1.0 - eligible for liquidation // … }, spoke: { address: "0x123…", chain: { chainId: 1, name: "Ethereum", }, // … }, // … }; ``` > [!NOTE] > Finding positions with a health factor below 1.0 is out of scope here. See > [Health Factor](../positions#health-factor). ## Select Liquidation Targets A liquidation targets one _debt_ reserve to repay and one _collateral_ reserve to seize, including the liquidation bonus. > [!NOTE] > Only liquidate when the liquidation bonus exceeds gas costs. ### 1. Choose the Debt Position First, identify which debt position to target by looking at the user’s borrow positions. Consider targeting debts with larger amounts. Fetch borrow positions from [User Borrows](./fetch#fetching-user-borrows), then pick the specific position you want to liquidate: ```ts title="Borrow Position" const debtPosition: UserBorrowItem = { reserve: { id: "SGVsbG8h", onChainId: "42", asset: { underlying: { address: "0xa0b8…", info: { symbol: "USDC", name: "USD Coin" } }, }, // … }, debt: { amount: { value: BigDecimal(2000), }, exchange: { value: BigDecimal(2000), // … }, // … }, // … }; ``` > [!NOTE] > If less than $1,000 USD of debt would remain in the target reserve, you must > liquidate all of it. ### 2. Choose the Collateral Position Next, identify which collateral position to target by examining the user’s supply positions that are enabled as collateral. Only supplies with `isCollateral: true` can be targeted for liquidation. Choose collateral in the token you prefer to receive as your liquidation bonus by fetching the supply positions from [User Supplies](./fetch#fetching-user-supplies): ```ts title="Supply Position" const collateral: UserSupplyItem = { reserve: { id: "V29ybGQ=", onChainId: "43", asset: { underlying: { address: "0xc02a…", info: { symbol: "WETH", name: "Wrapped Ether" } }, }, // … }, isCollateral: true, // Can be liquidated withdrawable: { amount: { value: BigDecimal(1.5), // … }, // … }, // … }; ``` > [!NOTE] > In Aave V4, liquidation bonuses follow a Dutch auction where lower health > factors result in higher liquidation bonuses. ## Liquidate the Position ### Step-by-Step with AaveKit After selecting the debt and collateral reserves, choose the repayment amount. You can send an exact value or let the protocol determine the needed amount by using max, restoring the position to a healthy state (HF ≥ 1.0). To liquidate an unhealthy position with AaveKit, follow these steps. #### 1. Configure Wallet Integration In React, first instantiate the hooks for the [wallet library of your choice](../getting-started/react#integrations). This wallet will pay the debt tokens and receive the seized collateral. - `useSendTransaction`: used to send ERC-20 approval and liquidation transactions - `useSignTypedData`: used to sign ERC-20 permits when available ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` #### 2. Define the Liquidation Flow Then, in React, use the `useLiquidatePosition` hook to prepare the liquidation operation. ```tsx title="Basic Usage" import { useLiquidatePosition } from "@aave/react"; const [liquidatePosition, { loading, error }] = useLiquidatePosition( (plan, { cancel }) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": // If token supports EIP-2612 permits, sign permit (recommended) if (plan.bySignature) { return signTypedData(plan.bySignature); } // Otherwise use traditional approval transaction return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }, ); ``` ```tsx title="Update Component State" import { useLiquidatePosition } from "@aave/react"; const [status, setStatus] = useState(""); const [liquidatePosition, { loading, error }] = useLiquidatePosition( (plan, { cancel }) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please sign the Liquidation transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Liquidating…")); case "Erc20Approval": if (plan.bySignature) { setStatus("Please sign the Permit in your wallet"); return signTypedData(plan.bySignature).andTee(() => setStatus("Approving…"), ); } setStatus("Please sign the Approval transaction in your wallet"); return sendTransaction(plan.byTransaction).andTee(() => setStatus("Approving…"), ); case "PreContractActionRequired": setStatus( "Please sign the Pre-Contract Action transaction in your wallet", ); return sendTransaction(plan.transaction); } }, ); ``` ```tsx title="Cancel Flow" import { useLiquidatePosition } from "@aave/react"; const [liquidatePosition, { loading, error }] = useLiquidatePosition( (plan, { cancel }) => { if ( window.confirm("Are you sure you want to liquidate this position?") === false ) { return cancel("User cancelled the liquidation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": if (plan.bySignature) { return signTypedData(plan.bySignature); } return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }, ); ``` In the `Erc20Approval` case, the `bySignature` field is only available if the token supports EIP-2612 permits. > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the hook calls your callback twice: reset to 0, then set the new value. > `bySignature` is `null` for these. #### 3. Execute the Liquidation Then, execute the liquidation operation. - **TypeScript**: Use the `liquidatePosition` action to create the transaction request for liquidating the unhealthy position. - **GraphQL**: Use the `liquidatePosition` query to prepare the liquidation execution plan. Specify an exact debt amount to cover, or use `amount: { max: true }` to bring the position back to a healthy state. Set `receiveShares: true` to receive the seized collateral as supply shares instead of the underlying asset (defaults to `false`). ```tsx title="Liquidate Specific Amount" import { bigDecimal, evmAddress, type UserBorrowItem, type UserPosition, type UserSupplyItem, } from "@aave/react"; const execute = async ( position: UserPosition, debt: UserBorrowItem, collateral: UserSupplyItem, ) => { const result = await liquidatePosition({ collateral: collateral.reserve.id, debt: debt.reserve.id, amount: { exact: { value: bigDecimal("1000") }, // 1000 USDC }, liquidator: evmAddress(wallet.account.address), // User's address user: position.user, }); // … }; ``` ```tsx title="Liquidate Maximum Amount" import { evmAddress, type UserPosition, type UserBorrowItem, type UserSupplyItem, } from "@aave/react"; const execute = async ( position: UserPosition, debt: UserBorrowItem, collateral: UserSupplyItem, ) => { const result = await liquidatePosition({ collateral: collateral.reserve.id, debt: debt.reserve.id, amount: { max: true, }, liquidator: evmAddress(wallet.account.address), // User's address user: position.user, }); // … }; ``` ```ts title="Liquidate Specific Amount" import { liquidatePosition } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; const result = await liquidatePosition(client, { collateral: collateral.reserve.id, debt: debtPosition.reserve.id, amount: { exact: { value: bigDecimal("1000") }, // 1000 USDC }, liquidator: evmAddress(wallet.account.address), user: position.user, }); // … ``` ```ts title="Liquidate Maximum Amount" import { liquidatePosition } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await liquidatePosition(client, { collateral: collateral.reserve.id, debt: debtPosition.reserve.id, amount: { max: true }, liquidator: evmAddress(wallet.account.address), user: position.user, }); // … ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: LiquidatePositionRequest!) { liquidatePosition(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on Erc20ApprovalRequired { reason requiredAmount { ...DecimalNumber } currentAllowance { ...DecimalNumber } approvals { byTransaction { ...TransactionRequest } bySignature { ...PermitTypedData } } originalTransaction { ...TransactionRequest } } ... on InsufficientBalanceError { required { ...DecimalNumber } available { ...DecimalNumber } } } } ``` ```graphql title="TransactionRequest" fragment TransactionRequest on TransactionRequest { to from data value chainId operations } ``` ```graphql title="PermitTypedData" fragment PermitTypedData on PermitTypedData { types primaryType domain { name version chainId verifyingContract } message } ``` In GraphQL, below is an example of a `LiquidatePositionRequest` object. ```json title="Liquidate Specific Amount" { "request": { "collateral": "V29ybGQ=", "debt": "SGVsbG8h", "amount": { "exact": { "value": "1000" } }, "liquidator": "0x789…", "user": "0x456…" } } ``` ```json title="Liquidate Maximum Amount" { "request": { "collateral": "V29ybGQ=", "debt": "SGVsbG8h", "amount": { "max": true }, "liquidator": "0x789…", "user": "0x456…", "receiveShares": true } } ``` ```json title="Permit-based Approval" { "request": { "collateral": "V29ybGQ=", "debt": "SGVsbG8h", "amount": { "exact": { "value": "1000", "permitSig": { "deadline": 1700000000, "value": "0xabcdef…" } } }, "liquidator": "0x789…", "user": "0x456…" } } ``` In TypeScript, to handle ERC-20 permit-based approval, wrap the `liquidatePosition` call with `permitWith` for the [wallet library of your choice](../getting-started/typescript#integrations). ```ts title="Permit-based (Viem)" import { liquidatePosition } from "@aave/client/actions"; import { permitWith } from "@aave/client/viem"; import { bigDecimal, evmAddress } from "@aave/client"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await permitWith(wallet, (permitSig) => liquidatePosition(client, { collateral: collateral.reserve.id, debt: debtPosition.reserve.id, amount: { exact: { value: bigDecimal("1000"), permitSig }, }, liquidator: evmAddress(wallet.account.address), user: position.user, }), ); // … ``` ```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(), }); ``` The `permitWith` helper: 1. Calls the `liquidatePosition` action without a permit signature 2. If the response is `Erc20ApprovalRequired` with permit signature available, signs the permit and calls `liquidatePosition` again with the signature to get an updated execution plan 3. Otherwise, returns the execution plan unchanged (no permit needed or token doesn’t support permits) > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > `permitWith` skips the permit and the next step handles both approvals. #### 4. Process the Execution Plan In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send the transactions in the execution plan, and await indexing with `client.waitForTransaction`. This wallet will pay the debt tokens and receive the seized collateral. ```ts title="Transaction-based" import { liquidatePosition } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await liquidatePosition(client, { // … }) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```ts title="Permit-based" import { liquidatePosition } from "@aave/client/actions"; import { bigDecimal, evmAddress } from "@aave/client"; import { permitWith, sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await permitWith(wallet, (permitSig) => liquidatePosition(client, { collateral: collateral.reserve.id, debt: debtPosition.reserve.id, amount: { exact: { value: bigDecimal("1000"), permitSig }, }, liquidator: evmAddress(wallet.account.address), user: position.user, }), ) .andThen(sendWith(wallet)) .andThen(client.waitForTransaction); ``` ```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(), }); ``` > [!NOTE] > `sendWith` handles all required approvals, including the allowance reset for > tokens like USDT. In GraphQL, if the response is a `TransactionRequest`, you can send it directly using the wallet associated with the from address. ```json title="TransactionRequest" { "data": { "liquidatePosition": { "__typename": "TransactionRequest", "to": "0x123…", "from": "0x789…", "data": "0xc2fa746c…", "value": "0", "chainId": 1, "operations": ["LIQUIDATION"] } } } ``` If the response is `Erc20ApprovalRequired`, you have two options: **Transaction-based approval** 1. Send each transaction in the `approvals` array in sequence 2. Then send `originalTransaction` **Permit-based approval** > [!NOTE] > This is available only when `approvals` contains a single `Erc20Approval` > item. 1. Sign the `approvals[0].bySignature` typed data with the sender’s account. 2. Call the `liquidatePosition` query again with the permit signature 3. The response will be a `TransactionRequest` you can then send directly ```jsonc title="Single Approval" { "data": { "liquidatePosition": { "__typename": "Erc20ApprovalRequired", "reason": "Insufficient allowance for ERC-20 token transfer", "requiredAmount": { "value": "1000.000000", "decimals": 6 }, "currentAllowance": { "value": "0.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "from": "0x789…", "data": "0x095ea7b3000000000000000000000000878…", "value": "0", "chainId": 1, "operations": null }, "bySignature": { "types": , "primaryType": "Permit", "domain": , "message": } } ], "originalTransaction": { "to": "0x123…", "from": "0x789…", "data": "0xc2fa746c…", "value": "0", "chainId": 1, "operations": ["LIQUIDATION"] } } } } ``` ```json title="Multiple Approvals (USDT-like)" { "data": { "liquidatePosition": { "__typename": "Erc20ApprovalRequired", "reason": "Token requires allowance reset before new approval", "requiredAmount": { "value": "1000.000000", "decimals": 6 }, "currentAllowance": { "value": "500.000000", "decimals": 6 }, "approvals": [ { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x789…", "data": "0x095ea7b3000000000000000000000000878…0", "value": "0", "chainId": 1, "operations": null }, "bySignature": null }, { "byTransaction": { "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "from": "0x789…", "data": "0x095ea7b3000000000000000000000000878…1000", "value": "0", "chainId": 1, "operations": null }, "bySignature": null } ], "originalTransaction": { "to": "0x123…", "from": "0x789…", "data": "0xc2fa746c…", "value": "0", "chainId": 1, "operations": ["LIQUIDATION"] } } } } ``` > [!NOTE] > With multiple approvals in `Erc20ApprovalRequired`, send each `byTransaction` > in order, then `originalTransaction`. For [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > the first resets the allowance to 0 and the second sets the required amount. If the response is an `InsufficientBalanceError`, inform the user that they don’t have enough funds to perform the liquidation. ```json title="InsufficientBalanceError" { "data": { "liquidatePosition": { "__typename": "InsufficientBalanceError", "required": { "value": "1000.000000", "decimals": 6 }, "available": { "value": "500.000000", "decimals": 6 } } } } ``` #### 5. Handle the Result Finally, in React and TypeScript, handle the result. ```tsx title="Example" const execute = async (/* … */) => { const result = await liquidatePosition(/* … */); if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } return; } console.log("Liquidation successful with hash:", result.value.txHash); }; ``` ```ts title="Example" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "ValidationError": console.error( "Insufficient balance:", `required: ${result.error.cause.required.value.toDisplayString(2)}`, `available: ${result.error.cause.available.value.toDisplayString(2)}`, ); break; case "UnexpectedError": console.error(result.error.message); break; } } else { console.log("Liquidation successful with hash:", result.value.txHash); } ``` ### Step-by-Step with Solidity Start with the spoke address and target user identifying the position: ```solidity title="Target User Position" address spokeAddress = 0x123…; address targetUser = 0x456…; ``` And with the on-chain reserve IDs for the collateral and debt: ```solidity title="Target Reserves" uint256 collateralReserveId = 43; uint256 debtReserveId = 42; ``` Choose the amount of debt to cover: ```solidity title="Liquidate Specific Amount" uint256 debtToCover = 1000e6; // 1000 USDC ``` ```solidity title="Liquidate Maximum Amount" uint256 debtToCover = type(uint256).max; ``` And follow these steps to liquidate the position onchain: #### 1. Import the Spoke Interface First, create an instance of the `ISpoke` interface. ```solidity title="Import the Spoke Interface" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; ISpoke spoke = ISpoke(spokeAddress); ``` #### 2. Approve Token Transfer Then, retrieve the debt reserve’s underlying token and approve the Spoke to transfer the debt tokens. ```solidity title="Retrieve Reserve and Approve" import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; ISpoke.Reserve memory debtReserve = spoke.getReserve(debtReserveId); IERC20 token = IERC20(debtReserve.underlying); token.approve(address(spoke), debtToCover); ``` #### 3. Execute Liquidation Finally, call the `liquidationCall` function on the Spoke contract, specifying the liquidation parameters. ```solidity title="Liquidate Position" spoke.liquidationCall( collateralReserveId, debtReserveId, targetUser, debtToCover, false ); ``` #### Complete Example Here are complete Solidity examples for checking position health and executing liquidation: ```solidity title="Check Position Health" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; function canLiquidate( address spokeAddress, address user ) external view returns (bool, uint256 healthFactor) { ISpoke spoke = ISpoke(spokeAddress); ISpoke.UserAccountData memory accountData = spoke.getUserAccountData(user); healthFactor = accountData.healthFactor; if (accountData.totalDebtValueRay == 0) { return (false, type(uint256).max); } return (healthFactor < 1e18, healthFactor); } ``` ```solidity title="Execute Liquidation" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IERC20 } from "aave-v4/src/dependencies/openzeppelin/IERC20.sol"; function liquidatePosition( address spokeAddress, uint256 collateralReserveId, uint256 debtReserveId, address user, uint256 debtToCover ) external { ISpoke spoke = ISpoke(spokeAddress); ISpoke.Reserve memory debtReserve = spoke.getReserve(debtReserveId); IERC20 debtToken = IERC20(debtReserve.underlying); debtToken.approve(spokeAddress, debtToCover); spoke.liquidationCall( collateralReserveId, debtReserveId, user, debtToCover, false ); } ``` --- Source: https://aave.com/docs/aave-v4/tools/balances.md # Aave V4 User Balances User balances show a user’s token holdings across chains, aggregated by token type with supply and borrow APY information. ## User Balance Data Structure User balance data provides information about a user’s token holdings, including: - Globally unique identifier: for each balance entry - Token identification: name, symbol, icon, decimals - Balance amounts: individual balances per network, total amounts - Yield information: highest and lowest supply/borrow APY for each token - Collateral factors: highest and lowest collateral factors for each token - Fiat valuations: converted amounts in selected currency The following TypeScript interfaces illustrate the core UserBalance type: ```ts title="UserBalance" interface UserBalance { __typename: "UserBalance"; id: UserBalanceId; info: TokenInfo; balances: TokenAmount[]; totalAmount: DecimalNumber; exchange: ExchangeAmount; highestSupplyApy: PercentNumber; highestBorrowApy: PercentNumber; lowestSupplyApy: PercentNumber; lowestBorrowApy: PercentNumber; highestCollateralFactor: PercentNumber | null; lowestCollateralFactor: PercentNumber | null; } ``` ```ts title="TokenInfo" interface TokenInfo { __typename: "TokenInfo"; id: TokenInfoId; name: string; symbol: string; icon: string; decimals: number; categories: TokenCategory[]; } ``` ```ts title="TokenAmount" type TokenAmount = Erc20Amount | NativeAmount; interface Erc20Amount { __typename: "Erc20Amount"; token: Erc20Token; amount: DecimalNumber; exchange: ExchangeAmount; exchangeRate: DecimalNumber; } interface NativeAmount { __typename: "NativeAmount"; token: NativeToken; amount: DecimalNumber; exchange: ExchangeAmount; exchangeRate: DecimalNumber; } ``` ```ts title="ExchangeAmount" interface ExchangeAmount { __typename: "ExchangeAmount"; value: BigDecimal; name: string; symbol: string; icon: string; decimals: number; } ``` The following GraphQL fragments illustrate the core UserBalance type: ```graphql title="UserBalance" fragment UserBalance on UserBalance { __typename id info { ...TokenInfo } balances { ...TokenAmount } totalAmount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } highestSupplyApy: supplyApy(metric: HIGHEST) { ...PercentNumber } highestBorrowApy: borrowApy(metric: HIGHEST) { ...PercentNumber } lowestSupplyApy: supplyApy(metric: LOWEST) { ...PercentNumber } lowestBorrowApy: borrowApy(metric: LOWEST) { ...PercentNumber } highestCollateralFactor: collateralFactor(metric: HIGHEST) { ...PercentNumber } lowestCollateralFactor: collateralFactor(metric: LOWEST) { ...PercentNumber } } ``` ```graphql title="TokenInfo" fragment TokenInfo on TokenInfo { __typename id name symbol icon decimals categories } ``` ```graphql title="TokenAmount" fragment TokenAmount on TokenAmount { __typename ... on Erc20Amount { token { ...Erc20Token } amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } } ... on NativeAmount { token { ...NativeToken } amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } } } ``` ```graphql title="ExchangeAmount" fragment ExchangeAmount on ExchangeAmount { __typename value name symbol icon decimals } ``` ## Fetching User Balances Use the `useUserBalances` hook in React, the `userBalances` action in TypeScript, or the `userBalances` query in GraphQL to fetch user token balances. In TypeScript, the examples filter balances by chains, hub, spoke, user position, or tokens. ```tsx title="Loading State" import { type UserBalancesRequest, useUserBalances } from "@aave/react"; function UserBalancesList({ request }: { request: UserBalancesRequest }) { const { data, loading, error } = useUserBalances(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: UserBalance[] return (
{data.map((balance) => (

{balance.info.name}

Total: {balance.totalAmount.value.toDisplayString(2)} {balance.info.symbol} {balance.exchange.symbol} {balance.exchange.value.toDisplayString(2)}

Supply APY: {balance.highestSupplyApy.normalized.toFixed(2)}%

))}
); } ``` ```tsx title="React Suspense" import { type UserBalancesRequest, useUserBalances } from "@aave/react"; function UserBalancesList({ request }: { request: UserBalancesRequest }) { const { data } = useUserBalances({ ...request, suspense: true, }); // data: UserBalance[] return (
{data.map((balance) => (

{balance.info.name}

Total: {balance.totalAmount.value.toDisplayString(2)} {balance.info.symbol} {balance.exchange.symbol} {balance.exchange.value.toDisplayString(2)}

Supply APY: {balance.highestSupplyApy.normalized.toFixed(2)}%

))}
); } ```
```ts title="Filter by Chains" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { chains: { chainIds: [chainId(1)], }, }, }); if (result.isOk()) { console.log("User balances:", result.value); // result.value: UserBalance[] } else { console.error("Error:", result.error); } ``` ```ts title="Filter by Hub" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; // By hub ID const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { hubId: { hubId: hub.id, // hub: Hub }, }, }); if (result.isOk()) { console.log("User balances:", result.value); // result.value: UserBalance[] } else { console.error("Error:", result.error); } // By hub address and chain ID const resultByAddress = await userBalances(client, { user: evmAddress("0x456…"), filter: { hub: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); ``` ```ts title="Filter by Spoke" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }); if (result.isOk()) { console.log("User balances:", result.value); // result.value: UserBalance[] } else { console.error("Error:", result.error); } ``` ```ts title="Filter by User Position" import { userBalances } from "@aave/client/actions"; import { evmAddress, type UserPosition } from "@aave/client"; import { client } from "./client"; // const position: UserPosition = … const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { userPosition: { userPositionId: position.id, }, }, }); if (result.isOk()) { console.log("User balances:", result.value); // result.value: UserBalance[] } else { console.error("Error:", result.error); } ``` ```ts title="Filter by Tokens" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { tokens: { chainTokens: [ { chainId: chainId(1), token: { erc20: evmAddress("0xA0b8…") } }, { chainId: chainId(1), token: { native: true } }, ], }, }, }); if (result.isOk()) { console.log("User balances:", result.value); // result.value: UserBalance[] } else { console.error("Error:", result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: UserBalancesRequest!, $currency: Currency! = USD) { userBalances(request: $request) { info { ...TokenInfo } balances { ...TokenAmount } totalAmount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } highestSupplyApy: supplyApy(metric: HIGHEST) { ...PercentNumber } highestBorrowApy: borrowApy(metric: HIGHEST) { ...PercentNumber } lowestSupplyApy: supplyApy(metric: LOWEST) { ...PercentNumber } lowestBorrowApy: borrowApy(metric: LOWEST) { ...PercentNumber } highestCollateralFactor: collateralFactor(metric: HIGHEST) { ...PercentNumber } lowestCollateralFactor: collateralFactor(metric: LOWEST) { ...PercentNumber } } } ``` ```graphql title="TokenAmount" fragment TokenAmount on TokenAmount { __typename ... on Erc20Amount { amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } token { ...Erc20Token } } ... on NativeAmount { amount { ...DecimalNumber } exchange(currency: $currency) { ...ExchangeAmount } exchangeRate(currency: $currency) { ...DecimalNumber } token { ...NativeToken } } } ```
Filter balances by chain, hub, spoke, user position, or token. In GraphQL, specify the `user` address and pass the filter in `filter`. ```tsx title="Filter by Chains" import { evmAddress, chainId } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { chains: { chainIds: [chainId(1)], }, }, }; ``` ```tsx title="Filter by Hub" import { evmAddress, chainId } from "@aave/react"; // By hub ID const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { hubId: { hubId: hub.id, // hub: Hub }, }, }; // By hub address and chain ID const requestByAddress: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { hub: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```tsx title="Filter by Spoke" import { evmAddress, chainId } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, }; ``` ```tsx title="Filter by User Position" import { evmAddress } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { userPosition: { userPositionId: position.id, }, }, }; ``` ```tsx title="Filter by Tokens" import { evmAddress, chainId } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { tokens: { chainTokens: [ { chainId: chainId(1), token: { erc20: evmAddress("0xA0b8…") } }, { chainId: chainId(1), token: { native: true } }, ], }, }, }; ``` ```json title="By Chains" { "request": { "user": "0x456…", "filter": { "chains": { "chainIds": [1] } } } } ``` ```json title="By Hub ID" { "request": { "user": "0x456…", "filter": { "hubId": { "hubId": "SGVsbG8h" } } } } ``` ```json title="By Hub Address" { "request": { "user": "0x456…", "filter": { "hub": { "address": "0x123…", "chainId": 1 } } } } ``` ```json title="By Spoke" { "request": { "user": "0x456…", "filter": { "spoke": { "address": "0x123…", "chainId": 1 } } } } ``` ```json title="By User Position" { "request": { "user": "0x456…", "filter": { "userPosition": { "userPositionId": "SGVsbG8h" } } } } ``` ```json title="By Tokens" { "request": { "user": "0x456…", "filter": { "tokens": { "chainTokens": [ { "chainId": 1, "token": { "erc20": "0xA0b8…" } }, { "chainId": 1, "token": { "native": true } } ] } } } } ``` Sort balances by name or balance value. In GraphQL, use the `orderBy` field. ```tsx title="By Balance" import { evmAddress, OrderDirection } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { balance: OrderDirection.Desc }, }; ``` ```tsx title="By Name" import { evmAddress, OrderDirection } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { name: OrderDirection.Asc }, }; ``` ```ts title="By Balance" import { userBalances } from "@aave/client/actions"; import { evmAddress, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { balance: OrderDirection.Desc }, }); ``` ```ts title="By Name" import { userBalances } from "@aave/client/actions"; import { evmAddress, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { // your filter criteria }, orderBy: { name: OrderDirection.Asc }, }); ``` ```jsonc title="By Balance" { "request": { "user": "0x456…", "filter": { // your filter criteria }, "orderBy": { "balance": "DESC" } } } ``` ```jsonc title="By Name" { "request": { "user": "0x456…", "filter": { // your filter criteria }, "orderBy": { "name": "ASC" } } } ``` Include tokens with zero balances in the results. ```tsx title="Include Zero Balances" const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { // your filter criteria }, includeZeroBalances: true, }; ``` ```ts title="Include Zero Balances" const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { chains: { chainIds: [chainId(1)] }, }, includeZeroBalances: true, }); ``` ```jsonc title="Include Zero Balances" { "request": { "user": "0x456…", "filter": { // your filter criteria }, "includeZeroBalances": true } } ``` Specify a different currency for displaying fiat amounts. In GraphQL, use the `currency` argument. ```tsx title="Custom Currency" import { evmAddress, Currency } from "@aave/react"; // … const { data, loading, error } = useUserBalances({ user: evmAddress("0x456…"), filter: { // your filter criteria }, currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId, Currency } from "@aave/client"; import { client } from "./client"; const result = await userBalances( client, { user: evmAddress("0x456…"), filter: { chains: { chainIds: [chainId(1)] }, }, }, { currency: Currency.Eur, } ); ``` ```jsonc title="Custom Currency" { "request": { "user": "0x456…", "filter": { // your filter criteria } }, "currency": "EUR" } ``` --- Source: https://aave.com/docs/aave-v4/tools/activities.md # Aave V4 User Activities View detailed activity history covering supplies, borrows, repayments, withdrawals, liquidations, and swaps, with built-in pagination support. ## Activity Data Structure Activity data provides detailed information about all user activities, including: - Transaction details: timestamp, transaction hash, chain, amount - Activity types: core operations (supply, borrow, withdraw, repay), liquidations, position settings, and swaps - User performing the activity - Type-specific details like reserve, spoke, and amounts The following TypeScript interfaces illustrate the core activity types: ```ts title="ActivityItem" type ActivityItem = | BorrowActivity | SupplyActivity | WithdrawActivity | RepayActivity | LiquidatedActivity | UsingAsCollateralActivity | UpdatedDynamicConfigActivity | UpdatedRiskPremiumActivity | TokenSwapActivity | SupplySwapActivity | BorrowSwapActivity | RepayWithSupplyActivity | WithdrawSwapActivity | LeverageActivity; ``` ```ts title="BorrowActivity" interface BorrowActivity { __typename: "BorrowActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; borrowed: Erc20Amount; chain: Chain; } interface BorrowSwapActivity { __typename: "BorrowSwapActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; sell: PositionAmount; buy: PositionAmount; explorerUrl: string; orderClass: SwapOrderClass; kind: BorrowSwapKind; status: SwapActivityStatus; } ``` ```ts title="SupplyActivity" interface SupplyActivity { __typename: "SupplyActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; supplied: Erc20Amount; chain: Chain; } interface SupplySwapActivity { __typename: "SupplySwapActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; sell: PositionAmount; buy: PositionAmount; explorerUrl: string; orderClass: SwapOrderClass; kind: SupplySwapKind; status: SwapActivityStatus; } ``` ```ts title="WithdrawActivity" interface WithdrawActivity { __typename: "WithdrawActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; withdrawn: Erc20Amount; chain: Chain; } interface WithdrawSwapActivity { __typename: "WithdrawSwapActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; withdraw: PositionAmount; buy: TokenAmount; explorerUrl: string; orderClass: SwapOrderClass; kind: WithdrawSwapKind; status: SwapActivityStatus; } ``` ```ts title="RepayActivity" interface RepayActivity { __typename: "RepayActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; repaid: Erc20Amount; chain: Chain; } interface RepayWithSupplyActivity { __typename: "RepayWithSupplyActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; repay: PositionAmount; supply: PositionAmount; explorerUrl: string; orderClass: SwapOrderClass; kind: RepayWithSupplyKind; status: SwapActivityStatus; } ``` ```ts title="Others" interface LiquidatedActivity { __typename: "LiquidatedActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; collateralReserve: ReserveInfo; collateral: Erc20Amount; liquidatorReceived: Erc20Amount; liquidationFee: Erc20Amount; debtReserve: ReserveInfo; debt: Erc20Amount; liquidator: EvmAddress; liquidationHealthFactor: HealthFactor; chain: Chain; } interface UsingAsCollateralActivity { __typename: "UsingAsCollateralActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; enabledAsCollateral: boolean; chain: Chain; } interface UpdatedDynamicConfigActivity { __typename: "UpdatedDynamicConfigActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; reserve: ReserveInfo; collateralFactor: PercentNumberChangeSnapshot; maxLiquidationBonus: PercentNumberChangeSnapshot; liquidationFee: PercentNumberChangeSnapshot; chain: Chain; } interface UpdatedRiskPremiumActivity { __typename: "UpdatedRiskPremiumActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash; spoke: Spoke; premium: PercentNumberChangeSnapshot; chain: Chain; } interface TokenSwapActivity { __typename: "TokenSwapActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; sell: TokenAmount; buy: TokenAmount; explorerUrl: string; orderClass: SwapOrderClass; kind: TokenSwapKind; status: SwapActivityStatus; } interface LeverageActivity { __typename: "LeverageActivity"; id: string; user: EvmAddress; timestamp: Date; txHash: TxHash | null; chain: Chain; collateral: PositionAmount; debt: PositionAmount; multiplier: BigDecimal; explorerUrl: string; orderClass: SwapOrderClass; status: SwapActivityStatus; } interface PercentNumberChangeSnapshot { before: PercentNumber; after: PercentNumber; } ``` The following GraphQL fragments illustrate the core activity types: ```graphql title="ActivityItem" fragment ActivityItem on ActivityItem { __typename ... on BorrowActivity { ...BorrowActivity } ... on SupplyActivity { ...SupplyActivity } ... on WithdrawActivity { ...WithdrawActivity } ... on RepayActivity { ...RepayActivity } ... on LiquidatedActivity { ...LiquidatedActivity } ... on UsingAsCollateralActivity { ...UsingAsCollateralActivity } ... on UpdatedDynamicConfigActivity { ...UpdatedDynamicConfigActivity } ... on UpdatedRiskPremiumActivity { ...UpdatedRiskPremiumActivity } ... on TokenSwapActivity { ...TokenSwapActivity } ... on SupplySwapActivity { ...SupplySwapActivity } ... on BorrowSwapActivity { ...BorrowSwapActivity } ... on RepayWithSupplyActivity { ...RepayWithSupplyActivity } ... on WithdrawSwapActivity { ...WithdrawSwapActivity } ... on LeverageActivity { ...LeverageActivity } } ``` ```graphql title="BorrowActivity" fragment BorrowActivity on BorrowActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } borrowed { ...Erc20Amount } chain { ...Chain } } fragment BorrowSwapActivity on BorrowSwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...PositionAmount } buy { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="SupplyActivity" fragment SupplyActivity on SupplyActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } supplied { ...Erc20Amount } chain { ...Chain } } fragment SupplySwapActivity on SupplySwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...PositionAmount } buy { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="WithdrawActivity" fragment WithdrawActivity on WithdrawActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } withdrawn { ...Erc20Amount } chain { ...Chain } } fragment WithdrawSwapActivity on WithdrawSwapActivity { __typename id user timestamp txHash chain { ...Chain } withdraw { ...PositionAmount } buy { ...TokenAmount } explorerUrl orderClass kind status } ``` ```graphql title="RepayActivity" fragment RepayActivity on RepayActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } repaid { ...Erc20Amount } chain { ...Chain } } fragment RepayWithSupplyActivity on RepayWithSupplyActivity { __typename id user timestamp txHash chain { ...Chain } repay { ...PositionAmount } supply { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="Others" fragment LiquidatedActivity on LiquidatedActivity { __typename id user timestamp txHash spoke { ...Spoke } collateralReserve { ...ReserveInfo } collateral { ...Erc20Amount } liquidatorReceived { ...Erc20Amount } liquidationFee { ...Erc20Amount } debtReserve { ...ReserveInfo } debt { ...Erc20Amount } liquidator liquidationHealthFactor chain { ...Chain } } fragment UsingAsCollateralActivity on UsingAsCollateralActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } enabledAsCollateral chain { ...Chain } } fragment TokenSwapActivity on TokenSwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...TokenAmount } buy { ...TokenAmount } explorerUrl orderClass kind status } fragment LeverageActivity on LeverageActivity { __typename id user timestamp txHash chain { ...Chain } collateral { ...PositionAmount } debt { ...PositionAmount } multiplier explorerUrl orderClass status } fragment UpdatedDynamicConfigActivity on UpdatedDynamicConfigActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } collateralFactor { ...PercentNumberChangeSnapshot } maxLiquidationBonus { ...PercentNumberChangeSnapshot } liquidationFee { ...PercentNumberChangeSnapshot } chain { ...Chain } } fragment UpdatedRiskPremiumActivity on UpdatedRiskPremiumActivity { __typename id user timestamp txHash spoke { ...Spoke } premium { ...PercentNumberChangeSnapshot } chain { ...Chain } } fragment PercentNumberChangeSnapshot on PercentNumberChangeSnapshot { __typename before { ...PercentNumber } after { ...PercentNumber } } ``` ## Fetching User Activities Fetch users' activities with filtering and pagination. Use the `useActivities` hook in React, the `activities` action in TypeScript, or the `activities` query in GraphQL to fetch paginated activities for a user. ```tsx title="Loading State" import { type ActivitiesRequest, useActivities } from "@aave/react"; function ActivitiesList({ request }: { request: ActivitiesRequest }) { const { data, loading, error } = useActivities(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: PaginatedActivitiesResult return (
{data.items.map((activity) => (

{activity.__typename}

Time: {activity.timestamp.toLocaleString()} Tx: {activity.txHash}
))}
); } ``` ```tsx title="React Suspense" import { type ActivitiesRequest, useActivities } from "@aave/react"; function ActivitiesList({ request }: { request: ActivitiesRequest }) { const { data } = useActivities({ ...request, suspense: true, }); // data: PaginatedActivitiesResult return (
{data.items.map((activity) => (

{activity.__typename}

Time: {activity.timestamp.toLocaleString()} Tx: {activity.txHash}
))}
); } ```
```ts title="Query by Chains" import { activities } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { chainIds: [chainId(1)], }, user: evmAddress("0x456…"), }); if (result.isOk()) { console.log("Activities:", result.value); // result.value: PaginatedActivitiesResult } else { console.error("Error:", result.error); } ``` ```ts title="Query by Spoke" import { activities } from "@aave/client/actions"; import { evmAddress, chainId } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, user: evmAddress("0x456…"), }); if (result.isOk()) { console.log("Activities:", result.value); // result.value: PaginatedActivitiesResult } else { console.error("Error:", result.error); } ``` ```ts title="Query by Transaction" import { activities } from "@aave/client/actions"; import { evmAddress, chainId, txHash } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { txHash: { txHash: txHash("0xabc123…"), chainId: chainId(1), }, }, user: evmAddress("0x456…"), }); if (result.isOk()) { // result.value: PaginatedActivitiesResult console.log("Activities:", result.value); } else { console.error("Error:", result.error); } ``` ```ts title="Query by User Position" import { activities } from "@aave/client/actions"; import { evmAddress } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { userPositionId: position.id, // position: UserPosition }, user: evmAddress("0x456…"), }); if (result.isOk()) { console.log("Activities:", result.value); // result.value: PaginatedActivitiesResult } else { console.error("Error:", result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: ActivitiesRequest!, $currency: Currency! = USD) { activities(request: $request) { items { ... on BorrowActivity { ...BorrowActivity } ... on SupplyActivity { ...SupplyActivity } ... on WithdrawActivity { ...WithdrawActivity } ... on RepayActivity { ...RepayActivity } ... on LiquidatedActivity { ...LiquidatedActivity } ... on UsingAsCollateralActivity { ...UsingAsCollateralActivity } ... on UpdatedDynamicConfigActivity { ...UpdatedDynamicConfigActivity } ... on UpdatedRiskPremiumActivity { ...UpdatedRiskPremiumActivity } ... on TokenSwapActivity { ...TokenSwapActivity } ... on SupplySwapActivity { ...SupplySwapActivity } ... on BorrowSwapActivity { ...BorrowSwapActivity } ... on RepayWithSupplyActivity { ...RepayWithSupplyActivity } ... on WithdrawSwapActivity { ...WithdrawSwapActivity } ... on LeverageActivity { ...LeverageActivity } } pageInfo { next prev } } } ``` ```graphql title="BorrowActivity" fragment BorrowActivity on BorrowActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } borrowed { ...Erc20Amount } chain { ...Chain } } fragment BorrowSwapActivity on BorrowSwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...PositionAmount } buy { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="SupplyActivity" fragment SupplyActivity on SupplyActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } supplied { ...Erc20Amount } chain { ...Chain } } fragment SupplySwapActivity on SupplySwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...PositionAmount } buy { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="WithdrawActivity" fragment WithdrawActivity on WithdrawActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } withdrawn { ...Erc20Amount } chain { ...Chain } } fragment WithdrawSwapActivity on WithdrawSwapActivity { __typename id user timestamp txHash chain { ...Chain } withdraw { ...PositionAmount } buy { ...TokenAmount } explorerUrl orderClass kind status } ``` ```graphql title="RepayActivity" fragment RepayActivity on RepayActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } repaid { ...Erc20Amount } chain { ...Chain } } fragment RepayWithSupplyActivity on RepayWithSupplyActivity { __typename id user timestamp txHash chain { ...Chain } repay { ...PositionAmount } supply { ...PositionAmount } explorerUrl orderClass kind status } ``` ```graphql title="Others" fragment LiquidatedActivity on LiquidatedActivity { __typename id user timestamp txHash spoke { ...Spoke } collateral { ...Erc20Amount } liquidatorReceived { ...Erc20Amount } liquidationFee { ...Erc20Amount } collateralReserve { ...ReserveInfo } debt { ...Erc20Amount } debtReserve { ...ReserveInfo } liquidator liquidationHealthFactor chain { ...Chain } } fragment UsingAsCollateralActivity on UsingAsCollateralActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } enabledAsCollateral chain { ...Chain } } fragment TokenSwapActivity on TokenSwapActivity { __typename id user timestamp txHash chain { ...Chain } sell { ...TokenAmount } buy { ...TokenAmount } explorerUrl orderClass kind status } fragment LeverageActivity on LeverageActivity { __typename id user timestamp txHash chain { ...Chain } collateral { ...PositionAmount } debt { ...PositionAmount } multiplier explorerUrl orderClass status } fragment UpdatedDynamicConfigActivity on UpdatedDynamicConfigActivity { __typename id user timestamp txHash spoke { ...Spoke } reserve { ...ReserveInfo } collateralFactor { ...PercentNumberChangeSnapshot } maxLiquidationBonus { ...PercentNumberChangeSnapshot } liquidationFee { ...PercentNumberChangeSnapshot } chain { ...Chain } } fragment UpdatedRiskPremiumActivity on UpdatedRiskPremiumActivity { __typename id user timestamp txHash spoke { ...Spoke } premium { ...PercentNumberChangeSnapshot } chain { ...Chain } } fragment PercentNumberChangeSnapshot on PercentNumberChangeSnapshot { __typename before { ...PercentNumber } after { ...PercentNumber } } ```
In React and GraphQL, see below some examples of how to use the hook or query. ```tsx title="Query by Chains" import { evmAddress, chainId } from "@aave/react"; const request: ActivitiesRequest = { query: { chainIds: [chainId(1)], }, user: evmAddress("0x456…"), }; ``` ```tsx title="Query by Spoke" import { evmAddress, chainId } from "@aave/react"; const request: ActivitiesRequest = { query: { spoke: { address: evmAddress("0x123…"), chainId: chainId(1), }, }, user: evmAddress("0x456…"), }; ``` ```tsx title="Query by Transaction" import { evmAddress, chainId, txHash } from "@aave/react"; const request: ActivitiesRequest = { query: { txHash: { txHash: txHash("0xabc123…"), chainId: chainId(1), }, }, user: evmAddress("0x456…"), }; ``` ```tsx title="Query by User Position" import { evmAddress } from "@aave/react"; const request: ActivitiesRequest = { query: { userPositionId: position.id, // position: UserPosition }, user: evmAddress("0x456…"), }; ``` ```json title="Query by Chains" { "request": { "query": { "chainIds": [1] }, "user": "0x456…" } } ``` ```json title="Query by Spoke" { "request": { "query": { "spoke": { "address": "0x123…", "chainId": 1 } }, "user": "0x456…" } } ``` ```json title="Query by Transaction" { "request": { "query": { "txHash": { "txHash": "0xabc123…", "chainId": 1 } }, "user": "0x456…" } } ``` ```json title="Query by User Position" { "request": { "query": { "userPositionId": "SGVsbG8h" }, "user": "0x456…" } } ``` Filter by specific activity types. In GraphQL, use the `types` field. ```tsx title="Core Activities" import { evmAddress, ActivityType } from "@aave/react"; const request: ActivitiesRequest = { query: { // your query criteria }, user: evmAddress("0x456…"), types: [ ActivityType.Borrow, ActivityType.Supply, ActivityType.Repay, ActivityType.Withdraw, ], }; ``` ```tsx title="Swap Activities" import { evmAddress, ActivityType } from "@aave/react"; const request: ActivitiesRequest = { query: { // your query criteria }, user: evmAddress("0x456…"), types: [ ActivityType.TokenToTokenSwap, ActivityType.SupplySwap, ActivityType.BorrowSwap, ActivityType.RepayWithSupply, ActivityType.WithdrawSwap, ], }; ``` ```ts title="Core Activities" import { activities } from "@aave/client/actions"; import { evmAddress, ActivityType } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { // your query criteria }, user: evmAddress("0x456…"), types: [ ActivityType.Borrow, ActivityType.Supply, ActivityType.Repay, ActivityType.Withdraw, ], }); ``` ```ts title="Swap Activities" import { activities } from "@aave/client/actions"; import { evmAddress, ActivityType } from "@aave/client"; import { client } from "./client"; const result = await activities(client, { query: { // your query criteria }, user: evmAddress("0x456…"), types: [ ActivityType.TokenToTokenSwap, ActivityType.SupplySwap, ActivityType.BorrowSwap, ActivityType.RepayWithSupply, ActivityType.WithdrawSwap, ], }); ``` ```jsonc title="Core Activities" { "request": { "query": { // your query criteria }, "user": "0x456…", "types": ["BORROW", "SUPPLY", "REPAY", "WITHDRAW"] } } ``` ```jsonc title="Swap Activities" { "request": { "query": { // your query criteria }, "user": "0x456…", "types": [ "TOKEN_TO_TOKEN_SWAP", "SUPPLY_SWAP", "BORROW_SWAP", "REPAY_WITH_SUPPLY", "WITHDRAW_SWAP" ] } } ``` Finally, specify a different currency for displaying fiat amounts. - **React**: You can also specify a different time window. - **GraphQL**: Use the `currency` argument. ```tsx title="Custom Time Window" import { evmAddress, TimeWindow } from "@aave/react"; const { data, loading, error } = useActivities({ query: { // your query criteria }, user: evmAddress("0x456…"), timeWindow: TimeWindow.LastWeek, }); ``` ```tsx title="Custom Currency" import { evmAddress, Currency } from "@aave/react"; const { data, loading, error } = useActivities({ query: { // your query criteria }, user: evmAddress("0x456…"), currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { activities } from "@aave/client/actions"; import { evmAddress, Currency } from "@aave/client"; import { client } from "./client"; const result = await activities( client, { query: { // your query criteria }, user: evmAddress("0x456…"), }, { currency: Currency.Eur, }, ); ``` ```jsonc title="Custom Currency" { "request": { "query": { // your query criteria }, "user": "0x456…" }, "currency": "EUR" } ``` ## Handle Pagination Navigate through large activity history sets using cursor-based pagination. Use the `pageInfo` field from the response to implement cursor-based pagination. Navigate back and forward using the `prev` and `next` cursors. ```tsx title="Basic Pagination" import { useActivities, evmAddress, chainId, PageSize, type Cursor, } from "@aave/react"; import { useState } from "react"; function PaginatedActivities() { const [cursor, setCursor] = useState(); const { data, loading, error } = useActivities({ query: { chainIds: [chainId(1)] }, user: evmAddress("0x456…"), pageSize: PageSize.Ten, cursor, }); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; return (

Transaction History

{data.items.map((activity) => (

{activity.__typename}: {activity.txHash}

))}
); } ```
```ts title="Fetch All Activities" import { activities } from "@aave/client/actions"; import { evmAddress, chainId, PageSize, type Cursor } from "@aave/client"; import { client } from "./client"; let cursor: Cursor | undefined; const all = []; while (true) { const res = await activities(client, { query: { chainIds: [chainId(1)] }, user: evmAddress("0x456…"), pageSize: PageSize.Ten, cursor, }); if (!res.isOk()) throw res.error; const { items, pageInfo } = res.value; all.push(...items); cursor = pageInfo.next ?? undefined; if (!cursor) break; } console.log("Activities:", all); ``` ```jsonc title="Get Initial Page" { "request": { "query": { // your query criteria }, "user": "0x456…", "pageSize": "TEN" } } ```
In GraphQL, the response includes pagination information as follows. ```json title="Response with Pagination" { "data": { "activities": { "items": […], "pageInfo": { "prev": "abc123…", "next": "xyz789…" } } } } ``` In GraphQL, navigate to subsequent or previous pages using respectively the `next` or `prev` cursors from `pageInfo`. ```jsonc title="Fetch Next Page" { "request": { "query": { // your query criteria }, "user": "0x456…", "pageSize": "TEN", "cursor": "xyz789…" } } ``` ## Network Fees Fetch the network fee (gas cost) and its historical fiat value for a specific activity transaction. > [!NOTE] > This experimental hook works only with Viem or Wagmi integrations. Use the `useNetworkFee` hook to fetch the network fee for an activity by fetching the transaction receipt and converting the gas cost to both native and fiat amounts. ```tsx title="Viem" import { type ActivityItem, Currency } from "@aave/react"; import { useNetworkFee } from "@aave/react/viem"; function ActivityFee({ activity }: { activity: ActivityItem }) { const { data: fee, loading, error, } = useNetworkFee({ query: { activity }, currency: Currency.Eur, }); if (loading) return Loading fee…; if (error) return Error: {error.message}; return (

Network Fee: {fee.amount.value.toDisplayString(2)} {fee.token.info.symbol} ≈{fee.exchange.symbol} {fee.exchange.value.toDisplayString(2)}

); } ``` Like other declarative hooks, the `useNetworkFee` hook can be used in React Suspense mode and implements pausable mode. ```tsx title="Suspense Mode" const { data: fee } = useNetworkFee({ query: { activity }, currency: Currency.Eur, suspense: true, }); ``` ```tsx title="Pausable Mode" function ActivityFee({ activity, }: { activity: ActivityItem | null | undefined; }) { const { data: fee, paused } = useNetworkFee({ query: { activity, }, pause: !activity, }); // … } ``` --- Source: https://aave.com/docs/aave-v4/tools/exchange-rate.md # Aave V4 Exchange Rates Exchange rates in Aave are provided by [Oracles](../../ecosystem/oracle) using Chainlink price feeds. AaveKit provides current conversion rates between ERC-20 tokens, native tokens, and supported currencies: USD, EUR, and GBP. For smart-contract integrations, query USD reserve prices directly from the spoke oracle. ## Fetching Exchange Rates - **React**: Use the `useExchangeRate` hook for live exchange rates with automatic polling every 10 seconds, or the imperative `useExchangeRateAction` hook for on-demand exchange rates. - **TypeScript**: Use the `exchangeRate` action, and in GraphQL, the `exchangeRate` query to fetch conversion rates. ```tsx title="Loading State" import { type ExchangeRateRequest, useExchangeRate } from "@aave/react"; function ExchangeRate({ request }: { request: ExchangeRateRequest }) { const { data, loading, error } = useExchangeRate(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data: ExchangeAmount return ( {data.symbol} {data.value.toFixed(2)} ); } ``` ```tsx title="React Suspense" import { type ExchangeRateRequest, useExchangeRate } from "@aave/react"; function ExchangeRate({ request }: { request: ExchangeRateRequest }) { const { data } = useExchangeRate({ ...request, suspense: true, }); // data: ExchangeAmount return ( {data.symbol} {data.value.toFixed(2)} ); } ``` ```tsx title="Imperative Read" import { type ExchangeRateRequest, useExchangeRateAction } from "@aave/react"; // … const [fetch, { called, data, error, loading }] = useExchangeRateAction(); const handler = async (request: ExchangeRateRequest) => { const result = await fetch(request); if (result.isOk()) { console.log(result.value); // ExchangeAmount } else { console.error(result.error); } }; ```
```ts title="ERC-20 Token" import { exchangeRate } from "@aave/client/actions"; import { evmAddress, chainId, Currency } from "@aave/client"; import { client } from "./client"; const result = await exchangeRate(client, { from: { erc20: { chainId: chainId(1), address: evmAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), }, }, to: Currency.Usd, }); if (result.isOk()) { // result.value: ExchangeAmount console.log("Exchange rate:", result.value); } else { console.error("Error:", result.error); } ``` ```ts title="Native Token" import { exchangeRate } from "@aave/client/actions"; import { chainId, Currency } from "@aave/client"; import { client } from "./client"; const result = await exchangeRate(client, { from: { native: chainId(1), }, to: Currency.Usd, }); if (result.isOk()) { // result.value: ExchangeAmount console.log("Exchange rate:", result.value); } else { console.error("Error:", result.error); } ``` ```ts title="Fiat Currency" import { exchangeRate } from "@aave/client/actions"; import { Currency } from "@aave/client"; import { client } from "./client"; const result = await exchangeRate(client, { from: { fiat: Currency.Eur, }, to: Currency.Usd, }); if (result.isOk()) { // result.value: ExchangeAmount console.log("Exchange rate:", result.value); } else { console.error("Error:", result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql query ExchangeRate($request: ExchangeRateRequest!) { exchangeRate(request: $request) { value name symbol } } ```
Example request objects for React and GraphQL: ```tsx title="ERC-20 Token" import { evmAddress, chainId, Currency } from "@aave/react"; const request: ExchangeRateRequest = { from: { erc20: { chainId: chainId(1), address: evmAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), }, }, to: Currency.Usd, }; ``` ```tsx title="Native Token" import { chainId, Currency } from "@aave/react"; const request: ExchangeRateRequest = { from: { native: chainId(1), }, to: Currency.Usd, }; ``` ```tsx title="Fiat Currency" import { Currency } from "@aave/react"; const request: ExchangeRateRequest = { from: { fiat: Currency.Eur, }, to: Currency.Usd, }; ``` ```json title="ERC-20 Token" { "request": { "from": { "erc20": { "chainId": 1, "address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } }, "to": "USD" } } ``` ```json title="Native Token" { "request": { "from": { "native": 1 }, "to": "USD" } } ``` ```json title="Fiat Currency" { "request": { "from": { "fiat": "EUR" }, "to": "USD" } } ``` In Solidity, start with the spoke address: ```solidity title="Spoke Address" address spokeAddress = 0x123…; ``` Then, get the oracle address from the spoke and query the price. ```solidity title="Single Reserve Price" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; address oracleAddress = ISpoke(spokeAddress).ORACLE(); IAaveOracle oracle = IAaveOracle(oracleAddress); uint256 reserveId = 1; uint256 price = oracle.getReservePrice(reserveId); ``` ```solidity title="Batch Reserve Prices" import { ISpoke } from "aave-v4/src/spoke/interfaces/ISpoke.sol"; import { IAaveOracle } from "aave-v4/src/spoke/interfaces/IAaveOracle.sol"; address oracleAddress = ISpoke(spokeAddress).ORACLE(); IAaveOracle oracle = IAaveOracle(oracleAddress); uint256[] memory reserveIds = new uint256[](2); reserveIds[0] = 1; reserveIds[1] = 2; uint256[] memory prices = oracle.getReservesPrices(reserveIds); ``` --- Source: https://aave.com/docs/aave-v4/tools/swaps.md # Aave V4 Swap Features Alongside the [Position Swaps](../positions/swaps/supply) feature, AaveKit provides the following tools for swapping: - **[Swap Tokens](#swap-tokens):** exchange tokens instantly at market price or set conditions with a limit order. - **[Monitor Swap Status](#monitor-swap-status):** track the status of a swap order. - **[User Swaps](#user-swaps):** list and filter user orders. - **[Cancel a Swap](#cancel-a-swap):** cancel a swap order in progress. > [!WARNING] > The swap API is deprecated. Move to the Order API: > - `prepareTokenSwap` → `prepareOrder` > - `swap` → `submitOrder` > - `swapStatus` → `orderStatus` > - `userSwaps` → `pendingOrders` > - `prepareSwapCancel` → `prepareCancelOrder` > - `cancelSwap` → `cancelOrder` > - React: `useTokenSwap` → `useTokenSwapOrder` > - React: `useSwapStatus` → `useOrderStatus` > - React: `useUserSwaps` → `usePendingOrders` > - React: `useCancelSwap` → `useCancelOrder` Swaps are implemented using a modular provider architecture. Currently, [CoW Protocol](https://cow.fi/) is the swap provider, offering MEV protection and optimal execution through batch auctions. > [!NOTE] > See [fees](#fees) for swap costs. ## Swap Tokens Token swaps can be executed in two ways: - **Intent-based**: The swap is signed off-chain and submitted as an intent, which is then executed by a solver. This is the preferred method as it is gasless for users. - **Transaction-based**: The swap is executed directly on-chain via a transaction. This method is used when intent-based execution is not available. > [!NOTE] > Native token swaps are always transaction-based since users must send funds > directly. Swapping tokens involves the following steps: 1. Select the token to swap from 2. Select the token to swap to 3. Choose between market order and limit order 4. Execute the swap operation ### Source Token Fetch user token balances that can be swapped. This allows you to display only tokens the user owns that are swappable, making source token selection easier. Use the `useUserBalances` hook in React, the `userBalances` action in TypeScript, or the `userBalances` query in GraphQL with the `swappable` filter to list user tokens that can be swapped. ```tsx title="Loading State" import type { UserBalancesRequest, TokenAmount } from "@aave/react"; import { useUserBalances } from "@aave/react"; function SwapFromToken({ request, onSelect, }: { request: UserBalancesRequest; onSelect: (amount: TokenAmount) => void; }) { const { data, loading, error } = useUserBalances(request); if (loading) return Loading…; if (error) return {error.message}; return ( ); } ``` ```tsx title="React Suspense" import { type UserBalancesRequest, type TokenAmount, useUserBalances, } from "@aave/react"; function SwapFromToken({ request, onSelect, }: { request: UserBalancesRequest; onSelect: (amount: TokenAmount) => void; }) { const { data } = useUserBalances({ ...request, suspense: true, }); if (data.length === 0) return No swappable tokens found; return ( ); } ``` ```ts title="By Chain IDs" import { userBalances } from "@aave/client/actions"; import { evmAddress, chainId, OrderDirection } from "@aave/client"; import { client } from "./client"; const result = await userBalances(client, { user: evmAddress("0x456…"), filter: { swappable: { chainIds: [chainId(1)], }, }, orderBy: { balance: OrderDirection.Desc }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: UserBalance[] result.value.forEach((balance) => { console.log( `${balance.info.symbol}: ${balance.totalAmount.value.toDisplayString(2)}`, ); }); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: UserBalancesRequest!) { userBalances(request: $request) { info { __typename ... on Erc20Token { symbol name address chainId } ... on NativeToken { symbol name chainId } } balances { ...TokenAmount } totalAmount { value } } } ``` ```graphql title="TokenAmount" fragment TokenAmount on TokenAmount { __typename ... on Erc20Amount { amount { value } token { address chainId } } ... on NativeAmount { amount { value } token { chainId } } } ``` - **React**: You can query for swappable token balances as follows. - **GraphQL**: Use the `filter.swappable` field to filter by swappable tokens. ```tsx title="By Chain IDs" import { evmAddress, chainId, OrderDirection } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { swappable: { chainIds: [chainId(1)], }, }, orderBy: { balance: OrderDirection.Desc }, }; ``` ```tsx title="Include Zero Balances" import { evmAddress, chainId, OrderDirection } from "@aave/react"; const request: UserBalancesRequest = { user: evmAddress("0x456…"), filter: { swappable: { chainIds: [chainId(1)], }, }, orderBy: { balance: OrderDirection.Desc }, includeZeroBalances: true, }; ``` ```json title="By Chain IDs" { "request": { "user": "0x456…", "filter": { "swappable": { "chainIds": [1] } }, "orderBy": { "balance": "DESC" } } } ``` ```json title="Include Zero Balances" { "request": { "user": "0x456…", "filter": { "swappable": { "chainIds": [1] } }, "orderBy": { "balance": "DESC" }, "includeZeroBalances": true } } ``` > [!NOTE] > See [User Balances](./balances#fetching-user-balances) for filtering and > sorting. ### Destination Token Once you’ve selected a source token, fetch the tokens you can swap TO. This ensures you only display valid swap destinations for the selected source token. Use `useSwappableTokens` in React, `swappableTokens` in TypeScript, or the `swappableTokens` query in GraphQL to list destination tokens based on your selected source token. ```tsx title="Loading State" import type { SwappableTokensRequest, Token } from "@aave/react"; import { useSwappableTokens } from "@aave/react"; function SwapToToken({ request, onSelect, }: { request: SwappableTokensRequest; onSelect: (token: Token) => void; }) { const { data, loading, error } = useSwappableTokens(request); if (loading) return Loading…; if (error) return {error.message}; return ( ); } ``` ```tsx title="React Suspense" import type { SwappableTokensRequest, Token } from "@aave/react"; import { useSwappableTokens } from "@aave/react"; function SwapToToken({ request, onSelect, }: { request: SwappableTokensRequest; onSelect: (token: Token) => void; }) { const { data } = useSwappableTokens({ ...request, suspense: true, }); return ( ); } ``` ```ts title="By Chain IDs" import { chainId } from "@aave/client"; import { swappableTokens } from "@aave/client/actions"; import { client } from "./client"; const result = await swappableTokens(client, { query: { chainIds: [chainId(1)] }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: Token[] result.value.forEach((token) => { console.log(`Token: ${token.info.symbol} (${token.info.name})`); }); } ``` ```ts title="For Selected Source Token" import { chainId, evmAddress } from "@aave/client"; import { swappableTokens } from "@aave/client/actions"; import { client } from "./client"; const result = await swappableTokens(client, { query: { from: { erc20: { address: evmAddress("0xA0b86991…"), chainId: chainId(1) }, }, }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: Token[] result.value.forEach((token) => { console.log(`Token: ${token.info.symbol} (${token.info.name})`); }); } ``` ```ts title="By Specific Tokens" import { chainId, evmAddress } from "@aave/client"; import { swappableTokens } from "@aave/client/actions"; import { client } from "./client"; const result = await swappableTokens(client, { query: { tokens: [ { address: evmAddress("0xA0b86991…"), chainId: chainId(1) }, { address: evmAddress("0x6B175474E…"), chainId: chainId(1) }, ], }, }); if (result.isErr()) { console.error(result.error); } else { // result.value: Token[] result.value.forEach((token) => { console.log(`Token: ${token.info.symbol} (${token.info.name})`); }); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql query ($request: SwappableTokensRequest!) { swappableTokens(request: $request) { __typename ... on Erc20Token { ...Erc20Token } ... on NativeToken { ...NativeToken } } } ``` - **React**: You can query for a list of swappable tokens as follows. - **GraphQL**: Use the `query` field to select destination tokens by different criteria. ```tsx title="By Chain IDs" const request: SwappableTokensRequest = { query: { chainIds: [chainId(1)], }, }; ``` ```tsx title="For Selected Source Token" const request: SwappableTokensRequest = { query: { from: { erc20: { address: evmAddress("0xA0b86991…"), chainId: chainId(1) }, }, }, }; ``` ```tsx title="By Specific Tokens" const request: SwappableTokensRequest = { query: { tokens: [ { address: evmAddress("0xA0b86991…"), chainId: chainId(1) }, { address: evmAddress("0x6B175474E…"), chainId: chainId(1) }, ], }, }; ``` ```json title="By Chain IDs" { "request": { "query": { "chainIds": [1] } } } ``` ```json title="For Selected Source Token" { "request": { "query": { "from": { "erc20": { "address": "0xA0b86991…", "chainId": 1 } } } } } ``` ```json title="By Specific Tokens" { "request": { "query": { "tokens": [ { "address": "0xA0b86991…", "chainId": 1 }, { "address": "0x6B175474E…", "chainId": 1 } ] } } } ``` ### Market or Limit Order Once you’ve identified the tokens to swap, the next step is choosing an order type. Market orders execute immediately at the current rate, while limit orders wait until your specified price conditions are met. #### Market Orders To place a market order, specify the token pair, amount, and swap direction. ```ts title="TypeScript" const request: TokenSwapQuoteRequest = { market: { chainId: chainId(1), buy: { erc20: evmAddress("0xA0b86991…") }, sell: { erc20: evmAddress("0x6B175474E…") }, amount: bigDecimal("1000"), kind: TokenSwapKind.Buy, user: evmAddress("0x742d35cc…"), // Your address receiver: evmAddress("0x742d35cc…"), // In case the receiver is different from the user selectedSlippage: bigDecimal("2"), // 2% }, }; ``` ```jsonc title="GraphQL Variables" { "request": { "market": { "chainId": 1, "buy": { "erc20": "0xA0b86991…" }, "sell": { "erc20": "0x6B175474E…" }, "amount": "1000", "kind": "BUY", "user": "0x742d35cc…", // Your address "receiver": "0x742d35cc…", // In case the receiver is different from the user "selectedSlippage": "2" // 2% } } } ``` The request takes the following parameters: - `chainId`: The target chain - `sell`: The token to sell (`native` or `erc20`) - `buy`: The token to receive (`native` or `erc20`) - `amount`: The swap amount, interpreted based on `kind` - `kind`: `TokenSwapKind.Sell` or `TokenSwapKind.Buy`, required; determines how `amount` is interpreted - `user`: The sender address - `receiver`: The recipient address (defaults to `user`) - `selectedSlippage`: Optional slippage tolerance to use instead of the suggested slippage Since only one amount is provided, the swap kind determines what gets calculated: | Swap Kind | User inputs… | System calculates… | | --------- | ------------------------------------------------------------ | ------------------------------------------------ | | **Sell** | How much of the token to _sell_ and which token to _buy_ | The amount of the buy token you’ll receive | | **Buy** | How much of the token to _buy_ and which token to _sell_ | The amount of the sell token you need to provide | Depending on the token pair, swaps can be performed in different ways: ```ts title="Erc20 → Erc20" const request: TokenSwapQuoteRequest = { market: { chainId: chainId(1), buy: { erc20: evmAddress("0xA0b86991…") }, sell: { erc20: evmAddress("0x6B175474E…") }, amount: bigDecimal("1000"), kind: TokenSwapKind.Sell, user: evmAddress("0x742d35cc…"), // Your address }, }; ``` ```ts title="Native → Erc20" const request: TokenSwapQuoteRequest = { market: { chainId: chainId(1), sell: { native: true }, buy: { erc20: evmAddress("0x6B175474E…") }, amount: bigDecimal("1000"), kind: TokenSwapKind.Sell, user: evmAddress("0x742d35cc…"), // Your address }, }; ``` ```ts title="Erc20 → Native" const request: TokenSwapQuoteRequest = { market: { chainId: chainId(1), sell: { erc20: evmAddress("0x6B175474E…") }, buy: { native: true }, amount: bigDecimal("1000"), kind: TokenSwapKind.Sell, user: evmAddress("0x742d35cc…"), // Your address }, }; ``` #### Limit Orders To place a limit order, specify exact amounts for both the sell and buy tokens. ```ts title="TypeScript" const request: TokenSwapQuoteRequest = { limit: { chainId: chainId(1), sell: { erc20: { address: evmAddress("0x6B175474E…"), value: bigDecimal("1000"), }, }, buy: { erc20: { address: evmAddress("0xA0b86991…"), value: bigDecimal("1000"), }, }, user: evmAddress("0x742d35cc…"), receiver: evmAddress("0x742d35cc…"), // kind: TokenSwapKind.Buy, default is TokenSwapKind.Sell // previousQuoteId: quote.quoteId, if available }, }; ``` ```json title="GraphQL Variables" { "request": { "limit": { "chainId": 1, "sell": { "erc20": { "address": "0x6B175474E…", "value": "1000" } }, "buy": { "erc20": { "address": "0xA0b86991…", "value": "1000" } }, "user": "0x742d35cc…", "receiver": "0x742d35cc…", "kind": "SELL" } } } ``` The request takes the following parameters: - `chainId`: The target chain - `sell`: The token and amount to sell - `buy`: The token and amount to receive - `user`: The sender address - `receiver`: The recipient address (defaults to `user`) - `kind`: Sell (default) or Buy, determines which amount is honored - `previousQuoteId`: Optional quote ID from a prior market order - `deadline`: Optional deadline as DateTime; if not provided, uses default expiry With both amounts specified, the swap kind determines which amount takes priority: | Swap Kind | User specifies… | What happens with the order | | --------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | | **Sell** | The exact _sell_ amount and a minimum _buy_ amount | The order is fulfilled when the buy price is large enough to accommodate the user’s ask and the swap costs | | **Buy** | The exact _buy_ amount and a maximum _sell_ amount | The order is fulfilled when the sell price is small enough to accommodate the user’s desired buy and the swap costs | Depending on the token pair, limit orders can be configured in different ways: ```ts title="Erc20 → Erc20" const request: TokenSwapQuoteRequest = { limit: { chainId: chainId(1), sell: { erc20: { address: evmAddress("0x6B175474E…"), value: bigDecimal("1000"), }, }, buy: { erc20: { address: evmAddress("0xA0b86991…"), value: bigDecimal("950"), }, }, user: evmAddress("0x742d35cc…"), }, }; ``` ```ts title="Erc20 → Native" const request: TokenSwapQuoteRequest = { limit: { chainId: chainId(1), sell: { erc20: { address: evmAddress("0xA0b86991…"), value: bigDecimal("3000"), }, }, buy: { native: bigDecimal("1"), }, user: evmAddress("0x742d35cc…"), }, }; ``` > [!NOTE] > Limit orders from native tokens are currently not supported via CoW Protocol > to avoid holding user funds. ### Execute Swaps To execute the swap operation with AaveKit, follow these steps. #### 1. Get a Swap Quote First, use the `useTokenSwapQuote` hook (or the imperative `useTokenSwapQuoteAction` variant) in React, the `tokenSwapQuote` action in TypeScript, or the `tokenSwapQuote` query in GraphQL to get a swap quote. The quote’s `orderQuoteId` is the ID you pass to the Order API. ```tsx title="Loading State" import { type TokenSwapQuoteRequest, useTokenSwapQuote } from "@aave/react"; function DisplayQuote({ request }: { request: TokenSwapQuoteRequest }) { const { data, loading, error } = useTokenSwapQuote(request); if (loading) return Loading…; if (error) { if (error.name === "ValidationError") { switch (error.cause.__typename) { case "InsufficientLiquidityError": return Not enough liquidity for this swap; } } return {error.message}; } return (

Swap Quote

{data.quoteId}

Suggested slippage: {data.suggestedSlippage.normalized.toFixed(2)}% Network costs: {data.costs.networkCosts.amount.value.toDisplayString(2)}
); } ``` ```tsx title="React Suspense" import { type TokenSwapQuoteRequest, useTokenSwapQuote } from "@aave/react"; function DisplayQuote({ request }: { request: TokenSwapQuoteRequest }) { const { data } = useTokenSwapQuote({ ...request, suspense: true, }); if (!data) return No quote found; return (

Swap Quote

{data.quoteId}

Suggested slippage: {data.suggestedSlippage.normalized.toFixed(2)}% Network costs: {data.costs.networkCosts.amount.value.toDisplayString(2)}
); } ``` ```tsx title="Imperative Read" import { type TokenSwapQuoteRequest, useTokenSwapQuoteAction, } from "@aave/react"; // … const [getQuote, { called, data, error, loading }] = useTokenSwapQuoteAction(); const handler = async (request: TokenSwapQuoteRequest) => { const result = await getQuote(request); if (result.isOk()) { console.log(result.value); // SwapQuote } else { console.error(result.error); } }; ```
```ts title="Get Quote" import { tokenSwapQuote } from "@aave/client/actions"; import { client } from "./client"; // … const result = await tokenSwapQuote(client, request); if (result.isErr()) { console.error(result.error); return; } // result.value.quote: SwapQuote ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: TokenSwapQuoteRequest!, $currency: Currency = USD) { tokenSwapQuote(request: $request) { __typename ... on SwapByIntent { ...SwapByIntent } ... on SwapByIntentWithApprovalRequired { ...SwapByIntentWithApprovalRequired } ... on SwapByTransaction { ...SwapByTransaction } ... on SwapByTransactionWithApprovalRequired { ...SwapByTransactionWithApprovalRequired } ... on InsufficientLiquidityError { reason } } } ``` ```graphql title="SwapByIntent" fragment SwapByIntent on SwapByIntent { __typename quote { ...SwapQuote } } ``` ```graphql title="SwapByIntentWithApprovalRequired" fragment SwapByIntentWithApprovalRequired on SwapByIntentWithApprovalRequired { __typename approvals { ...Erc20Approval } quote { ...SwapQuote } } ``` ```graphql title="SwapByTransaction" fragment SwapByTransaction on SwapByTransaction { __typename quote { ...SwapQuote } } ``` ```graphql title="SwapByTransactionWithApprovalRequired" fragment SwapByTransactionWithApprovalRequired on SwapByTransactionWithApprovalRequired { __typename quote { ...SwapQuote } approvals { ...Erc20Approval } } ``` ```graphql title="SwapQuote" fragment SwapQuote on SwapQuote { __typename accuracy quoteId suggestedSlippage { ...PercentNumber } selectedSlippage { ...PercentNumber } buy { ...TokenAmount } sell { ...TokenAmount } costs { __typename networkCosts { ...TokenAmount } partnerFee { ...TokenAmount } flashloanFee { ...TokenAmount } providerFee { ...TokenAmount } } finalBuy { ...TokenAmount } finalSell { ...TokenAmount } orderQuoteId } ```
> [!NOTE] > `useTokenSwapQuoteAction` doesn’t watch for updates. Use it for on-demand > fresh data, such as in an event handler. You can specify a different currency to return fiat amounts in. ```tsx title="Declarative Read" import { Currency } from "@aave/react"; const { data, error, loading } = useTokenSwapQuote({ ...request, currency: Currency.Eur, }); ``` ```tsx title="Imperative Read" import { Currency } from "@aave/react"; const [getQuote, { called, data, error, loading }] = useTokenSwapQuoteAction({ currency: Currency.Eur, }); ``` ```ts title="Custom Currency" import { Currency } from "@aave/client"; // … const result = await tokenSwapQuote(client, request, { currency: Currency.Eur, }); ``` ```json title="Custom Currency" { "request": { "market": { "chainId": 1, "buy": { "erc20": "0xA0b86991…" }, "sell": { "native": true }, "amount": "1000", "kind": "SELL", "user": "0x742d35cc…" } }, "currency": "EUR" } ``` > [!NOTE] > For limit orders, fetch a market quote first and use its `buy` and `sell` > values as a baseline. In GraphQL, `kind` works as described in [Market Orders](#market-orders). In GraphQL, depending on the token pair, swaps can be performed in different ways: ```jsonc title="Erc20 → Erc20" { "request": { "market": { "chainId": 1, "buy": { "erc20": "0xA0b86991…" }, "sell": { "erc20": "0x6B175474E…" }, "amount": "1000", "kind": "SELL", // SELL, BUY (see table above) "user": "0x742d35cc…" } } } ``` ```jsonc title="Native → Erc20" { "request": { "market": { "chainId": 1, "sell": { "native": true }, "buy": { "erc20": "0xA0b86991…" }, "amount": "1000", "kind": "BUY", // SELL, BUY (see table above) "user": "0x742d35cc…" } } } ``` ```jsonc title="Erc20 → Native" { "request": { "market": { "chainId": 1, "sell": { "erc20": "0xA0b86991…" }, "buy": { "native": true }, "amount": "1000", "kind": "SELL", // SELL, BUY (see table above) "user": "0x742d35cc…" } } } ``` #### 2. Configure Wallet Integration Then, in React, instantiate the hooks for the [wallet library of your choice](../getting-started/react#integrations): - `useSendTransaction`: used to send ERC-20 approval and swap transactions when needed - `useSignTypedData`: used to sign ERC-20 permits and swap order typed data ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData] = useSignTypedData(wallet); ``` #### 3. Define the Swap Flow Then, in React, use the `useTokenSwapOrder` hook to handle the operation. It fetches the quote, handles any ERC-20 approval, and prepares, signs, and submits the order. ```tsx title="Basic Usage" import { useTokenSwapOrder } from "@aave/react"; // … const [swap, { loading, error }] = useTokenSwapOrder((plan) => { switch (plan.__typename) { case "Erc20Approval": if (plan.bySignature) { return signTypedData(plan.bySignature); } return sendTransaction(plan.byTransaction); case "OrderTransactionRequest": return sendTransaction(plan.transaction); case "OrderTypedData": return signTypedData(plan); } }); ``` ```tsx title="Update Component State" import { useTokenSwapOrder } from "@aave/react"; // … const [status, setStatus] = useState(""); const [swap, { loading, error }] = useTokenSwapOrder((plan) => { switch (plan.__typename) { case "Erc20Approval": setStatus("Please approve the token in your wallet"); if (plan.bySignature) { return signTypedData(plan.bySignature).andTee(() => setStatus("Signing permit…"), ); } return sendTransaction(plan.byTransaction).andTee(() => setStatus("Approving…"), ); case "OrderTransactionRequest": setStatus("Please sign the Swap transaction in your wallet"); return sendTransaction(plan.transaction).andTee(() => setStatus("Swapping…"), ); case "OrderTypedData": setStatus("Please sign the Swap Order in your wallet"); return signTypedData(plan).andTee(() => setStatus("Signing…")); } }); ``` ```tsx title="Cancel Flow" import { useTokenSwapOrder } from "@aave/react"; // … const [swap, { loading, error }] = useTokenSwapOrder((plan, { cancel }) => { if (window.confirm("Are you sure you want to continue?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "Erc20Approval": if (plan.bySignature) { return signTypedData(plan.bySignature); } return sendTransaction(plan.byTransaction); case "OrderTransactionRequest": return sendTransaction(plan.transaction); case "OrderTypedData": return signTypedData(plan); } }); ``` #### 4. Handle Approvals Then, in TypeScript, using helpers from the [wallet library of your choice](../getting-started/typescript#integrations), use `signTypedDataWith` and `sendWith` to handle ERC-20 approvals, and `prepareOrder` with `signTypedDataWith` to sign intent-based swap orders. Each branch resolves to a `SubmitOrderRequest` for the next step. ```ts title="Handle Approvals" import { tokenSwapQuote } from "@aave/client/actions"; import { client } from "./client"; import { handleApprovals } from "./handleApprovals"; // … const result = await tokenSwapQuote(client, request) // .andThen(handleApprovals); ``` ```ts title="handleApprovals.ts" import { type TokenSwapQuoteResult, okAsync } from "@aave/client"; import { signTypedDataWith, sendWith } from "@aave/client/viem"; import { wallet } from "./wallet"; import { signSwapOrder } from "./signSwapOrder"; // … export function handleApprovals(result: TokenSwapQuoteResult) { switch (result.__typename) { case "SwapByTransaction": return okAsync({ byTransaction: { quoteId: result.quote.orderQuoteId }, }); case "SwapByTransactionWithApprovalRequired": return result.approvals .reduce( (acc, approval) => acc.andThen(() => sendWith(wallet, approval.byTransaction)), okAsync(undefined), ) .map(() => ({ byTransaction: { quoteId: result.quote.orderQuoteId }, })); case "SwapByIntent": return signSwapOrder({ quoteId: result.quote.orderQuoteId }); case "SwapByIntentWithApprovalRequired": // Permit-based approval (only available for single approval) if (result.approvals.length === 1 && result.approvals[0].bySignature) { const permitTypedData = result.approvals[0].bySignature; return signTypedDataWith(wallet, permitTypedData) .map((signature) => ({ deadline: permitTypedData.message.deadline, value: signature, })) .andThen((permitSig) => signSwapOrder({ quoteId: result.quote.orderQuoteId, permitSig }), ); } // Transaction-based approval (handles multiple approvals for USDT-like tokens) return result.approvals .reduce( (acc, approval) => acc.andThen(() => sendWith(wallet, approval.byTransaction)), okAsync(undefined), ) .andThen(() => signSwapOrder({ quoteId: result.quote.orderQuoteId })); case "InsufficientLiquidityError": throw new Error(`Insufficient liquidity: ${result.reason}`); } } ``` ```ts title="signSwapOrder.ts" import type { PrepareOrderRequest } from "@aave/client"; import { prepareOrder } from "@aave/client/actions"; import { signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; export function signSwapOrder(request: PrepareOrderRequest) { return prepareOrder(client, request).andThen(({ newQuoteId, data }) => signTypedDataWith(wallet, data).map((signature) => ({ bySignature: { quoteId: newQuoteId, signature }, })), ); } ``` ```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(), }); ``` > [!NOTE] > For tokens that need an allowance reset, like [USDT on Ethereum > Mainnet](https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7), > `sendWith` sends both approvals before the swap: reset to 0, then the new > allowance. #### 5. Handle Swap Quote Response In GraphQL, depending on the `TokenSwapQuoteResult` type, you’ll need to follow different actions: | Response Type | Action | | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `SwapByIntent` | Pass the `quote.orderQuoteId` to the `prepareOrder` query. | | `SwapByIntentWithApprovalRequired` | Send each transaction in `approvals` from the `user` account, then pass the `quote.orderQuoteId` to `prepareOrder`. | | `SwapByTransaction` | Keep a note of the `quote.orderQuoteId`. | | `SwapByTransactionWithApprovalRequired` | Send each transaction from `approvals` in sequence, then keep a note of the `quote.orderQuoteId`. | | `InsufficientLiquidityError` | Not enough liquidity available for this swap. Display the error to the user or suggest a smaller amount. | Below are examples illustrating the response for each response type. ```jsonc title="SwapByIntent" { "data": { "tokenSwapQuote": { "__typename": "SwapByIntent", "quote": { "orderQuoteId": "0x8f3…" // … } } } } ``` ```jsonc title="SwapByIntentWithApprovalRequired" { "data": { "tokenSwapQuote": { "__typename": "SwapByIntentWithApprovalRequired", "approvals": [ { // … } ], "quote": { "orderQuoteId": "0x8f3…" // … } } } } ``` ```jsonc title="SwapByTransaction" { "data": { "tokenSwapQuote": { "__typename": "SwapByTransaction", "quote": { "orderQuoteId": "0x8f3…" // … } } } } ``` ```jsonc title="SwapByTransactionWithApprovalRequired" { "data": { "tokenSwapQuote": { "__typename": "SwapByTransactionWithApprovalRequired", "approvals": [ { // … } ], "quote": { "orderQuoteId": "0x8f3…" // … } } } } ``` ```json title="InsufficientLiquidityError" { "data": { "tokenSwapQuote": { "__typename": "InsufficientLiquidityError", "reason": "Not enough liquidity available for this swap amount" } } } ``` #### 6. Prepare the Swap Then, in GraphQL, use the `prepareOrder` query to prepare the swap order. ```graphql title="Query" query ($request: PrepareOrderRequest!) { prepareOrder(request: $request) { __typename ... on PreparedOrder { ...PreparedOrder } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="PreparedOrder" fragment PreparedOrder on PreparedOrder { __typename newQuoteId data { ...OrderTypedData } } ``` ```graphql title="OrderTypedData" fragment OrderTypedData on OrderTypedData { __typename types primaryType domain { ...DomainData } message } ``` Define `PrepareOrderRequest` taking the `quote.orderQuoteId` from the previous step and the permit signature when needed. ```json title="QuoteId" { "request": { "quoteId": "" } } ``` ```json title="QuoteId and Signature" { "request": { "quoteId": "", "permitSig": { "value": "", "deadline": } } } ``` #### 7. Handle Prepare Swap Response In GraphQL, depending on the `PrepareOrderResult` type, you’ll need to follow different actions: | Response Type | Action | | ---------------------------- | ----------------------------------------------------------------------- | | `PreparedOrder` | Sign the typed data with the account performing the swap. | | `InsufficientBalanceError` | Notify the user that their balance is insufficient to perform the swap. | Below are examples illustrating the response for each response type. ```jsonc title="PreparedOrder" { "data": { "prepareOrder": { "__typename": "PreparedOrder", "newQuoteId": "0x8f3…", "data": { // … } } } } ``` ```json title="Error" { "data": { "prepareOrder": { "__typename": "InsufficientBalanceError", "required": { "value": "150.000000", "decimals": 6 }, "available": { "value": "75.500000", "decimals": 6 } } } } ``` #### 8. Execute the Swap Then, execute the swap. In React, the approach differs based on order type: market orders execute immediately at current prices, while limit orders let you set specific price conditions. For market orders, call `swap` with the `quoteId` from the last market order quote. ```tsx title="Basic Usage" const execute = async (quote: SwapQuote) => { const result = await swap({ fromQuote: { quoteId: quote.quoteId, }, }); if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value); }; ``` For limit orders, call `swap` with a `limit` request that includes the `previousQuoteId` from the last swap quote. ```tsx title="Execute Limit Order Request" const execute = async ({ limit }: TokenSwapQuoteRequest) => { const result = await swap({ limit: { ...limit, previousQuoteId: quote.quoteId, // from prior market order quote }, }); if (result.isErr()) { console.error(result.error); return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value); }; ``` - **TypeScript**: Use the `submitOrder` action to submit the swap order. For transaction-based swaps, use the `sendWith` helper to send the transaction. - **GraphQL**: Submit the swap order using the `submitOrder` mutation. ```ts title="Execute Swap" import { okAsync } from "@aave/client"; import { submitOrder, tokenSwapQuote } from "@aave/client/actions"; import { sendWith } from "@aave/client/viem"; import { client } from "./client"; import { handleApprovals } from "./handleApprovals"; import { wallet } from "./wallet"; const result = await tokenSwapQuote(client, request) .andThen(handleApprovals) .andThen((request) => submitOrder(client, request)) .andThen((plan) => { switch (plan.__typename) { case "OrderReceipt": return okAsync(plan); case "OrderTransactionRequest": return sendWith(wallet, plan.transaction).map(() => plan.orderReceipt); } }); // … ``` ```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="Mutation" mutation ($request: SubmitOrderRequest!) { submitOrder(request: $request) { __typename ... on OrderTransactionRequest { ...OrderTransactionRequest } ... on OrderReceipt { ...OrderReceipt } ... on InsufficientBalanceError { ...InsufficientBalanceError } } } ``` ```graphql title="OrderTransactionRequest" fragment OrderTransactionRequest on OrderTransactionRequest { __typename transaction { ...TransactionRequest } orderReceipt { ...OrderReceipt } } ``` ```graphql title="OrderReceipt" fragment OrderReceipt on OrderReceipt { __typename orderId } ``` For intent swaps, pass the `newQuoteId` from `prepareOrder` and the signature in `bySignature`. For transaction swaps, pass the `quote.orderQuoteId` from `tokenSwapQuote` in `byTransaction`. ```json title="Swap Intent" { "request": { "bySignature": { "quoteId": "", "signature": "0x456…" } } } ``` ```json title="Swap Transaction" { "request": { "byTransaction": { "quoteId": "" } } } ``` #### 9. Handle the Result Finally, handle the result. ```tsx title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; case "SigningError": console.error(`Failed to sign: ${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 "ValidationError": switch (result.error.cause.__typename) { case "InsufficientBalanceError": console.error( `Insufficient balance: ${result.error.cause.required.value.toDisplayString(2)} required.`, ); break; case "InsufficientLiquidityError": console.error(`Insufficient liquidity: ${result.error.cause.reason}`); break; } break; case "UnexpectedError": console.error(result.error.message); break; } return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` ```ts title="Handle Result" // … if (result.isErr()) { switch (result.error.name) { case "CancelError": console.error("Operation cancelled by user wallet"); break; case "SigningError": console.error("Signing failed:", result.error.message); break; case "TransactionError": console.error("Transaction failed:", result.error.message); break; case "ValidationError": switch (result.error.cause.__typename) { case "InsufficientBalanceError": console.error( `Insufficient balance: ${result.error.cause.required.value.toDisplayString(2)} required.`, ); break; case "InsufficientLiquidityError": console.error(`Insufficient liquidity: ${result.error.cause.reason}`); break; } break; case "UnexpectedError": console.error("Unexpected error:", result.error.message); break; } return; } // result.value: OrderReceipt console.log("Swap order placed:", result.value.orderId); ``` In GraphQL, depending on the `OrderExecutionPlan` type, you’ll need to follow different actions: | Response Type | Action | | ---------------------------- | ----------------------------------------------------------------------- | | `OrderTransactionRequest` | Send the transaction with the account performing the swap. | | `OrderReceipt` | The swap order has been placed. | | `InsufficientBalanceError` | Notify the user that their balance is insufficient to perform the swap. | Below are examples illustrating the response for each response type. ```jsonc title="OrderTransactionRequest" { "data": { "submitOrder": { "__typename": "OrderTransactionRequest", "transaction": { // … }, "orderReceipt": { "__typename": "OrderReceipt", "orderId": "0x123…" } } } } ``` ```json title="OrderReceipt" { "data": { "submitOrder": { "__typename": "OrderReceipt", "orderId": "0x123…" } } } ``` ```json title="Error" { "data": { "submitOrder": { "__typename": "InsufficientBalanceError", "required": { "value": "150.000000", "decimals": 6 }, "available": { "value": "75.500000", "decimals": 6 } } } } ``` You placed your first swap order. Keep track of its status in the [Monitor Swap Status](#monitor-swap-status) section. ## Monitor Swap Status Once the swap order is submitted, an `OrderReceipt` object is returned with an `orderId` field. Use this `orderId` to track the order status. For more details, see the [Execute Swaps](#execute-swaps) section. - **React**: Use the `useOrderStatus` hook to monitor the status of an order in real-time. - **TypeScript**: Use the `orderStatus` action to check the current status of an order, or `waitForOrderOutcome` to poll until it reaches a terminal state. - **GraphQL**: Use the `orderStatus` query to track the order status. ```tsx title="Loading State" import { useOrderStatus, type OrderReceipt } from "@aave/react"; function MonitorSwap({ orderReceipt }: { orderReceipt: OrderReceipt }) { const { data, loading, error } = useOrderStatus({ id: orderReceipt.orderId, }); if (loading) return Monitoring swap…; if (error) return Error: {error.message}; switch (data.__typename) { case "OrderOpen": return Swap is open, waiting for execution…; case "OrderPendingSignature": return Waiting for signature…; case "OrderFulfilled": return (
Swap completed successfully! View transaction
); case "OrderCancelled": return Swap was cancelled at {data.cancelledAt}; case "OrderExpired": return Swap expired at {data.expiredAt}; } } ``` ```tsx title="React Suspense" import { useOrderStatus, type OrderReceipt } from "@aave/react"; function MonitorSwap({ orderReceipt }: { orderReceipt: OrderReceipt }) { const { data } = useOrderStatus({ id: orderReceipt.orderId, suspense: true, }); switch (data.__typename) { case "OrderOpen": return Swap is open, waiting for execution…; case "OrderPendingSignature": return Waiting for signature…; case "OrderFulfilled": return (
Swap completed successfully! View transaction
); case "OrderCancelled": return Swap was cancelled at {data.cancelledAt}; case "OrderExpired": return Swap expired at {data.expiredAt}; } } ```
```ts title="Check Status" import { orderStatus } from "@aave/client/actions"; import { client } from "./client"; const result = await orderStatus(client, { id: orderReceipt.orderId }); if (result.isErr()) { console.error(result.error); } else { // result.value: OrderStatus | null switch (result.value?.__typename) { case "OrderOpen": console.log("Swap is open, waiting for execution…"); break; case "OrderPendingSignature": console.log("Waiting for signature…"); break; case "OrderFulfilled": console.log("Swap completed:", result.value.txHash); break; case "OrderCancelled": console.log("Swap was cancelled:", result.value.cancelledAt); break; case "OrderExpired": console.log("Swap expired:", result.value.expiredAt); break; } } ``` ```ts title="Poll Until Terminal State" import { waitForOrderOutcome } from "@aave/client/actions"; import { client } from "./client"; const result = await waitForOrderOutcome(client)(orderReceipt); // result.value: OrderFulfilled | OrderCancelled | OrderExpired ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { orderStatus(request: { id: "" }) { __typename ... on OrderOpen { ...OrderOpen } ... on OrderPendingSignature { ...OrderPendingSignature } ... on OrderCancelled { ...OrderCancelled } ... on OrderExpired { ...OrderExpired } ... on OrderFulfilled { ...OrderFulfilled } } } ```
In React, the hook automatically polls for status updates until the order reaches a terminal state: fulfilled, cancelled, or expired. In GraphQL, the `OrderStatus` object can be one of the following: ```graphql title="OrderOpen" fragment OrderOpen on OrderOpen { __typename orderId createdAt deadline explorerUrl operation { ...OrderOperation } } ``` ```graphql title="OrderPendingSignature" fragment OrderPendingSignature on OrderPendingSignature { __typename orderId createdAt deadline explorerUrl operation { ...OrderOperation } } ``` ```graphql title="OrderCancelled" fragment OrderCancelled on OrderCancelled { __typename orderId createdAt cancelledAt explorerUrl operation { ...OrderOperation } } ``` ```graphql title="OrderExpired" fragment OrderExpired on OrderExpired { __typename orderId createdAt expiredAt explorerUrl operation { ...OrderOperation } } ``` ```graphql title="OrderFulfilled" fragment OrderFulfilled on OrderFulfilled { __typename orderId createdAt fulfilledAt txHash explorerUrl operation { ...OrderOperation } } ``` ```graphql title="OrderOperation" fragment OrderOperation on OrderOperation { __typename ... on TokenSwap { sell { ...TokenAmount } buy { ...TokenAmount } kind orderClass } ... on SupplySwap { sell { ...PositionAmount } buy { ...PositionAmount } kind orderClass } ... on BorrowSwap { sell { ...PositionAmount } buy { ...PositionAmount } kind orderClass } ... on RepayWithSupply { repay { ...PositionAmount } supply { ...PositionAmount } kind orderClass } ... on WithdrawSwap { withdraw { ...PositionAmount } buy { ...TokenAmount } kind orderClass } ... on Leverage { collateral { ...PositionAmount } debt { ...PositionAmount } multiplier } } ``` ## User Swaps List and filter user orders with built-in pagination support. Use the `usePendingOrders` hook in React, the `pendingOrders` action in TypeScript, or the `pendingOrders` query in GraphQL to list user orders. Use `filterBy` to narrow the list by order status. ```tsx title="Loading State" import { usePendingOrders, type PendingOrdersRequest } from "@aave/react"; function ListUserOrders({ request }: { request: PendingOrdersRequest }) { const { data, loading, error } = usePendingOrders(request); if (loading) return
Loading…
; if (error) return
Error: {error.message}
; // data.items: Array return (

User Orders

{data.items.map((order) => (

Status - {order.__typename} - {order.explorerUrl}

))}
); } ``` ```tsx title="React Suspense" import { usePendingOrders, type PendingOrdersRequest } from "@aave/react"; function ListUserOrders({ request }: { request: PendingOrdersRequest }) { const { data } = usePendingOrders({ ...request, suspense: true, }); if (data.items.length === 0) return
No orders found
; return (

User Orders

{data.items.map((order) => (

Status - {order.__typename} - {order.explorerUrl}

))}
); } ```
```ts title="Basic Usage" import { chainId, evmAddress } from "@aave/client"; import { pendingOrders } from "@aave/client/actions"; import { client } from "./client"; const result = await pendingOrders(client, { chainId: chainId(1), user: evmAddress("0x742d35cc…"), }); if (result.isErr()) { console.error(result.error); } ``` ```ts title="Filter by Status" import { chainId, evmAddress, OrderStatusFilter } from "@aave/client"; import { pendingOrders } from "@aave/client/actions"; import { client } from "./client"; const result = await pendingOrders(client, { chainId: chainId(1), user: evmAddress("0x742d35cc…"), filterBy: [OrderStatusFilter.Open, OrderStatusFilter.PendingSignature], }); if (result.isErr()) { console.error(result.error); } ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query ($request: PendingOrdersRequest!) { pendingOrders(request: $request) { __typename items { ...OrderStatus } pageInfo { next prev } } } ``` ```graphql title="OrderStatus" fragment OrderStatus on OrderStatus { __typename ... on OrderOpen { ...OrderOpen } ... on OrderPendingSignature { ...OrderPendingSignature } ... on OrderCancelled { ...OrderCancelled } ... on OrderExpired { ...OrderExpired } ... on OrderFulfilled { ...OrderFulfilled } } ```
In React, the hook automatically polls for status updates until all listed orders reach a terminal state: fulfilled, cancelled, or expired. The `OrderStatus` fragments are listed under [Monitor Swap Status](#monitor-swap-status). - **React**: You can filter orders as follows. - **GraphQL**: The `PendingOrdersRequest` object should be defined as follows. ```tsx title="By Chain ID" import { evmAddress, chainId } from "@aave/react"; const request: PendingOrdersRequest = { user: evmAddress("0x742d35cc…"), chainId: chainId(1), }; ``` ```tsx title="By Status" import { evmAddress, chainId, OrderStatusFilter } from "@aave/react"; const request: PendingOrdersRequest = { user: evmAddress("0x742d35cc…"), chainId: chainId(1), filterBy: [OrderStatusFilter.Fulfilled, OrderStatusFilter.Cancelled], }; ``` ```json title="Basic Request" { "request": { "chainId": 1, "user": "0x742d35cc…" } } ``` ```json title="Request with Status Filter" { "request": { "chainId": 1, "user": "0x742d35cc…", "filterBy": ["FULFILLED"] } } ``` ## Cancel a Swap Before cancelling, identify the swap order by its status. > [!NOTE] > Only orders with status `OrderOpen` or `OrderPendingSignature` can be > cancelled. Pick the `OrderOpen` item (`order`) to cancel. ```ts title="User Orders" const orderItems: OrderStatus[] = [ { __typename: "OrderOpen", orderId: "0x123…", // … }, { __typename: "OrderPendingSignature", // … }, { __typename: "OrderCancelled", // … }, { __typename: "OrderExpired", // … }, { __typename: "OrderFulfilled", // … }, ]; ``` After identifying the order, follow the steps below to cancel it with AaveKit. ### 1. Configure Wallet Integration First, in React, instantiate the `useSendTransaction` and `useSignTypedData` hooks for the [wallet library of your choice](../getting-started/react#integrations). ```tsx title="Viem" import { useWalletClient } from "wagmi"; import { useSendTransaction, useSignTypedData } from "@aave/react/viem"; // … const { data: wallet } = useWalletClient(); const [sendTransaction] = useSendTransaction(wallet); const [signTypedData, signing] = useSignTypedData(wallet); ``` ### 2. Define the Cancel Flow Then, in React, use the `useCancelOrder` hook to prepare the cancel order operation. The hook checks the order status first, then prepares, signs, and submits the cancellation. ```tsx title="Basic Usage" import { useCancelOrder } from "@aave/react"; const [cancelOrder, { loading, error }] = useCancelOrder((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "OrderTypedData": return signTypedData(plan); } }); ``` ```tsx title="Update Component State" import { useCancelOrder } from "@aave/react"; const [status, setStatus] = useState(""); const [cancelOrder, { loading, error }] = useCancelOrder((plan) => { switch (plan.__typename) { case "TransactionRequest": setStatus("Please send the Cancel Order transaction in your wallet"); return sendTransaction(plan).andTee(() => setStatus("Cancelling…")); case "OrderTypedData": setStatus("Please sign the Cancel Order data in your wallet"); return signTypedData(plan).andTee(() => setStatus("Cancelling…")); } }); ``` ```tsx title="Cancel Flow" import { useCancelOrder } from "@aave/react"; const [cancelOrder, { loading, error }] = useCancelOrder((plan, { cancel }) => { if (window.confirm("Are you sure you want to cancel the swap?") === false) { return cancel("User cancelled the operation"); } switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "OrderTypedData": return signTypedData(plan); } }); ``` ### 3. Prepare Cancel Swap - **TypeScript**: Prepare the cancel typed data with `prepareCancelOrder`. - **GraphQL**: Use the `prepareCancelOrder` query to prepare the cancel. ```ts title="Prepare Cancel Swap" import { prepareCancelOrder } from "@aave/client/actions"; import { client } from "./client"; const result = await prepareCancelOrder(client, { id: order.orderId, }); ``` ```ts title="client.ts" import { AaveClient } from "@aave/client"; export const client = AaveClient.create(); ``` ```graphql title="Query" query { prepareCancelOrder(request: { id: "" }) { __typename data { ...OrderTypedData } } } ``` ```graphql title="OrderTypedData" fragment OrderTypedData on OrderTypedData { __typename types primaryType domain { ...DomainData } message } ``` - **TypeScript**: Use `signTypedDataWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to sign the typed data in `result.data`. - **GraphQL**: Sign the `data` of the `PrepareCancelOrderResult` response with the account that placed the order. ```ts title="Sign Cancel Swap" import { prepareCancelOrder } from "@aave/client/actions"; import { signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await prepareCancelOrder(client, { id: order.orderId, }).andThen((prepared) => signTypedDataWith(wallet, prepared.data)); if (result.isErr()) { console.error(result.error); } ``` ```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(), }); ``` ```jsonc title="PrepareCancelOrderResult" { "data": { "prepareCancelOrder": { "__typename": "PrepareCancelOrderResult", "data": { // … } } } } ``` ### 4. Execute Cancel Swap Then, execute the cancel order operation. - **TypeScript**: Execute the cancel with the `cancelOrder` action. - **GraphQL**: Use the `cancelOrder` mutation to execute the cancel. ```tsx title="Cancel Swap" const execute = async () => { const result = await cancelOrder({ id: order.orderId, }); }; ``` ```ts title="Execute Cancel Swap" import { prepareCancelOrder, cancelOrder } from "@aave/client/actions"; import { signTypedDataWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await prepareCancelOrder(client, { id: order.orderId, }) .andThen((prepared) => signTypedDataWith(wallet, prepared.data)) .andThen((signature) => cancelOrder(client, { bySignature: { id: order.orderId, signature, }, }), ); ``` ```graphql title="Query" mutation ($request: CancelOrderRequest!) { cancelOrder(request: $request) { __typename ... on TransactionRequest { ...TransactionRequest } ... on OrderCancelledResult { ...OrderCancelledResult } } } ``` ```graphql title="OrderCancelledResult" fragment OrderCancelledResult on OrderCancelledResult { __typename orderId } ``` In TypeScript, use `sendWith` for the [wallet library of your choice](../getting-started/typescript#integrations) to send transactions in the plan. ```ts title="Send Transaction" import { okAsync } from "@aave/client"; import { prepareCancelOrder, cancelOrder, waitForOrderOutcome, } from "@aave/client/actions"; import { signTypedDataWith, sendWith } from "@aave/client/viem"; import { client } from "./client"; import { wallet } from "./wallet"; const result = await prepareCancelOrder(client, { id: order.orderId, }) .andThen((prepared) => signTypedDataWith(wallet, prepared.data)) .andThen((signature) => cancelOrder(client, { bySignature: { id: order.orderId, signature, }, }), ) .andThen((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendWith(wallet, plan).andThen(() => waitForOrderOutcome(client)({ __typename: "OrderReceipt", orderId: order.orderId, }), ); case "OrderCancelledResult": return okAsync(plan); } }); ``` In GraphQL, the `CancelOrderRequest` object takes the signed typed data from the `prepareCancelOrder` query in `bySignature`, or the order ID in `byTransaction`. ```json title="Cancel Swap Intent" { "request": { "bySignature": { "id": "", "signature": "0x456…" } } } ``` ```json title="Cancel Swap Transaction" { "request": { "byTransaction": "" } } ``` ### 5. Handle the Result Finally, handle the result. ```tsx title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": // The user cancelled the operation return; 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 "CannotCancelOrderError": console.error(`Cannot cancel: ${result.error.message}`); break; case "UnexpectedError": console.error(result.error.message); break; } return; } // result.value: OrderCancelledResult console.log("Order cancelled:", result.value.orderId); ``` ```ts title="Handle Result" if (result.isErr()) { switch (result.error.name) { case "CancelError": console.error("Operation cancelled by user wallet"); break; 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; } return; } // result.value: OrderCancelledResult | OrderCancelled | OrderExpired | OrderFulfilled console.log("Order status:", result.value.__typename); ``` In TypeScript, when the cancellation is sent as a transaction, `waitForOrderOutcome` resolves to the final order status. Check for `OrderCancelled`, since the order may be fulfilled or expire before the cancellation takes effect. In GraphQL, depending on the `CancelOrderExecutionPlan` type, you’ll need to follow different actions: | Response Type | Action | | ---------------------- | ---------------------------------------------------------------------------------------- | | `TransactionRequest` | Send the transaction with the wallet associated with the account that placed the order. | | `OrderCancelledResult` | Order was cancelled successfully. | Below are examples illustrating the response for each response type. ```jsonc title="TransactionRequest" { "data": { "cancelOrder": { "__typename": "TransactionRequest" // … } } } ``` ```json title="OrderCancelledResult" { "data": { "cancelOrder": { "__typename": "OrderCancelledResult", "orderId": "0x123…" } } } ``` You cancelled your first swap order. Keep track of its status in the [Monitor Swap Status](#monitor-swap-status) section. ## Fees Swaps include a network fee, partner fee, provider fee, and in the case of [Position Swaps](../positions/swaps/supply) a flash loan fee. ### Network Fee The network fee covers gas for executing the swap. Transaction-based swaps pay it in the chain’s native token (e.g., ETH on Ethereum). Intent-based swaps are gasless for the user: the solver’s cost is included in the quote under `costs.networkCosts`. ### Partner Fee Aave Labs applies a fee to swaps done through the Aave Labs API. The fee depends on the [swap operation](../positions/swaps/supply) and token pair: - **Swap Borrow Asset**: 0% fee across all pairs. - **All other swap operations**: a discounted fee of **0.15%** is applied to swaps between correlated assets (e.g., ETH/wstETH), while **0.25%** is applied to all other pairs. > [!NOTE] > Correlated assets keep a stable price relationship, usually pegged to the same > asset or index. Their lower price risk earns the discounted fee. The following asset groups are considered correlated (list reviewed and updated periodically): - **Stablecoins**: USDC, USDT, DAI, GHO, EURC, USDbC, USDe, USDS, sUSDe, RLUSD, PYUSD, LUSD, sDAI, crvUSD, USD₮0, USDC.e, EURe, xDAI, wxDAI - **ETH correlated**: weETH, ETH, WETH, wstETH, cbETH, ezETH, wrsETH, osETH, rETH, ETHx - **BTC correlated**: cbBTC, WBTC, LBTC, tBTC, eBTC ### Provider Fee CoW Protocol charges a fee for swap execution: **0.02%** for most pairs, reduced to **0.003%** for tokens in their [Reduced Fee Tokens](https://forum.cow.fi/t/cip-74-retrospective-aligning-rewards-with-revenue/3358) list (a dynamic registry of major stablecoins and RWAs based on price volatility). The fee is included in the swap quote. ### Flash Loan Fee Some of the [Position Swaps](../positions/swaps/supply) require flash loans to execute atomically. When applicable, a flash loan fee of **0.05%** of the flash-loaned amount is charged. This fee is collected by the protocol treasury and controlled by the DAO through governance. Flash loan fees apply to operations that require borrowing assets temporarily (e.g., Swap Borrow Asset). Operations that use existing positions (e.g., Withdraw and Swap) typically do not incur flash loan fees. --- Source: https://aave.com/docs/aave-v4/reference/react-hooks.md # AaveKit React Hooks Reference Reference for all public AaveKit React hooks for Aave V4. ## useActivities Declarative hook to fetch paginated list of user activities. ```tsx title="Loading State" import { useActivities } from "@aave/react"; const { data, loading, error } = useActivities({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useActivities({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: ActivitiesRequestQuery` one of: - `hub: HubInput` - Fetch by hub - `spoke: SpokeInput` - Fetch by spoke - `chainIds: [ChainId!]` - Fetch by chain IDs - `txHash: TxHashInput` - Fetch by transaction hash - `request.user?: EvmAddress` - User address (optional) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data?.items: ActivityItem[]` - List of activities - `data?.pageInfo: PageInfo` - Pagination information - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the activities --- ## useActivitiesAction Imperative hook to fetch paginated list of user activities. ```tsx import { useActivitiesAction } from "@aave/react"; const [execute, state] = useActivitiesAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.query: ActivitiesRequestQuery` one of: - `hub: HubInput` - Fetch by hub - `spoke: SpokeInput` - Fetch by spoke - `chainIds: [ChainId!]` - Fetch by chain IDs - `txHash: TxHashInput` - Fetch by transaction hash - `request.user?: EvmAddress` - User address (optional) **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the activities - `state.called: boolean` - Whether the hook has been called - `state.data: PaginatedActivitiesResult | undefined` - Paginated activities result - `result: Result` - Type-safe success or failure value: - `Ok` - Paginated activities result - `Err` - Error fetching the activities --- ## useAsset Declarative hook to fetch information about a specific asset (ERC-20 token). ```tsx title="Loading State" import { useAsset } from "@aave/react"; const { data, loading, error } = useAsset({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useAsset({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: AssetRequestQuery` one of: - `token: Erc20Input` - ERC-20 token - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Chain ID where the token exists - `assetId: AssetId` - Asset ID - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for historical data (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Asset | null | undefined` - Asset information or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the asset --- ## useAssetBorrowHistory Declarative hook to fetch historical borrow data for an asset. ```tsx title="Loading State" import { useAssetBorrowHistory } from "@aave/react"; const { data, loading, error } = useAssetBorrowHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useAssetBorrowHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: AssetBorrowHistoryRequestQuery` one of: - `token: Erc20Input` - ERC-20 token (`address`, `chainId`) - `assetId: AssetId` - Asset ID - `request.window: TimeWindow` - Time window for historical data - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: AssetBorrowSample[] | undefined` - Array of historical borrow data points - `data[].date: Date` - Sample date - `data[].amount: DecimalNumber` - Total borrowed amount - `data[].highestApy: PercentNumber` - Highest borrow APY across hubs - `data[].lowestApy: PercentNumber` - Lowest borrow APY across hubs - `data[].averageApy: PercentNumber` - Average borrow APY across all hubs - `data[].breakdown: AssetSampleBreakdown[]` - Per-hub APY breakdown - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the borrow history --- ## useAssetPriceHistory Declarative hook to fetch historical price data for an asset. ```tsx title="Loading State" import { useAssetPriceHistory } from "@aave/react"; const { data, loading, error } = useAssetPriceHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useAssetPriceHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: AssetPriceHistoryRequestQuery` one of: - `token: Erc20Input` - ERC-20 token (`address`, `chainId`) - `assetId: AssetId` - Asset ID - `request.currency: Currency` - Currency for the data - `request.window: TimeWindow` - Time window for historical data - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: AssetPriceSample[] | undefined` - Array of historical price data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the price history --- ## useAssetSupplyHistory Declarative hook to fetch historical supply data for an asset. ```tsx title="Loading State" import { useAssetSupplyHistory } from "@aave/react"; const { data, loading, error } = useAssetSupplyHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useAssetSupplyHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: AssetSupplyHistoryRequestQuery` one of: - `token: Erc20Input` - ERC-20 token (`address`, `chainId`) - `assetId: AssetId` - Asset ID - `request.window: TimeWindow` - Time window for historical data - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: AssetSupplySample[] | undefined` - Array of historical supply data points - `data[].date: Date` - Sample date - `data[].amount: DecimalNumber` - Total supplied amount - `data[].highestApy: PercentNumber` - Highest supply APY across hubs - `data[].lowestApy: PercentNumber` - Lowest supply APY across hubs - `data[].averageApy: PercentNumber` - Average supply APY across all hubs - `data[].breakdown: AssetSampleBreakdown[]` - Per-hub APY breakdown - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the supply history --- ## useBorrow Imperative transaction hook to borrow assets from the protocol. ```tsx import { useBorrow } from "@aave/react"; const [execute, state] = useBorrow((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.amount: ReserveAmountInput` one of: - `erc20: { value: BigDecimal }` - ERC-20 amount, e.g. `{ erc20: { value: bigDecimal("100") } }` - `native: BigDecimal` - Native token amount - `request.sender: EvmAddress` - Borrower address **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useBorrowApyHistory Declarative hook to fetch borrow APY history for a specific reserve over time. ```tsx title="Loading State" import { useBorrowApyHistory } from "@aave/react"; const { data, loading, error } = useBorrowApyHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useBorrowApyHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.window?: TimeWindow` - Time window for historical data (default: `LAST_DAY`) - `request.includeRewards?: boolean` - Include Merkl rewards in the rates (default: true) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: ApySample[] | undefined` - Array of historical APY data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the borrow APY history --- ## useBorrowSwapOrder Imperative hook to execute a borrow (debt) swap through the Order API. It fetches a quote, collects the position-swap approval signatures, then prepares, signs, and submits the order. ```tsx import { useBorrowSwapOrder } from "@aave/react"; const [execute, state] = useBorrowSwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request: BorrowSwapQuoteRequest` one of: - `market: MarketDebtSwapQuoteInput` - Market order quote - `limit: LimitDebtSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteDebtSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useBorrowSwapQuote Declarative hook to fetch a quote for a borrow (debt) swap. ```tsx title="Loading State" import { useBorrowSwapQuote } from "@aave/react"; const { data, loading, error } = useBorrowSwapQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useBorrowSwapQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: BorrowSwapQuoteRequest` one of: - `market: MarketDebtSwapQuoteInput` - Market order quote - `limit: LimitDebtSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteDebtSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapQuote | undefined` - Swap quote - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useBorrowSwapQuoteAction Imperative hook to fetch a quote for a borrow (debt) swap. ```tsx import { useBorrowSwapQuoteAction } from "@aave/react"; const [execute, state] = useBorrowSwapQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: BorrowSwapQuoteRequest` one of: - `market: MarketDebtSwapQuoteInput` - Market order quote - `limit: LimitDebtSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteDebtSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: SwapQuote | undefined` - Swap quote - `result: Result` - Type-safe success or failure value: - `Ok` - Swap quote - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- ## useCancelOrder Imperative hook to cancel an open order. ```tsx import { useCancelOrder } from "@aave/react"; const [execute, state] = useCancelOrder((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "OrderTypedData": return signTypedData(plan); } }); const result = await execute(request); ``` **Arguments:** - `request.id: OrderId` - Order ID to cancel **Returns:** - `state.loading: boolean` - Loading state - `state.error: CancelOrderError | undefined` - Error cancelling the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderCancelledResult | undefined` - Cancelled order with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Cancelled order with the `orderId` - `Err` - Error cancelling the order Where `CancelOrderError` is one of: - `CancelError` - `CannotCancelOrderError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useChain Declarative hook to fetch a specific chain by ID. ```tsx title="Loading State" import { useChain } from "@aave/react"; const { data, loading, error } = useChain({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useChain({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.chainId: ChainId` - Chain ID to query - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Chain | null | undefined` - Chain information or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the chain --- ## useChainAction Imperative hook to fetch chain data on demand. Does not watch for updated data; use it to retrieve data as part of a larger workflow. ```tsx import { useChainAction } from "@aave/react"; const [execute, state] = useChainAction(); const result = await execute(request); ``` **Arguments:** - `request.chainId: ChainId` - Chain ID **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the chain - `state.called: boolean` - Whether the hook has been called - `state.data: Chain | null | undefined` - Chain data or null if not found - `result: Result` - Type-safe success or failure value: - `Ok` - Chain data or null if not found - `Err` - Error fetching the chain --- ## useChains Declarative hook to fetch all supported chains. ```tsx title="Loading State" import { useChains } from "@aave/react"; import { ChainsFilter } from "@aave/react"; const { data, loading, error } = useChains({ query: { filter: ChainsFilter.ALL }, pause, }); ``` ```tsx title="React Suspense" import { useChains } from "@aave/react"; import { ChainsFilter } from "@aave/react"; const { data } = useChains({ query: { filter: ChainsFilter.ALL }, pause, suspense: true, }); ``` **Arguments:** - `request.query: ChainsRequestQuery` one of: - `filter: ChainsFilter` - Filter for chains (e.g., `ChainsFilter.ALL`) - `chainIds: [ChainId!]` - Fetch by chain IDs - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Chain[] | undefined` - Array of supported chains - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the chains --- ## useClaimRewards Imperative transaction hook to claim rewards for a user on a specific chain. ```tsx import { useClaimRewards } from "@aave/react"; const [execute, state] = useClaimRewards((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.ids: [RewardId!]` - Reward IDs to claim - `request.user: EvmAddress` - User claiming the rewards - `request.chainId: ChainId` - Chain to claim on **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useExchangeRate Declarative hook to fetch the current exchange rate between two currencies. ```tsx title="Loading State" import { useExchangeRate } from "@aave/react"; const { data, loading, error } = useExchangeRate({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useExchangeRate({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.from: AssetInput` - Source asset (`erc20` or `native`) - `request.to: Currency` - Target currency - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: ExchangeAmount | undefined` - Exchange rate value - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the exchange rate --- ## useExchangeRateAction Imperative hook to fetch exchange rate between two currencies. ```tsx import { useExchangeRateAction } from "@aave/react"; const [execute, state] = useExchangeRateAction(); const result = await execute(request); ``` **Arguments:** - `request.from: AssetInput` - Source asset (`erc20` or `native`) - `request.to: Currency` - Target currency - `request.at?: Date` - Historical date (optional) **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the exchange rate - `state.called: boolean` - Whether the hook has been called - `state.data: ExchangeAmount | undefined` - Exchange rate value - `result: Result` - Type-safe success or failure value: - `Ok` - Exchange rate value - `Err` - Error fetching the exchange rate --- ## useHub Declarative hook to fetch a specific hub by address and chain ID. ```tsx title="Loading State" import { useHub } from "@aave/react"; const { data, loading, error } = useHub({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHub({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: HubRequestQuery` one of: - `hubInput: HubInput` - Hub address and chain ID - `address: EvmAddress` - Hub contract address - `chainId: ChainId` - Chain ID where the hub exists - `hubId: HubId` - Hub ID - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Hub | null | undefined` - Hub information or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the hub --- ## useHubAssetInterestRateModel Declarative hook to fetch the interest rate model curve for a specific Hub Asset. ```tsx title="Loading State" import { useHubAssetInterestRateModel } from "@aave/react"; const { data, loading, error } = useHubAssetInterestRateModel({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHubAssetInterestRateModel({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: HubAssetInterestRateModelRequestQuery`: - `hubAssetId: HubAssetId` - Hub Asset ID - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: HubAssetInterestRateModelPoint[] | undefined` - Array of interest rate model data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the interest rate model --- ## useHubAssetInterestRateModelAction Imperative hook to fetch interest rate model data for a Hub Asset. ```tsx import { useHubAssetInterestRateModelAction } from "@aave/react"; const [execute, state] = useHubAssetInterestRateModelAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.query: HubAssetInterestRateModelRequestQuery`: - `hubAssetId: HubAssetId` - Hub Asset ID **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the interest rate model - `state.called: boolean` - Whether the hook has been called - `state.data: HubAssetInterestRateModelPoint[] | undefined` - Array of interest rate model data points - `result: Result` - Type-safe success or failure value: - `Ok` - Array of interest rate model data points - `Err` - Error fetching the interest rate model --- ## useHubAssets Declarative hook to fetch Hub Assets for a specific chain and optional hub/user filtering. ```tsx title="Loading State" import { useHubAssets } from "@aave/react"; const { data, loading, error } = useHubAssets({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHubAssets({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: HubAssetsRequestQuery` one of: - `hubInput: HubInput` - Hub address and chain ID - `address: EvmAddress` - Hub contract address - `chainId: ChainId` - Chain ID - `hubId: HubId` - Hub ID - `request.user?: EvmAddress` - Filter by user address (optional) - `request.orderBy?: HubAssetsRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `availableLiquidity: OrderDirection` - Sort by available liquidity - `supplyApy: OrderDirection` - Sort by supply APY - `borrowApy: OrderDirection` - Sort by borrow APY - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: HubAsset[] | undefined` - Array of Hub Assets - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the Hub Assets --- ## useHubs Declarative hook to fetch all available hubs. ```tsx title="Loading State" import { useHubs } from "@aave/react"; const { data, loading, error } = useHubs({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHubs({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: HubsRequestQuery` one of: - `tokens: [Erc20Input!]` - Filter by underlying tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `assetIds: [AssetId!]` - Filter by asset IDs - `chainIds: [ChainId!]` - Filter by chain IDs - `request.orderBy?: HubsRequestOrderBy` one of: - `name: OrderDirection` - Sort by hub name - `totalBorrowed: OrderDirection` - Sort by total borrowed amount - `totalSupplied: OrderDirection` - Sort by total supplied amount - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Hub[] | undefined` - Array of hubs - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the hubs --- ## useHubsAction Imperative hook to fetch hubs data. ```tsx import { useHubsAction } from "@aave/react"; const [execute, state] = useHubsAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.query: HubsRequestQuery` one of: - `tokens: [Erc20Input!]` - Filter by underlying tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `chainIds: [ChainId!]` - Filter by chain IDs - `request.orderBy?: HubsRequestOrderBy` one of: - `name: OrderDirection` - Sort by hub name - `totalBorrowed: OrderDirection` - Sort by total borrowed amount - `totalSupplied: OrderDirection` - Sort by total supplied amount **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the hubs - `state.called: boolean` - Whether the hook has been called - `state.data: Hub[] | undefined` - Array of hubs - `result: Result` - Type-safe success or failure value: - `Ok` - Array of hubs - `Err` - Error fetching the hubs --- ## useHubSpokeConfigs Declarative hook to fetch per-asset configuration for a specific hub and spoke pair. ```tsx title="Loading State" import { useHubSpokeConfigs } from "@aave/react"; const { data, loading, error } = useHubSpokeConfigs({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHubSpokeConfigs({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.hubId: HubId` - Hub ID - `request.spokeId: SpokeId` - Spoke ID - `request.currency?: Currency` - Currency for nested amount conversions (default: USD) - `request.timeWindow?: TimeWindow` - Time window for nested change calculations (default: LAST_DAY) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: HubSpokeConfig[] | undefined` - Array of hub-spoke asset configurations - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the configs --- ## useHubSummaryHistory Declarative hook to fetch historical summary data for a specific hub. ```tsx title="Loading State" import { useHubSummaryHistory } from "@aave/react"; const { data, loading, error } = useHubSummaryHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useHubSummaryHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: HubSummaryHistoryRequestQuery` one of: - `hubInput: HubInput` - Hub address and chain ID - `address: EvmAddress` - Hub contract address - `chainId: ChainId` - Chain ID where the hub exists - `hubId: HubId` - Hub ID - `request.currency?: Currency` - Currency for value conversions (default: USD) - `request.window?: TimeWindow` - Time window for historical data (default: LAST_DAY) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: HubSummarySample[] | undefined` - Array of historical hub summary data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the hub summary history --- ## useLeverage Imperative hook to open or increase a leveraged position through the Order API. It flash-loans the debt asset, swaps it into the collateral asset, supplies the collateral, then borrows the debt to repay the flash loan. ```tsx import { useLeverage } from "@aave/react"; const [execute, state] = useLeverage((plan) => { switch (plan.__typename) { case "OrderAdapterApproval": case "OrderPositionManagerApproval": case "OrderSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderErc20Approval": return plan.byPermit ? signTypedData(plan.byPermit) : sendTransaction(plan.byTransaction); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request: LeverageQuoteRequest` one of: - `market: MarketLeverageQuoteInput` - Market order quote - `limit: LimitLeverageQuoteInput` - Limit order quote - `fromQuote: FromQuoteLeverageQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `request.permitSig?: ERC20PermitSignature` - Pre-built permit for the collateral top-up (optional; normally the handler signs it) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useLeverageQuote Declarative hook to fetch a quote for a leverage operation. ```tsx title="Loading State" import { useLeverageQuote } from "@aave/react"; const { data, loading, error } = useLeverageQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useLeverageQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: LeverageQuoteRequest` one of: - `market: MarketLeverageQuoteInput` - Market order quote - `limit: LimitLeverageQuoteInput` - Limit order quote - `fromQuote: FromQuoteLeverageQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: LeverageApprovalsRequired | undefined` - Leverage quote, required approvals, and `maxSafeMultiplier` - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useLeverageQuoteAction Imperative hook to fetch a quote for a leverage operation. ```tsx import { useLeverageQuoteAction } from "@aave/react"; const [execute, state] = useLeverageQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: LeverageQuoteRequest` one of: - `market: MarketLeverageQuoteInput` - Market order quote - `limit: LimitLeverageQuoteInput` - Limit order quote - `fromQuote: FromQuoteLeverageQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: LeverageApprovalsRequired | undefined` - Leverage quote, required approvals, and `maxSafeMultiplier` - `result: Result` - Type-safe success or failure value: - `Ok` - Leverage quote, required approvals, and `maxSafeMultiplier` - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- ## useLiquidatePosition Imperative transaction hook to liquidate an undercollateralized position. ```tsx import { useLiquidatePosition } from "@aave/react"; const [execute, state] = useLiquidatePosition((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request.collateral: ReserveId` - Collateral reserve ID - `request.debt: ReserveId` - Debt reserve ID - `request.amount: LiquidatePositionDebtAmount` one of: - `exact: { value: BigDecimal, permitSig?: ERC20PermitSignature }` - Exact debt amount to cover - `max: true` - Cover the maximum liquidatable debt - `request.liquidator: EvmAddress` - Liquidator address - `request.user: EvmAddress` - User address to liquidate - `request.receiveShares?: boolean` - Receive collateral shares instead of the underlying asset (default: false) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useMultichainAsset Declarative hook to fetch information about an asset (ERC-20 token) aggregated across multiple chains, matched by its token info ID or symbol. ```tsx title="Loading State" import { useMultichainAsset } from "@aave/react"; const { data, loading, error } = useMultichainAsset({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useMultichainAsset({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: MultichainAssetRequestQuery` one of: - `tokenInfo: TokenInfoId` - Token info ID - `symbol: String` - Token symbol (e.g. `"USDC"`) - `request.chainIds?: [ChainId!]` - Restrict aggregation to specific chains (optional) - `request.includeRewards?: boolean` - Fold Merkl rewards into APY ranges (default: true) - `currency?: Currency` - Currency for value conversions (default: USD) - `timeWindow?: TimeWindow` - Time window for historical changes (default: LastDay) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: MultichainAsset | undefined` - Aggregated asset data (`assets` and `summary`) - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the asset --- ## useNetworkFee Declarative hook to fetch the network fee for an activity (experimental). ```tsx title="Loading State" import { useNetworkFee } from "@aave/react"; const { data, loading, error } = useNetworkFee({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useNetworkFee({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: UseNetworkFeeRequestQuery` one of: - `activity: ActivityItem` - Calculate fee for past activity - `estimate: PreviewAction` - Estimate fee for preview action, one of: - `supply: SupplyRequest` - Supply action - `borrow: BorrowRequest` - Borrow action - `repay: RepayRequest` - Repay action - `withdraw: WithdrawRequest` - Withdraw action - `setUserSuppliesAsCollateral: SetUserSuppliesAsCollateralRequest` - Collateral changes - `updateUserPositionConditions: UpdateUserPositionConditionsRequest` - Position condition updates - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: NativeAmount | undefined` - Network fee amount - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the network fee --- ## useOrderStatus Declarative hook to monitor the status of an order. It polls until the order is fulfilled, cancelled, or expired. ```tsx title="Loading State" import { useOrderStatus } from "@aave/react"; const { data, loading, error } = useOrderStatus({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useOrderStatus({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.id: OrderId` - Order ID - `request.currency?: Currency` - Currency for value conversions (default: USD) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: OrderStatus | undefined` - Current order status, one of `OrderOpen`, `OrderPendingSignature`, `OrderFulfilled`, `OrderCancelled`, or `OrderExpired` - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the order status --- ## usePendingOrders Declarative hook to fetch a user’s orders on a chain. ```tsx title="Loading State" import { usePendingOrders } from "@aave/react"; const { data, loading, error } = usePendingOrders({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = usePendingOrders({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.chainId: ChainId` - Chain ID - `request.user: EvmAddress` - User address - `request.filterBy?: OrderStatusFilter[]` - Filter by status: `Open`, `PendingSignature`, `Fulfilled`, `Cancelled`, or `Expired` (optional) - `request.pageSize?: PageSize` - Page size (default: `FIFTY`) - `request.cursor?: Cursor` - Pagination cursor (optional) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: PaginatedOrdersResult | undefined` - Paginated orders (`items: OrderStatus[]`, `pageInfo`) - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the orders --- ## usePreview Declarative hook to preview the outcome of a transaction before executing. ```tsx title="Loading State" import { usePreview } from "@aave/react"; const { data, loading, error } = usePreview({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = usePreview({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.action: PreviewActionInput` one of: - `supply: SupplyRequest` - Preview a supply action - `borrow: BorrowRequest` - Preview a borrow action - `repay: RepayRequest` - Preview a repay action - `withdraw: WithdrawRequest` - Preview a withdraw action - `setUserSuppliesAsCollateral: SetUserSuppliesAsCollateralRequest` - Preview a collateral change - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: PreviewUserPosition | undefined` - Preview of user position after the action - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the preview --- ## usePreviewAction Imperative hook to preview the outcome of a transaction before executing. ```tsx import { usePreviewAction } from "@aave/react"; const [execute, state] = usePreviewAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.action: PreviewActionInput` one of: - `supply: SupplyRequest` - Preview a supply action - `borrow: BorrowRequest` - Preview a borrow action - `repay: RepayRequest` - Preview a repay action - `withdraw: WithdrawRequest` - Preview a withdraw action - `setUserSuppliesAsCollateral: SetUserSuppliesAsCollateralRequest` - Preview a collateral change **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the preview - `state.called: boolean` - Whether the hook has been called - `state.data: PreviewUserPosition | undefined` - Preview of user position after the action - `result: Result` - Type-safe success or failure value: - `Ok` - Preview of user position after the action - `Err` - Error fetching the preview --- ## useProtocolHistory Declarative hook to fetch protocol-wide historical data (deposits, borrows). ```tsx title="Loading State" import { Currency, TimeWindow } from "@aave/react"; import { useProtocolHistory } from "@aave/react"; const { data, loading, error } = useProtocolHistory({ currency: Currency.Usd, window: TimeWindow.LastWeek, pause, }); ``` ```tsx title="React Suspense" const { data } = useProtocolHistory({ currency: Currency.Usd, window: TimeWindow.LastWeek, suspense: true, pause, }); ``` **Arguments:** - `request.currency: Currency` - Currency for exchange amounts (default: USD) - `request.window: TimeWindow` - Time window for historical data (default: LAST_DAY) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: ProtocolHistorySample[] | undefined` - Array of protocol history data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the protocol history --- ## useRenounceSpokeUserPositionManager Imperative transaction hook to renounce a position manager of a user for a specific spoke. ```tsx import { useRenounceSpokeUserPositionManager } from "@aave/react"; const [execute, state] = useRenounceSpokeUserPositionManager((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.spoke: SpokeId` - Spoke ID - `request.manager: EvmAddress` - Address to remove as a position manager - `request.managing: EvmAddress` - Address that `manager` was managing **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useRepay Imperative transaction hook to repay borrowed assets. ```tsx import { useRepay } from "@aave/react"; const [execute, state] = useRepay((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.amount: RepayAmountInputWithPermit` one of: - `erc20: { value: AmountInput, permit?: RepaySignedPermitInput }` - ERC-20 amount, where `value` is `{ exact: BigDecimal }` or `{ max: true }` - `native: AmountInput` - Native token amount (`{ exact: BigDecimal }` or `{ max: true }`) - `request.sender: EvmAddress` - Address repaying the debt **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useRepayWithSupplyOrder Imperative hook to execute a repay with supply through the Order API. It fetches a quote, collects the position-swap approval signatures, then prepares, signs, and submits the order. ```tsx import { useRepayWithSupplyOrder } from "@aave/react"; const [execute, state] = useRepayWithSupplyOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request: RepayWithSupplyQuoteRequest` one of: - `market: MarketRepayWithSupplyQuoteInput` - Market order quote - `limit: LimitRepayWithSupplyQuoteInput` - Limit order quote - `fromQuote: FromQuoteRepayWithSupplyQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useRepayWithSupplyQuote Declarative hook to fetch a quote for a repay with supply. ```tsx title="Loading State" import { useRepayWithSupplyQuote } from "@aave/react"; const { data, loading, error } = useRepayWithSupplyQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useRepayWithSupplyQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: RepayWithSupplyQuoteRequest` one of: - `market: MarketRepayWithSupplyQuoteInput` - Market order quote - `limit: LimitRepayWithSupplyQuoteInput` - Limit order quote - `fromQuote: FromQuoteRepayWithSupplyQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapQuote | undefined` - Swap quote - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useRepayWithSupplyQuoteAction Imperative hook to fetch a quote for a repay with supply. ```tsx import { useRepayWithSupplyQuoteAction } from "@aave/react"; const [execute, state] = useRepayWithSupplyQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: RepayWithSupplyQuoteRequest` one of: - `market: MarketRepayWithSupplyQuoteInput` - Market order quote - `limit: LimitRepayWithSupplyQuoteInput` - Limit order quote - `fromQuote: FromQuoteRepayWithSupplyQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: SwapQuote | undefined` - Swap quote - `result: Result` - Type-safe success or failure value: - `Ok` - Swap quote - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- ## useReserve Declarative hook to fetch a specific reserve by reserve ID, spoke, and chain. ```tsx title="Loading State" import { useReserve } from "@aave/react"; const { data, loading, error } = useReserve({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useReserve({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: ReserveRequestQuery` one of: - `reserveId: ReserveId` - Reserve ID - `reserveInput: ReserveInput` - Reserve input - `chainId: ChainId` - Chain ID - `spoke: EvmAddress` - Spoke contract address - `onChainId: OnChainReserveId` - On-chain reserve ID - `request.user?: EvmAddress` - User address for position-specific data (optional) - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Reserve | null | undefined` - Reserve information or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the reserve --- ## useReserveAction Imperative hook to fetch reserve data. ```tsx import { useReserveAction } from "@aave/react"; const [execute, state] = useReserveAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) - `options.timeWindow?: TimeWindow` **Arguments:** - `request.query: ReserveRequestQuery` one of: - `reserveId: ReserveId` - Reserve ID - `reserveInput: ReserveInput` - Reserve input - `chainId: ChainId` - Chain ID - `spoke: EvmAddress` - Spoke contract address - `onChainId: OnChainReserveId` - On-chain reserve ID - `request.user?: EvmAddress` - User address for position-specific data (optional) **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the reserve - `state.called: boolean` - Whether the hook has been called - `state.data: Reserve | null | undefined` - Reserve data or null if not found - `result: Result` - Type-safe success or failure value: - `Ok` - Reserve data or null if not found - `Err` - Error fetching the reserve --- ## useReserveHolders Declarative hook to fetch a paginated list of top holders for a specific reserve. ```tsx title="Loading State" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; const { data, loading, error } = useReserveHolders({ reserve: { reserveId }, filter: ReserveHoldersFilter.Supplied, }); ``` ```tsx title="React Suspense" import { ReserveHoldersFilter, useReserveHolders } from "@aave/react"; const { data } = useReserveHolders({ reserve: { reserveId }, filter: ReserveHoldersFilter.Supplied, suspense: true, }); ``` **Arguments:** - `request.reserve: ReserveRequestQuery` one of: - `reserveId: ReserveId` - Reserve ID - `request.filter?: ReserveHoldersFilter` - Filter by holder type (default: `Supplied`): - `ReserveHoldersFilter.Supplied` - Wallets that have supplied to this reserve - `ReserveHoldersFilter.Borrowed` - Wallets that have borrowed from this reserve - `request.pageSize?: PageSize` - Number of results per page (default: `TEN`) - `request.cursor?: Cursor` - Pagination cursor - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: PaginatedReserveHoldersResult | undefined` - `data.items: ReserveHolder[]` - Array of holders - `address: EvmAddress` - Holder wallet address - `amount: Erc20Amount` - Amount supplied or borrowed - `weight: PercentNumber` - Percentage share of the total - `data.pageInfo: PaginatedResultInfo` - Pagination info with `next` and `prev` cursors - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching holders --- ## useReserveHoldersAction Imperative hook to fetch reserve holders on demand (e.g., for pagination). ```tsx import { useReserveHoldersAction } from "@aave/react"; const [execute, state] = useReserveHoldersAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.reserve: ReserveRequestQuery` - Reserve query (see `useReserveHolders`) - `request.filter?: ReserveHoldersFilter` - Holder type filter - `request.pageSize?: PageSize` - Page size - `request.cursor?: Cursor` - Pagination cursor **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching holders - `state.called: boolean` - Whether the hook has been called - `state.data: PaginatedReserveHoldersResult | undefined` - Paginated result - `result: Result` - Type-safe success or failure value: - `Ok` - Paginated holder data - `Err` - Error fetching holders --- ## useReserves Declarative hook to fetch reserves based on specified criteria. ```tsx title="Loading State" import { useReserves } from "@aave/react"; const { data, loading, error } = useReserves({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useReserves({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: ReservesRequestQuery` one of: - `spoke: SpokeInput` - Get reserves for a spoke - `address: EvmAddress` - Spoke contract address - `chainId: ChainId` - Chain ID - `spokeId: SpokeId` - Get reserves by spoke ID - `tokens: [Erc20Input!]` - Get reserves with underlying tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `hubToken: HubTokenInput` - Get reserves on hub for underlying - `chainId: ChainId` - Chain ID - `hub: EvmAddress` - Hub contract address - `token: EvmAddress` - Token address - `chainIds: [ChainId!]` - Get reserves on chains - `spokeToken: SpokeTokenInput` - Get reserves for spoke for underlying - `spoke: SpokeId` - Spoke ID - `token: EvmAddress` - Token address - `hub: HubInput` - Get reserves on hub - `userPositionId: UserPositionId` - Get reserves by user position ID - `hubId: HubId` - Get reserves by hub ID - `hubIdToken: HubIdTokenInput` - Get reserves on a hub (by ID) for an underlying (`hubId`, `token`) - `chainTokenCategories: [ChainTokenCategories!]` - Token categories per chain (`chainId`, `categories`) - `tokenInfo: TokenInfoId` - Get reserves by canonical token info ID, across chains - `symbolChainIds: SymbolInput` - Get reserves by raw symbol (`symbol`, `chainIds?`) - `request.user?: EvmAddress` - User address to include `ReserveUserState` (optional) - `request.filter?: ReservesRequestFilter` - Filter criteria (optional): `Supply`, `Borrow`, `Collateral`, or `All` - `request.orderBy?: ReservesRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `userBalance: OrderDirection` - Sort by user balance - `supplyApy: OrderDirection` - Sort by supply APY - `supplyAvailable: OrderDirection` - Sort by available supply - `borrowApy: OrderDirection` - Sort by borrow APY - `borrowAvailable: OrderDirection` - Sort by available borrow - `collateralFactor: OrderDirection` - Sort by collateral factor - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Reserve[] | undefined` - Array of reserves - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching reserves --- ## useReservesAction Imperative hook to fetch reserves list. ```tsx import { useReservesAction } from "@aave/react"; const [execute, state] = useReservesAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) - `options.timeWindow?: TimeWindow` - Time window for change values (optional) **Arguments:** - `request.query: ReservesRequestQuery` one of: - `spoke: SpokeInput` - Get all reserves for a spoke - `tokens: [Erc20Input!]` - Get all reserves with underlying tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `hubToken: HubTokenInput` - Get all reserves on a hub for an underlying - `chainId: ChainId` - Chain ID - `hub: EvmAddress` - Hub contract address - `token: EvmAddress` - Token address - `chainIds: [ChainId!]` - Get all reserves on a list of chains - `spokeToken: SpokeTokenInput` - Get all reserves for a spoke for an underlying - `spoke: SpokeId` - Spoke ID - `token: EvmAddress` - Token address - `hub: HubInput` - Get all tokens on a hub - `userPositionId: UserPositionId` - Get all reserves by user position ID - `hubId: HubId` - Get reserves by hub ID - `hubIdToken: HubIdTokenInput` - Get reserves on a hub (by ID) for an underlying (`hubId`, `token`) - `chainTokenCategories: [ChainTokenCategories!]` - Token categories per chain (`chainId`, `categories`) - `tokenInfo: TokenInfoId` - Get reserves by canonical token info ID, across chains - `symbolChainIds: SymbolInput` - Get reserves by raw symbol (`symbol`, `chainIds?`) - `request.user?: EvmAddress` - User address to include `ReserveUserState` (optional) - `request.filter?: ReservesRequestFilter` - Filter criteria (optional): `Supply`, `Borrow`, `Collateral`, or `All` **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching reserves - `state.called: boolean` - Whether the hook has been called - `state.data: Reserve[] | undefined` - Array of reserves - `result: Result` - Type-safe success or failure value: - `Ok` - Array of reserves - `Err` - Error fetching reserves --- ## useSendTransaction Send transactions through connected wallet. ```tsx title="Viem" import { useSendTransaction } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; const { data: walletClient } = useWalletClient(); const [sendTransaction, state] = useSendTransaction(walletClient); ``` ```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(); const [sendTransaction, state] = useSendTransaction(signer); ``` ```tsx title="Privy" import { useSendTransaction } from "@aave/react/privy"; const [sendTransaction, state] = useSendTransaction(); ``` ```tsx title="thirdweb" import { useSendTransaction } from "@aave/react/thirdweb"; import { createThirdwebClient } from "thirdweb"; const thirdwebClient = createThirdwebClient({ clientId: "", }); const [sendTransaction, state] = useSendTransaction(thirdwebClient); ``` **Arguments:** - `request: TransactionRequest` - Transaction request to send **Returns:** - `state.loading: boolean` - Loading state - `state.error: SendTransactionError | undefined` - Error sending the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: PendingTransaction | undefined` - Pending transaction - `result: Result` - Type-safe success or failure value: - `Ok` - Pending transaction - `Err` - Error sending the transaction Where `SendTransactionError` is one of: - `CancelError` - `SigningError` - `UnexpectedError` --- ## useSetSpokeUserPositionManager Imperative transaction hook to set a position manager for a spoke. ```tsx import { useSetSpokeUserPositionManager } from "@aave/react"; const [execute, state] = useSetSpokeUserPositionManager((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.chainId: ChainId` - Chain ID - `request.spoke: SpokeId` - Spoke ID - `request.manager: EvmAddress` - Position manager address **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useSetUserSuppliesAsCollateral Imperative transaction hook to enable or disable assets as collateral. ```tsx import { useSetUserSuppliesAsCollateral } from "@aave/react"; const [execute, state] = useSetUserSuppliesAsCollateral((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.changes: UserSupplyAsCollateral[]` - Array of collateral changes - `changes[].reserve: ReserveId` - Reserve ID - `changes[].enableCollateral: boolean` - Enable or disable as collateral - `request.sender: EvmAddress` - User’s address **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useSignTypedData Imperative transaction hook to sign EIP-712 typed data for ERC-20 permits and swap intents. This hook provides a unified interface for signing all types of typed data in AaveKit React. It returns a raw signature that is automatically wrapped with deadline information by transaction hooks like `useSupply`, `useRepay`, and `useTokenSwapOrder`. ```tsx title="Viem" import { useSignTypedData } from "@aave/react/viem"; import { useWalletClient } from "wagmi"; const { data: walletClient } = useWalletClient(); const [execute, state] = useSignTypedData(walletClient); const result = await execute(typedData); ``` ```tsx title="Ethers" import { useSignTypedData } from "@aave/react/ethers"; import { ethers } from "ethers"; const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const [execute, state] = useSignTypedData(signer); const result = await execute(typedData); ``` ```tsx title="Privy" import { useSignTypedData } from "@aave/react/privy"; const [execute, state] = useSignTypedData(); const result = await execute(typedData); ``` ```tsx title="thirdweb" import { useSignTypedData } from "@aave/react/thirdweb"; const [execute, state] = useSignTypedData(); const result = await execute(typedData); ``` **Arguments:** - `typedData: TypedData` - The EIP-712 typed data to sign. **Returns:** - `state.loading: boolean` - Loading state - `state.error: SignTypedDataError | undefined` - Error signing the typed data - `state.called: boolean` - Whether the hook has been called - `state.data: Signature | undefined` - Raw signature (deadline wrapping is handled automatically by transaction hooks) - `result: Result` - Type-safe success or failure value: - `Ok` - Raw signature - `Err` - Error signing the typed data --- ## useSpoke Declarative hook to fetch a specific spoke by address and chain ID. ```tsx title="Loading State" import { useSpoke } from "@aave/react"; const { data, loading, error } = useSpoke({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSpoke({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: SpokeRequestQuery` one of: - `spokeId: SpokeId` - Spoke ID - `spoke: SpokeInput` - Spoke address and chain ID - `address: EvmAddress` - Spoke contract address - `chainId: ChainId` - Chain ID - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Spoke | null | undefined` - Spoke information or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the spoke --- ## useSpokePositionManagers Declarative hook to fetch paginated list of position managers for a spoke. ```tsx title="Loading State" import { useSpokePositionManagers } from "@aave/react"; const { data, loading, error } = useSpokePositionManagers({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSpokePositionManagers({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.spoke: SpokeInput` - Spoke address and chain ID - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: PaginatedSpokePositionManagerResult | undefined` - Paginated list of position managers - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching position managers --- ## useSpokes Declarative hook to fetch spokes based on specified criteria. ```tsx title="Loading State" import { useSpokes } from "@aave/react"; const { data, loading, error } = useSpokes({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSpokes({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: SpokesRequestQuery` one of: - `hubId: HubId` - Spokes linked to a hub, by hub ID - `hub: HubInput` - Spokes linked to a hub, by hub address and chain ID - `chainIds: [ChainId!]` - Spokes on the given chains - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for change values (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Spoke[] | undefined` - Array of spokes - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the spokes --- ## useSpokeSummaryHistory Declarative hook to fetch historical deposits and borrows for a specific spoke. ```tsx title="Loading State" import { useSpokeSummaryHistory } from "@aave/react"; const { data, loading, error } = useSpokeSummaryHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSpokeSummaryHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: SpokeSummaryHistoryRequestQuery` one of: - `spokeInput: SpokeInput` - Spoke address and chain ID - `spokeId: SpokeId` - Spoke ID - `request.currency?: Currency` - Currency for value conversions (default: USD) - `request.window?: TimeWindow` - Time window for historical data (default: LAST_DAY) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SpokeSummarySample[] | undefined` - Array of historical spoke summary data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the spoke summary history --- ## useSpokeUserPositionManagers Declarative hook to fetch paginated list of user’s position managers for a spoke. ```tsx title="Loading State" import { useSpokeUserPositionManagers } from "@aave/react"; const { data, loading, error } = useSpokeUserPositionManagers({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSpokeUserPositionManagers({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.spoke: SpokeInput` - Spoke address and chain ID - `request.user: EvmAddress` - User address - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: PaginatedSpokeUserPositionManagerResult | undefined` - Paginated list of user’s position managers - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching user position managers --- ## useStableVault Declarative hook to fetch a stable vault by ID. ```tsx title="Loading State" import { useStableVault } from "@aave/react"; const { data, loading, error } = useStableVault({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useStableVault({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.id: StableVaultId` - Stable vault ID - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: StableVault | null | undefined` - Stable vault or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the vault --- ## useStableVaultClaimStatus Declarative hook to fetch the status of a deferred withdrawal claim. ```tsx title="Loading State" import { useStableVaultClaimStatus } from "@aave/react"; const { data, loading, error } = useStableVaultClaimStatus({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useStableVaultClaimStatus({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.claimId: StableVaultWithdrawClaimId` - Withdrawal claim ID - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: StableVaultClaimStatus | undefined` - Claim status (`READY` or `PENDING`) - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the claim status --- ## useStableVaultDeposit Imperative transaction hook to deposit assets into a stable vault. ```tsx import { useStableVaultDeposit } from "@aave/react"; const [execute, state] = useStableVaultDeposit((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); } }); const result = await execute(request); ``` **Arguments:** - `request.vault.id: StableVaultId` - Stable vault ID - `request.user: EvmAddress` - Depositor address - `request.amount: StableVaultAmountInput` - `address: EvmAddress` - Token address - `value: AmountInput` - `{ exact: BigDecimal }` or `{ max: true }` - `permitSig?: ERC20PermitSignature` - ERC-20 permit signature (optional) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useStableVaultUserPositions Declarative hook to fetch a user’s stable vault positions. ```tsx title="Loading State" import { useStableVaultUserPositions } from "@aave/react"; const { data, loading, error } = useStableVaultUserPositions({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useStableVaultUserPositions({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.filter?.vault.id: StableVaultId` - Restrict to one vault (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: StableVaultUserPosition[] | undefined` - User positions - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the positions --- ## useStableVaults Declarative hook to fetch the stable vaults managed by an admin address. ```tsx title="Loading State" import { useStableVaults } from "@aave/react"; const { data, loading, error } = useStableVaults({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useStableVaults({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.admin: EvmAddress` - Vault admin address - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: StableVault[] | undefined` - Stable vaults - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the vaults --- ## useStableVaultWithdraw Imperative transaction hook to withdraw from a stable vault. The result is a `TransactionReceipt` for an instant withdrawal, or a `StableVaultWithdrawClaim` for a deferred one that must be redeemed later with `useStableVaultWithdrawRedeem`. ```tsx import { useStableVaultWithdraw } from "@aave/react"; const [execute, state] = useStableVaultWithdraw((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.vault.id: StableVaultId` - Stable vault ID - `request.user: EvmAddress` - Withdrawer address - `request.amount: StableVaultAmountInput` - `address: EvmAddress` - Token address - `value: AmountInput` - `{ exact: BigDecimal }` or `{ max: true }` - `permitSig?: ERC20PermitSignature` - ERC-20 permit signature (optional) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | StableVaultWithdrawClaim | undefined` - Transaction receipt, or the withdrawal claim for a deferred withdrawal - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt, or the withdrawal claim for a deferred withdrawal - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useStableVaultWithdrawRedeem Imperative transaction hook to redeem a deferred withdrawal claim once `useStableVaultClaimStatus` returns `READY`. ```tsx import { useStableVaultWithdrawRedeem } from "@aave/react"; const [execute, state] = useStableVaultWithdrawRedeem((transaction) => sendTransaction(transaction), ); const result = await execute(request); ``` **Arguments:** - `request.claimId: StableVaultWithdrawClaimId` - Withdrawal claim ID **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useSupply Imperative transaction hook to supply assets to the protocol. ```tsx import { useSupply } from "@aave/react"; const [execute, state] = useSupply((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "Erc20Approval": return sendTransaction(plan.byTransaction); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.amount: ReserveAmountInputWithPermit` one of: - `erc20: { value: BigDecimal, permitSig?: ERC20PermitSignature }` - ERC-20 amount - `native: BigDecimal` - Native token amount - `request.enableCollateral?: true` - Enable the supply as collateral (optional) - `request.sender: EvmAddress` - Supplier address **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useSupplyApyHistory Declarative hook to fetch supply APY history for a specific reserve over time. ```tsx title="Loading State" import { useSupplyApyHistory } from "@aave/react"; const { data, loading, error } = useSupplyApyHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSupplyApyHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.window?: TimeWindow` - Time window for historical data (default: `LAST_DAY`) - `request.includeRewards?: boolean` - Include Merkl rewards in the rates (default: true) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: ApySample[] | undefined` - Array of historical APY data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the supply APY history --- ## useSupplySwapOrder Imperative hook to execute a supply swap through the Order API. It fetches a quote, collects the position-swap approval signatures, then prepares, signs, and submits the order. ```tsx import { useSupplySwapOrder } from "@aave/react"; const [execute, state] = useSupplySwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request: SupplySwapQuoteRequest` one of: - `market: MarketSupplySwapQuoteInput` - Market order quote - `limit: LimitSupplySwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteSupplySwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useSupplySwapQuote Declarative hook to fetch a quote for a supply swap. ```tsx title="Loading State" import { useSupplySwapQuote } from "@aave/react"; const { data, loading, error } = useSupplySwapQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSupplySwapQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: SupplySwapQuoteRequest` one of: - `market: MarketSupplySwapQuoteInput` - Market order quote - `limit: LimitSupplySwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteSupplySwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapQuote | undefined` - Swap quote - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useSupplySwapQuoteAction Imperative hook to fetch a quote for a supply swap. ```tsx import { useSupplySwapQuoteAction } from "@aave/react"; const [execute, state] = useSupplySwapQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: SupplySwapQuoteRequest` one of: - `market: MarketSupplySwapQuoteInput` - Market order quote - `limit: LimitSupplySwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteSupplySwapQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: SwapQuote | undefined` - Swap quote - `result: Result` - Type-safe success or failure value: - `Ok` - Swap quote - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- ## useSwappableTokens Declarative hook to fetch the tokens available for swapping. ```tsx title="Loading State" import { useSwappableTokens } from "@aave/react"; const { data, loading, error } = useSwappableTokens({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSwappableTokens({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query?: SwappableTokensRequestQuery` one of: - `tokens: [Erc20Input!]` - Filter by tokens - `chainIds: [ChainId!]` - Filter by chain IDs - `from: SwappableTokenInput` - Destination tokens for this source token (`erc20` or `native`) - `to: SwappableTokenInput` - Source tokens for this destination token (`erc20` or `native`) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: Token[] | undefined` - Swappable tokens - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the tokens --- ## useSwapStatus Deprecated: use `useOrderStatus` instead. The swap API remains functional but will be removed in a later release. Declarative hook to monitor the status of a swap operation in real-time. ```tsx title="Loading State" import { useSwapStatus } from "@aave/react"; const { data, loading, error } = useSwapStatus({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useSwapStatus({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.id: string` - Swap receipt ID from `SwapReceipt.id` - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapStatus | undefined` - Current swap status, one of: - `SwapOpen` - Swap is open and waiting for execution - `SwapPendingSignature` - Swap is waiting for user signature - `SwapFulfilled` - Swap completed successfully - `SwapCancelled` - Swap was cancelled - `SwapExpired` - Swap expired before execution - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the swap status --- ## useTokenSwapOrder Imperative hook to execute a token swap through the Order API. It fetches a quote and either submits a transaction or prepares, signs, and submits an intent, handling any required ERC-20 approval first. ```tsx import { useTokenSwapOrder } from "@aave/react"; const [execute, state] = useTokenSwapOrder((plan) => { switch (plan.__typename) { case "Erc20Approval": return plan.bySignature ? signTypedData(plan.bySignature) : sendTransaction(plan.byTransaction); case "OrderTransactionRequest": return sendTransaction(plan.transaction); case "OrderTypedData": return signTypedData(plan); } }); const result = await execute(request); ``` **Arguments:** - `request: TokenSwapQuoteRequest` one of: - `market: MarketOrderTokenSwapQuoteInput` - Market order quote - `limit: LimitOrderTokenSwapQuoteInput` - Limit order quote - `fromQuote: MarketOrderTokenSwapFromQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useTokenSwapQuote Declarative hook to fetch a quote for a token swap. ```tsx title="Loading State" import { useTokenSwapQuote } from "@aave/react"; const { data, loading, error } = useTokenSwapQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useTokenSwapQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: TokenSwapQuoteRequest` one of: - `market: MarketOrderTokenSwapQuoteInput` - Market order quote - `limit: LimitOrderTokenSwapQuoteInput` - Limit order quote - `fromQuote: MarketOrderTokenSwapFromQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapQuote | undefined` - Swap quote - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useTokenSwapQuoteAction Imperative hook to fetch a quote for a token swap. ```tsx import { useTokenSwapQuoteAction } from "@aave/react"; const [execute, state] = useTokenSwapQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: TokenSwapQuoteRequest` one of: - `market: MarketOrderTokenSwapQuoteInput` - Market order quote - `limit: LimitOrderTokenSwapQuoteInput` - Limit order quote - `fromQuote: MarketOrderTokenSwapFromQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: SwapQuote | undefined` - Swap quote - `result: Result` - Type-safe success or failure value: - `Ok` - Swap quote - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- ## useUpdateUserPositionConditions Imperative transaction hook to update a user’s position conditions (dynamic config and/or risk premium). ```tsx import { useUpdateUserPositionConditions, UserPositionConditionsUpdate, } from "@aave/react"; const [execute, state] = useUpdateUserPositionConditions((transaction) => sendTransaction(transaction), ); const result = await execute({ userPositionId: userPosition.id, update: UserPositionConditionsUpdate.AllDynamicConfig, }); ``` **Arguments:** - `request.userPositionId: UserPositionId` - User position identifier - `request.update: UserPositionConditionsUpdate` - Type of update to perform: - `UserPositionConditionsUpdate.JustRiskPremium` - Update only the risk premium - `UserPositionConditionsUpdate.AllDynamicConfig` - Update all dynamic config (includes risk premium) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` --- ## useUserBalances Declarative hook to fetch user wallet balances across specified chains. ```tsx title="Loading State" import { useUserBalances } from "@aave/react"; const { data, loading, error } = useUserBalances({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserBalances({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.filter: UserBalancesRequestFilter` one of: - `chains: UserBalancesByChains` - Balances on specified chains - `chainIds: ChainId[]` - Chain IDs to query - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `hub: UserBalancesByHub` - Balances for Hub Assets - `address: EvmAddress` - Hub address - `chainId: ChainId` - Hub chain ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `spoke: UserBalancesBySpoke` - Balances for spoke reserves - `address: EvmAddress` - Spoke address - `chainId: ChainId` - Spoke chain ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `userPosition: UserBalancesByUserPosition` - Balances for user position - `userPositionId: UserPositionId` - User position ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `request.orderBy?: UserBalancesRequestOrderBy` one of: - `name: OrderDirection` - Sort by token name - `balance: OrderDirection` - Sort by balance - `request.includeZeroBalances?: boolean` - Include zero balances (default: false) - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserBalance[] | undefined` - Array of user wallet balances - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching user balances --- ## useUserBalancesAction Imperative hook to fetch user wallet balances. ```tsx import { useUserBalancesAction } from "@aave/react"; const [execute, state] = useUserBalancesAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.user: EvmAddress` - User address - `request.filter: UserBalancesRequestFilter` one of: - `chains: UserBalancesByChains` - Balances on specified chains - `chainIds: ChainId[]` - Chain IDs to query - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `hub: UserBalancesByHub` - Balances for Hub Assets - `address: EvmAddress` - Hub address - `chainId: ChainId` - Hub chain ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `spoke: UserBalancesBySpoke` - Balances for spoke reserves - `address: EvmAddress` - Spoke address - `chainId: ChainId` - Spoke chain ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `userPosition: UserBalancesByUserPosition` - Balances for user position - `userPositionId: UserPositionId` - User position ID - `byReservesType: ReservesRequestFilter` - Reserve type filter (default: ALL) - `tokens: UserBalancesByTokens` - Balances for specific tokens - `chainTokens: ChainTokenInput[]` - Array of chain-token pairs - `chainId: ChainId` - Chain ID - `token: TokenInput` one of: - `native: AlwaysTrue` - Native token - `erc20: EvmAddress` - ERC-20 token address - `byReservesType?: ReservesRequestFilter` - Reserve type filter (default: ALL) - `request.orderBy?: UserBalancesRequestOrderBy` one of: - `name: OrderDirection` - Sort by token name - `balance: OrderDirection` - Sort by balance - `request.includeZeroBalances?: boolean` - Include zero balances (default: false) **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching user balances - `state.called: boolean` - Whether the hook has been called - `state.data: UserBalance[] | undefined` - Array of user wallet balances - `result: Result` - Type-safe success or failure value: - `Ok` - Array of user wallet balances - `Err` - Error fetching user balances --- ## useUserBorrows Declarative hook to fetch all user borrow positions. ```tsx title="Loading State" import { useUserBorrows } from "@aave/react"; const { data, loading, error } = useUserBorrows({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserBorrows({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: UserBorrowsRequestQuery` one of: - `userSpoke: UserSpokeInput` - Get borrows for user on spoke - `spoke: SpokeId` - Spoke ID - `user: EvmAddress` - User address - `userToken: UserToken` - Get borrows for user for token - `user: EvmAddress` - User address - `token: Erc20Input` - Token input - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `userPositionId: UserPositionId` - Get borrows for user position - `userChains: UserChains` - Get borrows for user across chains - `user: EvmAddress` - User address - `chainIds: [ChainId!]` - Chain IDs - `userHub: UserHub` - Get borrows for user on hub - `user: EvmAddress` - User address - `hub: UserHubInput` - Hub input (hub ID or hub details) - `request.orderBy?: UserBorrowsRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `created: OrderDirection` - Sort by creation date - `amount: OrderDirection` - Sort by borrow amount - `apy: OrderDirection` - Sort by APY - `request.includeZeroBalances?: boolean` - Include zero balances (default: false) - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserBorrowItem[] | undefined` - Array of user borrow positions - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching user borrows --- ## useUserBorrowsAction Imperative hook to fetch user borrow positions. ```tsx import { useUserBorrowsAction } from "@aave/react"; const [execute, state] = useUserBorrowsAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.query: UserBorrowsRequestQuery` one of: - `userSpoke: UserSpokeInput` - Get borrows for user on a spoke - `spoke: SpokeId` - Spoke ID - `user: EvmAddress` - User address - `userToken: UserToken` - Get borrows for user for a specific token - `user: EvmAddress` - User address - `token: Erc20Input` - Token input - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `userPositionId: UserPositionId` - Get borrows for a user position - `userChains: UserChains` - Get borrows for user across chains - `user: EvmAddress` - User address - `chainIds: [ChainId!]` - Chain IDs - `userHub: UserHub` - Get borrows for user on hub - `user: EvmAddress` - User address - `hub: UserHubInput` - Hub input (hub ID or hub details) - `request.orderBy?: UserBorrowsRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `created: OrderDirection` - Sort by creation date - `amount: OrderDirection` - Sort by borrow amount - `apy: OrderDirection` - Sort by APY **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching user borrows - `state.called: boolean` - Whether the hook has been called - `state.data: UserBorrowItem[] | undefined` - Array of user borrow positions - `result: Result` - Type-safe success or failure value: - `Ok` - Array of user borrow positions - `Err` - Error fetching user borrows --- ## useUserClaimableRewards Declarative hook to fetch all claimable rewards for a user on a specific chain. ```tsx title="Loading State" import { useUserClaimableRewards } from "@aave/react"; const { data, loading, error } = useUserClaimableRewards({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserClaimableRewards({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.chainId: ChainId` - Chain ID - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserClaimableReward[] | undefined` - Claimable rewards - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the rewards --- ## useUserClaimableRewardsAction Imperative hook to fetch a user’s claimable rewards on demand. Does not watch for updated data; use it to retrieve data as part of a larger workflow. ```tsx import { useUserClaimableRewardsAction } from "@aave/react"; const [execute, state] = useUserClaimableRewardsAction(); const result = await execute(request); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.chainId: ChainId` - Chain ID **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching the rewards - `state.called: boolean` - Whether the hook has been called - `state.data: UserClaimableReward[] | undefined` - Claimable rewards - `result: Result` - Type-safe success or failure value: - `Ok` - Claimable rewards - `Err` - Error fetching the rewards --- ## useUserPosition Declarative hook to fetch a specific user position by ID. ```tsx title="Loading State" import { useUserPosition } from "@aave/react"; const { data, loading, error } = useUserPosition({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserPosition({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.id: UserPositionId` - Unique position identifier - `request.user: EvmAddress` - User address - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for historical data (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserPosition | null | undefined` - User position or null if not found - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the user position --- ## useUserPositions Declarative hook to fetch all user positions across specified chains. ```tsx title="Loading State" import { useUserPositions } from "@aave/react"; const { data, loading, error } = useUserPositions({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserPositions({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.filter: UserPositionsRequestFilter` one of: - `tokens: [Erc20Input!]` - Filter by tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `chainIds: [ChainId!]` - Filter by chain IDs - `request.orderBy?: UserPositionsRequestOrderBy` one of: - `created: OrderDirection` - Sort by creation date - `balance: OrderDirection` - Sort by position balance - `netApy: OrderDirection` - Sort by net APY - `healthFactor: OrderDirection` - Sort by health factor - `netCollateral: OrderDirection` - Sort by net collateral - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for historical data (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserPosition[] | undefined` - Array of user positions - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching user positions --- ## useUserPositionsAction Imperative hook to fetch user positions. ```tsx import { useUserPositionsAction } from "@aave/react"; const [execute, state] = useUserPositionsAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) - `options.timeWindow?: TimeWindow` - Time window for historical data (optional) **Arguments:** - `request.user: EvmAddress` - User address - `request.filter: UserPositionsRequestFilter` one of: - `tokens: [Erc20Input!]` - Filter by tokens - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `chainIds: [ChainId!]` - Filter by chain IDs - `request.orderBy?: UserPositionsRequestOrderBy` one of: - `created: OrderDirection` - Sort by creation date - `balance: OrderDirection` - Sort by position balance - `netApy: OrderDirection` - Sort by net APY - `healthFactor: OrderDirection` - Sort by health factor - `netCollateral: OrderDirection` - Sort by net collateral **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching user positions - `state.called: boolean` - Whether the hook has been called - `state.data: UserPosition[] | undefined` - Array of user positions - `result: Result` - Type-safe success or failure value: - `Ok` - Array of user positions - `Err` - Error fetching user positions --- ## useUserRiskPremiumBreakdown Declarative hook to fetch the risk premium breakdown for a user position or spoke. ```tsx title="Loading State" import { useUserRiskPremiumBreakdown } from "@aave/react"; const { data, loading, error } = useUserRiskPremiumBreakdown({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserRiskPremiumBreakdown({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.query: UserRiskPremiumBreakdownRequestQuery` one of: - `userPositionId: UserPositionId` - Get breakdown for user position - `userSpoke: UserSpokeInput` - Get breakdown for user on spoke - `user: EvmAddress` - User address - `spoke: SpokeId` - Spoke ID - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserRiskPremiumBreakdownItem[] | undefined` - Array of risk premium breakdown items - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the risk premium breakdown --- ## useUserSummary Declarative hook to fetch a user’s financial summary. ```tsx title="Loading State" import { useUserSummary } from "@aave/react"; const { data, loading, error } = useUserSummary({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserSummary({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.filter?.spoke.address: EvmAddress` - Filter by spoke address (optional) - `request.filter?.spoke.chainId: ChainId` - Filter by chain ID (optional) - `request.currency?: Currency` - Currency for value conversions (optional) - `request.timeWindow?: TimeWindow` - Time window for historical data (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserSummary | undefined` - Aggregated metrics including total collateral, total debt, health factor, etc. - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the user summary --- ## useUserSummaryHistory Declarative hook to fetch user summary history over time. ```tsx title="Loading State" import { useUserSummaryHistory } from "@aave/react"; const { data, loading, error } = useUserSummaryHistory({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserSummaryHistory({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.user: EvmAddress` - User address - `request.window: TimeWindow` - Time window for historical data - `request.filter?.chainIds: ChainId[]` - Filter by specific chain IDs (optional) - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserSummaryHistoryItem[] | undefined` - Array of historical user summary data points - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the user summary history --- ## useUserSupplies Declarative hook to fetch all user supply positions. ```tsx title="Loading State" import { useUserSupplies } from "@aave/react"; const { data, loading, error } = useUserSupplies({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useUserSupplies({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request.query: UserSuppliesRequestQuery` one of: - `userSpoke: UserSpokeInput` - Get supplies for user on spoke - `spoke: SpokeId` - Spoke ID - `user: EvmAddress` - User address - `userToken: UserToken` - Get supplies for user for token - `user: EvmAddress` - User address - `token: Erc20Input` - Token input - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `userPositionId: UserPositionId` - Get supplies for user position - `userChains: UserChains` - Get supplies for user across chains - `user: EvmAddress` - User address - `chainIds: [ChainId!]` - Chain IDs - `userHub: UserHub` - Get supplies for user on hub - `user: EvmAddress` - User address - `hub: UserHubInput` - Hub input (hub ID or hub details) - `request.orderBy?: UserSuppliesRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `created: OrderDirection` - Sort by creation date - `amount: OrderDirection` - Sort by supply amount - `apy: OrderDirection` - Sort by APY - `request.includeZeroBalances?: boolean` - Include zero balances (default: false) - `request.currency?: Currency` - Currency for value conversions (optional) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: UserSupplyItem[] | undefined` - Array of user supply positions - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching user supplies --- ## useUserSuppliesAction Imperative hook to fetch user supply positions. ```tsx import { useUserSuppliesAction } from "@aave/react"; const [execute, state] = useUserSuppliesAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request.query: UserSuppliesRequestQuery` one of: - `userSpoke: UserSpokeInput` - Get supplies for user on a spoke - `spoke: SpokeId` - Spoke ID - `user: EvmAddress` - User address - `userToken: UserToken` - Get supplies for user for a specific token - `user: EvmAddress` - User address - `token: Erc20Input` - Token input - `address: EvmAddress` - Token contract address - `chainId: ChainId` - Token chain ID - `userPositionId: UserPositionId` - Get supplies for a user position - `userChains: UserChains` - Get supplies for user across chains - `user: EvmAddress` - User address - `chainIds: [ChainId!]` - Chain IDs - `userHub: UserHub` - Get supplies for user on hub - `user: EvmAddress` - User address - `hub: UserHubInput` - Hub input (hub ID or hub details) - `request.orderBy?: UserSuppliesRequestOrderBy` one of: - `assetName: OrderDirection` - Sort by asset name - `created: OrderDirection` - Sort by creation date - `amount: OrderDirection` - Sort by supply amount - `apy: OrderDirection` - Sort by APY **Returns:** - `state.loading: boolean` - Loading state - `state.error: UnexpectedError | undefined` - Error fetching user supplies - `state.called: boolean` - Whether the hook has been called - `state.data: UserSupplyItem[] | undefined` - Array of user supply positions - `result: Result` - Type-safe success or failure value: - `Ok` - Array of user supply positions - `Err` - Error fetching user supplies --- ## useWithdraw Imperative transaction hook to withdraw supplied assets. ```tsx import { useWithdraw } from "@aave/react"; const [execute, state] = useWithdraw((plan) => { switch (plan.__typename) { case "TransactionRequest": return sendTransaction(plan); case "PreContractActionRequired": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request.reserve: ReserveId` - Reserve ID - `request.amount: WithdrawReserveAmountInput` one of: - `erc20: AmountInput` - ERC-20 amount (`{ exact: BigDecimal }` or `{ max: true }`) - `native: AmountInput` - Native token amount (`{ exact: BigDecimal }` or `{ max: true }`) - `request.sender: EvmAddress` - Address withdrawing the supply **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the transaction - `state.called: boolean` - Whether the hook has been called - `state.data: TransactionReceipt | undefined` - Transaction receipt - `result: Result` - Type-safe success or failure value: - `Ok` - Transaction receipt - `Err` - Error executing the transaction Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useWithdrawSwapOrder Imperative hook to execute a withdraw and swap through the Order API. It fetches a quote, collects the position-swap approval signatures, then prepares, signs, and submits the order. ```tsx import { useWithdrawSwapOrder } from "@aave/react"; const [execute, state] = useWithdrawSwapOrder((plan) => { switch (plan.__typename) { case "PositionSwapAdapterContractApproval": case "PositionSwapPositionManagerApproval": case "PositionSwapSetCollateralApproval": return signTypedData(plan.bySignature); case "OrderTypedData": return signTypedData(plan); case "OrderTransactionRequest": return sendTransaction(plan.transaction); } }); const result = await execute(request); ``` **Arguments:** - `request: WithdrawSwapQuoteRequest` one of: - `market: MarketWithdrawSwapQuoteInput` - Market order quote - `limit: LimitWithdrawSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteWithdrawSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error executing the order - `state.called: boolean` - Whether the hook has been called - `state.data: OrderReceipt | undefined` - Order receipt with the `orderId` - `result: Result` - Type-safe success or failure value: - `Ok` - Order receipt with the `orderId` - `Err` - Error executing the order Where `E` is one of: - `CancelError` - `SigningError` - `TimeoutError` - `TransactionError` - `UnexpectedError` - `ValidationError` --- ## useWithdrawSwapQuote Declarative hook to fetch a quote for a withdraw and swap. ```tsx title="Loading State" import { useWithdrawSwapQuote } from "@aave/react"; const { data, loading, error } = useWithdrawSwapQuote({ pause, ...request, }); ``` ```tsx title="React Suspense" const { data } = useWithdrawSwapQuote({ pause, suspense: true, ...request, }); ``` **Arguments:** - `request: WithdrawSwapQuoteRequest` one of: - `market: MarketWithdrawSwapQuoteInput` - Market order quote - `limit: LimitWithdrawSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteWithdrawSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) - `request.currency?: Currency` - Currency for value conversions (default: USD) - `pause?: boolean` - Pause the query (default: false) **Returns:** - `data: SwapQuote | undefined` - Swap quote - `loading: boolean` - Loading state - `error: UnexpectedError | undefined` - Error fetching the quote --- ## useWithdrawSwapQuoteAction Imperative hook to fetch a quote for a withdraw and swap. ```tsx import { useWithdrawSwapQuoteAction } from "@aave/react"; const [execute, state] = useWithdrawSwapQuoteAction(options); const result = await execute(request); ``` **Options:** - `options.currency?: Currency` - Currency for value conversions (default: USD) **Arguments:** - `request: WithdrawSwapQuoteRequest` one of: - `market: MarketWithdrawSwapQuoteInput` - Market order quote - `limit: LimitWithdrawSwapQuoteInput` - Limit order quote - `fromQuote: FromQuoteWithdrawSwapQuoteInput` - Quote from an existing quote ID (`quoteId`) **Returns:** - `state.loading: boolean` - Loading state - `state.error: E | undefined` - Error fetching the quote - `state.called: boolean` - Whether the hook has been called - `state.data: SwapQuote | undefined` - Swap quote - `result: Result` - Type-safe success or failure value: - `Ok` - Swap quote - `Err` - Error fetching the quote Where `E` is one of: - `UnexpectedError` - `ValidationError` --- Source: https://aave.com/docs/aave-v4/reference/big-decimal.md # BigDecimal Reference AaveKit represents all decimal numbers using the `BigDecimal` type to ensure high-precision arithmetic for financial computations. Whenever you interact with balances, rates, or amounts in the SDK, they are returned as `BigDecimal` instances. ```ts title="React" import { bigDecimal, BigDecimal, RoundingMode } from "@aave/react"; ``` ```ts title="TypeScript" import { bigDecimal, BigDecimal, RoundingMode } from "@aave/client"; ``` ## Key Features - Arbitrary precision arithmetic - Safe conversion from various numeric types - Display formatting with adaptive precision - Static utility methods for common operations - Type-safe operations that return `BigDecimal` instances > [!NOTE] > `BigDecimal` is **immutable**: methods always return a new instance. It is > based on [big.js](https://github.com/MikeMcl/big.js/) and behaves the same in > Node.js and browsers. ## Creating BigDecimals ```ts // From string (recommended for precision) const a = bigDecimal("123.456789"); // From number const b = bigDecimal(123.456); // From bigint const c = bigDecimal(123456789n); ``` ## Arithmetic Operations All arithmetic operations return new `BigDecimal` instances, making them safe for immutable workflows. ### Addition ```ts const a = bigDecimal("100"); const b = bigDecimal("50"); a.plus(b); // BigDecimal('150') a.add(b); // Alias for .plus() ``` ### Subtraction ```ts const a = bigDecimal("100"); const b = bigDecimal("30"); a.minus(b); // BigDecimal('70') a.sub(b); // Alias for .minus() ``` ### Multiplication ```ts const a = bigDecimal("10"); const b = bigDecimal("5"); a.times(b); // BigDecimal('50') a.mul(b); // Alias for .times() ``` ### Division ```ts const a = bigDecimal("100"); const b = bigDecimal("3"); a.div(b); // BigDecimal('33.333...') // Division by zero throws bigDecimal("10").div("0"); // Throws: ±Infinity bigDecimal("0").div("0"); // Throws: NaN ``` ### Modulo ```ts const a = bigDecimal("10"); const b = bigDecimal("3"); a.mod(b); // BigDecimal('1') ``` ### Power ```ts const a = bigDecimal("2"); a.pow(3); // BigDecimal('8') a.pow(-1); // BigDecimal('0.5') // Range: -1e+6 to 1e+6 inclusive ``` ### Square Root ```ts const a = bigDecimal("16"); a.sqrt(); // BigDecimal('4') // Negative numbers throw bigDecimal("-1").sqrt(); // Throws: NaN ``` ### Absolute Value ```ts const a = bigDecimal("-123.45"); a.abs(); // BigDecimal('123.45') ``` ### Negation ```ts const a = bigDecimal("123.45"); a.neg(); // BigDecimal('-123.45') ``` ## Comparison Methods All comparison methods are inherited from big.js: ```ts const a = bigDecimal("100"); const b = bigDecimal("50"); a.gt(b); // true - greater than a.gte(b); // true - greater than or equal a.lt(b); // false - less than a.lte(b); // false - less than or equal a.eq(b); // false - equal to a.cmp(b); // 1 - compare (-1, 0, or 1) ``` ## Rounding & Precision ### Rounding Modes ```ts enum RoundingMode { Down = 0, // Towards zero (truncate) HalfUp = 1, // Nearest neighbor; away from zero if equidistant HalfEven = 2, // Nearest neighbor; towards even if equidistant Up = 3, // Away from zero } ``` ### Round to Decimal Places ```ts const a = bigDecimal("123.456789"); a.round(2, RoundingMode.HalfUp); // BigDecimal('123.46') a.round(0, RoundingMode.Down); // BigDecimal('123') a.round(); // BigDecimal('123') - defaults to 0 dp ``` ### Round to Significant Digits ```ts const a = bigDecimal("123.456789"); a.prec(4, RoundingMode.HalfUp); // BigDecimal('123.5') a.prec(2, RoundingMode.Down); // BigDecimal('120') ``` ## Scaling Multiply by 10^decimals (commonly used for on-chain conversions): ```ts const amount = bigDecimal("1.5"); // Scale up (e.g., ETH to wei) amount.rescale(18); // BigDecimal('1500000000000000000') // Scale down (e.g., wei to ETH) const wei = bigDecimal("1500000000000000000"); wei.rescale(-18); // BigDecimal('1.5') ``` ## Display Formatting ### Adaptive Precision Display The `toDisplayString` method formats numbers based on their magnitude: ```ts const large = bigDecimal("1234.5678"); const small = bigDecimal("0.0001234"); // For numbers >= 1: preserves integer digits, controls decimal precision large.toDisplayString(6); // '1234.57' (all integer digits + 2 decimals) // For numbers < 1: uses significant figures small.toDisplayString(3); // '0.000123' (3 significant figures) ``` ### Formatting Options ```ts const num = bigDecimal("123.456789"); // Basic precision num.toDisplayString(5); // '123.46' // With rounding mode num.toDisplayString(4, { rounding: RoundingMode.Down }); // '123.4' // With minimum fraction digits num.toDisplayString(3, { minFractionDigits: 4 }); // '123.4568' (enforces 4 decimal places) // Trim trailing zeros num.toDisplayString(10, { trimTrailingZeros: true }); // '123.456789' (no trailing zeros) // Combined options bigDecimal("100.5000").toDisplayString(5, { minFractionDigits: 2, trimTrailingZeros: true, }); // '100.5' (trimTrailingZeros runs after minFractionDigits, so trailing zeros are removed even below the minimum) ``` ### Examples by Number Type ```ts // Large numbers: preserves all integer digits bigDecimal("1234567.89").toDisplayString(10); // '1234567.89' // Small decimals: significant figures bigDecimal("0.00001234").toDisplayString(3); // '0.0000123' // Zero handling bigDecimal("0").toDisplayString(5); // '0' bigDecimal("0").toDisplayString(3, { minFractionDigits: 2 }); // '0.00' ``` ## Conversion Methods ### To String ```ts const a = bigDecimal("123.456"); a.toString(); // '123.456' a.toJSON(); // '123.456' (used by JSON.stringify) a.toFixed(); // '123.456' (fixed-point notation) a.toFixed(2); // '123.46' (2 decimal places) a.toFixed(2, RoundingMode.Down); // '123.45' (with rounding mode) a.toExponential(); // '1.23456e+2' a.toExponential(2); // '1.23e+2' (2 decimal places) a.toPrecision(); // '123.456' a.toPrecision(2); // '1.2e+2' (2 significant digits) a.toPrecision(4, RoundingMode.Down); // '123.4' (4 sig digits) ``` ### To Number (Approximate) Convert to JavaScript `number` with safe clamping: ```ts const safe = bigDecimal("123.456"); safe.toApproximateNumber(); // 123.456 // Handles extreme values const huge = bigDecimal("1e500"); huge.toApproximateNumber(); // Number.MAX_VALUE (clamped) const tiny = bigDecimal("1e-500"); tiny.toApproximateNumber(); // 0 (subnormal → zero) const negHuge = bigDecimal("-1e500"); negHuge.toApproximateNumber(); // -Number.MAX_VALUE (clamped) ``` #### Use Cases - Displaying approximate values in UI - Interfacing with APIs requiring `number` types - When precision loss is acceptable > [!WARNING] > This loses precision. Use `BigDecimal` operations for exact calculations. ## Static Utility Methods ### Type Guard ```ts const value: unknown = bigDecimal("123"); if (BigDecimal.isBigDecimal(value)) { // value is BigDecimal value.plus("10"); } ``` ### Min/Max ```ts const a = bigDecimal("100"); const b = bigDecimal("50"); const c = bigDecimal("75"); BigDecimal.min(a, b, c); // BigDecimal('50') BigDecimal.max(a, b, c); // BigDecimal('100') // Minimum two arguments required BigDecimal.min(a, b); // BigDecimal('50') ``` ## Best Practices 1. **Use string literals for precision:** ```ts // Good const amount = bigDecimal("0.1"); // Risky (0.1 already has floating-point error) const amount = bigDecimal(0.1); ``` 2. **Chain operations for clarity:** ```ts const result = bigDecimal("100") .times("1.05") // Apply 5% increase .round(2, RoundingMode.HalfUp); ``` 3. **Store monetary values as `BigDecimal`:** ```ts interface Transaction { amount: BigDecimal; // not number currency: string; } ``` 4. **Use `toDisplayString()` for UI formatting:** ```ts // Adaptive precision for display const formatted = balance.toDisplayString(6); ```