Solidity

如何每次都使用 getPastEvents 僅獲取過去 2 天的事件?

  • April 8, 2022

如何修改以下查詢以僅獲取過去兩天的事件:

const events= await MyContract.getPastEvents("eventName", {
 fromBlock: 0,
 toBlock: "latest"
});

每兩天大約有 12,343 個區塊,因此找到目前區塊編號並減去該數量將給出目標區塊編號。將其作為fromBlock參數傳遞給getPastEvents函式以限制該範圍:

const events= await MyContract.getPastEvents("EventName", {
 fromBlock: (await web3.eth.getBlockNumber()) - 12343,
 toBlock: "latest"
});

const getBlock = async () => {
   const result = await web3.eth.getBlockNumber()
   return web3.utils.hexToNumberString(result)
   
}

const calculated = getBlock().then((res) => { const calculated = Number(res) - 12343; return calculated});
const options =                                 
{
   address: getPair(tokenA, tokenB),
   fromBlock: calculated,
   toBlock: 'latest'

}

引用自:https://ethereum.stackexchange.com/questions/54967