简体   繁体   English

使用 web3j 库监听从智能合约发出的事件

[英]Listening to events emmited from smart contracts using web3j library

如何使用基于 java 的 web3j 库监听智能合约发出的事件?

// Our local test network.
var service = new BeaconNodeService("http://localhost:19601/");
var client = BeaconNodeClientFactory.build(service);

// We want to receive at least one event
var latch = new CountDownLatch(1);

// At the moment we are interested in any topic
var topics = EnumSet.allOf(BeaconEventType.class);

// Then subscribe to each event
client.getEvents().onEvent(topics, event -> {
    System.out.println("Received event: " + event);
    latch.countDown();
});

// Wait for the event
latch.await();

More info here .更多信息在这里

Lets consider Contract name as "SampleContract".让我们将合约名称视为“SampleContract”。 It includes a method "getSellerAddress()", at the end of the method an event is emitted, which is named as "emitSellerAddress".它包括一个方法“getSellerAddress()”,在该方法的末尾发出一个事件,它被命名为“emitSellerAddress”。

After calling the method getSellerAddress, create a filter that provides latest block details and add a topic with the Event Name.调用 getSellerAddress 方法后,创建一个过滤器,提供最新的区块详细信息,并添加一个带有事件名称的主题。 This event will be registered in the filter, which is passed into logFlowable.此事件将在过滤器中注册,过滤器将传递到 logFlowable。 Subscribing to this method will provide the event information and eventString in the below code will provide complete log information.订阅此方法将提供事件信息,下面代码中的 eventString 将提供完整的日志信息。 Based on the event emitting either it will be in the topic or data section.根据发出的事件,它将在主题或数据部分。

TransactionReceipt transactionReceiptData = sampleContract.getSellerAddress().send();

EthFilter filter = new EthFilter(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, sampleContract.getContractAddress());

String encodedEventSignature = EventEncoder.encode(sampleContract.EVENT_NAME);

filter.addSingleTopic(encodedEventSignature);
                
System.out.println("subscribing to event with filter");
                
Web3j.ethLogFlowable(filter).subscribe(eventString -> eventString.toString());
                

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM