简体   繁体   中英

Continuously listening to smart contract events

My NFT project architecture in such way that only when a minting event has occurred, a minted event is emitted and then I want to listen to that event so I trigger an upload of the JSON content that would be then visible to token owner (since anyone can potentially access the content of all the token by basically going to baseURI/tokenID and I want to keep the rarity of the tokens a secret until minted).

I want to create a function that continuously listens to new events from the minted event. I'm trying to access new events by using the following implementation, because I couldn't find an implementation that continuously listens to events from the contract.

async function listener() {
    events = nftContract.getPastEvents("minted",{fromBlock: 1}, function(err,res) {
        console.log(res);
    })

What is the best way to create a function that continues to poll events from the contract?

The full code of the solution is so:

const ethers = require('ethers');
const CONTRACT_ADDRESS = "0x10820dB......";
const ABIJSON = JSON.parse('{"_format": "hh-sol-artifact-1", "contractName": "testcontract", "....}')
provider = new ethers.providers.AlchemyProvider("ropsten");
const contract = new ethers.Contract(CONTRACT_ADDRESS, ABIJSON.abi, provider);

contract.on("eventName", ( caller,tokenID) => {
      //this section is called every time an event is emitted 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM