EIP-234 · Final · Interface · 2017-03-24
EIP-234: Add `blockHash` to JSON-RPC filter options.
Adds a blockHash option to eth_getLogs and eth_newFilter, so apps can fetch logs for one exact block and stay correct through chain reorganizations.
What problem does it solve?
Apps that index events, such as wallets, exchanges and dashboards, need to know both when logs appear and when a reorg removes them. Log subscriptions alone are fragile. If your WebSocket drops or the node restarts during a reorg, you never hear about the removed logs.
A robust pattern is to track blocks yourself and fetch logs block by block. Before EIP-234, though, eth_getLogs only accepted block numbers. If a reorg happened between "I saw block #100 with hash 0xabc" and "give me logs for #100", you could silently get logs from a different block #100. If the result was empty, you could not even tell which block it came from.
How it works
The filter object for eth_getLogs and eth_newFilter gets an optional blockHash field:
- The node returns the logs that match the filter in exactly that block, whether or not the block is still on the canonical chain.
- If the node does not know the hash, it returns an error rather than an empty list. The spec's test case uses code
-32000with message"Block not found.". blockHashis mutually exclusive withfromBlock/toBlock.addressandtopicsfiltering work as usual.
Now an empty result really means "this block had no matching logs", and an error means "roll back and resync".
Sample code
Raw JSON-RPC:
{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getLogs",
"params": [{
"blockHash": "0x<32-byte block hash>",
"address": "0x<contract address>",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}]
}
The topic above is keccak256("Transfer(address,address,uint256)").
ethers v6, fetching logs for a block you already saw:
import { JsonRpcProvider, id } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
provider.on("block", async (n: number) => {
const block = await provider.getBlock(n);
try {
const logs = await provider.getLogs({
blockHash: block!.hash!, // pin to this exact block
topics: [id("Transfer(address,address,uint256)")],
});
console.log(n, block!.hash, logs.length);
} catch {
// block vanished in a reorg: roll back local state and resync
}
});
Things to know
- This EIP is Final and supported by major clients. The spec lists Geth as the reference implementation.
- It depends on EIP-1474, the JSON-RPC spec EIP, which is Stagnant. The canonical RPC definition now lives in the
ethereum/execution-apisrepository. - EIP-1898 applies the same idea to state queries such as
eth_callandeth_getBalance, letting you pin them to a block hash. - Combine with a block's
logsBloomto skipeth_getLogscalls for blocks that cannot contain your events.