Events are used to tell font-end applications about blockchain actions.

It contains the information to log into EVM logs. These logs are stored as transaction logs in the blockchain. Client interfaces apps are notified with event actions.

Events in solidity:

  • used to log the event information to EVM logs.
  • Events are cheap than storing data in terms of gas consumption.
  • It maintains the history of transaction logs of every change to the transaction in the Blockchain
  • deposit and transfer actions are written as events in the blockchain.

Events in solidity can be done.

  • Create an event with solidity
  • Emit an event

How to create an event in solidity?

Events can be created using the event keyword.

Here is an example of how to create an event in solidity.

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

Events contain attributes that have the following properties.

  • a type of the data
  • variable
  • indexed keyword

What is an indexed keyword in events?

indexed is added to event attributes with up to 3 parameters. It means, the topic is data structured instead of data and store a single string of 32 bytes for value types and the Keccak-256 hash of the value is used for reference types.

if the indexed attribute does not exist, It is stored in ABI encoded data log.

Here is a solidity contract event definition example

contract EventTest {
    // Create a transfer event
    event transfer(address indexed _from, address indexed _to, uint amount);
}

It creates a transfer event with all the properties.

How to emit events in solidity?

Inside a contract, once the event is defined, You can trigger the events using emit keyword with the below syntax.

        emit transfer(_from, _to, amount);

Here is a complete create and emit events in Solidity.

contract EventTest {
    // Create an  transfer event
    event transfer(address indexed _from, address indexed _to, uint amount);

    function transferTo(address _from, address indexed _to uint amount) public {

        emit transfer(_from, _to, amount);
    }
}

It creates a transfer event with all the properties. Created a function transferTo which contains logic as well as emits an event Emit an event to client web applications. You have to write a front-end web app to listen to the events using web3 API.

How to listen to events in Solidity?

Once events are emitted from a contract, You can subscribe to catch events in javascript.

Following is a code to listen to and access the events in solidity.

let contract_abi = abi_json _code_during_contract_compilation;
let EventTest = web3.eth.contract(contract_abi);
let EventTestContract = ClientReceipt.at("0x98...");

EventTestContract.transfer(function(err, data) {
   if (!err)
   console.log(data);
});