Deploying Subgraphs on The Graph: Tutorial

Deploying Subgraphs on The Graph: Tutorial

In the decentralized web, indexing and querying blockchain data efficiently is paramount. The Graph has emerged as the leading protocol for indexing Ethereum (and other chains) into fast, queryable APIs called subgraphs. This tutorial provides a comprehensive, step-by-step guide to deploying subgraphs on The Graph, from project initialization to production deployment.

Background and Motivation

The Graph functions much like a decentralized search engine. It enables developers to define subgraphs—open APIs that describe how to ingest, index, and serve blockchain data. Instead of writing custom Ethereum RPC calls and parsing logs manually, you declare a GraphQL schema and mappings in AssemblyScript.

  • Performance: Rapid, indexed access to on-chain data.
  • Modularity: Reusable subgraphs for dApps and analytics.
  • Decentralization: Hosted either on The Graph’s Hosted Service or on the decentralized network.

Prerequisites

  • Node.js (v14 or later) and npm/yarn installed
  • graph-cli (GitHub) globally installed
  • An Ethereum endpoint (Infura, Alchemy, local node)
  • Access to The Graph Hosted Service or The Graph Network
  • Familiarity with GraphQL, TypeScript/AssemblyScript, and basic command-line usage

Step 1: Initialize Your Subgraph

Use the Graph CLI to bootstrap a new subgraph project:

npm install -g @graphprotocol/graph-cli
graph init --from-contract ltCONTRACT_ADDRESSgt ltGITHUB_USER/PROJECT_NAMEgt --network mainnet

This generates:

  • subgraph.yaml – defines data sources and mappings
  • schema.graphql – GraphQL type definitions
  • src/mapping.ts (AssemblyScript) – event handlers
  • Configuration files for hosting and codegen

Step 2: Define Schema and Data Sources

schema.graphql

Define entities for your subgraph in GraphQL types:

type TokenTransfer @entity {
  id: ID!
  from: Bytes!
  to: Bytes!
  value: BigInt!
  transactionHash: Bytes!
  timestamp: BigInt!
}

subgraph.yaml

Link to your contract ABI and event signatures:

dataSources:
  - kind: ethereum/contract
    name: YourContract
    network: mainnet
    source:
      address: 0x123...
      abi: YourContractABI
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.5
      language: wasm/assemblyscript
      file: ./src/mapping.ts
      entities:
        - TokenTransfer
      eventHandlers:
        - event: Transfer(indexed address,indexed address,uint256)
          handler: handleTransfer
      abis:
        - name: YourContractABI
          file: ./abis/YourContract.json

Step 3: Code Generation and Mappings

Generate AssemblyScript types and GraphQL bindings:

graph codegen

Implement your event handler in src/mapping.ts:

import { BigInt } from @graphprotocol/graph-ts
import { Transfer } from ../generated/YourContract/YourContract
import { TokenTransfer } from ../generated/schema

export function handleTransfer(event: Transfer): void {
  let id = event.transaction.hash.toHex()   -   event.logIndex.toString()
  let transfer = new TokenTransfer(id)
  transfer.from = event.params.from
  transfer.to = event.params.to
  transfer.value = event.params.value
  transfer.transactionHash = event.transaction.hash
  transfer.timestamp = event.block.timestamp
  transfer.save()
}

Step 4: Build and Deploy Locally

Before publishing, validate locally with a Graph Node instance:

# Build the subgraph
graph build

# Run a local Graph Node (requires docker)
docker run -it -p 8020:8020 -p 8000:8000 
  -e postgres=host=host.docker.internal,port=5432,user=graph,dbname=graph,pass=graphpass 
  -e ipfs=host=host.docker.internal,port=5001 
  graphprotocol/graph-node

# Deploy to local Graph Node
graph deploy --node http://127.0.0.1:8020/ --ipfs http://127.0.0.1:5001/ YourSubgraphName

Inspect indexing in real time via the local Graph Node UI: Graph Node Dashboard.

Step 5: Publish to The Graph Hosted Service or Decentralized Network

Configure authentication and access tokens in ~/.graphconfig, then:

Target Command
Hosted Service graph deploy --product hosted-service YourSubgraphName
Decentralized Network graph deploy --product subgraph-studio YourSubgraphName

Monitor your subgraph on The Graph Explorer: Explorer.

Testing and Debugging

  • Use graph test for AssemblyScript unit tests.
  • Leverage Graph Node logs to trace indexing issues.
  • Validate data integrity with GraphQL queries in Playground.

Advanced Topics

IPFS and Content Addressing

Subgraph manifests and mappings are stored on IPFS. Understanding content addressing ensures immutability and reproducibility. Read more on IPFS.

Multi-Chain Support

The Graph supports Ethereum, Polygon, BSC, Avalanche, and more. In subgraph.yaml, change network field and endpoint accordingly.

Authorization and Indexer Economics

On the decentralized network, subgraph deployment and indexing incur economic considerations: staking GRT tokens and paying indexing fees. Dive deeper at The Graph Network Docs.

Best Practices

  • Modular Mappings: Break logic into reusable functions.
  • Error Handling: Validate event data to avoid empty reads.
  • Schema Evolution: Use @derivedFrom and indexes in GraphQL for performance.
  • Version Control: Tag deployments and use CI/CD pipelines for automation.

Conclusion

Deploying subgraphs on The Graph transforms chaotic blockchain logs into structured, performant APIs. With clear schema definitions, robust AssemblyScript mappings, and a reliable deployment workflow, you can power decentralized applications with blazing-fast, real-time data access. Start building your next dApp with confidence—The Graph makes on-chain data indexing seamless and scalable.

For further reading and community support, visit The Graph’s official resources:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *