const ethers = require('ethers');
const ALCHEMY_SEPOLIA_URL = 'xxxxx';//Sepolia测试网络
const provider = new ethers.JsonRpcProvider(ALCHEMY_SEPOLIA_URL);
const contractAddress = '0xbDeaD2A70Fe794D2f97b37EFDE497e68974a296d';
const abi = [
"event Transfer(address indexed from, address indexed to, uint value)"
];
const contractUSDT = new ethers.Contract(contractAddress, abi, provider);
const main = async () => {
try {
console.log("n1.利用contract.once(), 监听一次Transfer事件");
const oncePromise = new Promise((resolve) => {
contractUSDT.once('Transfer', (from, to, value) => {
console.log(
`${from} -> ${to} ${ethers.formatUnits(ethers.getBigInt(value),0)}`
);
resolve();
})
})
await oncePromise;
console.log("n2. 利用contract.on(),持续监听Transfer事件");
contractUSDT.on('Transfer', (from, to, value)=>{
console.log(
`${from} -> ${to} ${ethers.formatUnits(ethers.getBigInt(value),0)}`
)
});
}
catch(e){
console.log(e);
}
}
main()
Program running results:
enter image description here
Why did contractUSDT.on only listen once before the program terminated?
Sometimes contractUSDT.on doesn’t even listen for an event once, and the program terminates.
My final goal is to achieve sequential output on the terminal:
console.log("n1.利用contract.once(), 监听一次Transfer事件");
console.log(`${from} -> ${to} ${ethers.formatUnits(ethers.getBigInt(value),0)}`);
console.log("n2. 利用contract.on(),持续监听Transfer事件");
console.log(`${from} -> ${to} ${ethers.formatUnits(ethers.getBigInt(value),0)}`)