Ric*_*ian 5 javascript node.js ethers.js hardhat
我正在尝试在 node.js 应用程序中使用 ethers.js (不是 web3)监听 USDT 合约 Transfer 函数发出的事件。
当我运行脚本时,代码运行没有错误,然后快速退出。我希望获得事件日志。我不确定我错过了哪一步。
我通过调用 getOwner() 方法并控制台记录结果来测试此脚本,这工作正常,所以我与主网的连接正常。
我正在使用炼金术网络套接字。
我的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);
});
Run Code Online (Sandbox Code Playgroud)
我的 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"
};`
Run Code Online (Sandbox Code Playgroud)
我通过删除解决了这个问题
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
Run Code Online (Sandbox Code Playgroud)
只需调用 main. Hardhat 文档中建议使用 .then 和 .catch 代码,但是当像此脚本使用contract.on() 那样运行长时间运行的进程时,它会导致脚本退出。
我这样做:
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
});
});
Run Code Online (Sandbox Code Playgroud)
该事件返回与事件和交易相关的所有数据。
| 归档时间: |
|
| 查看次数: |
17987 次 |
| 最近记录: |