Crypto Training
DeFi Incident Patterns: Oracle Games, Rounding Edges, and the Same Bug in Three Costumes
bZx, PancakeBunny and Cream read like three unrelated hacks. In each one a number the attacker could set inside a transaction crossed into the protocol's accounting, and reading post-mortems for that crossing turns them into questions you can ask of any codebase.
After enough post-mortems the storylines start to repeat. The chain, the token and the DEX change from one incident to the next, while the failure underneath stays the same: the protocol accepted a number that somebody else could set, and wrote it into its own books.
This post reads three well-documented cases that way: the two bZx attacks of February 2020, PancakeBunny in May 2021 and Cream in October 2021. They are old enough that every detail is public, and each one shows a different kind of number going wrong. The mechanics of TWAPs and data feeds are in our post on oracles and TWAPs, so here we stay with the pattern and with how to extract it from a writeup.
External state crosses into accounting#
A protocol keeps internal books of shares, debt, collateral, fees and reserves. To update them it consults something outside those books, such as an AMM's reserves, a price feed, a token balance, a vault's share price or the result of its own swap. The update then treats that reading as if it were stable, honest and expensive to move.
An attacker needs to break only one of those three assumptions, and a flash loan usually removes the third. The useful question about any oracle is therefore what the attacker gets to choose, since "we use an oracle" says nothing about that.
The incidents side by side#
| Incident | Number the protocol read | How the attacker set it | Where it entered accounting |
|---|---|---|---|
| bZx, 15 Feb 2020 | execution price of its own ETH to WBTC swap | opened a short large enough to move the Uniswap pool about threefold | a position was accepted while under-collateralized |
| bZx, 18 Feb 2020 | Kyber spot rate for sUSD | about 900 ETH of sUSD buys on thin reserves | collateral value of the sUSD deposit |
| PancakeBunny, May 2021 | PancakeSwap pair reserves | flash-swapped about 2.3M WBNB into the pair | size of the BUNNY reward mint |
| Cream, Oct 2021 | pricePerShare() of the yUSD vault | shrank the vault's supply, then donated to it | collateral value of crYUSD |
The second and third columns are the ones to fill in first when reading a post-mortem. They say what was measured and who controlled it.
bZx had two attacks with different causes#
The two bZx attacks happened three days apart and are often cited together as "the flash loan attacks". Read closely, they have different root causes, which makes them a good first exercise.
On 15 February 2020 the attacker borrowed 10,000 ETH from dYdX, used 5,500 of it to borrow 112 WBTC on Compound, and sent 1,300 ETH to bZx to open a 5x short on WBTC. To build that position bZx sold 5,637 ETH for 51 WBTC through Kyber, which routed to Uniswap, at roughly three times the market price. The attacker then sold the 112 WBTC into the same distorted pool for 6,871 ETH and repaid the loan. According to palkeo's transaction-level analysis, no oracle was involved. bZx had a check that should have rejected a position that was under water the moment it opened, and a logic bug meant the check never ran for this path. The external number was the execution price of bZx's own trade, and the missing bound was on how bad that price could be.
On 18 February the number was an oracle in the usual sense. The attacker spent about 900 ETH buying sUSD through Kyber's reserves, which more than doubled the sUSD price Kyber reported, then deposited about 1.1M sUSD as collateral on bZx and borrowed 6,796 ETH against it. bZx valued the collateral at Kyber's current rate. palkeo estimates the loss to the protocol at about $600k in each attack.
The lesson we take from the pair is to ask two separate questions of any protocol that trades on behalf of users: which price it reads to value positions, and which price it accepts when it executes. samczsun had reported the price-reading problem to bZx and DDEX in September 2019, and his writeup Taking undercollateralized loans for fun and for profit describes it before any funds were lost.
PancakeBunny sized a mint from spot reserves#
PancakeBunny paid part of its yield in freshly minted BUNNY. When a user claimed, BunnyMinter.mintForV2 converted the performance fee through PancakeSwap pools, asked PriceCalculatorBSCV1.valueOfAsset for its value in BNB, and minted BUNNY in proportion. Both the conversion and the valuation depended on current pair reserves, and cmichel's post-mortem notes that the calculator took a pool's value to be twice its WBNB reserve.
The attacker held a small position in the vault, flash-borrowed about 2.3M WBNB, and swapped it into the WBNB/USDT pair so that its WBNB reserve was enormous for the length of the transaction. Calling getReward() at that moment minted about 6.97M BUNNY for a position worth a few hundred dollars. The BUNNY was sold in the same transaction and the loans repaid, leaving a profit that cmichel puts at 114,631 WBNB. Our replay shows the trace step by step.
Two details are worth carrying into audits. The manipulated reading sized a mint with no upper bound relative to the user's deposit or the vault's size, so the damage scaled with the distortion. And the same code path already used a Chainlink BNB/USD feed for a final conversion, which means an independent reference was available and did not gate the amount.
Cream treated a share price as a price#
Cream accepted yUSD, a Yearn vault token, as collateral and valued it using the vault's pricePerShare(). That figure is the vault's asset balance divided by its share supply. It only behaves like a price while deposits and withdrawals are the sole way to change either term.
Cream's post-mortem lays out the sequence of 27 October 2021. Using flash loans of $500M in DAI and about $2B in ETH across two addresses, the attacker built up roughly $1.5B of crYUSD collateral, then withdrew from the yUSD vault until its supply was about 8M. A direct transfer of about 8M of the underlying to the vault doubled pricePerShare, the collateral was now valued at $3B, and the attacker borrowed enough to repay the loans and take about $130M more, most of the liquidity in Cream's Ethereum v1 markets. Yearn later recovered $9.42M of the donation.
No AMM was manipulated, and Mudit Gupta's analysis argues the price change was real in the sense that the vault did hold those assets. That is the point of the case. A ratio of balance to supply can be moved by anyone who can donate to the numerator or redeem from the denominator, and a lending market that treats it as a price inherits that property. Cream's own summary is that the vulnerability lay in the price calculation of a wrappable token. Our replay shows the doubling in the trace.
What to extract from a post-mortem#
Four questions turn a narrative into something reusable.
- What was the protocol measuring?
- What did it assume about that measurement?
- How did the attacker invalidate the assumption, and what did it cost them?
- Why did the protocol accept the result without a second opinion?
If a writeup lets you answer all four, you can usually name the class of fix without reading the code. If it does not, the writeup is incomplete, and the transaction trace is the place to look.
Four ways the number goes wrong#
"The attacker manipulated the price" covers several distinct mechanisms, and the defences differ.
- Spot reserves. The protocol reads an AMM's current state, which reflects only the marginal price of that pool at that instant. PancakeBunny and the second bZx attack are this case.
- A ratio the attacker can donate to. Vault share prices, LP token values and exchange rates are balance over supply. Cream is this case, and the empty-market attacks on Compound forks are its descendants.
- The protocol's own execution. A trade made on the user's behalf moves the market, and the protocol accepts the resulting price. The first bZx attack is this case.
- A window that is shorter or thinner than it looks. A TWAP over a few samples of a thin pool can be walked over several blocks. Rodeo Finance lost about 472 ETH on Arbitrum in July 2023 to a TWAP built from four samples taken 30 minutes apart, all of which the attacker poisoned.
Reading from an AMM can be a sound design. It needs a bound that is sized for the pool actually being read.
A mitigation playbook#
No single control covers all four mechanisms, so the table lists what each one stops and what it leaves open.
| Mitigation | What it stops | What it does not stop | Cost |
|---|---|---|---|
| TWAP | single-transaction spot moves | sustained moves on thin pools, short windows | latency |
| External feed such as Chainlink | AMM microstructure | stale or wrong reports, misconfigured adapters | dependency |
| Minimum liquidity check | thin-pool reads | manipulation of deep pools | tuning |
| Maximum deviation against a second source | large anomalies in one source | slow drift, both sources wrong | tuning |
| Caps and rate limits | draining everything at once | slow drains below the cap | UX and tuning |
| Circuit breakers | extreme readings | exploitation inside the bounds | operations |
Which rows to pick depends on how much the protocol can lose in one block and how fast anyone can react. In the incidents above, either a second independent price signal or a hard limit on what one reading could move would have bounded the loss.
Why the first fix often fails#
"We switched to a TWAP"#
A TWAP raises the cost of an attack from one transaction to several blocks of sustained distortion. Whether that cost is high depends on the pool's liquidity and the window, and Rodeo's four samples on a thin Camelot pool were cheap to walk. The oracles and TWAPs post works through the arithmetic.
"We added a slippage check"#
A minimum-output check protects the party that sets it, for the trade it wraps. It does nothing for a protocol that mints shares, issues debt or sizes a reward from a price, since those paths have no counterparty asking for a minimum. They need a deviation bound against a reference the attacker does not control. bZx had such a check for margin positions and lost money on the path that skipped it.
"We rate-limited borrows"#
Caps help when they are set in advance and sized against the liquidity at risk. They cannot depend on a human noticing. In Moonwell's wrsETH incident on Base in November 2025, the incident report on the project's forum says the attack ran within 30 seconds of the first bad oracle reading, and the response afterwards was to set the market's supply and borrow caps to zero. A cap set far above normal usage leaves that whole margin available to an attacker.
Where rounding enters#
Rounding rarely makes the headline of an oracle incident, and it often decides whether the attack is free. Cream's attacker wrote the donation off. The later empty-market attacks on Compound and Aave forks used the same donation idea against a market with almost no supply, and there the rounding of the redeem path let the attacker take the donation back out, which reduced the cost of the attack to a flash-loan fee. Hundred Finance and Sonne are the standard examples.
We cover the direction each conversion should round in Rounding in DeFi, and the cases where several correct-looking steps combine in Compositional rounding attacks.
A manipulation drill for audits#
When a protocol looks sensitive to a spot reading, the fastest way to find out is to run the attack skeleton on a fork. The outline is always the same.
// Foundry fork test, schematic. Replace the placeholders with the protocol under review.
function test_spotSensitivity() public {
uint256 start = quoteToken.balanceOf(address(this));
deal(address(baseToken), address(this), SWAP_SIZE); // stands in for a flash loan
_swap(baseToken, quoteToken, SWAP_SIZE); // 1. move the pool the protocol reads
_protocolActionThatReadsPrice(); // 2. mint, borrow or claim at the moved price
_swap(quoteToken, baseToken, _received()); // 3. move the pool back
// 4. compare what step 2 handed out with what steps 1 and 3 cost in fees and slippage
emit log_named_int("net", int256(quoteToken.balanceOf(address(this))) - int256(start));
}
If step 2 creates value (shares, borrowing capacity, a reward) in proportion to the distortion, the design is exposed and the remaining question is only how large SWAP_SIZE has to be. The drill does not need realistic funding to answer that. For ratio-based prices, replace the swaps with a direct transfer to the vault or pool and a redemption afterwards.
An audit lens for every oracle read#
We apply the same four steps to each place where code reads an external number.
Identify what is read#
Decide whether it is a signed off-chain report, a TWAP, a pool's spot state, a virtual price, a share price or a figure the protocol computes from balances. Each has a different way of being wrong.
Estimate the manipulation budget#
Find out how much liquidity backs the reading, whether an attacker can borrow that much for one transaction, and whether they would need to hold the position across blocks.
Size the blast radius#
List what a wrong value permits, such as borrowing too much, redeeming too much, minting too many shares or rewards, escaping liquidation, or liquidating healthy positions. The last one is the subject of our post on liquidation as a security property.
Add a bound that matches#
A large blast radius needs a deviation limit against an independent source, a window and liquidity floor, a per-block or per-account cap, or a breaker that pauses on anomalies. If none can be added, the protocol is acting as a price oracle for whoever integrates it and should say so.
Code patterns that reduce oracle risk#
A deviation bound between two sources#
uint256 internal constant MAX_DEVIATION_BPS = 200; // 2%, tune per asset
error PriceDeviation(uint256 primary, uint256 anchor);
/// Both prices must already be in the same units and decimals.
function _checkedPrice(uint256 primary, uint256 anchor) internal pure returns (uint256) {
uint256 diff = primary > anchor ? primary - anchor : anchor - primary;
if (diff * 10_000 > anchor * MAX_DEVIATION_BPS) revert PriceDeviation(primary, anchor);
return primary;
}
The two sources should fail independently, for example a data feed and a TWAP from a deep pool. Reverting is the right response for borrowing and minting. Withdrawals and repayments need a path that still works when the check fails, otherwise the bound becomes a way to freeze users.
Settlement by balance deltas#
Where the external number is the output of a call to a token, router or hook, measure the balance before and after and account for the difference. Return values are the callee's claim about what happened.
Caps on the path that creates value#
If the price-sensitive path is a borrow or a mint, cap it per block, per account and per market. A cap turns a one-block loss of the whole market into a bounded loss and gives monitoring something to catch. Listing new collateral with a low cap and raising it as liquidity grows is the cheapest version of this.
Questions to keep from every post-mortem#
| Question | Why it matters |
|---|---|
| Can the attacker borrow the manipulation budget for one transaction? | Flash liquidity removes cost as a defence |
| Is the pool being read the deepest market for the asset? | A thin pool can stand in for the market only on paper |
| Does the reading respond to spot state, an average or a ratio of balances? | It decides which of the four mechanisms applies |
| What is the largest loss in one block? | It sizes caps and breakers |
| Can a donation be taken back out? | Rounding on the exit path decides whether the attack is free |
Sources#
- palkeo, the bZx attacks explained: transaction-level analysis of both February 2020 attacks.
- cmichel, PancakeBunny exploit post-mortem: the
mintForV2andvalueOfAssetcode path. - C.R.E.A.M. Finance post-mortem, 27 October 2021: the team's step-by-step account and loss figure.
- Mudit Gupta, Cream hack analysis: the argument that the listing decision was the root cause.
- samczsun, So you want to use a price oracle: a survey of oracle designs and earlier incidents.
- Moonwell forum, wrsETH oracle malfunction: timing of the attack and the cap changes that followed.
- ethereum.org, Oracles: background on oracle types.