Spot the Bug: spot price from reserves
A lending protocol prices collateral with getPrice(), which reads pair.getReserves() and returns r1 * 1e18 / r0. The math is right and the pool is real. What is still wrong?
Review and apply
Worked answers
Try the quiz above first, then open an answer to compare your reasoning. These notes are also available to read without completing an attempt.
1. A lending protocol prices collateral with getPrice(), which reads pair.getReserves() and returns r1 * 1e18 / r0. The math is right and the pool is real. What is still wrong?
- A.Nothing, reading live on-chain reserves is the safest oracle
- B.Reserves are the instantaneous price, which an attacker can move within one transaction
- C.getReserves() should be called twice and averaged in the same call
- D.The function should be external, not public
Answer and explanation
B. Reserves are the instantaneous price, which an attacker can move within one transaction
Pool reserves give you the spot price: the ratio right now. That number is attacker-writable state. A swap moves the reserves, so a swap moves the price the oracle reports, all inside a single transaction.
2. How does an attacker turn a spot-price feed into a profit in one transaction?
- A.Wait several blocks for the price to drift, then borrow
- B.Flash-loan, swap to move the pool, borrow against the inflated collateral, swap back, repay, all atomically
- C.Front-run the Chainlink update with a higher gas bid
- D.Deploy a fake pool and register it as the price source
Answer and explanation
B. Flash-loan, swap to move the pool, borrow against the inflated collateral, swap back, repay, all atomically
It is one atomic sequence: borrow a flash loan, swap to push the reserves, read the moved price, take a loan against collateral now valued at the chosen number, swap back, and repay the flash loan. No block needs to pass and nothing reverts.
3. What is the correct fix for pricing collateral in a lending protocol?
- A.Cache getReserves() at deployment and reuse the stored value
- B.Add a require that the caller is not a contract
- C.Use a manipulation-resistant oracle: a TWAP over a long enough window, or a trusted feed like Chainlink
- D.Read reserves from two different pools and take the higher price
Answer and explanation
C. Use a manipulation-resistant oracle: a TWAP over a long enough window, or a trusted feed like Chainlink
Never price off an instantaneous on-chain source an attacker can move in the same block. Use a time-weighted average over a window long enough to make manipulation expensive, or a trusted feed like Chainlink with staleness and sequencer checks. Even a TWAP is not free: too short a window can still be dragged with large liquidity.
Read alongside: See it in real audits