简体   繁体   English

如何在 node.js 应用程序中使用 ethers.js contract.on() 监听来自智能合约的事件?

[英]How do I listen to events from a smart contract using ethers.js contract.on() in a node.js application?

I'm trying to listen to events emitted from the USDT contract Transfer function using ethers.js (not web3) in a node.js application.我正在尝试在 node.js 应用程序中使用 ethers.js(不是 web3)监听 USDT 合约传输函数发出的事件。

When I run the script, the code runs with no errors and then quickly exits.当我运行脚本时,代码运行没有错误,然后快速退出。 I'd expect to get the event logs.我希望得到事件日志。 I'm not sure what step I'm missing.我不确定我错过了哪一步。

I've tested this script by calling the getOwner() method and console logging that result, this works fine, so my connection to mainnet is ok.我已经通过调用 getOwner() 方法和控制台记录该结果来测试这个脚本,这工作正常,所以我与主网的连接没问题。

I'm using alchemy websocket.我正在使用炼金术 websocket。

My index.js file我的 index.js 文件

const hre = require("hardhat");
const ethers = require('ethers');
const USDT_ABI = require('../abis/USDT_ABI.json')

async function main() {

const usdt = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
const provider = new ethers.providers.WebSocketProvider("wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API");
const contract = new ethers.Contract(usdt, USDT_ABI, provider)

contract.on('Transfer', (from, to, value) => console.log(from, to, value))

}

main()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

My hardhat.config.js file我的 hardhat.config.js 文件


    require("@nomiclabs/hardhat-waffle");
require('dotenv').config()

// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
  const accounts = await ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
 module.exports = {
  paths: {
    artifacts: './src/artifacts',
  },

  networks: {
    mainnet: {
      url: "wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API",
      accounts: [`0x${process.env.PRIVATE_KEY}`]
    },
    hardhat: {
      chainId: 1337
    },
  },
  solidity: "0.4.8"
};`

I solved this by removing我通过删除解决了这个问题

.then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

and just calling main.只是打电话给主要的。 It's recommended in the hardhat docs to use the .then and .catch code but when running a long running process like this script does with contract.on(), it causes the script to exit.在 hardhat 文档中建议使用 .then 和 .catch 代码,但是当运行一个长时间运行的进程时,就像这个脚本使用 contract.on() 所做的那样,它会导致脚本退出。

I do this:我这样做:

const ethers = require('ethers');
const abi = [{...}]
const contractAddress = '0x000...'

const webSocketProvider = new ethers.providers.WebSocketProvider(process.env.ETHEREUM_NODE_URL, process.env.NETWORK_NAME);
const contract = new ethers.Contract(contractAddress, abi, webSocketProvider);

contract.on("Transfer", (from, to, value, event) => {
        console.log({
            from: from,
            to: to,
            value: value.toString(),
            data: event
        });
    });

The event return all data related to event and transaction.该事件返回与事件和事务相关的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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