如何在node.js中使用ethers.js contract.on()监听智能合约事件?

在 node.js 应用程序中使用 ethers.js(不是web3)监听USDT合约转移功能发出的事件。
当我运行该脚本时,没有报错直接闪退了。我想找到错误日志,不知道是不是错过了什么步骤。然后我用 getOwner()方法和控制台记录测试这个脚本,显示与mainnet的连接是正常的。
我正在使用的是 alchemy websocket。
index.js file:

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

hardhat.config.js file:

    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"
};

https://stackoverflow.com/que...

阅读 2.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题