Los timestamps de bloques en Ethereum proporcionan información de tiempo para transacciones y contratos inteligentes. Entender cómo trabajar con ellos es esencial para aplicaciones sensibles al tiempo.
// Obtener timestamp del bloque
const getBlockTimestamp = async (blockNumber) => {
const block = await web3.eth.getBlock(blockNumber);
return block.timestamp;
};
// Calcular tiempo promedio de bloque
const getAverageBlockTime = async (blockCount = 100) => {
const latestBlock = await web3.eth.getBlockNumber();
const oldBlock = await web3.eth.getBlock(latestBlock - blockCount);
const newBlock = await web3.eth.getBlock(latestBlock);
return (newBlock.timestamp - oldBlock.timestamp) / blockCount;
};