"Which customer has the most PTS?" A question that simple gives Raka a lot of work. He has to open the cash book at page one and add everything up himself, every time someone asks. It would be easier with an assistant who reads each new page once and updates a summary book per customer straight away, so every question is answered from the summary book. That assistant is an indexer: a program that reads blockchain events once, stores them in a database in a shape that is ready to be asked, and then answers questions from that database. The Graph is the best-known indexer: you write a subgraph (the rules for which data to take and how to transform it), and you ask for the result through GraphQL.
Why you need an indexer
We use the ERC-20 chain from the ERC-20 lesson: RakaPoints at 0x5FbD...0aa3, 10 blocks, replayed on a local Hardhat 3 node (public test accounts, no real money). It holds 8 Transfer events: 4 mints from earn, Dinda to Yoga 20, then PointsSwap taking 30, 70 and 20 from Dinda. The real eth_getLogs request, and the first log in its answer (some fields trimmed):
{"jsonrpc":"2.0","id":2,"method":"eth_getLogs","params":[{"address":"0x5FbDB2315678afecb367f032d93F642f64180aa3","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],"fromBlock":"0x1","toBlock":"latest"}]}
{"removed":false,"logIndex":"0x0","transactionHash":"0xe2e5e9abff4db16a14920daf778edd3773728106cef123a07f612a8a37e80a26","blockNumber":"0x2","address":"0x5fbdb2315678afecb367f032d93f642f64180aa3","data":"0x0000000000000000000000000000000000000000000000052663ccab1e1c0000","topics":["0xddf252ad...b3ef","0x0000000000000000000000000000000000000000000000000000000000000000","0x00000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8"]}
That is the 95 PTS mint to Dinda (topic1 = the zero address, topic2 = Dinda). To show "top PTS holders", a web page without an indexer has to fetch every Transfer since the deploy block, then add up each address's balance in the browser, every time the page opens. On this local chain that is 8 logs; with a provider limit of 3 blocks per request, it is already 4 requests. Mainnet has about 7,200 blocks a day, so about 2,628,000 blocks a year. With a limit of 2,000 blocks per request (an example), that is 1,314 requests for a single table. And eth_getLogs can only filter indexed parameters: "Transfers above 50 PTS" can't be filtered on the node, because value sits in data.
A subgraph: three files
A subgraph answers three questions: what data is stored (schema.graphql), from which contract and events (subgraph.yaml), and how events become data (the mapping, an AssemblyScript file). Versions used here: Graph CLI 0.98.1 and @graphprotocol/graph-ts 0.38.2 (npm, October 2026).
# schema.graphql
type Account @entity(immutable: false) {
id: Bytes! # the address
balance: BigInt! # balance in the smallest unit (18 decimals)
transferCount: Int!
}
type Transfer @entity(immutable: true) {
id: Bytes! # transaction hash + logIndex
from: Bytes!
to: Bytes!
value: BigInt!
blockNumber: BigInt!
transactionHash: Bytes!
}
# subgraph.yaml
specVersion: 1.3.0
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum
name: RakaPoints
network: localhost # a local graph-node; on Subgraph Studio, sepolia for example
source:
address: "0x5FbDB2315678afecb367f032d93F642f64180aa3"
abi: RakaPoints
startBlock: 1 # the block RakaPoints was deployed in
mapping:
kind: ethereum/events
apiVersion: 0.0.9
language: wasm/assemblyscript
entities: [Account, Transfer]
abis:
- name: RakaPoints
file: ./abis/RakaPoints.json
eventHandlers:
- event: Transfer(indexed address,indexed address,uint256)
handler: handleTransfer
file: ./src/raka-points.ts
// src/raka-points.ts (AssemblyScript: close to TypeScript, compiled to WebAssembly)
import { Address, BigInt } from "@graphprotocol/graph-ts"
import { Transfer as TransferEvent } from "../generated/RakaPoints/RakaPoints"
import { Account, Transfer } from "../generated/schema"
function loadAccount(address: Address): Account {
let account = Account.load(address)
if (account == null) {
account = new Account(address)
account.balance = BigInt.zero()
account.transferCount = 0
}
return account
}
export function handleTransfer(event: TransferEvent): void {
let transfer = new Transfer(event.transaction.hash.concatI32(event.logIndex.toI32()))
transfer.from = event.params.from
transfer.to = event.params.to
transfer.value = event.params.value
transfer.blockNumber = event.block.number
transfer.transactionHash = event.transaction.hash
transfer.save()
if (!event.params.from.equals(Address.zero())) { // not a mint
let sender = loadAccount(event.params.from)
sender.balance = sender.balance.minus(event.params.value)
sender.transferCount = sender.transferCount + 1
sender.save()
}
if (!event.params.to.equals(Address.zero())) { // not a burn
let receiver = loadAccount(event.params.to)
receiver.balance = receiver.balance.plus(event.params.value)
receiver.transferCount = receiver.transferCount + 1
receiver.save()
}
}
@entityturns the type into a table.immutable: trueis for data that never changes (Transfer); an Account changes, sofalse.startBlockmakes the indexer start at the deploy block, not block 0.eventHandlersmaps an event signature to a function. graph-node callshandleTransferonce per log, in block order and thenlogIndexorder.- The zero address means a mint (
from) or a burn (to): no balance is taken from or added to it. graph codegengenerates theTransferEvent,AccountandTransferclasses from the ABI and the schema ("Types generated successfully");graph buildcompiles the mapping to WebAssembly ("Build completed: build/subgraph.yaml").
The handler runs per event
This is the store after each block, exactly what the handler above produces for those 8 logs (checked with graph test, Matchstick 0.6.0: "All 1 tests passed!"):
| Block | Event | Dinda | Yoga | PointsSwap |
|---|---|---|---|---|
| 2 | mint 95 to Dinda | 95 | ||
| 3 | mint 75 to Yoga | 95 | 75 | |
| 4 | mint 40 to Yoga | 95 | 115 | |
| 5 | mint 65 to Dinda | 160 | 115 | |
| 6 | Dinda to Yoga 20 | 140 | 135 | |
| 7 | only Approval, the handler isn't called |
140 | 135 | |
| 8 | PointsSwap takes 30 | 110 | 135 | 30 |
| 9 | PointsSwap takes 70 | 40 | 135 | 100 |
| 10 | PointsSwap takes 20 | 20 | 135 | 120 |
The three always add up to 275, the same as totalSupply. That is a quick way to check your handler.
A GraphQL query
One request, the answer already computed:
const query = `{ accounts(orderBy: balance, orderDirection: desc) { id balance transferCount } }`
const res = await fetch('http://localhost:8000/subgraphs/name/raka-points', { // a local graph-node
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query }),
})
console.log(await res.json())
{
"data": {
"accounts": [
{ "id": "0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc", "balance": "135000000000000000000", "transferCount": 3 },
{ "id": "0x15d34aaf54267db7d7c367839aaf71a00a2c6a65", "balance": "120000000000000000000", "transferCount": 3 },
{ "id": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "balance": "20000000000000000000", "transferCount": 6 }
]
}
}
Bytescomes back as lowercase hex,BigIntas a string (an 18-decimals amount is too big for a JavaScript number).- You can filter on any field, including ones that are not
indexed:transfers(where: { value_gt: "50000000000000000000" }, orderBy: blockNumber)returns 4 Transfers (blocks 2, 3, 5 and 9). That is whateth_getLogscan't do.
Reorgs and finality: an indexer's problem
The newest block can be replaced (the reading blockchain data lesson). On a Hardhat node, evm_revert can imitate that: the old block 10 (hash 0x49b2...75f4) is dropped, then a new block 10 (hash 0x7abd...be3f) is mined on the same parent, block 9 0x809e...0131. It holds only Dinda's approve(PointsSwap, 0), so there is no Transfer.
A good indexer stores the hash of every block it has processed. When a new block's parentHash doesn't match, or the same block number arrives with another hash, it undoes every change from the dropped block, then processes the replacement. graph-node does this automatically. The result: the 20 PTS Transfer in block 10 disappears, Dinda is back to 40 PTS and PointsSwap to 100. If you write your own indexer, you have two choices: handle that rollback, or only process blocks up to finalized (about 13 minutes behind on mainnet). To know which block a subgraph's data has reached, ask _meta { block { number hash } }.
Where a subgraph runs
- The Graph's hosted service has been shut down since 12 June 2024. Old tutorials with
api.thegraph.com/subgraphs/name/...URLs no longer work. - Subgraph Studio:
graph auth <DEPLOY_KEY>thengraph deploy raka-points. The development query URL is limited to 3,000 queries a day, enough to try things on Sepolia. - The Graph Network: the decentralised network of indexers a subgraph is published to; all its activity, billing included, is on Arbitrum One. The Free Plan has 100,000 queries a month; after that you pay with GRT or a credit card.
- Your own graph-node for the local chain 31337: graph-node + Postgres + IPFS (usually through Docker), then
graph create --node http://localhost:8020/ raka-pointsandgraph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 raka-points.
📌 Alternatives to The Graph
They all solve the same problem (events in, tables out), in different ways. npm versions as of October 2026:
| Tool | What it is |
|---|---|
| Ponder 0.18.1 | a TypeScript indexer you run yourself, storing to Postgres, serving GraphQL and SQL |
Envio (envio 3.14.0) |
HyperIndex: TypeScript handlers, self-hosted or on Envio's service |
| Goldsky (CLI 13.17.0) | a paid service: runs the same subgraphs, plus Mirror to stream data into your own database |
| Your own Postgres indexer | a script doing getLogs in slices, saving to tables, plus the reorg logic above |
⚠️ What makes a subgraph slow or miscount
- Leaving out
startBlock. The indexer starts at block 0 and checks millions of empty blocks before it reaches your contract. - Forgetting the zero address. Without the
Address.zero()check, a mint subtracts from the zero address and an Account with a negative balance appears. - Storing
valueasInt.Intis only 32-bit; auint256value must be aBigInt. In JavaScript, readbalanceas a string, thenBigInt(...)orformatUnits. - Treating indexer data as final. Data up to the newest block can be undone by a reorg. For important decisions, check its block through
_metaor wait forfinalized.
TL;DR: eth_getLogs is fine for a little data, but for tables, rankings and long histories you need an indexer: read events once, store them, answer from the database. The Graph uses a subgraph: schema.graphql (entities), subgraph.yaml (contract, startBlock, event to handler) and an AssemblyScript mapping (handleTransfer turns an event into entities). From RakaPoints's 8 Transfers, accounts(orderBy: balance, orderDirection: desc) answers Yoga 135, PointsSwap 120, Dinda 20, and GraphQL can filter fields that are not indexed. Reorgs are an indexer's problem: a dropped block must be undone (Dinda back to 40), or wait for finalized. The hosted service has been gone since 12 June 2024; use Subgraph Studio and The Graph Network (Arbitrum One), your own graph-node, or alternatives such as Ponder, Envio and Goldsky.
⚡ An indexer: read once, answer from a database
Meaning: The Graph indexes blockchain data so it can be queried fast through GraphQL. Events are read once, stored in a shape that's ready to be asked, then questions are answered from that database.
⚡ A subgraph: three files
Meaning: schema.graphql says what data is stored, subgraph.yaml says which contract, startBlock and which event goes to which handler, and the AssemblyScript mapping turns events into entities.
⚡ One query, the answer already computed
Write:
const query = `{ accounts(orderBy: balance, orderDirection: desc) { id balance transferCount } }`
Meaning: The answer is Yoga 135, PointsSwap 120, Dinda 20. GraphQL can also filter fields that are not indexed, which eth_getLogs can't do.
⚡ Reorgs are an indexer's problem
Guess first: block 10 is dropped in a reorg, and its replacement holds no Transfer. What is Dinda's balance in the subgraph now?
Back to 40 PTS. graph-node undoes every change from the dropped block, so the 20 PTS Transfer in block 10 disappears.
Meaning: An indexer you write yourself must handle that rollback, or only process blocks up to finalized.