Blog
Blockchain & Web313 min read
Implementing Flash Loans: Attack Vectors and Defensive Patterns
B
BADJO Dibéa Koffi
Published on May 8, 2026
What Are Flash Loans?
A flash loan lets you borrow any amount with zero collateral — as long as you repay within the same transaction. If you don't repay, the entire transaction reverts.
The Anatomy of an Attack
Every flash loan exploit follows the same pattern:
- Borrow a large amount via flash loan
- Manipulate a price oracle or liquidity pool
- Exploit a protocol that trusts the manipulated price
- Repay the flash loan from the profits
Real Exploit: Price Oracle Manipulation
// VULNERABLE: spot price from AMM
function getPrice(address token) public view returns (uint256) {
(uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(pool).getReserves();
return reserve1 * 1e18 / reserve0;
}This exact pattern was used in the bZx attack ($8M) and Harvest Finance ($34M).
Defense 1: TWAP Oracles
Never use spot prices. Use a time-weighted average:
function getTWAP(address pool, uint32 period) public view returns (uint256) {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = period;
secondsAgos[1] = 0;
(int56[] memory ticks,) = IUniswapV3Pool(pool).observe(secondsAgos);
int24 avgTick = int24((ticks[1] - ticks[0]) / int56(uint56(period)));
return OracleLibrary.getQuoteAtTick(avgTick, 1e18, token0, token1);
}Defense 2: Reentrancy Guards
modifier nonReentrant() {
require(_status != ENTERED, "ReentrancyGuard: reentrant call");
_status = ENTERED;
_;
_status = NOT_ENTERED;
}Defense 3: Same-Block Protection
mapping(address => uint256) public lastActionBlock;
modifier noSameBlockAction() {
require(lastActionBlock[msg.sender] < block.number, "Same block");
lastActionBlock[msg.sender] = block.number;
_;
}This breaks the flash loan pattern — borrowing and repaying must happen in different blocks.
The Bottom Line
If your price source can be manipulated in a single transaction, your protocol can be drained in a single transaction.
solidityflash-loanssecuritydefi
Comments
Stay Updated
Get my latest articles delivered straight to your inbox.