โ†
Previous Module
Contract Upgrade Proxy

๐Ÿ› ๏ธ Subgraph Development: Build Custom Indexers

Learn how to create, deploy, and maintain subgraphs

Query blockchain data efficiently with The Graph

๐Ÿ› ๏ธ Building Your First Subgraph

A subgraph is your indexing specification. You define: (1) Schemaโ€”what data to store, (2) Manifestโ€”which contracts/events to watch, (3) Mappingsโ€”how to transform events into entities. Deploy to The Graph, indexers process your subgraph, and you get a GraphQL endpoint. It's like writing a database migration + ETL pipeline, but for blockchain data. We'll build a subgraph for an ERC-20 token to track all transfers.

๐ŸŽฎ Interactive: 4-Step Subgraph Builder

Walk through the subgraph development process. Click through each step to see the code, explanation, and how pieces fit together.

1. Define Schema (schema.graphql)

Step 1 of 4

Define entities (data models) that will be stored and queryable

type Token @entity {
  id: ID!
  address: Bytes!
  name: String!
  symbol: String!
  decimals: Int!
  totalSupply: BigInt!
}

type Transfer @entity {
  id: ID!
  token: Token!
  from: Bytes!
  to: Bytes!
  amount: BigInt!
  timestamp: BigInt!
  blockNumber: BigInt!
}
๐Ÿ’ก Explanation

@entity = stored in database. ID! = required unique identifier. Relationships: Transfer.token links to Token entity. Types map to GraphQL types (String, Int, BigInt, Bytes).

1 / 4

๐Ÿ” Key Concepts

Entities = Database Tables: Each @entity becomes a table. Fields become columns. Relationships work like foreign keys.
Event Handlers = Triggers: When blockchain event fires, your handler runs. Extract data, create/update entities, save to DB.
AssemblyScript = TypeScript Subset: Mappings written in AS (compiles to WebAssembly). Strictly typed, runs on indexers.
Derived Fields: Use @derivedFrom for reverse relationships. E.g., Token has transfers: [Transfer!] @derivedFrom(field: "token").

โšก Advanced Patterns

Block Handlers
Process every block (e.g., track total supply over time). Expensiveโ€”use sparingly.
Call Handlers
Trigger on contract function calls (not just events). Useful for non-event-emitting functions.
Data Source Templates
Dynamically index contracts created at runtime (e.g., every Uniswap pair).
IPFS Files
Fetch off-chain metadata (NFT images, JSON) and index alongside blockchain data.

๐Ÿ’ก Best Practices

โœ“
Use Composite IDs: Combine tx hash + log index for unique transfer IDs. Prevents collisions.
โœ“
Index Only What You Need: Every entity costs storage. Don't index fields you won't query.
โœ“
Set startBlock: Skip blocks before contract deployed. Saves sync time (hours โ†’ minutes).
โœ“
Test Locally: Use Graph Node Docker container to test before deploying to mainnet. Catch bugs early.
โ† Introduction