Skip to main content

How to Make a Flash Loan Using Aave on Base Sepolia

Updated on
Oct 23, 2026

12 min read

The code in this guide has not been audited. It is highly recommended that you audit any code before deploying it to production environments.

Overview​

A flash loan lets a smart contract borrow tokens without collateral, provided it returns the tokens plus a fee in the same transaction. This guide walks through deploying an Aave V3 receiver in Remix, borrowing 10 test USDC on Base Sepolia, and verifying repayment. The receiver performs no trades, so its prefunded USDC balance pays the fee. This example demonstrates the loan lifecycle, not an arbitrage strategy.

This guide uses Aave V3's Base Sepolia test market, which is available in Aave's app after enabling Test Mode. Resolve the market addresses from the address book before deploying.

TLDR​

  • Resolve the Base Sepolia provider, Pool, and USDC addresses with aave-address-book.
  • Deploy a Solidity receiver with Remix and a wallet connected to Base Sepolia.
  • Enable Aave's Test Mode, mint its Base Sepolia test USDC, and send one USDC to the receiver.
  • Borrow 10 USDC, approve repayment in the callback, and verify the successful transaction on Base Sepolia BaseScan.

What You Will Do​

  • Check that the selected market has usable USDC liquidity before deploying.
  • Distinguish wallet ETH for gas from contract USDC for the loan fee.
  • Authenticate the callback and restrict requests to the contract owner.
  • Confirm the loan's principal, fee, and repayment using events and token transfers.

What You Will Need​

  • A Quicknode account and a Base Sepolia Hypertext Transfer Protocol (HTTP) endpoint.
  • Node.js 24 with npm for the address lookup and read-only market check.
  • Remix IDE for compilation and deployment.
  • MetaMask or another browser wallet supported by Remix, with a dedicated test account.
  • Base Sepolia ETH for deployment, faucet claims, token transfers, and the flash loan transaction. Request gas tokens from the Quicknode faucet.
  • Aave's Base Sepolia test USDC, obtained in the funding section. Other tokens named USDC, including Circle's test USDC, are not interchangeable with this reserve.
  • Basic familiarity with Solidity, Ethereum Request for Comments 20 (ERC-20) tokens, and wallet transaction approval.

About Aave and Flash Loans​

Aave is a liquidity protocol where suppliers deposit assets and borrowers access those assets through smart contracts. Ordinary borrowing requires collateral. A flash loan instead relies on transaction atomicity: either every operation succeeds, including repayment, or the entire transaction reverts. A reverted transaction still consumes gas.

Aave V3's flashLoanSimple() borrows a single asset. The Pool transfers tokens to the receiver and calls its executeOperation() function. The receiver approves the principal plus the callback's premium; the Pool then pulls the repayment before the transaction ends. The fee is configurable, so read FLASHLOAN_PREMIUM_TOTAL() rather than assuming a fixed percentage. This value uses basis points: 5 means 0.05%.

Configure a Base Sepolia Endpoint​

Create a Base endpoint with Sepolia selected in the Quicknode dashboard, and copy its HTTP endpoint. Add it to your wallet as a custom remote procedure call (RPC) network using these settings:

SettingValue
Network nameBase Sepolia
RPC URLYour Quicknode Base Sepolia HTTP endpoint
Chain ID84532
Currency symbolETH
Block explorerhttps://sepolia.basescan.org

Switch your wallet to this network and claim Base Sepolia ETH. For the wallet configuration steps, see how to set a custom provider in MetaMask.

Keep your endpoint credentials local. The next section reads them from an environment file and does not need a private key.

Resolve Addresses and Check the Market​

Use the maintained aave-address-book registry, published as @aave-dao/aave-address-book, to select addresses for the same market. The USDC_UNDERLYING address identifies the token you borrow and transfer; USDC_A_TOKEN identifies the reserve's receipt token and holds its available underlying liquidity.

Create a small local project for the read-only check:

mkdir aave-flash-loan
cd aave-flash-loan
npm init -y
npm pkg set type=module
npm install --save-exact @aave-dao/aave-address-book@4.74.4 viem@2.57.7

Create .gitignore before adding credentials:

node_modules/
.env

Create .env, replacing the placeholder with your endpoint. Do not put a wallet private key in this file; you will sign transactions in your browser wallet.

QUICKNODE_RPC_URL=YOUR_QUICKNODE_BASE_SEPOLIA_HTTP_ENDPOINT

Create check-market.ts. This script gets addresses from the registry and reads the chain, provider, reserve configuration, available liquidity, decimals, and current fee. It rejects a wrong network or an unusable reserve before you spend gas deploying.

