Real-world smart contract exploits analyzed with reconstructed vulnerable code, attack flow breakdown, and corrected implementations.
These examples are for defensive educational purposes — understanding past exploits prevents future ones.
The DAO was a decentralized investment fund on Ethereum holding ~$150M. An attacker exploited a reentrancy vulnerability in the splitDAO function to drain ~$60M. This led to the Ethereum hard fork creating Ethereum (ETH) and Ethereum Classic (ETC).
❌ Reconstructed vulnerable withdrawal logic:
contract VulnerableDAO {
mapping(address => uint256) public balances;
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "No balance");
// INTERACTION before EFFECT
// Attacker's receive() function calls withdraw() again
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
// This line never executes during reentrancy because
// the attacker re-enters before reaching it
balances[msg.sender] = 0;
}
receive() external payable {}
}- Attacker deposits 1 ETH into the DAO
- Attacker calls
withdraw()from a malicious contract - DAO sends 1 ETH to attacker's contract via
.call{value: amount} - Attacker's
receive()function triggers, callingwithdraw()again - DAO checks
balances[attacker]— still 1 ETH (not yet zeroed) - DAO sends another 1 ETH
- Steps 4-6 repeat until the DAO is drained or gas runs out
- Call stack unwinds,
balances[msg.sender] = 0executes once
✅ CEI pattern with reentrancy guard:
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract SecureDAO is ReentrancyGuard {
mapping(address => uint256) public balances;
function withdraw() external nonReentrant {
uint256 amount = balances[msg.sender];
require(amount > 0, "No balance");
// EFFECT before INTERACTION
balances[msg.sender] = 0;
// INTERACTION - even if attacker re-enters,
// balance is already 0
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
}Lesson: Always update state before making external calls. The Checks-Effects-Interactions pattern exists because of this exploit.
Parity's multisig wallet used a shared library contract for its logic. The library's initWallet() function was left unprotected. An attacker called initWallet() on the library itself, became its owner, then called selfdestruct. This destroyed the shared library, permanently freezing ~$150M across all wallets that depended on it.
❌ Library with unprotected initializer:
contract WalletLibrary {
address public owner;
bool public initialized;
// No protection — anyone can call this on the library contract itself
function initWallet(address _owner) external {
owner = _owner;
initialized = true;
}
function execute(address to, bytes calldata data) external {
require(msg.sender == owner, "Not owner");
(bool success, ) = to.call(data);
require(success);
}
// Owner could kill the library, freezing all dependent wallets
function kill() external {
require(msg.sender == owner);
selfdestruct(payable(owner));
}
}
contract MultiSigWallet {
address public library;
// All calls delegated to the shared library
fallback() external payable {
(bool success, ) = library.delegatecall(msg.data);
require(success);
}
}- Attacker calls
initWallet(attackerAddress)directly on the WalletLibrary contract (not through a wallet) - Attacker becomes the owner of the library contract itself
- Attacker calls
kill()on the library - Library is destroyed via
selfdestruct - All multisig wallets that
delegatecallto the library now call into empty code - ~$150M in ETH permanently frozen — no way to recover without a hard fork
✅ Protected initializer with constructor lockdown:
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract SecureWalletLibrary is Initializable {
address public owner;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
// Prevent the implementation/library contract itself
// from being initialized
_disableInitializers();
}
function initWallet(address _owner) external initializer {
require(_owner != address(0), "Zero address");
owner = _owner;
}
// No selfdestruct - shared libraries must never be destroyable
}Lesson: Library and implementation contracts must be initialized in their constructor or have initialization permanently disabled. Never include selfdestruct in shared library contracts.
The Beauty Chain (BEC) ERC-20 token had a batchTransfer function with an unchecked multiplication. An attacker created an astronomical number of tokens from nothing by exploiting integer overflow, crashing the token's value to zero.
❌ Unchecked multiplication in batchTransfer:
// Solidity < 0.8.0 had no built-in overflow protection
pragma solidity ^0.4.16;
contract BECToken {
mapping(address => uint256) public balanceOf;
function batchTransfer(address[] _receivers, uint256 _value) public returns (bool) {
uint256 cnt = _receivers.length;
// OVERFLOW: if _value is very large, cnt * _value wraps to a small number
uint256 amount = cnt * _value;
require(balanceOf[msg.sender] >= amount); // Passes because amount overflowed to small value
balanceOf[msg.sender] -= amount; // Subtracts tiny amount
for (uint256 i = 0; i < cnt; i++) {
balanceOf[_receivers[i]] += _value; // Adds huge _value to each receiver
}
return true;
}
}- Attacker calls
batchTransferwith 2 receiver addresses - Sets
_valueto2^255(half of uint256 max) amount = 2 * 2^255 = 2^256 = 0(overflows to 0 in uint256)require(balanceOf[msg.sender] >= 0)passes (always true)balanceOf[msg.sender] -= 0(no deduction)- Each receiver gets
2^255tokens — effectively infinite supply - Token value collapses to zero on exchanges
✅ Solidity 0.8+ with built-in overflow protection:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SecureToken {
mapping(address => uint256) public balanceOf;
function batchTransfer(
address[] calldata receivers,
uint256 value
) external returns (bool) {
// Solidity 0.8+ automatically reverts on overflow
uint256 amount = receivers.length * value;
require(balanceOf[msg.sender] >= amount, "Insufficient balance");
balanceOf[msg.sender] -= amount;
for (uint256 i = 0; i < receivers.length; i++) {
require(receivers[i] != address(0), "Zero address");
balanceOf[receivers[i]] += value;
}
return true;
}
}Lesson: Use Solidity 0.8+ which has built-in overflow/underflow protection. For older contracts, use OpenZeppelin SafeMath. Be especially cautious with multiplication before comparison.
An attacker used a flash loan to manipulate Uniswap spot prices, then used the manipulated price to over-borrow from bZx. The attack was executed in a single transaction, netting ~$8M profit.
❌ Using AMM spot price as lending oracle:
contract VulnerableLending {
IUniswapV2Pair public ethUsdcPair;
function getEthPrice() public view returns (uint256) {
(uint112 reserveETH, uint112 reserveUSDC, ) = ethUsdcPair.getReserves();
// Spot price — directly manipulable with a large swap
return (uint256(reserveUSDC) * 1e18) / uint256(reserveETH);
}
function borrow(uint256 collateralEth) external payable {
uint256 ethPrice = getEthPrice();
// Attacker inflated ethPrice via flash loan swap
uint256 maxBorrow = collateralEth * ethPrice * 75 / 100; // 75% LTV
// Lends far more than collateral is worth at real price
USDC.transfer(msg.sender, maxBorrow);
}
}- Attacker borrows large ETH amount via flash loan (e.g., 10,000 ETH)
- Swaps most ETH → USDC on Uniswap, massively increasing ETH spot price
- Calls
borrow()with small ETH collateral — price oracle returns inflated price - Borrows far more USDC than collateral is worth at real market price
- Swaps USDC back to ETH on a different venue at real price
- Repays flash loan
- Keeps the profit (~$8M) — the lending protocol holds bad debt
✅ Manipulation-resistant oracle with Chainlink:
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract SecureLending {
AggregatorV3Interface public immutable priceFeed;
uint256 public constant MAX_PRICE_AGE = 1 hours;
uint256 public constant MAX_DEVIATION = 10; // 10% max change
uint256 private lastKnownPrice;
function getEthPrice() public view returns (uint256) {
(, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
require(price > 0, "Invalid price");
require(block.timestamp - updatedAt <= MAX_PRICE_AGE, "Stale price");
// Circuit breaker: reject sudden extreme price moves
if (lastKnownPrice > 0) {
uint256 deviation = price > int256(lastKnownPrice)
? uint256(price) * 100 / lastKnownPrice - 100
: lastKnownPrice * 100 / uint256(price) - 100;
require(deviation <= MAX_DEVIATION, "Price deviation too high");
}
return uint256(price);
}
}Lesson: Never use AMM spot prices as oracles for financial operations. Flash loans make same-block manipulation trivially cheap. Use time-weighted averages (TWAP) or off-chain oracles like Chainlink.
Multiple protocols have lost funds to signature replay attacks where a valid off-chain signature is reused on a different chain, or submitted multiple times. This is a recurring vulnerability pattern rather than a single incident.
❌ Signature without uniqueness constraints:
contract VulnerableRelay {
address public admin;
function executeAction(
address to,
uint256 amount,
bytes calldata signature
) external {
// Signed message has no nonce, no chain ID, no contract address
bytes32 messageHash = keccak256(abi.encodePacked(to, amount));
bytes32 ethSignedHash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash)
);
address signer = ECDSA.recover(ethSignedHash, signature);
require(signer == admin, "Invalid signature");
// Same signature works:
// - Multiple times (no nonce)
// - On any chain (no chainId)
// - Against any deployed copy (no contract address)
payable(to).transfer(amount);
}
}- Admin signs a valid withdrawal for 10 ETH on Chain A
- Attacker captures the signature from the Chain A transaction
- Attacker submits the same signature on Chain B (same contract deployed there)
- Signature validates because it contains no chain-specific data
- 10 ETH drained on Chain B without admin authorization
- Alternatively: attacker replays on Chain A again (no nonce prevents reuse)
✅ EIP-712 typed structured data with replay protection:
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract SecureRelay is EIP712 {
address public admin;
mapping(address => uint256) public nonces;
bytes32 private constant ACTION_TYPEHASH = keccak256(
"ExecuteAction(address to,uint256 amount,uint256 nonce,uint256 deadline)"
);
constructor() EIP712("SecureRelay", "1") {}
function executeAction(
address to,
uint256 amount,
uint256 deadline,
bytes calldata signature
) external {
require(block.timestamp <= deadline, "Signature expired");
uint256 currentNonce = nonces[admin]++;
bytes32 structHash = keccak256(abi.encode(
ACTION_TYPEHASH,
to,
amount,
currentNonce,
deadline
));
// EIP-712 domain separator includes chain ID and contract address
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, signature);
require(signer == admin, "Invalid signature");
payable(to).transfer(amount);
}
}Lesson: Use EIP-712 typed data for all off-chain signatures. The domain separator binds signatures to a specific chain and contract. Nonces prevent replay on the same chain. Deadlines prevent indefinite validity.
The Ronin bridge connecting Axie Infinity to Ethereum was protected by a 5-of-9 validator multisig. Four of the nine validators were controlled by Sky Mavis (the developer), and a fifth had granted temporary access to Sky Mavis. When the Sky Mavis keys were compromised, the attacker had 5-of-9 and drained ~$625M in ETH and USDC.
❌ Centralized multisig with insufficient distribution:
contract VulnerableBridge {
address[] public validators; // 9 validators
uint256 public threshold; // 5 required
function processWithdrawal(
address token,
address to,
uint256 amount,
bytes[] calldata signatures
) external {
bytes32 hash = keccak256(abi.encode(token, to, amount));
uint256 validSigs = 0;
for (uint256 i = 0; i < signatures.length; i++) {
address signer = ECDSA.recover(hash, signatures[i]);
if (isValidator(signer)) validSigs++;
}
// 5 of 9 — but 5 keys were controlled by one organization
require(validSigs >= threshold, "Not enough signatures");
IERC20(token).transfer(to, amount);
}
}- Attacker compromised Sky Mavis infrastructure (4 validator keys)
- Sky Mavis had temporary authorization on a 5th validator (from Axie DAO)
- Attacker now controlled 5-of-9 validators — meeting the threshold
- Attacker forged withdrawal signatures for 173,600 ETH and 25.5M USDC
- Bridge processed the withdrawals as valid (5 valid signatures)
- Breach went undetected for 6 days — discovered when a user tried to withdraw
✅ Distributed key management with monitoring:
contract SecureBridge {
// Higher threshold, truly distributed validators
uint256 public constant THRESHOLD = 7; // 7 of 9
// Rate limiting to bound damage from compromise
uint256 public constant DAILY_LIMIT = 10_000 ether;
mapping(uint256 => uint256) public dailyWithdrawn; // day => amount
// Timelock for large withdrawals
uint256 public constant LARGE_WITHDRAWAL = 1_000 ether;
uint256 public constant TIMELOCK_DELAY = 24 hours;
mapping(bytes32 => uint256) public pendingWithdrawals;
function processWithdrawal(
address token,
address to,
uint256 amount,
bytes[] calldata signatures
) external {
// Validate signatures from truly independent parties
require(countValidSignatures(signatures) >= THRESHOLD);
uint256 today = block.timestamp / 1 days;
dailyWithdrawn[today] += amount;
require(dailyWithdrawn[today] <= DAILY_LIMIT, "Daily limit exceeded");
if (amount >= LARGE_WITHDRAWAL) {
// Queue large withdrawals with a delay
bytes32 id = keccak256(abi.encode(token, to, amount, block.timestamp));
pendingWithdrawals[id] = block.timestamp + TIMELOCK_DELAY;
emit LargeWithdrawalQueued(id, to, amount);
return; // Must call finalize() after delay
}
IERC20(token).transfer(to, amount);
}
}Lesson: Multisig security depends on actual key distribution, not just the number of keys. Combine multisig with rate limiting, timelocks for large operations, and real-time monitoring. No single organization should control enough keys to meet the threshold.
Audius, a decentralized music platform, was exploited for ~$6M when an attacker exploited a storage collision between their governance proxy and its implementation. The proxy allowed the attacker to bypass governance and execute a malicious proposal directly.
❌ Custom proxy with storage slot collision:
// The proxy stored governance-critical state at predictable slots
contract VulnerableGovernanceProxy {
// Slot 0: proxyAdmin
address public proxyAdmin;
// Slot 1: implementation
address public implementation;
// Governance implementation expected different layout at slots 0-1
// Attacker exploited the mismatch to manipulate governance state
fallback() external payable {
address impl = implementation;
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// Implementation expected slot 0 to be something else
contract GovernanceImplementation {
// Slot 0 here collides with proxyAdmin in the proxy
bool public initialized;
// Slot 1 collides with implementation address
address public guardian;
}- Attacker identified that proxy storage layout conflicted with implementation
- By calling an initialization function through the proxy, attacker overwrote governance state
- Attacker set themselves as guardian / governance authority
- Attacker submitted and executed a malicious governance proposal
- Proposal transferred ~$6M in AUDIO tokens to attacker's address
- Attacker immediately swapped tokens and bridged out funds
✅ EIP-1967 compliant proxy with deterministic slots:
contract SecureGovernanceProxy {
// EIP-1967 slots — computed from hash, will never collide with
// sequential storage used by implementations
bytes32 private constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
bytes32 private constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
constructor(address _implementation, address _admin) {
_setImplementation(_implementation);
_setAdmin(_admin);
}
function _setImplementation(address impl) private {
assembly { sstore(IMPLEMENTATION_SLOT, impl) }
}
function _setAdmin(address admin) private {
assembly { sstore(ADMIN_SLOT, admin) }
}
fallback() external payable {
address impl;
assembly { impl := sload(IMPLEMENTATION_SLOT) }
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}Lesson: Always use EIP-1967 standard storage slots for proxy state. Use OpenZeppelin's proxy contracts instead of custom implementations. Audit storage layouts when upgrading.
Cream Finance (and other DeFi protocols like Lendf.Me and imBTC) were exploited through ERC-777 token callbacks. ERC-777 tokens send a tokensReceived hook to the recipient during transfers, which creates a reentrancy vector even in seemingly safe token transfer code. Cream Finance lost ~$130M across multiple incidents.
❌ Not accounting for ERC-777 transfer hooks:
contract VulnerableLending {
mapping(address => mapping(address => uint256)) public deposits;
mapping(address => uint256) public totalDeposits;
function deposit(address token, uint256 amount) external {
// If token is ERC-777, this triggers tokensReceived on the recipient
// The attacker can re-enter during this transfer
IERC20(token).transferFrom(msg.sender, address(this), amount);
deposits[msg.sender][token] += amount;
totalDeposits[token] += amount;
}
function borrow(address token, uint256 amount) external {
uint256 collateralValue = calculateCollateral(msg.sender);
require(collateralValue >= amount, "Insufficient collateral");
IERC20(token).transfer(msg.sender, amount);
}
}- Attacker deploys a contract that implements
IERC777Recipient - Attacker calls
deposit()with an ERC-777 compatible token - During
transferFrom, the ERC-777 token callstokensReceivedon the lending contract - Inside the callback, attacker calls
borrow()— their deposit hasn't been recorded yet - But they manipulate collateral calculations by re-entering with carefully crafted state
- Or: attacker re-enters
deposit()again, getting credit for the same tokens multiple times - Attacker withdraws inflated balance
✅ ReentrancyGuard on all token-interacting functions:
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract SecureLending is ReentrancyGuard {
using SafeERC20 for IERC20;
mapping(address => mapping(address => uint256)) public deposits;
mapping(address => uint256) public totalDeposits;
function deposit(address token, uint256 amount) external nonReentrant {
// Record state BEFORE transfer (CEI pattern)
deposits[msg.sender][token] += amount;
totalDeposits[token] += amount;
// Transfer after state update — even if ERC-777 re-enters,
// the guard will block it
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 received = IERC20(token).balanceOf(address(this)) - balanceBefore;
// Adjust for actual received amount (fee-on-transfer)
if (received < amount) {
deposits[msg.sender][token] -= (amount - received);
totalDeposits[token] -= (amount - received);
}
}
function borrow(address token, uint256 amount) external nonReentrant {
uint256 collateralValue = calculateCollateral(msg.sender);
require(collateralValue >= amount, "Insufficient collateral");
IERC20(token).safeTransfer(msg.sender, amount);
}
}Lesson: Treat every token transfer as a potential reentrancy vector. ERC-777 tokens, ERC-1155 tokens, and any token with transfer hooks can trigger callbacks. Apply ReentrancyGuard and CEI pattern on all functions that interact with arbitrary tokens.
| Exploit | Year | Loss | Category | Root Cause |
|---|---|---|---|---|
| The DAO | 2016 | ~$60M | Reentrancy | External call before state update |
| Parity Multisig | 2017 | ~$150M frozen | Access Control | Unprotected library initializer + selfdestruct |
| BEC Token | 2018 | Token collapse | Integer Overflow | Unchecked multiplication in batch transfer |
| bZx | 2020 | ~$8M | Oracle Manipulation | AMM spot price as lending oracle |
| Signature Replay | Various | Various | Signature | Missing nonce, chain ID, contract binding |
| Ronin Bridge | 2022 | ~$625M | Access Control | Centralized multisig key management |
| Audius | 2022 | ~$6M | Storage Collision | Custom proxy with slot conflicts |
| Cream Finance | 2021 | ~$130M | Reentrancy | ERC-777 token transfer callbacks |
| Attack Vector | Primary Defense | Secondary Defense |
|---|---|---|
| Reentrancy | CEI pattern + ReentrancyGuard | Token callback awareness (ERC-777/1155) |
| Access Control | Modifiers + two-step ownership | Multisig + timelock for admin functions |
| Integer Overflow | Solidity 0.8+ built-in checks | Careful unchecked block review |
| Oracle Manipulation | Chainlink or TWAP oracle | Circuit breakers + deviation bounds |
| Signature Replay | EIP-712 + nonce + domain separator | Signature deadlines |
| Key Compromise | Distributed multisig + rate limiting | Timelocks + monitoring + alerting |
| Storage Collision | EIP-1967 standard slots | OpenZeppelin proxy contracts |
| Flash Loan Attacks | Manipulation-resistant oracles | Same-block manipulation detection |