Listening to Events in Hardhat using Ethers.js
This tutorial will help you with listening to Solidity smart contract events.
You can install Hardhat from here if you haven't already.
Step 1) Create a Hardhat Sample project with the following command
npx hardhat
To make life easy I will use the sample project provided by Hardhat for demonstrating events. Hopefully you can later use this example to add and listen to an event in your smart contract.
Note: Hardhat has upgraded since 2021 April, hence we get `lock.sol` contract by default instead of `greeter.sol` contract
Step 2) Create greeter.sol
file and add an event to the contract as shown below
We create an event named GreeterEvent()
to log any change in the greeting message.
Step 3) Open a new terminal and start a Hardhat network on localhost
npx hardhat node
Step 4) Create a file name sample-script.js
copy and paste the below code. Open another terminal and deploy your contract. The sample deploy script is already there for you
npx hardhat run --network localhost scripts/sample-script.js
Step 5) The main step — Connect with your smart contract and listen to events, here ethers.js library is used, refer to ethers lib for more details.
Hardhat is used for compiling, deploying, and testing your contract and Ethers is used to work with network providers, EVM, contracts and data regarding it.
Create a new file event.js
in scripts folder as shown above.
I am really in love with Hardhat and ethers.js especially after looking at the ABI, thanks to RicMoo. The ABI is so much more readable and easy to understand than the provided standard.
I plan to create a tool for converting contract code to the above ABI format.
Make sure to add your contract address
let contractAddress = "your contract address";
Step 6) Run the script
npx hardhat run --network localhost scripts/event.js
Finally!!
Lets add Filter to our event
Note: Hardhat has upgraded since 2021 April, so you can also refer: https://docs.ethers.io/v5/concepts/events/ for more info
To Filter the parameter we have to add the indexed
keyword before the argument
Deploy the contract
npx hardhat run --network localhost scripts/sample-script.js
in event.js
make changes to the ABI
Add the following lines to the end
Now you can filter the event as per the address of the greeting setter.
Hope this becomes a quick snippet for event listening.