Events

Web3j在解析日誌時如何獲取事件參數?

  • September 22, 2021

我正在嘗試在 web3j 版本 4.0.1 中獲取事件參數。

我使用文件中解釋的簡單語法。我正在獲取日誌對象,但其中沒有args屬性或類似的東西。這是我的程式碼:

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
   DefaultBlockParameterName.LATEST, <contract-address>);
web3j.ethLogFlowable(filter).subscribe(log -> {
   System.out.println(log);
});

我希望找到argslog不存在。有一個data索引,它的值是一些不可讀的十六進製字元串。我必須提到,我能夠在 remix 甚至 truffle 測試交易收據中看到日誌參數。但是在 web3j 中沒有成功。

對於以下事件:

event MyEvent(address indexed _arg1, bytes32 indexed _arg2, uint8 _arg3); 

您可以像這樣從日誌中提取事件參數

// Event definition
public static final Event MY_EVENT = new Event("MyEvent", Arrays.<TypeReference<?>>asList(new TypeReference<Address>(true) {}, new TypeReference<Bytes32>(true) {}, new TypeReference<Uint8>(false) {}));

// Event definition hash
private static final String MY_EVENT_HASH = EventEncoder.encode(MY_EVENT);

// Filter
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, <contract-address>);

// Pull all the events for this contract
web3j.ethLogFlowable(filter).subscribe(log -> {
   String eventHash = log.getTopics().get(0); // Index 0 is the event definition hash

   if(eventHash.equals(MY_EVENT_HASH)) { // Only MyEvent. You can also use filter.addSingleTopic(MY_EVENT_HASH) 
       // address indexed _arg1
       Address arg1 = (Address) FunctionReturnDecoder.decodeIndexedValue(log.getTopics().get(1), new TypeReference<Address>() {});
       // bytes32 indexed _arg2
       Bytes32 arg2 = (Bytes32) FunctionReturnDecoder.decodeIndexedValue(log.getTopics().get(2), new TypeReference<Bytes32>() {});
       // uint8 _arg3
       Uint8 arg3 = (Uint8) FunctionReturnDecoder.decodeIndexedValue(log.getTopics().get(3), new TypeReference<Uint8>() {});
   }

});

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