In this track: Smart contract security foundations
advanced · 4 MIN READ
Reentrancy explained with a counterexample
An unfinished withdrawal can expose an old entitlement to a callback.
LET’S PICTURE IT
A ticket is paid out before anyone marks it used.
SEE IT FOR YOURSELF
A valid counter call, step by stepStep 1 / 4
This example begins with count zero and a request to call increment(). No real contract is deployed.
This example begins with count zero and a request to call increment(). No real contract is deployed.Execution follows the code’s input and permission rules. A website button is not the access-control mechanism.The function reads zero, calculates zero plus one, and writes one to persistent storage.The accepted state contains count one. Later reads can inspect it. Events are emitted only if the code implements them.
Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.
Read the unsafe order
Suppose a toy withdrawal sends value before reducing the user’s recorded credit. During the external call, the old credit is still visible.
Follow the callback
The recipient can call the withdrawal path again before the first frame resumes. The second call may pass the same entitlement check.
Identify the invariant violation
The flaw is not simply that two frames exist. It is that application accounting permits more value to be released than the entitlement authorizes.
Test a corrected transition
Use consistent effects before interaction and suitable guards where needed. A local hostile receiver should attempt reentry and assert that total released value remains bounded.
Reason about the scenario
UNSAFE teaching order:
check credit
external payout
reduce credit afterward
Review with a local mock; do not deploy this order.
Pseudocode or a simplified scenario for local reasoning. This is not a production contract or a completed security review.
QUICK CHECK · NO PRESSURE
What makes the toy order unsafe?
The old entitlement can be reused while the first frame is unfinished.