Spot the Bug: sends first, asks later
A withdraw sends the caller their funds with msg.sender.call{value: amt}(""), then runs balance[msg.sender] -= amt. The math is right and it works for a normal wallet. 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 withdraw sends the caller their funds with msg.sender.call{value: amt}(""), then runs balance[msg.sender] -= amt. The math is right and it works for a normal wallet. What is still wrong?
- A.Nothing, the subtraction happens so the accounting balances
- B.The external call runs before the balance drops, so a contract receiver can re-enter withdraw while its balance still reads full
- C.call is more expensive than transfer
- D.amt should be a uint256 not a uint
Answer and explanation
B. The external call runs before the balance drops, so a contract receiver can re-enter withdraw while its balance still reads full
The transfer hands execution to the receiver before the state update. If the receiver is a contract, its fallback runs while balance[msg.sender] is still the full amount, so it can call withdraw again and again against the same balance until the vault is empty.
2. How does the attacker actually drain the vault here?
- A.By deploying a contract whose receive/fallback calls withdraw again during the transfer, before the first call has decremented the balance
- B.By sending a huge amt that overflows the subtraction
- C.By front-running the transaction in the mempool
- D.By calling withdraw from two different wallets at once
Answer and explanation
A. By deploying a contract whose receive/fallback calls withdraw again during the transfer, before the first call has decremented the balance
The malicious contract's fallback re-enters withdraw during the external call. Because the balance is only reduced after the call returns, each nested call sees the full balance and passes its checks. The recursion repeats until the vault runs out of funds.
3. What is the correct fix?
- A.Wrap the transfer in a try/catch
- B.Update balance[msg.sender] -= amt before the external call, or add a nonReentrant guard: checks, effects, interactions
- C.Emit an event before the transfer
- D.Cap withdraw to one call per block
Answer and explanation
B. Update balance[msg.sender] -= amt before the external call, or add a nonReentrant guard: checks, effects, interactions
Reduce the balance first so any re-entrant call sees the lowered value and fails its own check, then do the external call. OpenZeppelin's ReentrancyGuard with nonReentrant closes the same window. The rule is checks, then effects, then interactions, in that order.
Read alongside: See it in real audits