Functions & Modifiers
Functions are executable units of code. Modifiers are higher-order functions that wrap around a function's execution, commonly used for access control checks (e.g. `onlyOwner`) or state validations.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A common pattern: using a modifier to gate access to a sensitive function.
Core Concepts
msg.sender
Global variable representing the address that called the function.
modifier
A compile-time code wrapper. The `_;` symbol is replaced by the function body.
view/pure
State mutability modifiers. View reads state; Pure reads nothing.
Mental Model
The Bouncer and the VIP Club
A **Modifier** is the bouncer at the club door. He checks your ID (`msg.sender`) before he lets you in (`_;`). If you don't pass the check (`require`), you get turned away immediately, and no resources are wasted inside.
Under the Hood
Modifiers result in 'bytecode inlining'. The compiler literally copies the modifier's code and pastes the function's code where the `_;` is. This means heavy modifiers increase contract size for every function they attach to.
Gas Analysis
Modifiers are generally efficient, but big modifiers bloat bytecode.
- • If a modifier is used many times and is large, consider making it call an internal function to reduce bytecode size.
Security Risks
Modifiers are the first line of defense.
- ! Incorrect logic in modifiers leaves the entire contract vulnerable.
- ! Forgeting `_;` causes the function to simply finish without executing its body.
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Click Run to execute the simulation
Then use the step controls to navigate