How to properly encode topics for eth_getLogs
These web3.js and ethers.js scripts provide a straightforward way to generate encoded event signatures and parameters that can be utilized in the topics filter when pulling logs from an EVM-compatible chain.
Overview
Overview
When retrieving logs from an EVM-compatible blockchain, developers often use the eth_getLogs
method. One of the key parameters of this method is the topics filter, which allows you to narrow down the search to specific event logs based on their encoded signature and parameters.
This script will show you how to encode this data using web3.js and ethers.js.
Environment setup
Environment setup
Create a Web3 instance
Create a Web3 instance
web3.js:
The first step is to create a Web3
instance to be able to access the web3.js tools.
This script uses two tools from the web.js library. The keccak256
function and the padLeft
util.
ethers.js:
The first step is to create a utils
instance to be able to access the utils tools.
This script uses three tools from the ethers.js library. The keccak256
function, the toUtf8Bytes
, and the hexZeroPad
function.
Create a function to encode the event signature
Create a function to encode the event signature
The event signature is generated by hashing the event’s name and its parameter types using the Keccak-256 algorithm, also known as SHA-3. This produces a 32-byte hash value.
The event signature is used in the topics filter of the eth_getLogs
method to match the corresponding event logs on the blockchain.
By using the web3.js or ethers.js libraries, developers can easily generate these event signatures and efficiently filter event logs to extract the data they need.
Create a function to encode the parameters
Create a function to encode the parameters
Each topic in the topics filter must be a 32-bytes long string, even if the original parameter value is shorter.
To achieve this, a developer can add zeros in front of the value until it becomes a 32-bytes long string, which is equal to 64 characters (starting with 0x
).
The padLeft
in web.js and hexZeroPad
in ethers.js functions do exactly this.
Call the functions from a main function
Call the functions from a main function
Within the main
function, define the event and parameters to encode, then call the functions with the event and parameter as input.
You will also find an example of a topics
array to use in the eth_getLogs
filter.
Log the results
Log the results
The last part of the main function is to log the results.