0

I'm using Web3j 3.2.0 and Infura to get information about new blocks and transactions in Ethereum.

    val web3j = Web3j.build(HttpService("https://mainnet.infura.io/<mytoken>"))
    log.info("Connected to Ethereum client version: ${web3j.web3ClientVersion().send().getWeb3ClientVersion()})

    val startingBlock = DefaultBlockParameter.valueOf(BigInteger.valueOf(4866661))

    web3j.catchUpToLatestAndSubscribeToNewTransactionsObservable(startingBlock)
        .filter { !it.value.equals(BigInteger.ZERO) }
        .subscribe {
            println("Block #${it.blockNumber}: ${it.blockHash.substring(2..8)}.. -- Transaction Index: ${it.transactionIndex} -- From ${it.from} To ${it.to} -- Value ${it.value}")
        }

My code does the scan and shows all the blocks but doesn't continue scanning for future blocks. How can I fix this?

1

Using web3j 3.5.0 and the Infura WebSocket endpoint, you can subscribe to an Observable to capture new block events:

String url = "wss://mainnet.infura.io/ws";

// Connection to the node
WebSocketService web3jService = new WebSocketService(url, true);
web3jService.connect();
web3j = Web3j.build(web3jService);

String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();
System.out.println(String.format("Connected to Ethereum node %s : %s", url, clientVersion));

// Subsribe to blocks
web3j.blockObservable(false).subscribe(block -> {
    System.out.println("NEW BLOCK -> " + block.getBlock().getNumber().intValue());
});

And this is the output

Connected to Ethereum node wss://mainnet.infura.io/ws : Geth/v1.8.15-omnibus-255989da/linux-amd64/go1.10.1
NEW BLOCK -> 6742046
NEW BLOCK -> 6742047
NEW BLOCK -> 6742048
0

As far as I know, this problem is related to the INFURA filters

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.