import { AaveV3BaseSepolia } from '@aave-dao/aave-address-book';
import { createPublicClient, formatUnits, http, parseAbi } from 'viem';
import { baseSepolia } from 'viem/chains';

async function main() {
const rpcUrl = process.env.QUICKNODE_RPC_URL;
if (!rpcUrl) throw new Error('Set QUICKNODE_RPC_URL in .env');
const client = createPublicClient({ chain: baseSepolia, transport: http(rpcUrl) });
if (await client.getChainId() !== baseSepolia.id) {
throw new Error('Use a Base Sepolia endpoint (chain ID 84532)');
}

const provider = AaveV3BaseSepolia.POOL_ADDRESSES_PROVIDER;
const pool = AaveV3BaseSepolia.POOL;
const usdc = AaveV3BaseSepolia.ASSETS.USDC;
const resolvedPool = await client.readContract({
address: provider,
abi: parseAbi(['function getPool() view returns (address)']),
functionName: 'getPool',
});
if (resolvedPool.toLowerCase() !== pool.toLowerCase()) {
throw new Error('Provider and registry Pool differ; check the address book');
}

const poolAbi = parseAbi([
'function FLASHLOAN_PREMIUM_TOTAL() view returns (uint128)',
'function getConfiguration(address asset) view returns ((uint256 data))',
]);
const tokenAbi = parseAbi([
'function decimals() view returns (uint8)',
'function balanceOf(address account) view returns (uint256)',
]);
const [premiumBps, config, decimals, liquidity] = await Promise.all([
client.readContract({ address: pool, abi: poolAbi, functionName: 'FLASHLOAN_PREMIUM_TOTAL' }),
client.readContract({ address: pool, abi: poolAbi, functionName: 'getConfiguration', args: [usdc.UNDERLYING] }),
client.readContract({ address: usdc.UNDERLYING, abi: tokenAbi, functionName: 'decimals' }),
client.readContract({ address: usdc.UNDERLYING, abi: tokenAbi, functionName: 'balanceOf', args: [usdc.A_TOKEN] }),
]);
const flag = (bit: bigint) => ((config.data >> bit) & 1n) === 1n;
if (!flag(56n) || flag(60n) || !flag(63n)) {
throw new Error('USDC is inactive, paused, or flash loans are disabled');
}
if (decimals !== 6 || liquidity < 10_000_000n) {
throw new Error('Unexpected USDC decimals or less than 10 USDC available');
}

console.log('Provider:', provider);
console.log('Pool:', pool);
console.log('USDC:', usdc.UNDERLYING);
console.log('USDC decimals:', decimals);
console.log('Available USDC:', formatUnits(liquidity, decimals));
console.log('Flash loan premium (basis points):', premiumBps.toString());
}

main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});

Run the check:

node --env-file=.env check-market.ts

Your output should look like this. The available USDC and flash loan premium can change:

Provider: 0xE4C23309117Aa30342BFaae6c95c6478e0A4Ad00
Pool: 0x8bAB6d1b75f19e9eD9fCe8b9BD338844fF79aE27
USDC: 0xba50Cd2A20f6DA35D788639E581bca8d0B5d4D5f
USDC decimals: 6
Available USDC: 35504417.735842
Flash loan premium (basis points): 5

Here is what each address is for:

  • Provider resolves the address of Aave's Pool. Pass this address to the constructor.
  • Pool handles the flash loan and repayment.
  • USDC is the test token you borrow and use to pay the fee.

Save the printed Provider and USDC addresses for the deployment and funding steps. If the check fails, resolve its error before continuing. Public testnet liquidity is shared and can change between this check and your transaction. If there is less than 10 USDC, wait for liquidity to become available and rerun the check before deploying.

Write the Flash Loan Smart Contract​

Open Remix, create contracts/SimpleFlashLoan.sol, and paste this contract. The versioned imports use Aave's V3 receiver base and ERC-20 interface. The constructor takes the provider and token addresses printed by your check.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {FlashLoanSimpleReceiverBase} from "@aave/core-v3@1.19.3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import {IPoolAddressesProvider} from "@aave/core-v3@1.19.3/contracts/interfaces/IPoolAddressesProvider.sol";
import {IERC20} from "@aave/core-v3@1.19.3/contracts/dependencies/openzeppelin/contracts/IERC20.sol";

