Smart contract bugs / Is the math and the design right?
Business logic flaws
Each line of code is correct, but the design lets an attacker take value: rewards claimed twice, debt that disappears, a liquidation that pays the liquidated account.
OWASP SC02:2026 · 211 real exploits · $903.4M lost
How the attack works
- The protocol has an invariant that nobody wrote down, for example "total shares always match total assets".
- One path breaks it: a transfer that does not update a reward index, a burn that skips a debt check, a self-liquidation, a deposit and a withdraw in one block.
- The attacker repeats the path, often with a flash loan to make each step large.
- These bugs pass audits because no single function is wrong. The bug is in how the functions work together.
Vulnerable and fixed code
// Rewards use the balance at claim time, not the time held.
function claim() external {
uint256 owed = balanceOf(msg.sender) * rewardPerToken - paid[msg.sender];
paid[msg.sender] += owed;
reward.transfer(msg.sender, owed);
}
// Attack: claim, transfer the tokens to a 2nd address, claim again, repeat.// Settle rewards for both accounts on EVERY balance change.
function _update(address from, address to, uint256 amt) internal override {
_settle(from);
_settle(to);
super._update(from, to, amt);
}
function _settle(address a) internal {
if (a == address(0)) return;
owed[a] += balanceOf(a) * (rewardPerToken - paidPerToken[a]) / 1e18;
paidPerToken[a] = rewardPerToken;
}Review checklist
- Write the invariants of the protocol in plain words before you write code. Put them in the docs and in the tests.
- For each state variable, list every function that changes it. Check that all of them keep the invariants.
- Check the edge cases: the first and last user, zero amounts, the same address as sender and receiver, many actions in one block.
- If you fork a protocol, list each change that you made and why it keeps the invariants of the original.
How to test for it
- Write invariant (stateful fuzz) tests in Foundry or Echidna. Let the fuzzer call all functions in random order.
- Write a test for each attack path from the real examples below.
Real exploits (211)
-
Euler Finance: Euler Finance lost about $197M because the donateToReserves function, added in EIP-14, did not check the donor's account health, so an attacker could create bad debt and liquidate it for profit.
Root cause and fix
Vulnerable code:
EToken · donateToReservesThe donateToReserves function, added to Euler through EIP-14, lets users send eTokens to the reserves. It did not check that the donor's position stayed healthy afterwards. The attacker used flash-loaned funds and Euler's leverage to build a large position on one contract. That contract then donated eTokens, which left it with more dTokens than eTokens (underwater). A second contract acted as liquidator, bought the inflated eToken collateral at a discount, and withdrew the underlying assets.
What would have stopped it: Run a health-factor (solvency) check at the end of every function that lowers a user's collateral, including donateToReserves. Add invariant tests that no user action can leave an account undercollateralized, and review new upgrades for interactions with the liquidation logic.
-
Compound: Compound lost about $147M of COMP that was wrongly distributed by a bug in the updated Comptroller (Proposal 62), and the public drip() on the Reservoir let the loss grow.
Root cause and fix
Vulnerable code:
Comptroller · drip()A governance upgrade (Proposal 62) to the Comptroller contained a bug that made it pay out far too much COMP to users. About $80M was wrongly distributed at first. Anyone could call drip() on the Reservoir vault, which refilled the Comptroller from the 200k+ COMP stored there. That let the faulty distribution continue, bringing the total to about $147M. The article does not describe the exact code error.
What would have stopped it: Test and review reward-distribution changes thoroughly before a governance upgrade goes live, including checks on payout amounts. Add a pause or emergency stop, and limit how fast the Reservoir can refill the Comptroller, so a faulty release cannot be repeated while a fix is voted on.
-
Mirror Protocol: Mirror Protocol lost about $90M in October 2021 because its lock contract allowed unlock_position_funds to be called repeatedly for one position, and a second ~$2M loss in May 2022 came from a stale LUNC oracle price.
Root cause and fix
Vulnerable code:
mirror_lock · unlock_position_fundsThe mirror_lock contract had no duplicate-call check on withdrawals. The attacker called unlock_position_funds many times for their own position ID in one transaction. Each call released collateral again, so the contract paid out funds that other users had deposited. The article says the bug went unnoticed for seven months and was patched quietly in May 2022. A second, separate exploit used a stale LUNC oracle after the Terra relaunch.
What would have stopped it: Mark a position's locked funds as released (or delete the entry) in the same call that pays them out, and reject any repeat unlock for the same position. Add tests that call the unlock function several times in one transaction and check that the total paid out never exceeds what was locked.
-
Compound: Compound's Comptroller, after proposal 62, wrongly paid out about $80M in excess COMP rewards because of a ">" that should have been ">=" in two places.
Root cause and fix
Vulnerable code:
Comptroller (comptrollerImplementation)The reward calculation in the Comptroller implementation handled long-term users who were supplying or borrowing before compInitialIndex was set. It used ">" where it needed ">=" in two places, which broke the comparison against the initial index. Some users could then claim rewards they had not earned. Early claimants got hugely inflated payouts until the Comptroller's COMP balance ran low.
What would have stopped it: Write boundary-condition tests for the case where the user's index equals compInitialIndex, and for users who were active before the index was set. Run the upgrade on a mainnet fork and compare the reward amounts it produces with the expected amounts before the proposal goes live.
-
Uranium Finance: Uranium Finance, a Uniswap V2 fork on BSC, lost about $57.2M because a constant changed from 1000 to 10000 in only some places of the swap invariant check.
Root cause and fix
Vulnerable code:
UraniumPair · swap()When forking Uniswap V2, the team changed the fee scaling constant from 1000 to 10000 in two places of the UraniumPair swap check but not in the final comparison. This broke the constant-product (x*y=k) invariant check, so it no longer enforced the right amount of input. The attacker sent the minimum amount (1 wei) of a token to each pair and called the low-level swap() to take about 98% of the other token's reserves, draining many pools.
What would have stopped it: Do not edit core AMM invariant math in a fork without a full review, and keep the fee constants consistent across the whole formula. Add invariant and fuzz tests that check k never decreases after a swap, and get an audit of any changed code before deploying or migrating liquidity.
-
Aave (CoW Protocol swap integration): A user lost about $50M of aEthUSDT on Aave when a collateral swap via CoW Protocol routed through a ~$74k SushiSwap pool with ~99% price impact, because the new interface had no hard price-impact or slippage cap.
Root cause and fix
Vulnerable code:
SushiSwap AAVE/WETH pool (0xD75EA151a61d06868E31F8988D28DFE5E9df57B4)No contract was broken. The Aave interface's new CoW Protocol swap integration, which replaced the ParaSwap one in December 2025, lacked the old hard slippage cap of about 30%. A CoW solver routed a $50.4M USDT-to-AAVE swap through Uniswap V3 into WETH, then pushed 17,957 WETH into a SushiSwap AAVE/WETH pool holding only 17.65 WETH. That is about 1,017 times the pool's reserve, and the user got 327 AAVE (about $36k). The UI showed only warnings and a checkbox, which the user accepted on mobile. The 1.21% slippage setting did not help, because the quote itself already had a 99% price impact. An MEV bot then backran the distorted pools for about $12.5M.
What would have stopped it: Enforce a hard, default-on price-impact block (Aave later added Aave Shield, a 25% block) in the frontend and in solver or order validation, rather than only a warning and checkbox. When replacing an integration, test that every safety limit of the old one carried over. Reject routes that go through pools far smaller than the trade.
-
Aave: Aave lost $27.78M of healthy wstETH E-Mode positions to wrongful liquidations when its CAPO oracle was misconfigured and priced wstETH 2.85% too low.
Root cause and fix
Vulnerable code:
wstETH CAPO oracle · snapshotRatio / snapshotTimestamp updateThe wstETH CAPO oracle was initialized in early 2024 with a snapshotRatio of about 1.15 and left stale. On March 10, Chaos Labs' off-chain engine computed a correct ratio of about 1.2282 with a timestamp seven days back. The on-chain rate limiter (3% per 3 days) accepted only about 1.1919, but the timestamp was still set to the seven-day-old point. The two parameters no longer matched, so CAPO's growth-capped ceiling came out at about 1.1939, below the market rate of about 1.2285. Aave priced wstETH 2.85% too low, and liquidators took 34 leveraged E-Mode positions. AgentHub executed the update automatically one block later with no human review.
What would have stopped it: Update the ratio and timestamp together on-chain and reject any update where the ratio is clamped but the timestamp is not. Add a sanity check that the CAPO price stays within a tolerance of the underlying feed, and run simulations of the resulting prices before an automated update goes live. Also reconcile stale anchors regularly, and review near-misses.
-
Popsicle Finance: Popsicle Finance lost about $20M because fee rewards were not updated correctly when PLP tokens were transferred, so the same LP tokens could claim fees many times.
Root cause and fix
Vulnerable code:
Sorbetto Fragola · collectFees()The Sorbetto Fragola contract did not account for fees properly when LP (PLP) tokens were transferred. A new holder could call collectFees() and be paid rewards as if it had earned them, while the sender's reward accounting was not settled. The attacker flash-loaned large amounts from Aave and deposited into a pool with contract A. It moved the PLP tokens A to B to C, calling collectFees() at each hop, then moved them back to A and withdrew. B and C then each claimed millions in fees. The attacker repeated this across eight pools.
What would have stopped it: Update and settle a user's reward accounting (fee-per-share checkpoints) on every token transfer, not only on deposit and withdraw. Add tests that move LP tokens between several addresses and check that total claimable fees never exceed fees actually earned. This is the known RewardDistribution bug pattern, so audits should check for it.
-
bEarn (BearnFi): bEarn's BvaultsBank on BSC lost about $18M because withdraw treated the same amount as BUSD in the bank but as ibBUSD in the strategy.
Root cause and fix
Vulnerable code:
BvaultsBank · withdrawBvaultsBank's withdraw logic assumes the amount is denominated in BUSD. BvaultsStrategy's withdraw logic reads the same amount as ibBUSD, an interest-bearing token worth more than BUSD. The attacker flash-loaned about 7.8M BUSD from CREAM and deposited it into BvaultsBank, which sent it to the strategy and on to the Alpaca Vault for ibBUSD. They then withdrew the same nominal amount, which the strategy treated as ibBUSD worth more BUSD. The leftover credit built up over repeated rounds until the pool was drained, then the flash loan was repaid.
What would have stopped it: Use one consistent unit of account across the bank and strategy interfaces, or convert explicitly between BUSD and ibBUSD using the exchange rate. Add invariant tests that check a deposit followed by a withdrawal never returns more than was deposited.
-
Team Finance: Team Finance lost about $15.8M from locked Uniswap V2 liquidity of four projects (CAW, TSUKA, KNDX, FEG) because its migrate() function from V2 to V3 was flawed.
Root cause and fix
Vulnerable code:
Team Finance Liquidity Locks contract · migrate()The migrate() function, which moves locked Uniswap V2 LP positions to Uniswap V3, was flawed. The attacker had it move real V2 liquidity into a new V3 pair they controlled, with a skewed price. This left a large leftover that was refunded to the attacker as profit. The check on who may send was also bypassed by locking any token, so the attacker passed the authorization check.
What would have stopped it: Check in migrate() that the V3 pool or price comes from the canonical factory and is not set by the caller, and enforce a price or slippage bound on the migration. Tie the authorization check to ownership of the specific lock being migrated, not to the caller owning any lock.
201 more examples in the full guide.