What is a flash loan attack?

A flash loan attack is an exploit paid for with a loan that is borrowed and repaid inside a single transaction, so the attacker needs almost no money of their own. A flash loan scales up a flaw that was already there, such as a price read from a pool, a reward measured at the moment of a call, or a function that skips a solvency check. Write every check so it still holds against a caller who controls unlimited capital for the length of one transaction.

Last updated . 6 minute read. By the QuillAudits Team.

How does a flash loan attack work?

A flash loan lender sends tokens to a contract, calls it back, and checks before the transaction ends that the loan and a fee came back. If they didn't, the whole transaction reverts, so the lender takes no credit risk and can lend amounts few borrowers could post collateral for. ERC-3156 standardises the pattern: the lender calls onFlashLoan on the receiver, which must return a fixed hash for the loan to go through.

The attack runs inside that callback:

  1. Borrow a large amount from one or more flash loan lenders.
  2. Use it to move something the target trusts: a pool price, a vote count, a share of a reward pool, or the target's own accounting.
  3. Call the target while that value is wrong, and take out more than you put in.
  4. Unwind what you can, repay the loans and fees, and keep the difference.

Every step happens in one transaction, so a check that reads a balance, a price or a vote at the moment of the call sees whatever the attacker arranged a moment earlier. The useful review question for each check is: what if the caller held more tokens than the whole protocol, but only until the end of this transaction?

Which bugs do flash loans make worse?

  • Spot prices. A price computed from a pool's reserves moves with one large swap. The oracle price manipulation page covers this case.
  • Measurements taken at call time. Rewards, votes or fee shares computed from the balance someone holds at the moment they call, with no time requirement.
  • Share prices that move with donations, such as a young ERC-4626 vault's exchange rate. See the ERC-4626 inflation attack.
  • Missing solvency checks. A function that changes a position without checking that the account is still healthy afterwards. Euler's donateToReserves, below, is a well-documented case.
  • Rounding that pays a little on each call. Repeated thousands of times in one transaction, an error of one wei becomes a real loss. See rounding and precision errors.

What does vulnerable code look like?

This pool pays each epoch's rewards in proportion to the stake a caller holds when they claim. Nothing requires the stake to have been there before the call.

Vulnerable: rewards measured at the moment of the claim (illustrative, not audited code) EpochRewards.sol

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

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

contract EpochRewards {
    IERC20 public immutable stakeToken;
    IERC20 public immutable rewardToken;
    address public immutable owner;

    mapping(address => uint256) public staked;
    uint256 public totalStaked;
    uint256 public epoch;
    uint256 public epochRewards;
    mapping(uint256 => mapping(address => bool)) public claimed;

    constructor(IERC20 stakeToken_, IERC20 rewardToken_) {
        stakeToken = stakeToken_;
        rewardToken = rewardToken_;
        owner = msg.sender;
    }

    function stake(uint256 amount) external {
        require(stakeToken.transferFrom(msg.sender, address(this), amount), "transfer failed");
        staked[msg.sender] += amount;
        totalStaked += amount;
    }

    function unstake(uint256 amount) external {
        staked[msg.sender] -= amount;
        totalStaked -= amount;
        require(stakeToken.transfer(msg.sender, amount), "transfer failed");
    }

    function startEpoch(uint256 rewards) external {
        require(msg.sender == owner, "not owner");
        require(rewardToken.transferFrom(msg.sender, address(this), rewards), "transfer failed");
        epoch += 1;
        epochRewards = rewards;
    }

    // The share is the caller's stake right now. A stake that arrived
    // earlier in this same transaction counts in full.
    function claim() external {
        require(!claimed[epoch][msg.sender], "already claimed");
        claimed[epoch][msg.sender] = true;
        uint256 owed = (epochRewards * staked[msg.sender]) / totalStaked;
        require(rewardToken.transfer(msg.sender, owed), "transfer failed");
    }
}

An attacker flash-borrows the staking token, stakes it, claims, unstakes and repays, all in one transaction. With a stake many times larger than everyone else's, their share of totalStaked approaches 100%, so they take nearly the whole epoch's rewards for a stake that existed for no time at all.

How do you fix it?

Pay rewards for time staked, not for the balance at claim time. This version streams rewards per second and settles each account whenever its stake changes, so a stake added and removed in the same transaction earns nothing.

Fixed: rewards accrue per second staked (illustrative, not audited code) StreamedRewards.sol

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

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