/// @notice Educational receiver for Aave's Base Sepolia test USDC reserve.
contract SimpleFlashLoan is FlashLoanSimpleReceiverBase {
address public immutable owner;
IERC20 public immutable USDC;

event FlashLoanExecuted(uint256 amount, uint256 premium);

modifier onlyOwner() {
require(msg.sender == owner, "Only owner");
_;
}

constructor(address provider, address usdc)
FlashLoanSimpleReceiverBase(IPoolAddressesProvider(provider))
{
require(block.chainid == 84532, "Use Base Sepolia");
require(usdc != address(0), "Invalid USDC");
owner = msg.sender;
USDC = IERC20(usdc);
}

/// @notice Borrow an amount expressed in USDC's six-decimal base units.
function requestFlashLoan(uint256 amount) external onlyOwner {
require(amount > 0, "Amount is zero");
POOL.flashLoanSimple(address(this), address(USDC), amount, "", 0);
}

/// @notice Aave calls this after transferring the borrowed USDC.
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata
) external override returns (bool) {
require(msg.sender == address(POOL), "Only Aave Pool");
require(initiator == address(this), "Invalid initiator");
require(asset == address(USDC), "Unexpected asset");

// No trades: the prefunded USDC balance must cover the premium.
uint256 amountOwed = amount + premium;
require(USDC.balanceOf(address(this)) >= amountOwed, "Fund premium first");
require(USDC.approve(address(POOL), amountOwed), "Approval failed");
emit FlashLoanExecuted(amount, premium);
return true;
}

function getBalance() external view returns (uint256) {
return USDC.balanceOf(address(this));
}

function premiumBps() external view returns (uint128) {
return POOL.FLASHLOAN_PREMIUM_TOTAL();
}

/// @notice Recover unused test USDC after the transaction has completed.
function withdrawUSDC() external onlyOwner {
require(USDC.transfer(owner, USDC.balanceOf(address(this))), "Transfer failed");
}
}

requestFlashLoan() restricts borrowing to the deploying wallet. The callback verifies both the Pool caller and the loan initiator, preventing another account from making the Pool invoke this receiver to consume its fee balance. It approves only the amount owed. Aave pulls that amount after the callback returns; the receiver does not send a separate repayment transaction.

Deploy the Flash Loan Contract​

Compile the receiver, then deploy it using the addresses from the same market check:

  1. Open Remix's Solidity Compiler panel. Select compiler 0.8.20, expand Advanced Configurations, leave Optimization unchecked, and set EVM Version to paris (Ethereum Virtual Machine target). Then compile SimpleFlashLoan.sol.
  2. Open Deploy & Run Transactions, select Browser Extension from Environment, then choose your wallet (for example, MetaMask) from the wallet dropdown and connect your test account. Confirm your wallet is on Base Sepolia with chain ID 84532.
  3. Open the Deploy tab, select SimpleFlashLoan, and enter the printed Provider address as provider and the printed USDC address as usdc. Leave Value at zero.
  4. Click Deploy, approve the wallet transaction, and wait for its receipt.
  5. Open Deployed Contracts, expand your receiver, and copy its address. Call the owner(), USDC(), and POOL() read functions. Check that owner() returns your wallet address and that USDC() and POOL() match the token and Pool addresses printed by the script.

For source verification, enable Remix's Contract Verification plugin and verify on Base Sepolia using the same compiler, EVM target, optimization setting, and constructor arguments. If the selected verification service requests an API key, configure it in the plugin. Verification helps readers inspect deployed code; it does not audit the contract.

Fund the Flash Loan Premium​

Your wallet pays gas in Base Sepolia ETH. Your receiver pays the flash loan premium in the borrowed token, Aave's test USDC. First mint the test tokens to your wallet, then send one USDC to the receiver.

Mint Test USDC From Aave​

  1. Visit Aave's app and open Settings in the top-right corner.
  2. Enable Test Mode. Open the market selector and choose Base in the test-market list. Confirm the market header shows Base, Sepolia, and V3.
  3. Connect your test wallet and confirm it is on Base Sepolia (chain ID 84532).
  4. Open the Faucet tab, find USDC, and click its Faucet button.
  5. Approve the faucet transaction in your wallet and wait for confirmation. The faucet supplies more than the one USDC needed for this example.
Enable Test Mode to See the Faucet

The Faucet tab and test markets are hidden until you enable Test Mode in Aave's Settings. Select the Base Sepolia V3 test market and confirm your wallet is on chain ID 84532. Aave's faucet supplies reserve test tokens; obtain Base Sepolia ETH for gas from a separate ETH faucet.

Import USDC and Send the Fee Balance​

  1. In MetaMask, confirm Base Sepolia is selected. In the Tokens tab, open Import tokens (it may be under the three-dot menu) and choose Custom token.
  2. Paste the USDC address printed by check-market.ts as the token contract address. Confirm the symbol is USDC and decimals are 6, then import the token. Do not use an aToken address or another token merely named USDC.
  3. Open the imported USDC token, click Send, and paste your deployed SimpleFlashLoan contract address as the recipient.
  4. Enter 1 USDC in the wallet's amount field, review the recipient and amount, and confirm. Wallet amount fields use whole-token values, so enter 1, not 1000000.
  5. Wait for confirmation, return to your SimpleFlashLoan instance under Remix's Deployed Contracts, and call getBalance(). It should return 1000000, one USDC expressed in six-decimal base units.

