Flash loans allow uncollateralized borrowing of any amount, provided the funds are repaid within the same transaction. This mechanism enables attackers to manipulate prices, drain protocols, or execute governance attacks using borrowed capital. Flash loan exploits have cost over $250M, including PancakeBunny ($45M, 2021), bZx ($954K, 2020), and Euler Finance ($197M, 2023). Firepan's HOUND AI detects flash loan vulnerabilities automatically during development and post-deployment monitoring, covering continuous analysis across the full contract lifecycle.
Flash loans are atomic, uncollateralized loans that must be repaid in the same transaction. Protocols like Aave and dYdX offer them at near-zero cost. The atomic guarantee (all-or-nothing) was designed to prevent theft—if funds aren't repaid, the entire transaction reverts.
However, flash loans enable state-manipulation attacks:
Unlike traditional reentrancy, flash loan attacks don't require multiple transactions or external contracts—a single transaction can drain an entire protocol's reserves if it depends on spot prices.
Flash loan exploits typically follow the pattern:
// VULNERABLE — example only
// Demonstrates: Flash Loan Attack
// Do NOT use in production
pragma solidity ^0.8.0;
interface IFlashLoanReceiver {
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external returns (bool);
}
contract VulnerableProtocol is IFlashLoanReceiver {
mapping(address => uint256) public balances;
address public priceOracle; // Uses spot price for collateral
// VULNERABLE: Uses spot price (manipulable via flash loan)
function borrow(address token, uint256 amount) public {
uint256 tokenPrice = PriceOracle(priceOracle).getPrice(token);
uint256 collateralRequired = (amount * 120) / tokenPrice; // 120% collateral
require(balances[msg.sender] >= collateralRequired);
// Borrow proceeds...
}
// Flash loan receiver callback
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external override returns (bool) {
// VULNERABLE: State changes inside flash loan callback
// Attacker can manipulate price, borrow at inflated collateral, swap, liquidate
uint256 amountOwed = amount + premium;
IERC20(asset).approve(msg.sender, amountOwed);
return true;
}
}
contract Attacker {
VulnerableProtocol public target;
address public flashLoanProvider; // Aave, dYdX, etc.
function exploitFlashLoan(address token, uint256 borrowAmount) public {
// Step 1: Request flash loan
IFlashLoanProvider(flashLoanProvider).flashLoan(
address(this),
token,
borrowAmount,
abi.encodeWithSignature(
"executeOperation(address,uint256,uint256,address,bytes)",
token,
borrowAmount,
0,
address(this),
""
)
);
}
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external returns (bool) {
// Step 2: Attacker has 'amount' borrowed funds
// Swap on DEX to crash price
uint256 swapAmount = amount / 2;
IDex(DEX).swap(asset, USDC, swapAmount); // Crashes price
// Step 3: Borrow against new "cheap" asset, liquidate, or arbitrage
target.borrow(asset, amount); // Borrow at manipulated price
// Step 4: Liquidate at favorable price
target.liquidate(attacker_address); // Collect liquidation bonus
// Step 5: Repay flash loan
uint256 amountOwed = amount + premium;
IERC20(asset).approve(msg.sender, amountOwed);
return true; // Transaction succeeds, attacker keeps profit
}
}
| Protocol | Date | Loss | Root Cause | |----------|------|------|-----------| | PancakeBunny | 2021-05 | $45M | Price oracle manipulation via flash loan swap | | Euler Finance | 2023-03 | $197M | Flash loan to manipulate collateral, liquidate at favorable prices | | bZx (Fulcrum) | 2020-02 | $954K | Oracle price manipulation to trigger liquidations | | Harvest Finance | 2020-10 | $34M | Flash loan to crash stablecoin price, drain yield farm | | Balancer | 2020-08 | $500K | Liquidity pool token price manipulation |
Manual detection focuses on price dependencies and flash loan integration:
Red flags:
Firepan's HOUND AI performs multi-level analysis:
Firepan's HOUND AI engine detects flash loan exploits across all monitored contracts.
1. Use Time-Weighted Average Price (TWAP)
Never use spot price for critical calculations. Use Uniswap V3 TWAP:
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
function getTWAPPrice(address pool, uint32 timeWindow)
internal view returns (uint256)
{
(int56[] memory tickCumulatives, ) =
IUniswapV3Pool(pool).observe(new uint32[](2));
int56 tickCumulativeDelta = tickCumulatives[1] - tickCumulatives[0];
int24 timeWeightedTick = int24(tickCumulativeDelta / int56(uint56(timeWindow)));
return TickMath.getSqrtRatioAtTick(timeWeightedTick);
}
2. Use Chainlink Oracle with Circuit Breaker
Rely on external price feeds with deviation checks:
function getPrice(address token) public view returns (uint256) {
(, int256 answer, , uint256 updatedAt, ) = priceFeed.latestRoundData();
require(block.timestamp - updatedAt < 1 hours, "Stale price");
require(answer > 0, "Invalid price");
return uint256(answer);
}
3. Separate Flash Loan Callback Logic
Never modify critical state inside flash loan callbacks:
// SECURE: Callbacks don't modify core state
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external override returns (bool) {
// Only repay; no lending or liquidation logic here
IERC20(asset).approve(lender, amount + premium);
return true;
}
4. Whitelist Flash Loan Providers
Only accept flash loans from trusted sources:
mapping(address => bool) public whitelistedFlashLoanProviders;
function executeOperation(...) external override returns (bool) {
require(whitelistedFlashLoanProviders[msg.sender], "Untrusted provider");
...
}
5. Monitor for Flash Loan Attacks Post-Deployment
Track unusual liquidations, swaps, and arbitrage within single transactions. Use Firepan's post-deployment monitoring to detect flash loan attack patterns in mempool.
Q: What is flash loan attack in smart contracts?
A: Flash loan attack involves borrowing massive sums without collateral, manipulating prices or state, extracting value, then repaying the loan in a single transaction. The attacker profits while all borrowed funds are repaid, making theft undetectable.
Q: Which protocols have been exploited via flash loan?
A: PancakeBunny ($45M, 2021), Euler Finance ($197M, 2023), and bZx ($954K, 2020) suffered major flash loan attacks. Attackers manipulated oracle prices, triggered liquidations, and arbitraged token prices atomically within single transactions.
Q: How does Firepan detect flash loan attack?
A: Firepan traces flash loan flows, identifies price oracle calls within callbacks, detects state changes dependent on spot prices, simulates extreme price scenarios, and finds liquidation cascades and arbitrage paths that expose flash loan exploitability.
Q: Can flash loan attack be exploited after deployment?
A: Yes. Flash loans are instant; attackers can strike the moment a vulnerable contract is live. They typically target oracle-dependent protocols, liquidation engines, or governance mechanisms. Mempool attacks detect flash loan requests and frontrun them.
Q: How do I prevent flash loan attack?
A: Use Time-Weighted Average Price (TWAP) instead of spot price. Integrate Chainlink Oracle with deviation checks. Avoid state changes within flash loan callbacks. Whitelist flash loan providers. Monitor for unusual liquidation/arbitrage patterns post-deployment.
Flash loans democratized DeFi composability but introduced a new exploit vector: atomic price manipulation. Protocols that depend on spot prices or single-transaction state consistency remain vulnerable. Using Chainlink oracles and Uniswap TWAP, and separating callback logic from critical state changes, greatly reduces flash loan risk. Firepan's HOUND AI detects exploitable flash loan paths across all monitored contracts.
Start securing your smart contracts at https://app.firepan.com/
Firepan
12,453 contracts secured. 2,851 vulnerabilities blocked. 236 exploits prevented. Run a free surface scan — results in minutes, no credit card required.
Run Free Scan →