Web3j

Web3j 沒有觀察到新的塊/事務

  • November 20, 2018

我正在使用 Web3j 3.2.0 和 Infura 來獲取有關乙太坊中新區塊和交易的資訊。

   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}")
       }

我的程式碼進行掃描並顯示所有塊,但不會繼續掃描未來的塊。我怎樣才能解決這個問題?

使用 web3j 3.5.0 和 Infura WebSocket 端點,您可以訂閱 Observable 以擷取新的塊事件:

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());
});

這是輸出

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

據我所知,這個問題與 INFURA 過濾器有關

引用自:https://ethereum.stackexchange.com/questions/35381