Introduction
Events help your blockchain program tell the outside world when something important happens. They make it easy to track and react to changes.
Events help your blockchain program tell the outside world when something important happens. They make it easy to track and react to changes.
event EventName(type indexed param1, type param2, ...);
event Transfer(address indexed from, address indexed to, uint256 value);event UserRegistered(address user, string name);
This contract starts with 1000 tokens for the creator. When tokens are sent, it updates balances and emits a Transfer event to notify listeners.
pragma solidity ^0.8.0; contract SimpleToken { event Transfer(address indexed from, address indexed to, uint256 value); mapping(address => uint256) public balances; constructor() { balances[msg.sender] = 1000; } function transfer(address to, uint256 amount) public { require(balances[msg.sender] >= amount, "Not enough tokens"); balances[msg.sender] -= amount; balances[to] += amount; emit Transfer(msg.sender, to, amount); } }
Events do not store data on the blockchain but create logs that external apps can read.
Use indexed for up to 3 parameters to make searching easier.
Events let your contract send messages about important actions.
Declare events with the event keyword inside your contract.
Emit events inside functions to log activity for external apps.
event in a blockchain smart contract?Transfer with two indexed address parameters from and to in Solidity?type indexed name inside parentheses.indexed after the type and before the parameter name.sendTokens is called?contract Token {
event Sent(address indexed from, address indexed to, uint amount);
function sendTokens(address receiver, uint amount) public {
emit Sent(msg.sender, receiver, amount);
}
}emit Sent(...) which triggers the event with given parameters.contract Example {
event LogMessage(string message);
function log(string memory msg) public {
emit LogMessage(msg);
}
}LogMessage with a string parameter is valid and emitted correctly.msg is allowed as a variable name; it does not conflict with reserved keywords.Approval that logs the owner, spender, and amount approved. You also want to filter logs by owner and spender efficiently. Which is the best event declaration?Pass the test and this pattern moves unknown