protocols/the-graph

The Graph — Subgraph Development & GraphQL Queries

multichaintechnical-doc👥 Communityconfidence highhealth 100%
v1.0·by @openbuild·Updated 4/3/2026

The Graph is a decentralized indexing protocol for querying blockchain data via GraphQL.

Querying Existing Subgraphs

// Query Uniswap V2 — latest 10 swaps
const ENDPOINT = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2'

const query = `
  {
    swaps(first: 10, orderBy: timestamp, orderDirection: desc) {
      id
      timestamp
      amount0In
      amount0Out
      token0 { symbol }
      token1 { symbol }
    }
  }
`

const response = await fetch(ENDPOINT, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query }),
})
const { data } = await response.json()

Building a Subgraph

1. subgraph.yaml (manifest)

specVersion: 0.0.5
schema:
  file: ./schema.graphql
dataSources:
  - kind: ethereum
    name: MyContract
    network: mainnet
    source:
      address: '0xContractAddress'
      abi: MyContract
      startBlock: 18000000
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.7
      language: wasm/assemblyscript
      entities:
        - Transfer
      eventHandlers:
        - event: Transfer(indexed address,indexed address,uint256)
          handler: handleTransfer
      file: ./src/mapping.ts

2. schema.graphql

type Transfer @entity {
  id: ID!
  from: Bytes!
  to: Bytes!
  value: BigInt!
  blockTimestamp: BigInt!
}

3. mapping.ts (AssemblyScript handler)

import { Transfer as TransferEvent } from '../generated/MyContract/MyContract'
import { Transfer } from '../generated/schema'

export function handleTransfer(event: TransferEvent): void {
  let entity = new Transfer(event.transaction.hash.toHex() + '-' + event.logIndex.toString())
  entity.from = event.params.from
  entity.to = event.params.to
  entity.value = event.params.value
  entity.blockTimestamp = event.block.timestamp
  entity.save()
}

Deployment

npm install -g @graphprotocol/graph-cli
graph init --studio my-subgraph
graph codegen && graph build
graph auth --studio <DEPLOY_KEY>
graph deploy --studio my-subgraph

Key Concepts

TermDescription
SubgraphIndexing definition: events to watch + how to store data
Manifest (subgraph.yaml)Specifies contract, network, event handlers
SchemaGraphQL entity definitions
MappingAssemblyScript handlers that transform events to entities
IndexerNode running subgraphs and serving queries
Subgraph StudioHosted deployment for The Graph Network