Technical Introduction to Events and Logs in Ethereum

An introduction to use cases for events and logs on the Ethereum blockchain with sample code.

Consensys
ConsenSys Media
6 min readJun 6, 2016

--

Events and logs are important in Ethereum because they facilitate communication between smart contracts and their user interfaces. In traditional web development, a server response is provided in a callback to the frontend. In Ethereum, when a transaction is mined, smart contracts can emit events and write logs to the blockchain that the frontend can then process. There are different ways to address events and logs. This technical introduction will explain some sources of confusion regarding events and some sample code for working with them.

Events can be confusing because they can be used in different ways. An event for one may not look like an event for another. There are 3 main use cases for events and logs:

  1. smart contract return values for the user interface
  2. asynchronous triggers with data
  3. a cheaper form of storage

The terminology between events and logs is another source of confusion and this will be explained in the third use case.

1) Smart contract return values for the user interface

The simplest use of an event is to pass along return values from contracts, to an app’s frontend. To illustrate, here is the problem.

Assuming exampleContract is an instance of ExampleContract, a frontend using web3.js, can obtain a return value by simulating the contract execution:

However, when web3.js submits the contract call as a transaction, it cannot obtain the return value[1]:

The return value of a sendTransaction method is always the hash of the transaction that’s created. Transactions don’t return a contract value to the frontend because transactions are not immediately mined and included in the blockchain.

The recommended solution is to use an event, and this is one of the intended purposes for events.

2) asynchronous triggers with data

3) a cheaper form of storage

Aside — Indexed parameters

Up to 3 parameters can be indexed. For example, a proposed token standard has: event Transfer(address indexed _from, address indexed _to, uint256 _value) . This means that a frontend can efficiently just watch for token transfers that are:

  • sent by an address tokenContract.Transfer({_from: senderAddress})
  • or received by an address tokenContract.Transfer({_to: receiverAddress})
  • or sent by an address to a specific address
    tokenContract.Transfer({_from: senderAddress, _to: receiverAddress})

Conclusion

More technical tutorials

Subscribe to our Ethereum developer newsletter

Get the latest tutorials, tools, and pro tips straight to your inbox.

--

--

Consensys
ConsenSys Media

A complete suite of products to create and participate in web3.