ethers js监听合约事件

监听合约事件

contract.on

在ethersjs中,合约对象有一个contract.on的监听方法,让我们持续监听合约的事件:

contract.on("eventName", function)

contract.on有两个参数,一个是要监听的事件名称"eventName",需要包含在合约abi中;另一个是我们在事件发生时调用的函数。

contract.once

合约对象有一个contract.once的监听方法,让我们只监听一次合约释放事件,它的参数与contract.on一样:

contract.once("eventName", function)

监听pancakeswap PairCreated事件

      
	   let url  = "wss://dawn-capable-arrow.bsc.discover.quiknode.pro/3448487c9c9591fc513b1bd08a0d780a24e10cc9/"
       const provider = new ethers.providers.JsonRpcProvider(url);
       let PANCAKE_FACTORY_CONTRACT = "0xca143ce32fe78f1f7019d7d551a6402fc5350c73"
       let abi = ["event PairCreated(address indexed token0, address indexed token1, address pair, uint)"]; 
       let contract = new ethers.Contract(PANCAKE_FACTORY_CONTRACT,abi,provider);
       contract.on("PairCreated", async (token0Address,token1Address,pairAddress)=> {
             this.logger.info("***********[PairCreated]*****************");
            this.logger.info("token0Address:",token0Address);
             this.logger.info("token1Address:",token1Address);
            this.logger.info("pairAddress:",pairAddress);
      }