patternjavascriptTip
The Graph: querying indexed blockchain data with GraphQL subgraphs
Viewed 0 times
The Graph Protocol
The GraphsubgraphGraphQLindexingevent indexingdApp backend
Problem
Querying historical on-chain events directly from an RPC node is slow and expensive for complex queries across many blocks.
Solution
Deploy a subgraph to The Graph that indexes contract events into a queryable GraphQL API. Query it with a standard GraphQL client.
query {
transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
from { id }
to { id }
amount
}
}Why
The Graph nodes index events in real-time and store them in a structured database, making complex queries (filtering, sorting, aggregating) fast and cheap.
Gotchas
- Subgraph data is eventually consistent — there can be a lag of 1-2 blocks behind chain head
- Entity updates are expensive in subgraph handlers — minimize write operations
- The hosted service is being sunset; use The Graph Network for production deployments
Code Snippets
Query a subgraph from a React dApp
import { request, gql } from 'graphql-request';
const SUBGRAPH_URL = 'https://api.thegraph.com/subgraphs/name/yourname/yoursubgraph';
const GET_TRANSFERS = gql`
query GetTransfers($user: String!) {
transfers(where: { to: $user }, first: 10, orderBy: timestamp, orderDirection: desc) {
id
from { id }
amount
timestamp
}
}
`;
async function fetchTransfers(userAddress) {
const data = await request(SUBGRAPH_URL, GET_TRANSFERS, { user: userAddress.toLowerCase() });
return data.transfers;
}Context
Building dApp frontends that need to display transaction history or aggregated on-chain data
Revisions (0)
No revisions yet.