Events and Logging in Solidity

Kavit (zenwraight)
Block Magnates
Published in
2 min readApr 26, 2022

--

Solidity events are integral for smart contract developers, allowing smart contracts to be tested for specific variables, frontends to be changed in an automated manner, and much more. In general, knowing how to use events in Solidity makes smart contract development a whole lot easier.

In this post, we’ll look into the logging and events feature of the Ethereum Virtual Machine (EVM) from a smart contract developer’s perspective, covering what logging and events are used for, indexed events, and how to use logging and events in Hardhat and Brownie.

The EVM is what makes Ethereum and many other blockchains tick. The EVM has a logging functionality used to “write” data to a structure outside smart contracts. One such important piece of data is Solidity events. Events allow us to “print” information on the blockchain in a way that is more searchable and gas efficient than just saving to public storage variables in our smart contracts.

Logs are a special data structure on the blockchain. They cannot be accessed by smart contracts, and give information about what goes on in transactions and blocks. It’s their inaccessibility to smart contracts that makes them cheaper to emit.

You can also watch our video on events and logging in Solidity here:

What Is an Event?

Events allow us to easily query “stuff” that happened in blocks and transactions. If you run a blockchain node, you can “listen” for certain events by subscribing to them.

What Are Events Used For?

With Solidity events, you can:

  1. Test your smart contracts for specific variables;
  2. Index variables to rebuild storage state;
  3. Listen for events to change a front end;
  4. Create subgraphs for reading data faster;

What Does an Event Look Like?

You can think of this as a new special type. We have created a “type” of event called myNumberEvent. The event name is called myNumberEvent and can hold a number of variables.

We can then emit an event like so:

Here is a full example contract:

Now, when we deploy the contract and then trigger the updateNumber() method, we can see the logs as below:-

Conclusion

Logs and events are an important part of smart contract development and critical infrastructure for many Decentralized projects.

--

--