contract StreamedRewards {
    IERC20 public immutable stakeToken;
    IERC20 public immutable rewardToken;
    address public immutable owner;

    uint256 public rewardRate; // reward tokens per second
    uint256 public periodFinish;
    uint256 public lastUpdate;
    uint256 public rewardPerTokenStored; // scaled by 1e18
    uint256 public totalStaked;
    mapping(address => uint256) public staked;
    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    constructor(IERC20 stakeToken_, IERC20 rewardToken_) {
        stakeToken = stakeToken_;
        rewardToken = rewardToken_;
        owner = msg.sender;
    }

    function lastTimeRewardApplicable() public view returns (uint256) {
        return block.timestamp < periodFinish ? block.timestamp : periodFinish;
    }

    function rewardPerToken() public view returns (uint256) {
        if (totalStaked == 0) return rewardPerTokenStored;
        uint256 elapsed = lastTimeRewardApplicable() - lastUpdate;
        return rewardPerTokenStored + (elapsed * rewardRate * 1e18) / totalStaked;
    }

    function earned(address account) public view returns (uint256) {
        uint256 accrued = rewardPerToken() - userRewardPerTokenPaid[account];
        return (staked[account] * accrued) / 1e18 + rewards[account];
    }

    // Settles the account before its stake changes. No time passes inside one
    // transaction, so a stake that comes and goes in it accrues nothing.
    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdate = lastTimeRewardApplicable();
        rewards[account] = earned(account);
        userRewardPerTokenPaid[account] = rewardPerTokenStored;
        _;
    }

    function stake(uint256 amount) external updateReward(msg.sender) {
        require(stakeToken.transferFrom(msg.sender, address(this), amount), "transfer failed");
        staked[msg.sender] += amount;
        totalStaked += amount;
    }

    function unstake(uint256 amount) external updateReward(msg.sender) {
        staked[msg.sender] -= amount;
        totalStaked -= amount;
        require(stakeToken.transfer(msg.sender, amount), "transfer failed");
    }

    function claim() external updateReward(msg.sender) {
        uint256 owed = rewards[msg.sender];
        rewards[msg.sender] = 0;
        require(rewardToken.transfer(msg.sender, owed), "transfer failed");
    }

    function startPeriod(uint256 amount, uint256 duration) external updateReward(address(0)) {
        require(msg.sender == owner, "not owner");
        require(duration > 0, "zero duration");
        require(block.timestamp >= periodFinish, "period running");
        require(rewardToken.transferFrom(msg.sender, address(this), amount), "transfer failed");
        rewardRate = amount / duration;
        periodFinish = block.timestamp + duration;
        lastUpdate = block.timestamp;
    }
}
  • Measure over time, not at a moment. Accrue rewards per second staked, read voting power from a snapshot taken before the vote opened, and read prices from a source that one transaction can't move.
  • Check health after every state change. Any function that lowers collateral or adds debt should end with the same solvency check that borrowing uses, donations and transfers of collateral tokens included.
  • Don't try to ban flash loans. A check such as require(tx.origin == msg.sender) also locks out smart contract wallets, and EIP-7702, which lets an externally owned account run code, lists guards of that style among the things it breaks. Fix the measurement instead.
  • If you receive flash loans, check who started them. ERC-3156 warns that no argument of the callback can be trusted without verification, and its reference borrower reverts unless the initiator is the borrower itself.

What happened in the Euler Finance flash loan attack?

Protocol Euler Finance
Date 13 March 2023
Chain Ethereum
Loss about $197M
What happened The attacker took a 30 million DAI flash loan from Aave V2 and deposited 20 million DAI into Euler. Its contract then used Euler's mint function to borrow against its own deposit, twice, and gave away 100 million eDAI through donateToReserves, a function added in the eIP-14 upgrade that did not check the health of the account making the donation. The position was left with debt and no matching collateral, and a second attacker contract liquidated it at Euler's maximum 20% discount and withdrew 38.9M DAI from the pool.
Sources Omniscia, Bloomberg

The flash loan paid for every step. Omniscia's post-mortem puts the cause in the donation mechanism, which did not account for the donor's debt health. Anyone holding 30 million DAI could have run the same steps; the loan only removed the need to hold it.

The function also arrived after launch, in an improvement proposal, which is why the guide to reviewing changes since your last audit uses the same case.

What should a reviewer check?

  • List every value the contract reads at call time: pool reserves, token balances, vault share prices, vote counts, reward shares.
  • For each one, ask what happens if the caller borrows enough to move it earlier in the same transaction.
  • Does every function that lowers collateral or adds debt end with a solvency check, including donations, collateral token transfers and self-liquidation paths?
  • Are rewards and voting power measured over time or from a past snapshot, never from the balance at the moment of the call?
  • Can a direct token transfer to the contract move its share price or exchange rate?
  • If the contract receives flash loans, does onFlashLoan check both the lender and the initiator?
  • Is there a test that gives the attacker more tokens than the protocol holds and runs the whole sequence in one transaction?

How does QuillShield check for flash loan attacks?

A flash loan attack crosses contracts: the lender, a pool, your protocol and often a second attacker contract. QuillShield runs a full audit of the Solidity codebase in your Foundry project, builds a security graph of the code and lists the invariants the code must keep. Before the audit you can add context such as the whitepaper, trust assumptions, privileged roles and previous audit reports, so write down which prices and balances you treat as trustworthy and why.

Before you see a finding, a separate reviewer agent has tried to disprove it. The ones that survive list the exact lines, the impact and a recommended fix, and full audits add a proof of concept. QuillShield then checks every pull request on GitHub or GitLab.com against the audit's security graph.

Run a full audit: sign-up is free, and new accounts get $50 in credit, good for up to half of an order. Full audits start at $49, as the pricing page shows. QuillShield does not replace a manual audit, and you can request a manual audit from QuillAudits.

FAQ

Is a flash loan attack a bug in the lender?

No. The lender gets its tokens back in the same transaction or the transaction reverts. The bug is in the protocol that trusted a value one transaction could move.

Can a flash loan attack happen without a flash loan?

Yes. Anyone with enough capital can run the same steps. Inverse Finance's write-up of its April 2022 incident says it was not a flash loan attack: the attacker started with 901 ETH withdrawn from Tornado Cash.

Should a protocol block flash loans?

It rarely works. An attacker can split a loan across lenders or use their own capital, and EIP-7702 breaks guards of the tx.origin == msg.sender style. Remove the dependency on values that one transaction can move.

How do I test for a flash loan attack in Foundry?

Write a test in which the attacker starts with more tokens than the protocol holds, runs the full sequence in one transaction, and then assert the protocol's solvency and balance invariants. If the invariants hold only while the attacker is short of capital, the code is vulnerable.

Which OWASP or SWC entry covers flash loan attacks?

The OWASP Smart Contract Top 10 (2025) lists them as SC07, Flash Loan Attacks. The SWC Registry has no entry for them.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts