Events as data
About 2583 wordsAbout 9 min
Week 6 · Part 2 — Events as data
Core question — how does an app show what already happened on a contract, before the user even arrived?
So far your app can read the present: records(account) tells you what a record is now. It cannot tell you who changed it, when, or what it said before. That history is not kept in readable state. It is in the contract's events.
This Part turns those events into an activity history your frontend can show, and teaches you to check that the history is right.
Picture a shop's receipt roll
The shelf shows what is in stock today. The receipt roll shows every sale that got it there. You rebuild "what happened" from the receipts, not from the shelf.
Where the picture stops: receipts belong to the shop. Event logs are part of the chain, and anyone can read them. But not every node keeps the old ones, so which node you ask matters.
The hard skill
Turn contract events into a typed, ordered activity history with viem, and verify it against the contract's current state.
After this Part you can:
- read past events from a contract, starting at its deployment block;
- cope with an RPC that rejects a wide block range, or has dropped old logs;
- order events correctly and attach times to the ones you show;
- check that your history agrees with what the contract says now.
Core / reference material
Events are history; state is the present
The Registry stores each account's current record in records. It also emits an event every time one changes, including once in the constructor:
event RecordUpdated(address indexed account, string value);Two details matter for the code you will write:
accountis indexed, so a node can filter by it for you.valueis not indexed, so you can only read it after the event is decoded.setRecordrejects an empty string, so the only way aRecordUpdatedcarries an empty value is when the owner calledclearRecord. Treat an empty value as "cleared", not as "set to nothing".
An event is returned as a log with a block number, transaction hash and logIndex. logIndex is the position of a log within its block. Because it is block-wide, sorting logs by blockNumber and then logIndex preserves their chain order even when several transactions in the same block emitted logs. If you see transactionIndex, that is the transaction's position within the block; it does not replace logIndex. The account field is indexed: the node stores it in a filterable topic so a query can find logs for one account efficiently. value is not indexed, so it is decoded from the log data after the match is found.
The core distinction is:
State answers what is true now? Events answer what did the contract announce happened over time? Events are useful history, not a substitute for reading the current state.
If you changed the event in Part 2, use your version. Everything below works the same way.
You read events from outside the chain with getContractEvents. Under the hood it is an eth_getLogs request to your RPC. JSON-RPC is the request/response protocol used between Ethereum software; eth_getLogs is the standard method for asking a node for matching event logs.
bigint is JavaScript's integer type for exact whole numbers larger than the safe range of Number. viem uses it for block numbers and token-like values, so render it with .toString() instead of converting it through Number.
Where to start: the deployment block
A contract cannot have events from before it existed. npm run deploy saved your contract's deployment block in deployments/sepolia.json, next to its address. If you are still on the shared Registry, the file holds its block, 11853110.
Five things that go wrong
| Problem | Why it happens | What to do |
|---|---|---|
| Scanning from block 0 is slow or rejected | The contract did not exist before its deployment block | Start at blockNumber from deployments/sepolia.json |
| The RPC rejects a wide range | Free RPCs cap how many blocks one eth_getLogs call may cover, and the cap differs by provider. On 21 October 2026, one allowed under 10,000 blocks per call, another only 50 | Read in windows of a fixed size. If a window is rejected, halve it and retry from the same start |
pruned history unavailable | Some free RPCs keep only recent logs, sometimes just the last day or two. Smaller windows do not help | Stop shrinking at a floor and show the error. Then switch to an RPC that keeps history (below) |
| The list looks shuffled | Provider response order is not the ordering your UI needs, and several logs can share a block | Sort by blockNumber, then logIndex, newest first |
| No timestamps | A log has a block number, not a time | Fetch each distinct block once with getBlock, only for the rows you show |
Recent blocks can also be reorganised, so the newest few rows are the least settled part of the list. For an activity list that is usually fine.
Provider-specific history behaviour
The table above describes provider behaviour, not a protocol guarantee. In a current provider example checked on 21 October 2026, the starter's PublicNode endpoint returned pruned history unavailable for logs about 108,000 blocks old, dRPC rejected a 10,000-block range, and Tenderly's public gateway served the full range. These observations can change. The durable lesson is that RPC providers may limit block ranges and historical retention, so the code must handle those limits rather than depend on one endpoint.
An RPC that keeps history
The starter's default RPC, https://ethereum-sepolia-rpc.publicnode.com, is quick for reads and writes but keeps only recent logs. If your contract is more than a day or two old, you will hit pruned history unavailable. For the event script, change RPC_URL in .env; that is the setting read by scripts/client.ts. VITE_RPC_URL is the frontend setting introduced in W6P1. Change both only if you also want the frontend to use the same provider; after changing VITE_RPC_URL, restart npm run dev.
RPC_URL=https://sepolia.gateway.tenderly.co
VITE_RPC_URL=https://sepolia.gateway.tenderly.coAt the time of that check, Tenderly's public gateway was free, needed no account and served every block from the shared Registry's deployment onwards. Any Sepolia provider that keeps full history works as well; verify the current limits before relying on it.
Worked helper pattern: read bounded block windows
An RPC may reject a request that covers too many blocks. This helper accepts your event-query function, starts at the deployment block you provide, and shrinks the window only for a recognised block-range limit. It stops at a minimum size, reports pruned history separately, and lets unrelated errors surface unchanged.
type BlockQuery<T> = (fromBlock: bigint, toBlock: bigint) => Promise<T[]>
function errorText(error: unknown): string {
const messages: string[] = []
const seen = new Set<Error>()
let current: unknown = error
while (current instanceof Error && !seen.has(current)) {
seen.add(current)
messages.push(current.message)
current = (current as Error & { cause?: unknown }).cause
}
return (messages.join(' ') || String(current ?? error)).toLowerCase()
}
function isPrunedHistory(message: string): boolean {
return /prun|missing trie|historical.*(?:unavailable|not available)/.test(message)
}
function isBlockRangeLimit(message: string): boolean {
const knownPatterns = [
/(?:block|log) range.*(?:limit|too (?:wide|large)|exceed|maximum)/,
/(?:max|maximum|limit|limited).{0,40}(?:block|log|range|blocks?)/,
/(?:too many|more than \d+) logs?/,
]
return knownPatterns.some((pattern) => pattern.test(message))
}
async function readInWindows<T>(
query: BlockQuery<T>,
deploymentBlock: bigint,
latestBlock: bigint,
initialWindow = 2_000n,
minimumWindow = 100n,
): Promise<T[]> {
if (minimumWindow < 1n || initialWindow < minimumWindow) {
throw new Error('The minimum window must be positive and no larger than the initial window.')
}
if (deploymentBlock > latestBlock) return []
const rows: T[] = []
let fromBlock = deploymentBlock
let windowSize = initialWindow
while (fromBlock <= latestBlock) {
const windowEnd = fromBlock + windowSize - 1n
const toBlock = windowEnd < latestBlock ? windowEnd : latestBlock
try {
const page = await query(fromBlock, toBlock)
for (const row of page) rows.push(row)
fromBlock = toBlock + 1n
} catch (error) {
const message = errorText(error)
if (isPrunedHistory(message)) {
throw new Error(
`This RPC has pruned the requested history. Use a provider that retains older logs. Original error: ${message}`,
)
}
if (!isBlockRangeLimit(message)) throw error
if (windowSize === minimumWindow) {
throw new Error(
`The RPC rejected the minimum ${minimumWindow}-block range. Original error: ${message}`,
)
}
const half = windowSize / 2n
windowSize = half < minimumWindow ? minimumWindow : half
}
}
return rows
}Use the query callback to select the event and contract you need:
const latestBlock = await client.getBlockNumber()
const logs = await readInWindows(
(fromBlock, toBlock) => client.getContractEvents({
address: address!,
abi,
eventName: 'RecordUpdated',
fromBlock,
toBlock,
}),
BigInt(deployment.blockNumber),
latestBlock,
)This is generic provider plumbing. You may copy and adapt the pattern in your own project. You should be able to explain why it chunks requests and retries only a known range-limit error, but inventing the retry algorithm is not the Web3 skill being assessed. Your app still maps the decoded events into rows, sorts them, shows loading/empty/error states, and verifies history against current contract state.
Worked example: your first look
Run these commands from the starter repository root. Read one window of events, starting at the deployment block. Save the script as scripts/events-first-look.ts:
import { readFileSync } from 'node:fs'
import { abi, address } from '../shared/contract.js'
import { client, requireSepolia } from './client.js'
await requireSepolia()
const deployment = JSON.parse(readFileSync('deployments/sepolia.json', 'utf8'))
const from = BigInt(deployment.blockNumber)
const logs = await client.getContractEvents({
address: address!,
abi,
eventName: 'RecordUpdated',
fromBlock: from,
toBlock: from + 1_999n,
})
console.log(`Blocks ${from} to ${from + 1_999n}: ${logs.length} event(s)`)
for (const log of logs) {
console.log(log.blockNumber, log.logIndex, log.args.account, JSON.stringify(log.args.value))
}Run it:
npx tsx scripts/events-first-look.tsAgainst the shared Registry, with Tenderly's gateway as RPC_URL:
Blocks 11853110 to 11855109: 1 event(s)
11853110n 412 0xE234F67EaB4638Cb6C7f93D1bfcD0bb9DCE09252 "Hello from NTU Blockchain Builder Lab"That one line is the constructor's event: the owner and the starting text. With your own contract you will see your deployer address instead, plus anything you wrote in the first 2,000 blocks. With the default publicnode RPC, the same script fails with pruned history unavailable.
Why each part is there:
fromBlockis the deployment block. Nothing earlier can contain this contract's events.toBlockbounds the window. One call covers 2,000 blocks. Your code repeats this until it reaches the latest block.log.args.accountandlog.args.valueare already decoded. viem uses the ABI inshared/contract.ts, so you write no decoding yourself.blockNumberis abigint. Use.toString()when you render it.
Hands-on task
Complete section 4. Events in src/App.tsx, for the contract shared/contract.ts points at (your own, after Part 3).
Add the helper functions from the worked pattern above in src/App.tsx, outside the existing App() component. Add the query in the existing section 4 TODO; do not create a second App() component.
- Load the history. Use the provided worked helper pattern with a
getContractEventsquery forRecordUpdated, from the deployment block to the latest block. Copy the pattern into your working project if useful. Map the decoded events into typed rows (account, value, kindsetorcleared, block number, log index and transaction hash), then sort newest first. Explain why a rejected wide range shrinks, why it stops at a floor, and why pruned history needs another RPC. - Show it. Render the newest 25 rows: the account shortened, what happened (set to a value, or cleared), the block and its time, and a link to the transaction on Sepolia Etherscan. Show clear loading, empty and error states.
- Verify it. For one account, check that the value in its newest event equals what
records(account)returns now. Then open one transaction from your list on Etherscan and confirm it matches the row.
Reuse the public client from W6P1. A public RPC address in a VITE_ variable is fine. A private key never is.
Out of scope: live updates, pagination controls, indexers and subgraphs, and styling.
Use AI as a pair, not a replacement
An assistant can draft the loop quickly. Before you keep it, check four things: does it start at the deployment block, does it halve the window on an error, does it stop at a floor, and does it sort by block and log index? Then run your verification step.
Evidence required
- A link to your commit for the events code.
- A screenshot of the Events section showing your list (or the empty state).
- Your verification output: the account, its newest event value, and
records(account). - Two or three sentences: what does the provided worked helper pattern do when the RPC rejects a range, what happens when history is pruned, and what does a "cleared" row mean?
Completion and revision
This Part is worth 100 points in the Academy progression. Academy participants submit it for a binary Complete or Revise review against the criteria above. Independent readers may use those criteria as a self-check; formal points are tracked through organised Academy participation. There is no partial-score rubric.
Your work is complete when:
Further exploration — optional, not assessed
- Filter by one account with the
argsoption:args: { account }. Why does this work foraccountbut not forvalue? - Point
RPC_URLback at publicnode and run your loader. Does your error message tell a user what to do? - Think about what this approach cannot do for a contract with millions of events, and why teams use indexers for that.
Sources and attribution
- viem — getContractEvents — Link, referenced only
- viem — getBlock — Link, referenced only
- Ethereum JSON-RPC API — eth_getLogs — Link, referenced only
- Blockchain@NTU Academy Builder starter — Reuse (MIT), the
Registrycontract,scripts/client.tsanddeployments/sepolia.json
Changelog
f0652-docs(curriculum): migrate Academy to 10-week structure (#34)on4fee9-docs(curriculum): close prerequisite gaps across Foundation and Deep Dive (#33)on69ce3-docs(builder): improve Deep Dive teaching clarity and engineering guidance (#31)onffe9a-docs(track): add Builder W5 Part 5 events as data (#28)on