Events [solidity]

 Events

Introduction

Each transaction has an attached receipt, which contains zero or more log entries. The log entries represent the result of the events having been fired from a smart contract. An event in Solidity is defined as:


event <event_name> (<event_parameters>)


After you have defined an event, you can call it or trigger it from inside any function you wish. You can call an event using the emit keyword in the following manner:


emit <event_name> (<event_arguments>)


// SPDX-License-Identifier: MIT

pragma solidity ^0.8.13;


contract Event {

    // Event declaration

    // Up to 3 parameters can be indexed.

    // Indexed parameters helps you filter the logs by the indexed parameter

    event messLog(address indexed sender, string message);

    event messLog2();


    function test() public {

        emit messLog(msg.sender, "Hello World!");

        emit messLog(msg.sender, "Hello EVM!");

        emit messLog2();

    }

}

Indexing Events using Indexed Keyword

DApps, or anything connected to the Ethereum JSON-RPC API, can listen to these events and act accordingly. An event can be indexed, so that the event history is searchable later.

You can use the indexed keyword before the parameter when you want an event to be indexed. This is useful in case someone wants to search the history and filter the events on a particular index.

These indexed parameters are stored inside the logs inside a special kind of data structure called 'topics'.


event Transfer(address indexed from, address indexed to, uint amount);

contract Test {

   event Deposit(address indexed _from, bytes32 indexed _id, uint _value);



   function deposit(bytes32 _id) public payable {      

      emit Deposit(msg.sender, _id, msg.value);

   }

}



Comments