Reading Blockchain Data — Web3

Reading a blockchain is free: ETH balances (eth_getBalance, in ethers provider.getBalance(address)), view/pure functions (eth_call, viem readContract), and…

How much PTS does Dinda have now? How much did she have at block 3? When did she earn it? You can ask a node all three: an address's balance, what a contract's view function answers, and what has happened so far. Reading is free: no transaction, no signature, no gas. Raka's Shirt Shop's ledger on display behind glass works much the same. Anyone may look at the last page (the current state), turn back to an old page (an old block), or look up every entry marked "Dinda" (event logs). Looking changes nothing in the book, so there is nothing to pay.

The local chain we read

Every number in this lesson was really read from a Hardhat 3 node on a laptop (npx hardhat node, address http://127.0.0.1:8545, chain ID 31337). The accounts are the public Hardhat/Anvil test accounts, whose private keys the node prints itself, so no real money is ever involved. What the chain holds:

Block Transaction (from Raka) Event
1 deploy RakaPoints at 0x5FbD...0aa3
2 earn(Dinda, 95000), Coffee Print Shirt Earned(Dinda, 95 PTS)
3 earn(Yoga, 75000), Plain Black Shirt Earned(Yoga, 75 PTS)
4 earn(Yoga, 40000), Raka Cap Earned(Yoga, 40 PTS)
5 earn(Dinda, 65000), Coffee Print Mug Earned(Dinda, 65 PTS)

The library (viem or ethers) sends questions to the node in JSON-RPC form. The three methods used most, all free:

Method Reads viem ethers v6
eth_getBalance an address's ETH balance getBalance({ address }) provider.getBalance(address)
eth_call the answer of a view/pure function readContract(...) contract.balanceOf(...)
eth_getLogs events that happened getLogs(...) contract.queryFilter(...)

Dinda's ETH balance, through ethers: await provider.getBalance(DINDA) returns 10000000000000000000000n (in wei), and ethers.formatEther(...) writes it as '10000.0'. That is the node's built-in test ETH.

eth_call: running a function without a transaction

import { createPublicClient, http, parseAbi, formatUnits } from 'viem'
import { hardhat } from 'viem/chains'

const PTS = '0x5FbDB2315678afecb367f032d93F642f64180aa3'
const DINDA = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'
const abi = parseAbi([
  'function balanceOf(address) view returns (uint256)',
  'function pointsFor(uint256 cents) pure returns (uint256)',
  'event Earned(address indexed customer, uint256 amount)',
])
const client = createPublicClient({ chain: hardhat, transport: http() })

const balance = await client.readContract({ address: PTS, abi, functionName: 'balanceOf', args: [DINDA] })
console.log(formatUnits(balance, 18)) // '160'

const points = await client.readContract({ address: PTS, abi, functionName: 'pointsFor', args: [9500n] })
console.log(points) // 95000000000000000000n

What was really sent for pointsFor(9500), and the node's answer:

request:  {"jsonrpc":"2.0","id":5,"method":"eth_call","params":[{"data":"0xa68f0ebe000000000000000000000000000000000000000000000000000000000000251c","to":"0x5FbDB2315678afecb367f032d93F642f64180aa3"},"latest"]}
response: {"jsonrpc":"2.0","id":5,"result":"0x0000000000000000000000000000000000000000000000052663ccab1e1c0000"}

Reading the state at a given block

Replace "latest" with a block number, and the node answers with the state as it was then:

await client.readContract({ address: PTS, abi, functionName: 'balanceOf', args: [DINDA], blockNumber: 3n })
// 95000000000000000000n
blockNumber 1 2 3 4 5
Dinda's PTS 0 95 95 95 160

At block 3 Dinda only had her Coffee Print Shirt, so the answer is 95 PTS. Her mug was only recorded in block 5. On a local chain every old block is available. A public node usually keeps only recent state; for state from long ago you need an archive node.

Events and logs: the trail a transaction leaves

Every emit Earned(customer, amount) writes one log into the transaction's receipt. A log has three parts: address (the contract that wrote it), topics (at most 4, 32 bytes each, usable for filtering) and data (the rest). For event Earned(address indexed customer, uint256 amount):

const logs = await client.getLogs({
  address: PTS,
  event: abi[2],
  args: { customer: DINDA },
  fromBlock: 0n,
  toBlock: 'latest',
})
for (const log of logs) console.log(log.blockNumber, formatUnits(log.args.amount, 18))
// 2n '95'
// 5n '65'

The request viem sent, and the first log in the answer (a few fields cut):

{"jsonrpc":"2.0","id":11,"method":"eth_getLogs","params":[{"address":"0x5FbDB2315678afecb367f032d93F642f64180aa3","topics":["0x053fa1fc52294a40b4ff1a988765bd298c00caa24d685cc3f767dcfde254ef9a","0x00000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8"],"fromBlock":"0x0","toBlock":"latest"}]}

{"blockNumber":"0x2","transactionHash":"0xacdc047f3ef77ff502d9bcd8ad4fb5d4592beb206c7186662a1b317dc68328af","logIndex":"0x0","address":"0x5fbdb2315678afecb367f032d93f642f64180aa3","topics":["0x053fa1fc...ef9a","0x00000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8"],"data":"0x0000000000000000000000000000000000000000000000052663ccab1e1c0000"}

The data 0x...052663ccab1e1c0000 reads as 95000000000000000000n, 95 PTS. The node filters by topics, so only indexed parameters can be filtered on. "Every Earned whose amount is 95" can't be asked through a filter; fetch all the logs, then filter them yourself.

Block ranges and RPC provider limits

fromBlock and toBlock say which blocks get searched. Without them, the node only searches the newest block. Five blocks on a local chain is light, but Sepolia or mainnet have millions of blocks, and RPC providers limit eth_getLogs: the block range per request, the number of logs per answer, or both. The numbers differ per provider, so read their docs. The pattern is always the same: start at the block where the contract was deployed (not 0), then ask in slices:

const DEPLOY_BLOCK = 1n // the block RakaPoints was deployed in
const STEP = 2n // a tiny example; on a public network, say 2000n
const head = await client.getBlockNumber() // 5n
const logs = []
for (let from = DEPLOY_BLOCK; from <= head; from += STEP) {
  const to = from + STEP - 1n < head ? from + STEP - 1n : head
  logs.push(...(await client.getLogs({ address: PTS, event: abi[2], fromBlock: from, toBlock: to })))
}
console.log(logs.length) // 4, from 3 requests: blocks 1-2, 3-4, 5

latest, safe, finalized

The newest block isn't necessarily permanent. Besides a number, a node accepts three labels:

Label Meaning
latest the newest block the node has. It can still be replaced (a reorg)
safe already backed by most validators, very unlikely to change
finalized final. On mainnet and Sepolia it usually trails latest by about 13 minutes (2 epochs, 64 slots × 12 seconds)

A local Hardhat node has no validators, so getBlock({ blockTag: 'safe' }) and 'finalized' both return block 5, the same as latest. To show a balance, latest is enough. For a decision that's costly to get wrong, such as shipping goods after an on-chain payment, wait until finalized.

📌 Reading storage directly

eth_call runs a getter. The state itself sits in 32-byte storage slots, and eth_getStorageAt reads them raw. RakaPoints keeps owner in slot 0 and totalSupply in slot 1:

getStorageAt(PTS, 0x0) = 0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266   (Raka)
getStorageAt(PTS, 0x1) = 0x00000000000000000000000000000000000000000000000ee86442fcd06c0000   (275 PTS)

This also proves that private in Solidity isn't secret: anyone can read the slot.

⚠️ What throws your reads off

TL;DR: Reading a blockchain is free: ETH balances (eth_getBalance, in ethers provider.getBalance(address)), view/pure functions (eth_call, viem readContract), and events (eth_getLogs, viem getLogs). eth_call runs the contract's code on the node's copy of the state and throws the changes away; with blockNumber you read past state (Dinda: 95 PTS at block 3, 160 at block 5). A log holds address, topics and data: topic0 = keccak256 of the event signature (Earned(address,uint256) = 0x053fa1fc...), indexed parameters become the next topics and can be filtered, the rest sits in data. Limit fromBlock/toBlock and ask in slices because RPC providers have limits. latest can change, safe almost certainly won't, finalized is permanent.

⚡ Reading is free

Meaning: ETH balances (eth_getBalance), the answers of view/pure functions (eth_call) and event logs (eth_getLogs) can all be read with no transaction, no signature and no gas.

⚡ The state at a given block

Write:

await client.readContract({ address: PTS, abi, functionName: 'balanceOf', args: [DINDA], blockNumber: 3n })
// 95000000000000000000n
Guess first: at block 5 Dinda has 160 PTS. Read at block 3, what's the answer?

95 PTS. At block 3 Dinda only had her Coffee Print Shirt; her mug was only recorded in block 5.

Meaning: Replace "latest" with a block number, and the node answers with the state as it was then. State from long ago needs an archive node.

⚡ A log: address, topics, data

Meaning: topic0 = keccak256 of the event signature, so Earned(address,uint256) gives 0x053fa1fc.... indexed parameters become the next topics and can be filtered on. amount sits in data, so you filter it in your own code.

⚡ latest isn't necessarily permanent

Meaning: The latest block can still be replaced (a reorg). For a decision that's costly to get wrong, such as shipping goods after an on-chain payment, wait for finalized.

What you will learn