Ethers.js – How to Listen for All Events of a Smart Contract with Ethers.js on Polygon

etherethers.jseventsnodejspolygon

What I would like to know is if there is a way to continuously listen for a single contract and fetch all the events emitted in real time. What I was able to find right now are ways of listening for only one event at a time in specific contract. To be more precise:
I have a smart contract deployed in polygon testnet (mumbai), this is an upgradable contract that is connected to other contracts and as usual it emits events that I would like to capture.
I use Alchemy as provider.
Another fact that is not clear to me is why in polyscan the method in the event is listed like 0x40c10f19 and not with the name.

I also try to use this code before asking you guys of how to do this:
`

filter = {
    address: CONTRACT_ADDRESS,
    topics:[
        utils.id("MarketItemCreated(address,uint256,address,uint256,uint256)"),
        utils.id("Transfer(address,address,address,uint256,uint256)")
    ]
}

provider.on(filter,(log,event)=>{
    console.log(log)
    console.log(event)
})

But when I actually interact with the contract I can't capture the events (the console.log does not display anything) but I can see the event in polyscan. I also try with by filtering only with the address without specifying the topic and I also try withproveder.once` but no way.

What am I doing wrong? or instead, What am I missing? every hints or contributions are appreciate 🙂

Best Answer

Hi developer advocate at Chainstack here!

Web3.js has a subscriprion method to easily to that!

const Web3 = require("web3");

const node_url = "CHAINSTACK_WSS_URL";
const web3 = new Web3(node_url)

var logs = web3.eth.subscribe("logs", {
        address: "CONTRACT_ADDRESS",
        topics: []
    }, function(error, result) {
        if (!error)
            console.log(result);
    })
    .on("connected", function(subscriptionId) {
        console.log(subscriptionId);
    })
    .on("data", function(log) {
        console.log(log);
    })
    .on("changed", function(log) {});

Remember that you need a web-socket endpoint to use subscriptions in web3.js.

You can find more examples in the Chainstack docs API reference, and in the web3.js docs.

I hope this helps you!

Related Topic