1

Given logs are streamed to a client via the eth_subscribe(“logs”) rpc method with a logIndex, is there a way to tell the number of total logs in a block from its header?

1 Answer 1

1

The number of logs emitted is not stored in the block header, but you can easily get that information using the eth_getLogs method.

You can get all of the logs emitted by all of the transactions in a block by running eth_getLogs and leaving only the block you need in the filter.

Then you can either calculate how many objects the result returned or inspect the results and extract the logIndex field; the last logIndex will tell you the total amount of logs in the block (it is zero-index based, so you need to add 1 to the value).

Here is an example of getting all of the logs in a block using cURL:

curl 'YOUR_NODE_ENDPOINT' \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '{
  "method": "eth_getLogs",
  "params": [
    {
      "fromBlock": "latest",
      "toBlock": "latest"
    }
  ],
  "id": 1,
  "jsonrpc": "2.0"
}'

This setup will retrieve all of the logs emitted in the specified block.

Here is how to extract all the logIndex values in web3.js:

const Web3 = require('web3');
const url = 'YOUR_NODE_URL';
const web3 = new Web3(URL);

async function getLatestBlockNumber() {
  return await web3.eth.getBlockNumber();
}

async function getLogsFromLatestBlock() {
  const latestBlockNumber = await getLatestBlockNumber();
  console.log(`Block ispected: ${latestBlockNumber}`)
  
  const logs = await web3.eth.getPastLogs({
    fromBlock: latestBlockNumber,
    toBlock: latestBlockNumber
  });

  return logs;
}

async function extractLogIndexValues() {
  const logs = await getLogsFromLatestBlock();
  const logIndexes = logs.map(log => log.logIndex);
  console.log(`Logs emitted in this block: ${logIndexes.length}`)
}

extractLogIndexValues();

This specific example retrieves the latest block and then finds how many logs were emitted by grouping all of the log index values and then counting how many exist.

You can see more examples on the Chainstack docs | eth_getLogs, or learn more about logs in general by reading Tracking some Bored Apes: The Ethereum event logs tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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