0
0
Blockchain / Solidityprogramming~5 mins

Event declaration in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Events help your blockchain program tell the outside world when something important happens. They make it easy to track and react to changes.

When you want to notify users that a token transfer happened.
When you want to log that a new user registered on your contract.
When you want to track changes in contract ownership.
When you want to record that a payment was received.
When you want to signal that a specific action was completed.
Syntax
Blockchain / Solidity
event EventName(type indexed param1, type param2, ...);
Events are declared inside a contract but outside functions.
The keyword indexed allows filtering events by that parameter.
Examples
This event logs token transfers with sender, receiver, and amount.
Blockchain / Solidity
event Transfer(address indexed from, address indexed to, uint256 value);
This event logs when a new user registers with their address and name.
Blockchain / Solidity
event UserRegistered(address user, string name);
Sample Program

This contract starts with 1000 tokens for the creator. When tokens are sent, it updates balances and emits a Transfer event to notify listeners.

Blockchain / Solidity
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);
    }
}
OutputSuccess
Important Notes

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.

Summary

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.