DeFi Attacks
Finance
DeFi protocols manage billions in assets and present unique attack vectors including flash loans, oracle manipulation, and economic exploits.
Flash Loan Attacks
solidity
// Flash loans allow borrowing without collateral
// Must repay in same transaction
interface IFlashLender {
function flashLoan(uint256 amount) external;
}
contract FlashLoanAttacker {
function attack() external {
// 1. Borrow massive amount
lender.flashLoan(1000000 ether);
// 2. Manipulate price oracle
// - Swap on DEX to move price
// - Read manipulated oracle price
// 3. Exploit protocol using bad price
// - Borrow more than collateral allows
// - Liquidate positions unfairly
// 4. Profit
// 5. Repay flash loan (must happen in same tx)
}
function executeOperation(uint256 amount) external {
// Flash loan callback - execute attack here
// ...
// Repay loan + fee
}
}Price Oracle Manipulation
solidity
// VULNERABLE: Using spot price as oracle
function getPrice() public view returns (uint256) {
// BAD: Spot price can be manipulated
return reserve1 / reserve0;
}
// Attack pattern:
// 1. Flash loan large amount
// 2. Swap to move DEX price
// 3. Interact with protocol using bad price
// 4. Swap back
// 5. Repay flash loan, keep profit
// SECURE: Use TWAP (Time-Weighted Average Price)
// Or Chainlink oracles with multiple sources
// Real exploits:
// - bZx ($8M, 2020) - Flash loan + oracle manipulation
// - Harvest Finance ($24M, 2020) - USDC/USDT arbitrage
// - Cream Finance ($130M, 2021) - Oracle manipulation