Blockchain Data Indexing
Blockchain indexing enables efficient querying of on-chain data through structured storage and optimized query mechanisms.
Indexing Architecture
The Graph
Subgraph Definition
# subgraph.yaml
specVersion: 0.0.5
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum
name: Token
network: mainnet
source:
address: "0x1234567890123456789012345678901234567890"
abi: Token
startBlock: 12345678
mapping:
kind: ethereum/events
apiVersion: 0.0.7
language: wasm/assemblyscript
entities:
- Token
- Transfer
- Approval
abis:
- name: Token
file: ./abis/Token.json
eventHandlers:
- event: Transfer(indexed address,indexed address,uint256)
handler: handleTransfer
- event: Approval(indexed address,indexed address,uint256)
handler: handleApproval
file: ./src/token.ts
Schema Definition
# schema.graphql
type Token @entity {
id: Bytes!
name: String!
symbol: String!
decimals: BigInt!
totalSupply: BigInt!
transfers: [Transfer!]! @derivedFrom(field: "token")
balances: [Balance!]! @derivedFrom(field: "token")
}
type Transfer @entity(immutable: true) {
id: Bytes!
token: Token!
from: User!
to: User!
value: BigInt!
timestamp: BigInt!
blockNumber: BigInt!
transactionHash: Bytes!
}
type Approval @entity(immutable: true) {
id: Bytes!
token: Token!
owner: User!
spender: User!
value: BigInt!
timestamp: BigInt!
}
type Balance @entity {
id: Bytes!
token: Token!
user: User!
amount: BigInt!
lastUpdated: BigInt!
}
type User @entity {
id: Bytes!
balances: [Balance!]! @derivedFrom(field: "user")
transfers: [Transfer!]! @derivedFrom(field: "to")
}
Event Handlers
// src/token.ts
import {
Transfer as TransferEvent,
Approval as ApprovalEvent
} from '../generated/Token/Token';
import { Token, Transfer, Approval, Balance, User } from '../generated/schema';
import { BigInt, Bytes } from '@graphprotocol/graph-ts';
export function handleTransfer(event: TransferEvent): void {
// Get or create token
let token = Token.load(event.address);
if (!token) {
token = new Token(event.address);
token.name = 'Token';
token.symbol = 'TKN';
token.decimals = BigInt.fromI32(18);
token.totalSupply = BigInt.fromI32(0);
}
// Get or create users
let fromUser = User.load(event.params.from);
if (!fromUser) {
fromUser = new User(event.params.from);
fromUser.save();
}
let toUser = User.load(event.params.to);
if (!toUser) {
toUser = new User(event.params.to);
toUser.save();
}
// Create transfer entity
let transfer = new Transfer(event.transaction.hash);
transfer.token = token.id;
transfer.from = fromUser.id;
transfer.to = toUser.id;
transfer.value = event.params.value;
transfer.timestamp = event.block.timestamp;
transfer.blockNumber = event.block.number;
transfer.transactionHash = event.transaction.hash;
transfer.save();
// Update balances
let fromBalanceId = event.params.from.toHex() + '-' + event.address.toHex();
let fromBalance = Balance.load(fromBalanceId);
if (!fromBalance) {
fromBalance = new Balance(fromBalanceId);
fromBalance.token = token.id;
fromBalance.user = fromUser.id;
fromBalance.amount = BigInt.fromI32(0);
}
fromBalance.amount = fromBalance.amount.minus(event.params.value);
fromBalance.lastUpdated = event.block.timestamp;
fromBalance.save();
let toBalanceId = event.params.to.toHex() + '-' + event.address.toHex();
let toBalance = Balance.load(toBalanceId);
if (!toBalance) {
toBalance = new Balance(toBalanceId);
toBalance.token = token.id;
toBalance.user = toUser.id;
toBalance.amount = BigInt.fromI32(0);
}
toBalance.amount = toBalance.amount.plus(event.params.value);
toBalance.lastUpdated = event.block.timestamp;
toBalance.save();
// Update token total supply
token.totalSupply = token.totalSupply.plus(event.params.value);
token.save();
}
export function handleApproval(event: ApprovalEvent): void {
let approval = new Approval(event.transaction.hash);
approval.token = event.address;
approval.owner = event.params.owner;
approval.spender = event.params.spender;
approval.value = event.params.value;
approval.timestamp = event.block.timestamp;
approval.save();
}
Custom Indexers
Event Indexing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract EventIndexer {
struct EventData {
bytes32 eventHash;
address sender;
uint256 value;
uint256 timestamp;
bytes data;
}
mapping(bytes32 => EventData) public events;
bytes32[] public eventList;
event EventIndexed(
bytes32 indexed eventHash,
address indexed sender,
uint256 value,
uint256 timestamp
);
function indexEvent(
address sender,
uint256 value,
bytes calldata data
) external returns (bytes32 eventHash) {
eventHash = keccak256(
abi.encodePacked(
sender,
value,
data,
block.timestamp,
block.number
)
);
events[eventHash] = EventData({
eventHash: eventHash,
sender: sender,
value: value,
timestamp: block.timestamp,
data: data
});
eventList.push(eventHash);
emit EventIndexed(eventHash, sender, value, block.timestamp);
}
function getEvent(bytes32 eventHash) external view returns (EventData memory) {
return events[eventHash];
}
function getEventsBySender(address sender) external view returns (bytes32[] memory) {
bytes32[] memory result = new bytes32[](0);
for (uint256 i = 0; i < eventList.length; i++) {
if (events[eventList[i]].sender == sender) {
result.push(eventList[i]);
}
}
return result;
}
}
GraphQL Queries
# Query all tokens with their transfers
query GetTokens {
tokens(first: 100, orderBy: totalSupply, orderDirection: desc) {
id
name
symbol
decimals
totalSupply
transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
id
from {
id
}
to {
id
}
value
timestamp
blockNumber
transactionHash
}
}
}
# Query user balances
query GetUserBalances($userAddress: Bytes!) {
balances(where: { user: $userAddress }, first: 100) {
id
token {
id
name
symbol
decimals
}
amount
lastUpdated
}
}
# Query transfers in time range
query GetTransfersInRange($startTime: BigInt!, $endTime: BigInt!) {
transfers(
where: {
timestamp_gte: $startTime,
timestamp_lte: $endTime
}
first: 1000
orderBy: timestamp
orderDirection: asc
) {
id
token {
symbol
}
from {
id
}
to {
id
}
value
timestamp
}
}
Historical Queries
Time-Series Data
// Historical data aggregation
async function getHistoricalData(tokenAddress: string, days: number) {
const query = `
query HistoricalData($tokenAddress: Bytes!, $startDate: BigInt!, $interval: BigInt!) {
tokenTransfers(
where: {
token: $tokenAddress,
timestamp_gte: $startDate
}
orderBy: timestamp
orderDirection: asc
) {
timestamp
value
from
to
}
}`;
const startDate = Math.floor(Date.now() / 1000) - (days * 24 * 60 * 60);
const response = await fetch(THE_GRAPH_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query,
variables: {
tokenAddress: tokenAddress.toLowerCase(),
startDate: startDate.toString(),
interval: (24 * 60 * 60).toString() // 1 day
}
})
});
return response.json();
}
Aggregation Queries
# Daily volume aggregation
query GetDailyVolume($tokenAddress: Bytes!, $days: Int!) {
dailyStats(
where: { token: $tokenAddress }
orderBy: date
orderDirection: desc
first: $days
) {
date
totalVolume
transferCount
uniqueUsers
avgTransferSize
}
}
# Top holders
query GetTopHolders($tokenAddress: Bytes!, $first: Int!) {
balances(
where: { token: $tokenAddress, amount_gt: "0" }
orderBy: amount
orderDirection: desc
first: $first
) {
user {
id
}
amount
lastUpdated
}
}
Real-Time Updates
WebSocket Subscriptions
# Real-time transfer subscription
subscription OnTransfer($tokenAddress: Bytes!) {
transfers(
where: { token: $tokenAddress }
orderBy: timestamp
orderDirection: desc
) {
id
from {
id
}
to {
id
}
value
timestamp
blockNumber
}
}
# Real-time balance updates
subscription OnBalanceUpdate($userAddress: Bytes!) {
balances(
where: { user: $userAddress }
) {
id
token {
symbol
}
amount
lastUpdated
}
}
WebSocket Client
import { createClient } from 'graphql-ws';
const client = createClient({
url: 'wss://api.thegraph.com/subgraphs/name/your-subgraph',
});
// Subscribe to transfers
const unsubscribe = client.subscribe(
{
query: `
subscription OnTransfer($tokenAddress: Bytes!) {
transfers(where: { token: $tokenAddress }) {
id
from { id }
to { id }
value
timestamp
}
}
`,
variables: { tokenAddress: '0x...' },
},
{
next: (data) => {
console.log('New transfer:', data);
updateUI(data);
},
error: (error) => {
console.error('Subscription error:', error);
},
complete: () => {
console.log('Subscription complete');
},
}
);
// Unsubscribe when done
// unsubscribe();
Trade-offs
| Feature | The Graph | Custom Indexer | Direct Query |
|---|---|---|---|
| Setup Complexity | Low | High | Low |
| Cost | Medium | High | Low |
| Flexibility | Medium | High | Low |
| Performance | High | High | Low |
| Real-time | Yes | Yes | No |
Real-World Example: Uniswap V3 Analytics
# Uniswap V3 pool analytics
query GetPoolAnalytics($poolAddress: Bytes!) {
pool(id: $poolAddress) {
token0 {
symbol
decimals
}
token1 {
symbol
decimals
}
liquidity
sqrtPrice
tick
feeTier
totalValueLockedUSD
volumeUSD
feesUSD
txCount
dayData(first: 30, orderBy: date, orderDirection: desc) {
date
volumeUSD
feesUSD
tvlUSD
open
high
low
close
}
hourData(first: 24, orderBy: periodStartUnix, orderDirection: desc) {
periodStartUnix
volumeUSD
feesUSD
}
}
}
Interview Questions
-
Explain the difference between push-based and pull-based indexing. What are the trade-offs of each approach?
-
How does The Graph handle chain reorganizations and ensure data consistency?
-
Design an indexing solution for a DEX that needs to provide real-time analytics, historical data, and aggregated statistics.
Quiz Questions
-
What is the primary purpose of a subgraph in The Graph?
- A) Deploy smart contracts
- B) Index and query blockchain data
- C) Execute transactions
- D) Store private keys
-
Which GraphQL operation is used for real-time updates?
- A) Query
- B) Mutation
- C) Subscription
- D) Fragment
-
What is the main challenge when indexing blockchain data?
- A) High gas costs
- B) Chain reorganizations
- C) Limited storage
- D) Slow internet
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions