Sub topic 3
Where on-chain data comes from
Every metric in this tutorial starts as raw records on a blockchain. Before you compute daily active addresses or exchange netflow, you need to know which layer of tooling produced your numbers. That layer decides what is complete, what is delayed, and what you have to trust.
This chapter assumes you know what a block, a transaction, and a wallet are. It also assumes you can read short Python scripts and make HTTP requests. The ledger models from the first chapter matter here too. Account-based chains and UTXO chains expose different raw records.
The three layers of access
On-chain data reaches you through one of three layers. Each layer is built on the one before it.
- Nodes hold the chain itself and answer low-level queries.
- Indexers read from nodes, decode the records, and store them in a database you can query.
- Analytics platforms and APIs sit on top of indexers. They add labels, pre-computed metrics, dashboards, and hosted SQL.
Moving down the layers makes the data easier to use. It also moves you further from the original records, so you rely more on someone else's decoding, definitions, and labels.
Nodes: the primary source
A node is software that downloads, validates, and stores the blockchain. You can run your own, such as Bitcoin Core or an Ethereum execution client like Geth, Nethermind, or Erigon. You can also rent access from a provider that runs nodes for you.
Nodes expose a JSON-RPC interface. This is an HTTP or WebSocket API where you send a method name and parameters and get JSON back.
On an account-based chain such as Ethereum, common calls are:
eth_blockNumberreturns the latest block height.eth_getBlockByNumberreturns a block with its transactions and timestamp.eth_getLogsreturns event logs that match a filter.eth_getBalancereturns an address balance at a given block.
Bitcoin Core offers getblock, getrawtransaction, and gettxout instead. A UTXO chain returns transactions with inputs and outputs. Inputs reference earlier outputs, so you must look up the spent output to learn the sender's address and the amount.
Full nodes versus archive nodes
A full node validates everything but keeps full historical state only for recent blocks. An archive node keeps the state at every block. On Ethereum, that distinction matters:
- Balances at a recent block are cheap to query on any node.
- Balances at an old block (
eth_getBalancewith a historic block number) need an archive node. - Replaying transactions to see internal calls needs traces (
debug_traceTransactionortrace_block), which are heavy to produce and often only offered by archive-capable clients.
If you plan to build holder distributions at past dates, this matters a lot. You can reconstruct balances by summing transfers from genesis. You can also ask an archive node for historical balances. Both approaches cost real storage or compute.
Why token transfers come from logs
On Ethereum, a native ETH transfer is a field of a transaction. An ERC-20 token transfer is different. The token contract emits a Transfer(address,address,uint256) event, and that event appears as a log in the transaction receipt. Token balances live inside the contract's own storage.
A raw scan of transactions would therefore miss almost all token movement. To measure a token, filter logs by the contract address and the Transfer event signature. The signature hash is 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef.
ERC-20 Transfer logs carry the sender and receiver as indexed topics and the amount in the data field. ERC-721 (NFT) transfers use the same signature but index the token ID as a third topic, so they have four topics instead of three. A decoder must check the topic count.
A minimal log fetcher
The script below pulls ERC-20 Transfer logs over a block range, splitting the range into chunks. Providers cap the block range or result count of eth_getLogs, and the exact limits differ by provider. Set RPC_URL to a node or provider endpoint, and change TOKEN to the contract you want.
import json
import os
import urllib.request
RPC_URL = os.environ["RPC_URL"]
# USDC on Ethereum mainnet
TOKEN = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
TRANSFER_TOPIC = (
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
)
CONFIRMATIONS = 12
CHUNK = 1000
def rpc(method, params):
body = json.dumps(
{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
).encode()
req = urllib.request.Request(
RPC_URL, data=body, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=30) as resp:
payload = json.load(resp)
if "error" in payload:
raise RuntimeError(payload["error"])
return payload["result"]
def decode_transfer(log):
topics = log["topics"]
if len(topics) != 3 or log["data"] == "0x":
return None # not a standard ERC-20 Transfer
return {
"block": int(log["blockNumber"], 16),
"tx": log["transactionHash"],
"log_index": int(log["logIndex"], 16),
"from": "0x" + topics[1][-40:],
"to": "0x" + topics[2][-40:],
"value": int(log["data"], 16), # raw units, not divided by decimals
}
def fetch_transfers(start_block, end_block):
transfers = []
for lo in range(start_block, end_block + 1, CHUNK):
hi = min(lo + CHUNK - 1, end_block)
logs = rpc(
"eth_getLogs",
[{
"fromBlock": hex(lo),
"toBlock": hex(hi),
"address": TOKEN,
"topics": [TRANSFER_TOPIC],
}],
)
for log in logs:
row = decode_transfer(log)
if row:
transfers.append(row)
return transfers
if __name__ == "__main__":
head = int(rpc("eth_blockNumber", []), 16)
safe_head = head - CONFIRMATIONS
rows = fetch_transfers(safe_head - 200, safe_head)
print(f"{len(rows)} transfers between blocks {safe_head - 200} and {safe_head}")
if rows:
print(rows[0])Three details in this script come up again and again in real pipelines:
- It stops
CONFIRMATIONSblocks behind the head. Recent blocks can be replaced in a reorganization, so reading right up to the head risks storing records that later vanish. - It keeps
valueas a raw integer. Tokens define adecimalsfield, and USDC uses 6, so divide only at the reporting step. - It records
log_indexandtxso that each transfer has a unique key. You need that key to deduplicate when you re-fetch a range.
The output has block numbers but no timestamps. The daily active address example from the next chapters used a ts field. To get it, call eth_getBlockByNumber for each distinct block and map the block number to its timestamp.
Indexers: turning raw records into tables
Scanning logs with eth_getLogs works for one token over a short window. It does not scale to "every transfer of every token for five years". An indexer solves this by reading blocks once, decoding them, and writing structured rows to a database. Queries then run against the database rather than against the node.
Indexers come in several forms:
- Your own ETL (extract, transform, load) job. You write code like the script above, run it continuously, and load results into PostgreSQL, ClickHouse, or a similar store. You control definitions, but you also own the maintenance, including reorg handling.
- Subgraph-style indexers. A tool such as The Graph lets you define which events to track and how to map them to entities. The network or a host runs the indexing and serves a GraphQL API.
- Public datasets. Some providers publish decoded chain data in a data warehouse. Google's BigQuery public blockchain datasets are a well-known example. You write SQL against tables of blocks, transactions, and token transfers.
An indexer makes decisions that change your metrics. It decides how to treat failed transactions, whether internal transfers (value moved by contract calls, visible only in traces) are included, and how to represent tokens with unusual events. Two indexers can return different "transfer counts" for the same day without either being wrong.
Analytics platforms and APIs
At the top layer, platforms hand you finished metrics or a query interface. Examples include community SQL platforms like Dune, commercial metric providers like Glassnode and Nansen, and block explorer APIs like Etherscan.
These services add two things that raw nodes cannot offer.
- Pre-computed metrics. Active addresses, exchange netflow, and supply by age arrive as time series, so you skip building the pipeline.
- Entity labels. A label says that an address belongs to an exchange, a fund, a bridge, or a known contract. Exchange flow metrics depend entirely on such labels. No node can tell you who controls an address.
The trade-off is transparency. A provider's "active addresses" might count only senders, or both senders and receivers. It might drop contract addresses, or use a different day boundary. The definition may change between versions, and the provider may not publish it fully. When you compare two providers, you are often comparing two definitions as well as two datasets.
Choosing a source
| Source | Strength | Weakness | Fits when |
|---|---|---|---|
| Own node | Full control, no third-party trust | Storage, sync time, maintenance | You need verified raw data or custom definitions |
| Hosted node (RPC provider) | Quick start, no sync | Rate limits, block-range caps, provider trust | Prototyping or small, targeted queries |
| Own indexer or ETL | Custom schema, fast queries | Engineering effort, reorg handling | Repeated analysis across many tokens or dates |
| Public warehouse dataset | Familiar SQL, large history | Fixed schema, some lag behind the head | Historical research and one-off studies |
| Analytics platform | Labels and ready metrics | Opaque or shifting definitions | You need entity-level metrics such as exchange flows |
A practical pattern is to use a platform for labels and exploration, then verify key numbers against raw data from a node or warehouse. If the two disagree, you learn something about definitions.
Common errors
These errors recur when people first build on on-chain data.
- Reading unconfirmed blocks. Rows near the head can change. Keep a confirmation depth or a rewrite window.
- Missing token transfers. Scanning only transactions on Ethereum captures native ETH, not ERC-20 movement. Use logs.
- Double counting. Re-fetching a range without a unique key (
txpluslog_index) duplicates rows. - Ignoring decimals. A raw value of
5000000is 5 USDC but 5,000,000 units of an 18-decimal token that would be a negligible amount. Normalize with each token's decimals. - Silent truncation. Providers may return an error or cap results when a log query matches too many records. Handle both, and shrink the block range when needed.
- Mixed time zones and boundaries. Block timestamps are in UTC seconds. Define your day boundaries once and reuse them.
- Trusting labels as ground truth. Labels are inferences. Treat an exchange-flow figure as an estimate with an error margin, which later chapters return to.
Exercise
You compute daily transfer counts for a token by calling eth_getLogs up to the latest block each hour and appending the results to a table. Two weeks later, your counts for some past days are slightly higher than a public dataset's counts for the same days. Name two likely causes in your pipeline and one fix for each.
Show answer
First cause: you read blocks near the chain head and a reorg later replaced some of them, so your table holds rows from blocks that are no longer on the canonical chain. Fix: only ingest blocks at a confirmation depth (for example, 12 blocks behind the head on Ethereum), or detect reorgs and delete and re-fetch affected rows. Second cause: overlapping hourly fetches re-inserted the same logs, so rows are duplicated. Fix: give each row a unique key made of the transaction hash and log index, and insert with an upsert or deduplicate before counting.
Exercise
A colleague says they can compute holder balances from ten years ago by calling eth_getBalance on their provider's standard endpoint. The calls fail. What is the likely reason, and what are two ways around it?
Show answer
Historical state queries need an archive node, and the standard endpoint probably serves a full node that keeps state only for recent blocks. One way around it is to use an archive-capable endpoint or run an archive node. The other is to rebuild balances yourself by summing every transfer from the token's first block (using logs for tokens, or transactions and traces for native currency) up to the target date.