2

How it is possible to listen to events emitted from smart contract using web3j library based on java?

Wang Liang
  • 4,244
  • 6
  • 22
  • 45
shaikh47
  • 21
  • 1

2 Answers2

2

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());
                
Sravan Kumar
  • 41
  • 2
  • 6
0
// 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.

MrFrenzoid
  • 1,208
  • 6
  • 21