DeFi Flash Loan Attacks Explained (Authorized Labs Only)
DeFi flash loan attack explained the honest way: flash loans are rarely the root bug. They are a same-block capital amplifier that turns a small logic, pricing, or access flaw into a large drain. This Andrax tutorial — by Syed Zada Abrar — covers ~65% theory, ~35% DVD / local lab pointers.
Prerequisites: Foundry + Slither Setup; Solidity Reentrancy Explained; Smart Contract Access Control Bugs Hunters Actually Find.
Also useful: Hub; How to Start Web3 Bug Hunting in 2026; Solidity Essentials.
Ethics fence: flash-loan PoCs belong in Damn Vulnerable DeFi, public CTF challenges, Remix VM, Foundry unit tests, or Anvil forks of public CTF / intentionally vulnerable lab code. Do not flash-loan attack live protocols, and do not broadcast exploit txs on mainnet or public testnets of in-scope bounty code. Cite OWASP’s 2026 ranking entry SC04: Flash Loan–Facilitated Attacks on the Smart Contract Top 10. Follow Immunefi rules.
What a flash loan is (developer mental model)
Aave documents flash loans as special transactions that borrow an asset without prior collateral, provided the borrowed amount plus fee is returned before the transaction ends (one-block / atomic borrow) (Aave v3 Flash Loans guide).
Conceptual flow (Aave-style; read their docs for exact APIs):
- Your receiver contract calls the pool (
flashLoan/flashLoanSimple). - Pool transfers funds, then calls your
executeOperation(callback). - Inside the callback you run arbitrary logic — swaps, deposits, liquidations, calls into a vulnerable target.
- Before the tx ends you repay amount + premium (or open an allowed debt position, depending on API mode).
- If repayment fails, the whole transaction reverts.
That atomicity is why flash loans matter to hunters: an attacker can temporarily control enormous inventory without owning it, as long as every step fits in one successful transaction.
Aave v3 notes two entry shapes: multi-asset flashLoan() and gas-lean single-asset flashLoanSimple(), plus a configurable fee (FLASHLOAN_PREMIUM_TOTAL) (guide). Treat fee percentages as protocol-defined and changeable — always read current docs / on-chain getters rather than memorizing blog numbers.
Amplifier vs root cause (the report framing that matters)
OWASP SC04 frames flash-loan–facilitated attacks as using large uncollateralized loans to magnify small bugs in logic, pricing, or arithmetic into large drains, via complex multi-step sequences in a single transaction (Top 10 overview).
When you write notes (and later bounty reports), separate:
| Layer | Question | Example |
|---|---|---|
| Root cause | What invariant broke without needing a loan? | Spot price from thin pool; missing access check; broken CEI |
| Amplifier | How did flash capital make it profitable / atomic? | Borrow → skew pool → borrow against fake collateral → repay |
| Impact | Funds / rights at risk now under program IVS | Direct theft, unfair mint, insolvent pool |
Triage teams see “flash loan attack” titles constantly. The ones that land explain the broken assumption first, then show the flash-loan path as the exploit vehicle.
Common flash-loan–facilitated shapes (theory)
1) Spot oracle / pool price skew
Borrow → swap hard on a low-liquidity pool that a protocol treats as price truth → borrow, mint, or liquidate against the fake price → unwind → repay. This is why the next guide (oracle manipulation) pairs tightly with this one. See also OWASP SC03: Price Oracle Manipulation (SC03).
2) Governance / voting power without snapshots
Borrow governance tokens → vote or pass a malicious proposal in the same window → repay. Root cause is often missing vote snapshots / timelock assumptions — flash loan is the amplifier.
3) Read-only / cross-function inconsistency windows
Flash capital funds a path that triggers callbacks or multi-module reads while state is mid-update (pairs with reentrancy guide).
4) Donation / share-inflation setups
Flash funds seed a vault or pool to manipulate share price before a victim (or the attacker’s second hop) deposits — related to ERC-4626 patterns covered later in this series (covered in a later guide in this path).
5) Liquidation / arbitrage that is intended
Not every flash loan is an exploit. Aave’s own docs list liquidation and arbitrage as legitimate applications (guide). Hunters must distinguish intended economic use from broken invariants.
ILLUSTRATIVE local pattern — flash callback into a bad price reader
This is a toy for mental models — not a copy of any live protocol and not a DVD solution.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// ILLUSTRATIVE / LOCAL LAB ONLY
interface IFlashLender {
function flashLoan(address receiver, uint256 amount) external;
}
interface IFlashReceiver {
function onFlashLoan(uint256 amount, uint256 fee) external;
}
/// Naive lender for Foundry demos — not Aave
contract ToyFlashLender is IFlashLender {
uint256 public constant FEE_BPS = 5; // 0.05% toy fee
function flashLoan(address receiver, uint256 amount) external {
uint256 balBefore = address(this).balance;
require(balBefore >= amount, "liquidity");
uint256 fee = (amount * FEE_BPS) / 10_000;
(bool sent, ) = receiver.call{value: amount}("");
require(sent, "send");
IFlashReceiver(receiver).onFlashLoan(amount, fee);
require(address(this).balance >= balBefore + fee, "not repaid");
}
receive() external payable {}
}
/// Victim trusts instantaneous "spot" from a manipulable reserve pair (sketch)
contract ToySpotOracle {
uint256 public reserveA = 100 ether;
uint256 public reserveB = 100_000 ether; // fake USD units
function spotPriceBPerA() public view returns (uint256) {
return (reserveB * 1e18) / reserveA;
}
function swapAForB(uint256 amountA) external payable {
require(msg.value == amountA, "value");
uint256 out = (amountA * reserveB) / (reserveA + amountA);
reserveA += amountA;
reserveB -= out;
// payout omitted for brevity in this sketch
}
}
Teaching point: the lender is not “vulnerable.” The oracle/consumer assumptions are. Your bounty write-up should name the consumer bug even if the exploit starts with flashLoan.
Lab pointers — Damn Vulnerable DeFi & local CTF (authorized only)
Option A — Damn Vulnerable DeFi (preferred curriculum lab)
Damn Vulnerable DeFi is a Foundry-oriented training ground with challenges covering flash loans, price oracles, governance, DEXes, lending pools, and more (site lists challenges such as Naive receiver, Side Entrance, The Rewarder, Selfie, Puppet variants, etc.). Follow the repository install / play instructions on the site.
How to use DVD ethically in this guide:
- Install and solve challenges locally per DVD rules.
- For each flash-loan-tagged level, write a private note: root cause · amplifier steps · invariant broken · fix idea.
- Do not paste full public spoilers into bounty reports for unrelated programs; do not “practice” the same pattern against live mainnet twins.
Option B — Anvil fork of a public CTF deployment
If a CTF publishes challenge contract addresses on a public network for the competition:
# Concept only — point RPC at a public endpoint YOU are allowed to use for read/fork
anvil --fork-url "$RPC_URL" --fork-block-number "$CTF_BLOCK"
Use the fork to run Foundry tests against CTF addresses. This is still not permission to attack random DeFi.
What you will not do in Andrax labs
- Flash-loan drain PoCs aimed at live protocols
- Mainnet “confirmation” txs inside bounty scope (Immunefi: testing on mainnet / public testnet of in-scope code can mean permanent ban — rules)
- Malware, phishing kits, or crime how-tos
Hunting checklist when you see flash-loan surface
- Which functions read spot / pool reserves / share price in the same tx as user actions?
- Can an attacker atomically: borrow → manipulate → benefit → repay?
- Are there governance actions without snapshots?
- Do callbacks (
executeOperation, hooks, ERC-777/721/1155 receivers) re-enter sensitive logic? - Is the “bug” actually intended liquidations/arbitrage?
- Can you prove impact on a local DVD/CTF/toy deployment?
Mapping to prior guides
| Prior skill | Flash-loan relevance |
|---|---|
| Access control | Unprotected executeOperation-style entry; wrong trusted caller |
| Reentrancy | Callback windows during flash repayment / hooks |
| Reading contracts | Trace pool → receiver → victim call graph on explorers (read-only) |
| Foundry | forge test against local lender + victim; optional Anvil CTF fork |
How to phrase findings (preview)
Bad: “Flash loan attack drains protocol.” Better: “Protocol X prices collateral from a single thin Uniswap V2 pair with no TWAP or external feed. An attacker can atomically skew reserves (flash liquidity), borrow against inflated collateral, and repay — demonstrated on local fork of the challenge deployment / Foundry fixtures. Root cause: unsafe spot dependency. Amplifier: flash loan.”
Severity still follows the program’s IVS (funds at risk), not whether a flash loan appeared in the PoC.
Common hunter traps
| Trap | Better habit |
|---|---|
| Blaming the flash-loan provider | Name the consumer invariant |
| Copying mainnet exploit txs as “PoC” | Rebuild on DVD / local toys |
| Ignoring fees / liquidity limits | Model profitability honestly in the lab |
| Treating every flash loan as Critical | Intended liquidations aren’t vulns |
| Skipping the next oracle guide | Most amplifiers are pricing assumptions |
Next steps
- Prev (live): Smart Contract Access Control Bugs Hunters Actually Find
- Live: Solidity Reentrancy Explained · Foundry + Slither · Hub
- Next (live): Oracle Manipulation in Smart Contracts: Spot, TWAP, Staleness
- Start DVD flash-loan-tagged challenges; keep a root-cause journal
Educational content by Syed Zada Abrar for Andrax (andraxpentester.in). Authorized research only. Toy contracts ILLUSTRATIVE / local lab only. No live protocol abuse.