Events in Solidity

Published by Mario Oettler on

Introduction to Ethereum Events

Light clients do not evaluate the whole blockchain. But in some cases, it would be convenient for them to react upon a function call in a certain contract. Imagine you want to get informed by e-mail as soon as someone sent some Ether to your smart contract. The smart contract cannot communicate with you. That’s why clients have to observe the blockchain for any change.

The first way to do this is to monitor all transactions and state changes in a smart contract. But that is very cumbersome and infeasible for light clients.

For that reason, Ethereum introduced events. Events are basically a separated data storage that can be read easily by nodes. Light clients can subscribe to certain events with the full node they connect to. The location where events are stored is called transaction logs (or sometimes just log).

The documentation says:

These logs are associated with the address of the contract, are incorporated into the blockchain, and stay there as long as a block is accessible (forever as of now, but this might change with Serenity). The Log and its event data is not accessible from within contracts (not even from the contract that created them).

Using Events in Solidity

An event needs to be declared in the smart contract. This is done similarly to declaring a variable. The emittance of an event is done with the keyword emit in the respective function.

pragma solidity 0.8.20;
contract events{
    event myFirstEvent(address indexed sender, uint256 indexed amount, string message);
    function executeEvent(string memory _message) public payable returns(string memory){
        emit myFirstEvent(msg.sender, msg.value, _message);
        return _message;

The declaration starts with the keyword “event” followed by the name of the event. Then, as parameters, you declare what data types your parameters have.

The attribute “indexed” adds the parameters to a special data structure called topics. Each topic consists of the topic name and the data field. The topic name is a 32 bit field that describes what happened in the smart contract at the time when the event was emitted. It is possible to use the indexed attribute for three parameters.

In order to emit an event, the keyword emit is used, followed by the parameters in the same order as in the event declaration.

Most development environments let you inspect the transaction’s log in their console.

You can find the documentation here: