Working web3j.replayTransactionsObservable example

990 Views Asked by At

I want to retrieve the transaction history between 2 blocks and I came upon this replay filter To replay the individual transactions contained within a range of blocks:

Subscription subscription = web3j.replayTransactionsObservable( <startBlockNumber>, <endBlockNumber>) .subscribe(tx -> { ... });

However, I am unable to find any working example related of this filter. Can anyone just help in providing a working example?

1

There are 1 best solutions below

6
On BEST ANSWER

Simply getting access to the transaction objects is pretty straightforward:

Web3j web3j = Web3j.build(new HttpService());

web3j.replayTransactionsObservable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(System.out::println));

will print out all of the transactions that have occurred on the peer node running on your localhost. Just change System.out::println to tx -> //do something with tx (tx is a org.web3j.protocol.core.methods.response.EthBlock$TransactionObject).

Note that this will only replay the history. You won't see any new transaction objects as blocks are added to the chain.

A more complicated example of using subscriptions comes if you want to do something like listen for specific events emitted. I've included an example of that below in case it helps. If you need help with a specific problem, please post questions with more details and sample code.

// Prints event emitted from a deployed contract
// Event definition:
// event MyEvent(address indexed _address, uint256 _oldValue, uint256 _newValue);
public static void eventTest() {
  try {
    Web3j web3j = Web3j.build(new HttpService());

    Event event = new Event("MyEvent",
                            Arrays.asList(new TypeReference<Address>() {}),
                            Arrays.asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));

    // Note contract address here. See https://github.com/web3j/web3j/issues/405
    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, "6dd7c1c13df7594c27e0d191fd8cc21efbfc98b4");

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

    web3j.ethLogObservable(filter).subscribe(log -> System.out.println(log.toString()));
  }
  catch (Throwable t) {
    t.printStackTrace();
  }
}