Fallback & Receive
These are special functions that run when a contract receives ETH without data (`receive`) or when a function call doesn't match any exist function signature (`fallback`). They are the 'catch-all' handlers.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A Wallet that accepts ETH and logs unknown interaction attempts.
Core Concepts
msg.data
The raw calldata sent with the transaction.
Selection
Solidity tries to match function selector -> then receive() -> then fallback().
2300 Gas
Standard `transfer()` only forwards 2300 gas, barely enough to emit an event in receive().
Mental Model
The Receptionist
If you ask for a specific person (`function foo()`), you get them. If you walk in silently handing over cash, the `receive` receptionist takes it. If you walk in speaking gibberish, the `fallback` receptionist handles you (usually by kicking you out or redirecting you).
Under the Hood
The function selector dispatcher is just a `switch` statement in bytecode. If no case matches `msg.sig`, it jumps to the fallback block.
Gas Analysis
Keep receive/fallback extremely simple.
- • If receive() runs out of gas (because sender used `.transfer()`), the ETH transfer fails. Always test this.
- • Use `emit` only in fallback if you expect simple transfers.
Security Risks
The most common vector for Reentrancy.
- ! Attacker contracts put malicious logic in their `fallback` function to hijack control flow during a `.call()`.
- ! Always follow Checks-Effects-Interactions pattern.
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