tokens – How to Listen to Events Involving a Specific Contract

erc-1155erc-721eventsnfttokens

I would like to do something when an NFT from my contract gets transferred to another user. Can I listen to events like this? If not, what would be the best way to get around this?

Best Answer

Yes, there is a RPC call to filter logs.

Here is a permissively licensed script that specifically listens for Transfer so we can prepare to take some action. There is another script in the same repo to perform the actions.

https://github.com/su-squares/update-script/blob/master/have-there-been-updates.mjs

Here is the relevant code:

// From Su Squares, the first ERC-721 NFT for sale

import fs from "fs";
import { ethers } from "ethers";
const config = JSON.parse(fs.readFileSync("./config.json"));
const state = JSON.parse(fs.readFileSync("./build/resume.json"));
const provider = new ethers.providers.JsonRpcProvider(config.provider);

// Contracts ///////////////////////////////////////////////////////////////////
const suSquares = {
    address: "0xE9e3F9cfc1A64DFca53614a0182CFAD56c10624F",
    abi: [
        "event Personalized(uint256 squareNumber)",
        "event Transfer(address indexed from, address indexed to, uint256 indexed squareNumber)"
    ],
    startBlock: 6645906
};
suSquares.contract = new ethers.Contract(suSquares.address, suSquares.abi, provider);


// Filters /////////////////////////////////////////////////////////////////////
const filterSold = suSquares.contract.filters.Transfer(suSquares.address, null, null);
const sold = suSquares.contract.queryFilter(filterSold, state.startBlock);

const filterPersonalized = suSquares.contract.filters.Personalized();
const personalized = suSquares.contract.queryFilter(filterPersonalized, state.startBlock);


// Main program ////////////////////////////////////////////////////////////////
await Promise.all([sold, personalized]).then((values) => {
    const [soldEvents, personalizedEvents] = values;
    console.log("Scanning since block", state.startBlock);
    console.log(
        "Count of events",
        soldEvents.length,
        personalizedEvents.length,
    );
    if (soldEvents.length + personalizedEvents.length === 0) {
        process.exit(0); // success
    }
    process.exit(1); // failure
});
Related Topic