ReasonJun

Hardhat : Event filtering (attach, getLogs, topic, Interface, getTransactionReceipt, parseLog) 본문

Blockchain/HardHat

Hardhat : Event filtering (attach, getLogs, topic, Interface, getTransactionReceipt, parseLog)

ReasonJun 2023. 10. 20. 17:00
728x90
import { ethers } from "hardhat";
const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";

async function purchase(amount: number) {
  const VendingMachine = await ethers.getContractFactory("VendingMachine");
  const vendingMachine = await VendingMachine.attach(contractAddress);
  const topic = [vendingMachine.filters.Purchase().topics!].toString();
  const filter = {
    address: contractAddress.toString(),
    fromBlock: 0,
    toBlock: 10000000,
    topics: [topic]    
  };
  const logs = await ethers.provider.getLogs(filter);
  //특정 이벤트만 필터링 하기 위한 로그 값
   //console.log("logs >>>", logs)
  let abi = require("../artifacts/contracts/VendigMachine.sol/VendingMachine.json").abi;
  let iface = new ethers.utils.Interface(abi);
  //로그를 분석하기 위해서 abi를 가져옴
  logs.forEach(async(logs) => {
    //실제로 이벤트 로그 내용을 분석하기 위해서는 각각의 트랜잭션 receipt를 가져와서 처리해야 한다.
    const receipt = await ethers.provider.getTransactionReceipt(logs.transactionHash);
    //console.log("receipt >>>", receipt);
    //반복문을 통해서 각로그들의 내용 출력 진행
    receipt.logs.forEach((log) => {
      // console.log("iface.parseLog(log) >>", iface.parseLog(log));
      console.log("purchaser >>",iface.parseLog(log).args[0]);
      console.log("amount >>",iface.parseLog(log).args[1]);
    });
  })
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
purchase(10).catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Here is a breakdown of the script:

  • import { ethers } from "hardhat"; imports the ethers library.
  • const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; defines the address of the VendingMachine contract.
  • async function purchase(amount: number) { defines the purchase() function.
    • const VendingMachine = await ethers.getContractFactory("VendingMachine"); creates a contract factory for the VendingMachine contract.
    • const vendingMachine = await VendingMachine.attach(contractAddress); attaches the contract factory to the VendingMachine contract at the specified address.
    • const topic = [vendingMachine.filters.Purchase().topics!].toString(); defines the topic for the Purchase event.
    • const filter = { defines the filter for the getLogs() method.
      • address: contractAddress.toString() specifies the address of the VendingMachine contract.
      • fromBlock: 0 specifies that the logs should be returned from the genesis block.
      • toBlock: 10000000 specifies that the logs should be returned up to block 10000000.
      • topics: [topic] specifies the topic for the Purchase event.
    • const logs = await ethers.provider.getLogs(filter); gets the logs for the VendingMachine contract.
    • let abi = require("../artifacts/contracts/VendigMachine.sol/VendingMachine.json").abi; imports the ABI for the VendingMachine contract.
    • let iface = new ethers.utils.Interface(abi); creates an interface object for the VendingMachine contract.
    • logs.forEach(async(logs) => { iterates over the logs.
      • const receipt = await ethers.provider.getTransactionReceipt(logs.transactionHash); gets the transaction receipt for the log.
      • receipt.logs.forEach((log) => { iterates over the logs in the transaction receipt.
        • console.log("purchaser >>",iface.parseLog(log).args[0]); prints the purchaser value of the log.
        • console.log("amount >>",iface.parseLog(log).args[1]); prints the amount value of the log.
      • });
    • });
  • purchase(10).catch((error) => { calls the purchase() function with an argument of 10.
    • console.error(error); prints the error to the console.
    • process.exitCode = 1; sets the exit code of the process to 1.
  • }); ends the purchase() function.

This script can be used to analyze the logs of any contract that emits the Purchase event. By parsing the logs, you can get information about who purchased cupcakes, how many cupcakes were purchased, and when the purchase was made.

728x90
Comments