Entender y gestionar el consumo de gas a nivel de bloque es crucial para optimizar los costos de transacción y garantizar el funcionamiento fiable de las aplicaciones Ethereum.
// Obtener límite de gas del bloque
const getBlockGasLimit = async () => {
const block = await web3.eth.getBlock('latest');
return block.gasLimit;
};
// Estimar precio óptimo de gas
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);
};