Events in Solidity smart contracts

Events are used to inform a calling application about the current state of a smart contract. As transactions occur on the block chain events are logged and this information is valuable for applications that want to listen to new state changes in a contract, account, chain information or search for historical events.

Events are a way to log actions that occur in a smart contract. These events are recorded in the transaction log of the block chain and are separate from transactions and blocks. Event logs are accessible using the Web3 and the address of the contract as long as the address still exists on the blockchain (contracts can be disposed). Since these events are stored separately on the block chain, they are not accessible from within a smart contracts not even the contracts which have created them.

Keep in mind

  • Events are declared using the “event” keyword
  • To emit an event in a function use the “emit’ keyword
  • Events are recorded in the transaction log of the block chain
  • Events are cheaper to store then state variables
  • Smart contracts cannot directly access the event logs

Below is an example of how to declare an event in a Solidity smart contract

pragma solidity ^0.7.0;

//contract name is MyFirstContract
contract MyFirstContract {

    //create a variable called name
    string private name;

    
    //declare an event
    event nameEvent(string newName);

Try it in Remix

Let take this example one step further and declare an event and then emit the event when a function is called. This will result in the emitted event being logged.

pragma solidity ^0.7.0;

//contract name is MyFirstContract
contract MyFirstContract {

    //create a variable called name
    string private name;

    
    //declare an event
    event nameEvent(string newName);


    //set name and emit an event
    function setName(string memory newName) public {
        name = newName;

        
   //emit an event to the log when this function is called
        emit nameEvent(name);
    }

}

Try it in Remix

Event logs can be accessed using Web3 in Python or Java Scrips. You can search for past events and subscribe to incoming events.

If you index events they are easier and faster to find in the transaction log.  Up to 3 parameters can be indexed.

Example: event Log(address indexed sender, string message).  Then send a search query to the Ethereum logs where the sender is a specific address.

For more information read the docs.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Error Handling in Solidity smart contracts

Leave a Reply