Tokens

有沒有辦法監聽涉及特定契約的事件?

  • January 15, 2022

當我的契約中的 NFT 轉移給另一個使用者時,我想做一些事情。我可以聽這樣的事件嗎?如果沒有,解決此問題的最佳方法是什麼?

是的,有一個 RPC 呼叫來過濾日誌。

這是一個專門監聽的許可腳本,Transfer因此我們可以準備採取一些行動。在同一個 repo 中有另一個腳本來執行這些操作。

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

以下是相關程式碼:

// 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
});

引用自:https://ethereum.stackexchange.com/questions/118996