Listen to Solidity Smart-Contract events using ethers.js and Hardhat

Sumit PatilSumit Patil
1 min read

Events in solidity are the signals fired by smart-contract.

ethers.js has once function for listening to the emitted events.

The function takes two parameters:

  1. eventName Name of the event. It should be a string.

  2. listener It is the function. The task you are supposed to perform goes here.

Contract.once("eventName", listener)

Contract is the name of the Solidity Smart-Contract.

Here's an example for you using ethers.js in Hardhat development environment :

 async function mainFunc() {
    const contract = await ethers.getContract("ContractName", deployerAccount)
    await new Promise(async (resolve, reject) => {
        contract.once("NameOfTheEvent", () => {
            // perform your tasks here
            // & don't forget to resolve the promise
        })
    })
}
0
Subscribe to my newsletter

Read articles from Sumit Patil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sumit Patil
Sumit Patil

I'm a Web3 enthusiast, currently learning and making decentralized/semi-decentralized apps on the Ethereum blockchain using Solidity, Hardhat, ethers.js, Javascript, and essential tools.