Events and Logs
Emit events for off-chain listeners.
Code
contract Events {
// Declare event (stored in logs, not state — cheaper)
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function transfer(address to, uint256 amount) external returns (bool) {
require(balanceOf[msg.sender] >= amount, "Insufficient");
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
// Emit event (indexed fields are searchable)
emit Transfer(msg.sender, to, amount);
return true;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
}
// Off-chain (JavaScript with ethers.js):
// contract.on("Transfer", (from, to, value) => {
// console.log(from, to, value.toString());
// });
// Filter: contract.queryFilter(contract.filters.Transfer(fromAddr))Explanation
Events are the standard way for contracts to communicate with off-chain apps. They're stored in transaction logs (much cheaper than state). indexed parameters (up to 3) enable efficient filtering — they're stored as topics in a Merkle tree. Non-indexed parameters are ABI-encoded in the data field. Use events for state changes that UIs/ indexers need to react to; do not use events as a cheap on-chain variable (off-chain readers can't easily read historical state at event time without an archive node).
More Solidity Snippets
Contract Basics
Define a basic smart contract with state and functions.
Functions and Visibility
Function visibility, payable, and return values.
Modifiers and Access Control
Reuse validation logic with modifiers.
Mappings, Structs & Nested Storage
Group related data with structs and look it up by key with mappings.
Inheritance, Abstract & Interfaces
Reuse logic via inheritance; define contracts with abstract and interface.
Payable, receive & fallback (ETH flows)
Receive ETH via payable functions and the receive/fallback hooks.