How to get ERC-20 token transfer logs using ethers.js
This recipe shows you how to use the Ethers library with a Chainstack Ethereum node to retrieve transfer logs for an ERC-20 token.
Prerequisites
Prerequisites
You will need a Chainstack account and an Ethereum node to follow this recipe.
Environment setup
Environment setup
- Install node.js in case it is not installed yet.
Create a new directory for your project, then install the ethers.js
library.
npm install ethers
Initialize a provider instance
Initialize a provider instance
Create a new file, index.js
, import the ethers.js library, and initialize a new provider instance using your Chainstack node URL.
Paste your Chainstack node URL in the nodeUrl
const.
Initialize the ABI and smart contract instance
Initialize the ABI and smart contract instance
Now we need to create a smart contract instance using the address and ABI.
In this case, we only use the part of the ABI describing the transfer
event.
This specific example retrieves the transfer logs for the APE token, but you can use any ERC-20 token smart contract address.
Function to retrieve the logs
Function to retrieve the logs
Create a function called getLogs
where we define the range of blocks to query and call the queryFilter
function to retrieve the transfer logs.
We query the past 100 blocks in this example and use the getBlockNumber()
method to identify the latest block.
Create the main function and parse the response
Create the main function and parse the response
Now we can create a main()
function used to run the main program.
This function will call the getLogs()
function and parse the response extracting only the data that we want; in this case:
- Transaction hash
- From address
- To address
- Amount of Ape tokens transferred
Run the index.js file
Run the index.js file
Now you can save and run the file with:
node index.js
The script will retrieve the logs from the past 100 blocks and print the transfer information on the screen.