Events & Logs
Events allow contracts to print logs to the blockchain. These logs are NOT accessible by other contracts (meaning you can't read them on-chain), but they are indexed and searchable by off-chain services (frontends, The Graph, indexers).
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
Emit an event whenever critical state changes.
Core Concepts
indexed
Adds the parameter to a Bloom Filter, enabling efficient searching/filtering of logs.
emit
The keyword to trigger an event.
logs
Data written to the transaction receipt, cheaper than storage.
Mental Model
The Megaphone
Emitting an event is like shouting into a megaphone. Your smart contract (the speaker) announces something happened. People in the crowd (the frontend/users) hear it and react. However, other contracts on stage *cannot* hear the megaphone logs.
Under the Hood
Events use the `LOG0` to `LOG4` opcodes. The number corresponds to the number of 'topics' (indexed parameters). Data is stored in a special 'Logs' field of the block, not in the state trie.
Gas Analysis
Events are much cheaper than Storage.
- • Store historical data (like a history of moves in a game) in Events, not Arrays, if the contract doesn't need to read it back.
- • Use `indexed` sparingly (costs more gas), only for fields you actually need to search by.
Security Risks
Events are reliable but not immediate for all observers.
- ! Phishing: Events can be spoofed by other contracts if frontends don't verify the `address` emitting the event.
- ! Don't rely on events for on-chain logic.
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