Events
Events write searchable logs to the blockchain. Apps like wallets and block explorers listen for them, and they cost far less gas than storing the same data in contract storage.
Contracts cannot read their own logs. Events are for the outside world: a frontend, an indexer or a notification service. If your contract's own logic needs a value later, store it in a variable. If only the outside world needs it, emit an event.
Mark up to three parameters as indexed so clients can filter on them. Indexed values go into topics, which are searchable. Non-indexed values go into the data part of the log and are cheaper, but you cannot filter by them directly.
Emit an event whenever important state changes, such as transfers, approvals, ownership changes and deposits. The ERC-20 and ERC-721 standards require specific events, and wallets rely on them to show balances correctly.
Name events in the past tense, for example Deposited or OwnerChanged. Keep the parameters useful on their own, so that someone reading the logs can understand what happened without extra lookups.
contract Wallet { address public owner = msg.sender; mapping(address => uint256) public balanceOf; event Deposited(address indexed who, uint256 amount); event Withdrawn(address indexed who, uint256 amount); event OwnerChanged(address indexed oldOwner, address indexed newOwner); function deposit() external payable { balanceOf[msg.sender] += msg.value; emit Deposited(msg.sender, msg.value); } function withdraw(uint256 amount) external { require(balanceOf[msg.sender] >= amount, "Low balance"); balanceOf[msg.sender] -= amount; emit Withdrawn(msg.sender, amount); (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "Transfer failed"); } function setOwner(address next) external { require(msg.sender == owner, "Not owner"); emit OwnerChanged(owner, next); owner = next; } }
Try it yourself
Add an event Received(address from, uint256 amount) and a receive() external payable function that emits it, then compile. In Remix you can deploy the contract and read the event in the transaction logs.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.