简体   繁体   中英

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". It includes a method "getSellerAddress()", at the end of the method an event is emitted, which is named as "emitSellerAddress".

After calling the method getSellerAddress, create a filter that provides latest block details and add a topic with the Event Name. This event will be registered in the filter, which is passed into logFlowable. Subscribing to this method will provide the event information and eventString in the below code will provide complete log information. 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());
                

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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