Learn to create and deploy The Graph subgraphs. Index smart contract events and query blockchain data with GraphQL.">

Subgraph Tutorial

Index blockchain data with The Graph

Build Custom Data Indexers

Learn to create subgraphs to index smart contract events and query with GraphQL

Create Subgraph

# Install graph CLI
npm install -g @graphprotocol/graph-cli

# Initialize new subgraph
graph init --product hosted-service your-name/subgraph

Define Schema

# schema.graphql
type Transfer @entity {
  id: ID!
  from: Bytes!
  to: Bytes!
  amount: BigInt!
  blockNumber: BigInt!
  timestamp: BigInt!
}

Map Events

import { Transfer } from '../generated/schema';

export function handleTransfer(event: TransferEvent): void {
  const transfer = new Transfer(event.transaction.hash.toHex());
  transfer.from = event.params.from;
  transfer.to = event.params.to;
  transfer.amount = event.params.value;
  transfer.blockNumber = event.block.number;
  transfer.timestamp = event.block.timestamp;
  transfer.save();
}

Deploy

# Build and deploy
graph build
graph deploy --product hosted-service your-name/subgraph