Understanding and managing gas consumption at the block level is crucial for optimizing transaction costs and ensuring reliable operation of Ethereum applications.
// Get block gas limit
const getBlockGasLimit = async () => {
const block = await web3.eth.getBlock('latest');
return block.gasLimit;
};
// Estimate optimal gas price
const getOptimalGasPrice = async () => {
const blockCount = 10;
const latest = await web3.eth.getBlockNumber();
const blocks = await Promise.all([...Array(blockCount)].map((_, i) => web3.eth.getBlock(latest - i)));
const gasPrices = blocks.map((block) => block.baseFeePerGas);
return Math.floor(gasPrices.reduce((a, b) => a + b) / blockCount);
};