Query blockchain data from multiple subgraphs using The Graph

Query blockchain data from multiple subgraphs using The Graph

In this guide we'll build and deploy a GraphQL API that combines blockchain data from multiple subgraphs using The Graph.

The Graph is an indexing protocol for organizing blockchain data and making it easily accessible with GraphQL. It is a decentralized system that allows users to query data from blockchain networks, facilitating the development of decentralized applications (DApps).

Grafbase is a fully managed GraphQL platform that allows you to combine data from multiple sources into a single GraphQL API using connectors.

Begin by initializing a new Grafbase project. Run the following command in your new project folder:

npx grafbase init

Next, open the grafbase.config.ts file and add your subgraphs using the GraphQL connector. In this guide we'll use the Polygon and Optimism subgraphs.

import { config, connector, graph } from '@grafbase/sdk' const g = graph.Standalone() const polygon = connector.GraphQL('polygon', { url: g.env('POLYGON_GRAPHQL_API_URL'), }) g.datasource(polygon) const optimism = connector.GraphQL('optimism', { url: g.env('OPTIMISM_GRAPHQL_API_URL'), }) g.datasource(optimism) export default config({ graph: g, auth: { rules: rules => { rules.public() }, }, })

Next add the environment variables for both subgraphs to the .env file in your project folder.

You get the GraphQL API URLs for the subgraphs from the Graph Explorer. Click the Query button on the subgraph page to get the GraphQL API URL.

The Graph Query

To start the local development server, run the following command:

npx grafbase dev

Now that your project is running locally, you can query the subgraphs using Pathfinder. Open the following URL in your browser:

http://localhost:4000

Now let's query assets from Polygon and Optimism using a single GraphQL operation. Note the namespaced subgraphs in the query.

query Assets { polygon { assets(first: 5) { id blockNumber } } optimism { assets(first: 5) { id blockNumber } } }

When you're ready to deploy your project, run the following command to create and deploy your project:

npx grafbase create

Once the project is deployed you can access your GraphQL API using the URL that's displayed in the output.

Grafbase supports Edge Caching to improve query performance globally. To enable Edge Caching, open the grafbase.config.ts file and add the following configuration:

export default config({ graph: g, auth: { rules: rules => { rules.public() }, }, cache: { rules: [ { types: ['Query'], maxAge: 60, staleWhileRevalidate: 60, }, ], }, })

All queries that are sent to the GraphQL API will now be cached for 60 seconds , globally. Go ahead and try it yourself to achieve double digit milliseconds response times!

Get Started

Build your API of the future now.