Events

如何為函式 getPastLogs () 設置“主題”?

  • June 14, 2021

先生,我想用 getPastLogs() 讀取過去的事件日誌,但我得到了整個日誌。我希望我能過濾一些日誌。我發現我可以在 getPastLogs() 中設置“主題”,但它總是失敗。我應該如何在 getPastLogs() 中設置“主題”?

以下是我的契約:

pragma solidity ^0.4.25;
contract ReadLogPOC
{
   uint gi_sum;
   event adduintevent(uint indexed p_data,uint p_sum);    


   function adduint(uint p_1) external returns(uint){
       gi_sum = 10 + p_1;
       emit adduintevent(p_1,gi_sum);
       return gi_sum;
   }
   function getsum() external returns(uint){
       return gi_sum;
   }    
}

我使用 Node.js,這段程式碼顯示所有過去的事件日誌。我的程式碼是:

var abi = [{"constant":false,"inputs":[{"name":"p_1","type":"uint256"}],"name":"adduint","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"getsum","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"p_data","type":"uint256"},{"indexed":false,"name":"p_sum","type":"uint256"}],"name":"adduintevent","type":"event"}];
var address = "0x61fab6aa9f16369e8e051688ceca7e01a61b9780";
var readlogpocContract = new web3.eth.Contract(abi,'0x61fab6aa9f16369e8e051688ceca7e01a61b9780'); 

web3.eth.getPastLogs(
 {
   address: '0x61fab6aa9f16369e8e051688ceca7e01a61b9780',
   fromBlock: "0x1",
   toBlock: "latest"
     }
).then(console.log).catch(e => console.log(e));

如果我在geth中執行"readlogpoc.adduint.sendTransaction(8,{from: “0x3d626b8fae039078fe5c33964e035c5a9d47b2e9”, gas:900000}",然後我設置這樣的主題:

web3.eth.getPastLogs(
 {
   address: '0x61fab6aa9f16369e8e051688ceca7e01a61b9780',
   fromBlock: "0x1",
   toBlock: "latest",
   topics:[web3.utils.sha3("adduintevent(uint,uint)"),web3.utils.sha3("0x8")]
     }
).then(console.log).catch(e => console.log(e));

輸出是

$$ $$ 應該如何設置主題?我的環境: Web3版本是^1.0.0-beta.36 Node版本是v10.5.0 geth版本是版本:1.8.11-stable 平台:Ubuntu 16.04.4 LTS

謝謝~~

或者,您可以直接指定事件的名稱,如下所示:

 contractInstance.getPastEvents('adduintevent', {
                 filter: {yourIndexedParameter: _value},
                 fromBlock: 0,
                 toBlock: 'latest'
             }, (error, events) => { 
                 if (!error){
                  console.log(events)
              }
               })

問題在於:

topics:[web3.utils.sha3("adduintevent(uint,uint)"),web3.utils.sha3("0x8")]

它應該是:

topics:[web3.utils.sha3("adduintevent(uint256,uint256)")]

希望這可以幫助

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