How Do State Variables Protect against Unexpected External Calls?

State variables protect against unexpected external calls primarily through the use of a "reentrancy guard" or a "lock" variable. This is a boolean state variable, initially set to false.

At the beginning of a critical function, the guard is set to true, and a check ensures it is not already true. At the end of the function, it is reset to false.

If an external call attempts to re-enter the function before the first execution completes, the check will fail, and the transaction will revert, effectively blocking the reentrancy.

Can a Reentrancy Guard Be Bypassed?
How Does the Concept of “Slippage” in Trading Relate to Unexpected Fee Changes?
What Is a Mutex in Traditional Programming, and How Does It Relate to a Reentrancy Guard?
What Happens to a Contract’s State Variables during a Mutable Upgrade?
Do Reentrancy Guards Protect against Both Single-Function and Cross-Function Attacks?
What Is the Concept of “Reentrancy” and How Does It Relate to Flash Loan Exploits?
How Can a Time-Lock Smart Contract Be Used to Prevent the Immediate Withdrawal of LP Tokens?
What Is the Overhead of Using a Reentrancy Guard?

Glossar