3

Leverage Web3j TransactionObservable together with filter, i can monitor ETH/ETC transactions as following code snippet illustrates.

web3j.transactionObservable().filter(tx -> isWantedTransaction(tx)).subscribe(processTransaction,errorHandler,OnCompleteHandler);

How to implement same function with web3j for customerized ERC20 tokens?

  • Hi, I'm solving the same issue. Have u found a solution yet? – sinoTrinity Mar 24 '18 at 17:19
1

You can use Web3j ethLogObservable to subscribe to particular events on a smart contract.

1. Definition of the ERC20 Transfer Event

// event Transfer(address indexed from, address indexed to, uint tokens);
final Event TRANSFER_EVENT = new Event("MemberAdded", 
        Arrays.<TypeReference<?>>asList(
          new TypeReference<Address>(true) {},
          new TypeReference<Address>(true) {}, 
          new TypeReference<Uint256>(false) {}));

2. Build the filter

A web3j Log filter is composed of:

  • startBlock: Filter events by block number lower bound (special keywords: earliest and latest)
  • endBlock: Filter events by block number higher bound (special keywords: earliest and latest)
  • contractAddress: Filter events by contract address
EthFilter filter = new EthFilter(startBlock, endBlock, contractAddress);

At this point, you will get all the events for the contract deployed at contractAddress between startBlock and endBlock. If you want to monitor only Transfer, you can add a topic (sort of filter)

filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT));

3. Subscribe to the observable and filter by transaction if needed

The latest part consists to subscribe to the ethLog observable with the filter configured above. It is also possible to add a filter on transactionHash (like you example)

web3j.ethLogObservable(filter)
        .filter(event -> isWantedTransaction(event.getTransactionHash()))
        .subscribe(event -> ...);

More details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.