Skip to content

Instantly share code, notes, and snippets.

@abdul
Last active July 14, 2022 05:13
Show Gist options
  • Save abdul/30822c4c8c8ab94040bff1da8b79f3cc to your computer and use it in GitHub Desktop.
Save abdul/30822c4c8c8ab94040bff1da8b79f3cc to your computer and use it in GitHub Desktop.
Get Ethereum Stats (using Web3.js) - current block number, block heigh (transactions count), TPS (transaction per second), average gas price
const Web3 = require("web3");
const INFURA_END_POINT = "https://mainnet.infura.io/v3/<ENTER_INFURA_API_TOKEN>"
const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_END_POINT));
const getEthStats = async () => {
const gasPrice = await web3.eth.getGasPrice(); //average gas price
const currentBlock = await web3.eth.getBlock("latest");
let result = null;
if (currentBlock.number !== null) { //only when block is mined not pending
const previousBlock = await web3.eth.getBlock(currentBlock.parentHash);
if(previousBlock.number !== null)
{
const timeTaken = currentBlock.timestamp - previousBlock.timestamp;
const transactionCount = currentBlock.transactions.length;
const tps = transactionCount / timeTaken;
result = {currentBlockNumber:currentBlock.number, transactionCount, timeTaken, tps, gasPrice}
}
}
return result;
}
const printStats = async () => {
const stats = await getEthStats()
if (stats !== null) {
const {currentBlockNumber, transactionCount, timeTaken, tps, gasPrice} = stats;
console.log(`Current Block (#${currentBlockNumber}): ${transactionCount} in ${timeTaken} seconds at the rate of ${tps} transactions/seconds. The average gas price is ${gasPrice} wei.`)
}
}
printStats();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment