Web3 Indexing Subgraphs

Comprehensive guide for web3 indexing subgraphs covering essential concepts, practical examples, and production best practices.

Web3 indexing subgraphs are declarative, GraphQL-based data models that extract, transform, and serve blockchain event data for decentralized applications. They enable dApps to query historical and real-time state from Ethereum and other blockchains with the performance and flexibility of a relational database, without writing low-level blockchain clients. Subgraphs matter when an application needs to answer complex queries across multiple smart contracts, aggregate event data, or expose a rich, performant API to frontend clients—especially when the blockchain’s native RPC endpoints are too slow or too coarse-grained.

Defining a Subgraph

A subgraph is defined by a subgraph.yaml file and a set of mappings written in AssemblyScript or TypeScript. The file specifies metadata, data sources, and the schema of the resulting GraphQL API.

specVersion: 0.0.2
description: "Tracks token transfers and swaps on Uniswap V2"
schema:
  file: ./schema.graphql
dataSources:
  - kind: ethereum/contract
    name: UniswapV2Pair
    network: mainnet
    source:
      abi: UniswapV2Pair
      address: "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.4
      language: assemblyscript
      entities:
        - Token
        - Pair
        - Swap
      abis:
        - name: UniswapV2Pair
          file: abi/UniswapV2Pair.json
      eventHandlers:
        - event: Swap(indexed uint256, indexed address, uint256, uint256, uint256, uint256, address)
          handler: handleSwap
      file: ./src/mappings.ts

The schema.graphql file defines the entity types and their fields:

type Token @entity {
  id: ID!
  symbol: String!
  name: String!
  decimals: Int!
  totalSupply: BigInt!
  pairs: [Pair!]! @derivedFrom(field: "tokens")
}

type Pair @entity {
  id: ID!
  token0: Token!
  token1: Token!
  reserve0: BigDecimal!
  reserve1: BigDecimal!
  totalSupply: BigDecimal!
  swaps: [Swap!]!
}

type Swap @entity {
  id: ID!
  pair: Pair!
  amount0In: BigDecimal!
  amount1In: BigDecimal!
  amount0Out: BigDecimal!
  amount1Out: BigDecimal!
  sender: String!
  recipient: String!
  timestamp: Int!
}

Deploying a Subgraph

Deploying a subgraph to a network (e.g., The Graph) involves running graph deploy with a deployment key.

graph deploy --ipfs https://api.thegraph.com/ipfs --node https://api.thegraph.com/deploy --access-token $GRAPH_ACCESS_TOKEN my-namespace/my-subgraph

The deployment process compiles the AssemblyScript code, uploads the schema and mappings to IPFS, and registers the subgraph with a gateway. The command returns a deployment ID and a manifest URL.

Deployment fails silently if the subgraph.yaml does not validate against the schema. Common errors include:

The subgraph starts indexing from the specified block number. If the startBlock is not set in subgraph.yaml, it defaults to 0. The deployment logs show the block range, the number of events processed, and any mapping errors.

Handling Events and State Transitions

Subgraphs process Ethereum events by listening to contract logs. Each eventHandler in subgraph.yaml maps an event signature to a handler function in the mapping file.

export function handleSwap(event: SwapEvent): void {
  let pairId = event.address.toHexString();
  let pair = Pair.load(pairId);
  if (!pair) {
    pair = new Pair(pairId);
    pair.token0 = event.params.token0.toHexString();
    pair.token1 = event.params.token1.toHexString();
    pair.reserve0 = BigInt.fromI32(0);
    pair.reserve1 = BigInt.fromI32(0);
  }

  pair.reserve0 = pair.reserve0.plus(event.params.amount0In);
  pair.reserve1 = pair.reserve1.plus(event.params.amount1In);
  pair.totalSupply = pair.totalSupply.plus(event.params.amount0Out);
  pair.swaps = pair.swaps.concat([event.transaction.hash.toHexString()]);

  const swap = new Swap(event.transaction.hash.toHexString());
  swap.pair = pairId;
  swap.amount0In = event.params.amount0In.toBigDecimal();
  swap.amount1In = event.params.amount1In.toBigDecimal();
  swap.amount0Out = event.params.amount0Out.toBigDecimal();
  swap.amount1Out = event.params.amount1Out.toBigDecimal();
  swap.sender = event.params.sender.toHexString();
  swap.recipient = event.params.recipient.toHexString();
  swap.timestamp = event.block.timestamp.toI32();

  swap.save();
  pair.save();
}

Events are processed in batches. The mapping function receives Event objects with block, transaction, and params fields. Each event handler runs in a separate thread, and the state is persisted to a PostgreSQL database on a per-block basis.

The most common failure mode is event mapping crashes due to uncaught exceptions. A crash in handleSwap leads to the subgraph pausing at that block. The error appears in logs as:

ERROR: Failed to process event at block 1234567: TypeError: Cannot read property 'toHexString' of undefined
    at handleSwap (mappings.ts:42)

To recover, the subgraph must be redeployed with a new startBlock or manually reindexed from a given block.

Querying Indexed Data

Once deployed, a subgraph exposes a GraphQL endpoint at https://api.thegraph.com/subgraphs/name/my-namespace/my-subgraph.

A typical query retrieves a pair’s swaps and reserves:

query {
  pairs(where: { id: "0x7a250d5630b4cf539739df2c5dacb4c659f2488d" }) {
    id
    token0 {
      symbol
      name
    }
    token1 {
      symbol
      name
    }
    reserve0
    reserve1
    swaps(first: 10, orderBy: timestamp, orderDirection: desc) {
      amount0In
      amount1In
      amount0Out
      amount1Out
      sender
      recipient
      timestamp
    }
  }
}

The response includes a data object with pairs and nested swaps. The Graph service caches query results using a Bloom filter and materialized views for common patterns.

Queries may return null fields when entities are not fully indexed. A swaps list might be empty if the subgraph hasn’t processed events past a certain block. The first and skip arguments are used for pagination.

Reindexing and Upgrades

Subgraphs may need reindexing when the schema or mapping logic changes. Reindexing starts from a specified block and processes all events from that point forward.

To reindex from block 1000000:

graph reindex --from-block 1000000 my-namespace/my-subgraph

The subgraph enters reindexing mode. During reindexing, the subgraph.yaml is updated with startBlock and reindexing: true. The subgraph becomes available for queries, but data may be inconsistent until the process completes.

Reindexing silently fails if the startBlock is less than the last block processed. The subgraph logs:

WARNING: Reindexing from block 1000000, but last processed block is 1050000. Skipping forward.

Upgrading a subgraph involves creating a new version in the subgraph.yaml file and redeploying.

specVersion: 0.0.2
schema:
  file: ./schema.graphql
  version: "1.2.3"
dataSources:
  # ... unchanged ...

The new version is deployed with a version field in the manifest. The subgraph updates its schemaVersion and starts serving queries with the new schema. Clients may use the @version directive to query specific schema versions.

Managing Dependencies and Deployments

Subgraphs depend on external ABIs, which are referenced by name and stored in the abis/ directory. The ABI must be in JSON format and match the contract’s ABI structure.

[
  {
    "inputs": [
      { "name": "tokenA", "type": "address", "indexed": true },
      { "name": "tokenB", "type": "address", "indexed": true }
    ],
    "name": "Swap",
    "outputs": [
      { "name": "", "type": "uint256" }
    ],
    "type": "event"
  }
]

When a subgraph uses UniswapV2Pair ABI, the mapping section must declare:

abis:
  - name: UniswapV2Pair
    file: abi/UniswapV2Pair.json

If the ABI file is missing or malformed, the deployment fails with:

Error: ABI file 'abi/UniswapV2Pair.json' not found in the subgraph directory
Error: Invalid ABI format: expected 'inputs' array but found 'input' in event 'Swap'

Monitoring and Debugging

Monitoring a subgraph involves checking its status via HTTP endpoints. The status endpoint returns a JSON object with progress, sync state, and errors.

{
  "id": "my-namespace/my-subgraph",
  "status": {
    "synced": true,
    "latestBlock": 1234567,
    "chainHeadBlock": 1234567,
    "processing": true,
    "errors": [
      {
        "message": "Failed to process event at block 1234567",
        "blockNumber": 1234567,
        "timestamp": "2023-05-15T12:00:00Z"
      }
    ],
    "node": {
      "version": "0.28.1",
      "uptime": "3d 12h 45m"
    }
  }
}

The synced field indicates whether the subgraph has caught up to the chain head. If latestBlock < chainHeadBlock, the subgraph is lagging.

The errors list captures mapping failures, connection issues, and indexing delays. Each error includes a message, blockNumber, and timestamp.

To debug a subgraph, engineers query the underlying PostgreSQL database directly. The pair table has a swaps column of type text[], storing IDs of Swap entities. A query to inspect recent swaps:

SELECT p.id, p.reserve0, p.reserve1, s.amount0In, s.amount1Out
FROM public."Pair" p
JOIN public."Swap" s ON s."pairId" = p.id
WHERE p.id = '0x7a250d5630b4cf539739df2c5dacb4c659f2488d'
ORDER BY s.timestamp DESC
LIMIT 10;

When a query is slow, the EXPLAIN ANALYZE output reveals missing indexes or inefficient joins.

Failure Modes and Common Pitfalls

Subgraphs are robust, but their strength lies in consistency: every block, every event, every entity is a first-class citizen in a decentralized data layer.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.