Are you using the `ìndexed` keyword when writing events in Solidity?

Let's see what it actually does.

Transfer event
Transfer event

First, let’s take a step back to understand the events and how they are stored.

Events in Solidity serve as a mechanism for smart contracts to emit information. They are triggered by functions within the contract and can be monitored by external applications.

An event log is a record of an event that has been triggered and recorded on the blockchain in a form of a special data structure.

Event logs are a more economically friendly method for storing data that is not required for smart contracts to function properly.

Logs require 8 gas per byte while smart contract storage requires 20k gas per 32 bytes. However, it is essential to note that logs are not accessible by smart contracts.

Each event log contains information about the event, an array of topics, and data.

Topics are used to describe the event. The maximum number of topics we can store in a log is 4.

The first topic usually consists of the signature of the event name, including the types of its parameters. This signature is not included as the first topic when emitting anonymous events.

Topics can only hold a maximum of 32 bytes of data, so things like arrays or strings cannot be stored correctly. If you try to store data bigger than 32 bytes, the topic will be hashed instead.

But, arrays and strings can be stored as event data. Event data is not limited to 4x32 byes like topics, which means it can store more complex data.

It's important to note that topics are searchable, but data is not. That means you can filter event logs by topic values. On the other hand, including data is a lot cheaper than including topics.

Event parameters that are marked as `indexed` will be included as additional topics in the topics array of the event log. The rest of the event parameters will still be available in event data, but you won't be able to filter logs by those values.

Event logs can be read using Ethereum client libraries or any specialized library such as ethers.js.

To read an event log, you need to know the contract address, contract ABI, the event name, and the block range in which the event was triggered.

Example of logs query
Example of logs query

The `indexed` keyword allows us to optimize the way event data is stored on the blockchain, making it easier to retrieve as needed.

Subscribe to 0xMarko
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.