Last block is not immediately availiable

I’m using event subscriptions (via web3 websocket provider). When a new event is logged, i need to augment the smart contract event data with some block information. It looks like even though the block is mined (since the event is logged) infura does not have the block information (it returns null).
I’m suspecting some difference in how the events and blocks are cached by infura, since calling getBlock a short amount of time after returns the information:

Below is a small snippet that reproduces the problem (after plugging in a smart contract and its address + triggering a new event):

(async () => {
  try {
    const assert = require('assert');

    const Web3 = require('web3');
    const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws/v3/<id>'));
    setInterval (() => web3.eth.net.isListening().then( (status) => {}), 1000);

    const MyContract = require('./MyContract.json')
    const myContract = new web3.eth.Contract(MyContract.abi, "0x00");

    let lastBlockNumber = await web3.eth.getBlockNumber();

    myContract.events.MyContractEvent({
      fromBlock: lastBlockNumber
    }, async (error, event) => {

      let block = await web3.eth.getBlock (event.blockNumber);
     
      assert.notEqual(block, null);
    });

      } catch (e) {
    console.error(e);
      }
    })();

Hi @fbielejec welcome to our community!

When listening for events over a WSS subscription, part of the response is the blockHash or blockNumber. After you receive the event, what are you trying to do next with the data from the getBlockByNumber? I might be able to suggest an alternative solution.

I use it to get the (memoized) block timestamp. But at the same time I’m trying to understand the mechanism of this, why is the block not available at the same time as the event arrives?

Unfortunately this can occur because we have different systems serving different types of requests as you suspected. We will be deploying a major change to our architecture post the mainnet Istanbul fork that will address many if not all of these issues.

In the meantime I would recommend using the block hash from your event to then request the block data using eth_getBlockByHash() and loop on that while the response is null.

Apologies for having to use a work around but we will keep you and the community updated once those changes are live.

1 Like