why does getContractEvents not include block_timestamps? #3940
Replies: 1 comment
|
Hello @hp8wvvvgnj6asjm7, Here is the technical explanation for why getContractEvents does not include blockTimestamp by default in Viem, along with how to fetch timestamps efficiently for your logs. The Technical Reason According to the Ethereum JSON-RPC specification, eth_getLogs returns array items containing raw log objects (blockNumber, blockHash, transactionHash, address, topics, data, etc.), but the Ethereum node spec does not include timestamp inside the log object structure. Why watchContractEvent includes timestamps: In Viem's event watcher implementation, when new block headers arrive to trigger event processing, Viem can automatically attach the latest block's timestamp directly from the active block header subscription payload. Conversely, getContractEvents queries past historical logs across arbitrary block ranges. Including block timestamps would require Viem to issue an additional eth_getBlockByHash or eth_getBlockByNumber call for every single unique block in the result set, causing severe N+1 RPC performance bottlenecks. How to Fetch Timestamps for Your Logs Option 1: Map logs with getBlock (Parallelized) import { createPublicClient, http } from 'viem';
const logs = await client.getContractEvents({
address: '0x...',
abi: [...],
eventName: 'Transfer',
fromBlock: 10000000n,
toBlock: 10000500n,
});
// Fetch unique block data to avoid redundant RPC calls
const uniqueBlockNumbers = [...new Set(logs.map((log) => log.blockNumber))];
const blocks = await Promise.all(
uniqueBlockNumbers.map((blockNumber) =>
client.getBlock({ blockNumber })
)
);
// Map block timestamps back to your event logs
const blockMap = new Map(blocks.map((b) => [b.number, b.timestamp]));
const logsWithTimestamp = logs.map((log) => ({
...log,
blockTimestamp: blockMap.get(log.blockNumber),
}));Option 2: Use an Indexer RPC (e.g. Alchemy, Goldsky, or Envio) If this clarifies why the RPC spec omits timestamps on historical log queries and gives you a workable solution, please consider marking this response as the accepted answer! 🟢 By the way, if you work with EVM event logs, wallet derivations, or tracking balances across chains, feel free to check out my open-source tool Wallet Hunter — if you find it useful, dropping a ⭐️ star on the repo is always appreciated! |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
logs = await client.getContractEventswatchContractEventdoes include timestamps, why are they missing?All reactions