Skip to main content

Logging data from smart contracts with events

smart contracts
remix
solidity
events
Intermediate
jdourlens
April 3, 2020
2 minute read

In Solidity, events are dispatched signals the smart contracts can fire. Dapps, or anything connected to Ethereum JSON-RPC API, can listen to these events and act accordingly. An event can also be indexed so that the event history is searchable later.

Events

One of the most common events on the Ethereum blockchain is the Transfer event that is emitted by ERC-20 tokens when someone transfers tokens.

event Transfer(address indexed from, address indexed to, uint256 value);

The event signature is declared inside of the contract code and can be emitted with the emit keyword. For example, the transfer event logs who sent the transfer (from), to who (to) and how much tokens were transferred (value).

Let’s get back to the Counter smart contract from deploying your first smart contract and log every time the value is changed. It would look like this:

Notice that:

  • Line 6: we declare our event and what it contains, the old value and the new value.

  • Line 14: When we increment our count variable, we emit the event.

If we now deploy the contract and call the increment function, we’ll see that Remix will automatically display it if you click on the new transaction inside an array named logs.

Remix screenshot

Logs are really useful for debugging your smart contracts but they are also important if you build applications used by different people and make it easier to make analytics to track and understand how your smart contract is used. The logs generated by transactions are displayed in popular block explorers and you can also for example use them to create offchain scripts for listening to specific events and taking action when they occur.