在区块级别理解和管理燃气消耗对于优化交易成本和确保以太坊应用程序的可靠运行至关重要。
// 获取区块燃气限制
const getBlockGasLimit = async () => {
const block = await web3.eth.getBlock('latest');
return block.gasLimit;
};
// 估算最佳燃气价格
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);
};