Read the receiver's premiumBps() before borrowing. If it returns 5, a 10 USDC loan costs 0.005 USDC, or 5000 base units. One prefunded USDC covers that fee with room for repeated tests. If the fee changes, fund enough to cover the current premium. The callback uses the actual premium Aave passes, not this illustrative calculation.

Execute and Verify the Flash Loan​

Your receiver has the fee balance and is ready to borrow. Keep the deploying wallet selected, expand requestFlashLoan, and enter 10000000 as amount. USDC has six decimals, so this requests 10 USDC. Leave the transaction's ETH Value at zero, submit, and approve in your wallet.

After confirmation, open the transaction on BaseScan Sepolia explorer and verify:

  1. The transaction status is Success.
  2. In the Logs tab, find your receiver's FlashLoanExecuted event with amount = 10000000 and the actual premium.
  3. In the same tab, find the Aave Pool's FlashLoan event for your receiver and the USDC asset.
  4. Check the USDC token transfers. They should show the principal arriving from the reserve's aToken address and the principal plus premium returning to it.
  5. Back in Remix, call getBalance() on your receiver. With a starting balance of 1000000 and a premium of 5000, it should return 995000 (0.995 USDC).

For reference, see this successful 10 USDC flash loan on Base Sepolia. Its receiver source is verified on Sourcify, and its premium is 5000 base units (0.005 USDC).

A successful receipt confirms the entire transaction, including repayment after the callback. The borrowed principal does not remain in the receiver or your wallet. Call withdrawUSDC() from the deploying wallet to recover unused fee funds after testing.

Troubleshoot Failed Transactions​

  • Wrong chain or provider: Confirm chain ID 84532, rerun check-market.ts, and compare the constructor arguments with its output. The Pool address and provider address are different contracts.
  • Fund premium first: Transfer Aave's underlying test USDC to the receiver, then check getBalance(). ETH in your wallet cannot pay a USDC premium.
  • Only owner: Switch to the wallet that deployed the receiver.
  • Insufficient liquidity or a paused reserve: Rerun the market check. Wait for liquidity or an unpaused reserve before trying again. A successful faucet claim does not itself supply liquidity to Aave.
  • Gas estimation fails: Inspect the revert reason before submitting. Confirm your connected wallet is on Base Sepolia, then check the receiver's token balance, wallet gas balance, market configuration, and requested amount before increasing the gas limit.

Conclusion​

You deployed a receiver on Base Sepolia, funded its fee balance, and requested a single-asset Aave V3 flash loan. You can verify the full lifecycle through the receipt, events, token transfers, and remaining USDC balance.

Next Steps​

Review Aave's flash loan execution flow before adding trading logic inside executeOperation(). Any strategy must finish with enough of the borrowed asset to repay principal plus the actual premium. Keep this example on testnet; production strategies need additional controls and a security review.

Frequently Asked Questions​

What is a flash loan?

A flash loan lets a contract borrow assets without collateral when it returns the principal plus a fee within the same transaction. If repayment fails, the entire transaction reverts, but gas is still spent.

Why use Base Sepolia for this guide?

Aave's app exposes a Base Sepolia V3 test market and a reserve-token faucet in Test Mode. This guide resolves that market's addresses through aave-address-book and verifies available liquidity before deployment.

What is the fee for an Aave V3 flash loan?

Read FLASHLOAN_PREMIUM_TOTAL() on the selected Pool, or premiumBps() on this receiver. The value is in basis points, so 5 means 0.05%. The fee can change, and the callback's premium is the amount the contract must repay in addition to the principal.

Why can't I see Aave's test token faucet?

Enable Test Mode in Aave's Settings, select the Base Sepolia V3 test market, and open the Faucet tab. The faucet supplies reserve test tokens. Base Sepolia ETH for gas comes from a separate ETH faucet.

Can I use any Base Sepolia token named USDC?

No. Use the USDC underlying address in AaveV3BaseSepolia.ASSETS.USDC from aave-address-book. Aave's test reserve token is distinct from other USDC deployments, including Circle's test token and the reserve's aToken.

Do I need to supply collateral or fund the loan principal?

This flashLoanSimple example needs neither collateral nor a prefunded principal. The receiver needs enough Aave test USDC to cover the premium because it generates no trading profit, and the wallet needs Base Sepolia ETH for gas. The reserve must also have enough available liquidity.