Emitting events lets a blockchain program send messages that others can see and react to. It helps track what happens inside the program.
0
0
Emitting events in Blockchain / Solidity
Introduction
When you want to notify users that something important happened, like a transfer of tokens.
When you want to keep a record of actions for later review or auditing.
When you want other programs or interfaces to respond to changes in your contract.
When you want to debug or log what your contract is doing during execution.
Syntax
Blockchain / Solidity
event EventName(type indexed param1, type param2); // To emit the event inside a function: emit EventName(value1, value2);
Events are declared once, usually at the top of the contract.
Use emit keyword to send the event when something happens.
Examples
This example shows a Transfer event with sender, receiver, and amount. It is emitted when tokens are sent.
Blockchain / Solidity
event Transfer(address indexed from, address indexed to, uint amount);
function send(address to, uint amount) public {
// ... transfer logic ...
emit Transfer(msg.sender, to, amount);
}This example emits a simple message event with a text string.
Blockchain / Solidity
event Message(string text);
function sayHello() public {
emit Message("Hello, blockchain!");
}Sample Program
This contract lets users deposit money. Each deposit emits a Deposit event with who sent money and how much.
Blockchain / Solidity
pragma solidity ^0.8.0;
contract SimpleBank {
event Deposit(address indexed accountHolder, uint amount);
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
}OutputSuccess
Important Notes
Events are stored in the blockchain logs and do not cost much gas compared to storing data.
Indexed parameters help filter events easily when searching logs.
Events cannot be read by contracts, only by external tools or users.
Summary
Events send messages from blockchain programs to the outside world.
Use emit to trigger events inside functions.
Events help track actions and communicate with users or other programs.