Why Must State Updates Occur before External Calls?

State updates must occur before external calls to prevent a reentrancy attack. If an external call is made before the contract's state variables (like a user's balance) are updated, the external contract can recursively call back into the original function.

The original function will then execute again, seeing the old, un-updated state, allowing the attacker to withdraw funds repeatedly. By updating the state first, the re-entrant call will see the correct, updated balance and fail the check, protecting the funds.

What Is the Preventative Measure Called Checks-Effects-Interactions?
Can the CEI Pattern Prevent All Types of Reentrancy?
What Is Reentrancy and Why Is It a Critical Smart Contract Vulnerability?
What Is a Mutex in Traditional Programming, and How Does It Relate to a Reentrancy Guard?
Can a Reentrancy Attack Be Performed without a Fallback Function?
How Does a Reentrancy Attack Specifically Exploit Smart Contract Logic?
What Are the Differences between Single-Function and Cross-Function Reentrancy Attacks?
What Is the Checks-Effects-Interactions Pattern and How Does It Prevent Reentrancy?

Glossar