Truffle

使用 web3j (2018) 訂閱事件

  • September 2, 2021

我正在嘗試使用web3j從我的 java 應用程序訂閱智能合約事件。

我將我的契約部署到松露,這裡是:

pragma solidity ^0.4.24;

contract MyContract {

 string message;
 event MyEvent(address contractAddress, string message);


 constructor() public {
   message = "I'm ready!";
 }

 function setGreetings(string _message) public {
   message = _message;
 }

 function getGreetings() public view returns (string) {
   return message;
 }

 function triggetEvent() public {
   MyEvent(address(this), message);
 }

}

在我的 java 應用程序中,我訂閱了這個事件:

web3 = Web3j.build(new HttpService("http://localhost:9545/"));
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
MyContract myContract = MyContract.load(CONTRACT_ADDRESS, web3, credentials, GAS_PRICE, GAS_LIMIT);
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, myContract.getContractAddress());
String encodedEventSignature = EventEncoder.encode(MyContract.MYEVENT_EVENT);
filter.addSingleTopic(encodedEventSignature);
log.info("subscribing to event with filter");
web3.ethLogObservable(filter).subscribe(eventString -> log.info("event string={}", eventString.toString()));

哪裡MyContract.MYEVENT_EVENT看起來像這樣:

public static final Event MYEVENT_EVENT = new Event("MyEvent", 
           Arrays.<TypeReference<?>>asList(),
           Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Utf8String>() {}));

現在我triggetEvent()從 truffle 控制台呼叫該方法,該方法執行但我的 java 應用程序沒有列印任何內容。我在這裡想念什麼?

這個解決了它: https ://ethereum.stackexchange.com/a/41606/37689

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, greetingsContract.getContractAddress().substring(2));

注意.substring(2)

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