Docs
Search⌘ K
  • Home
  • About The Graph
  • Supported Networks
  • Protocol Contracts
  • Subgraphs
    • Substreams
      • Token API
        • Indexing
          • Resources
            Subgraphs > Querying > Graph Client

            11 minutes

            The Graph Client Tools

            This repo is the home for The Graph consumer-side tools (for both browser and NodeJS environments).

            Background

            The tools provided in this repo are intended to enrich and extend the DX, and add the additional layer required for dApps in order to implement distributed applications.

            Developers who consume data from The Graph GraphQL API often need peripherals for making data consumption easier, and also tools that allow using multiple indexers at the same time.

            Features and Goals

            This library is intended to simplify the network aspect of data consumption for dApps. The tools provided within this repository are intended to run at build time, in order to make execution faster and performant at runtime.

            The tools provided in this repo can be used as standalone, but you can also use it with any existing GraphQL Client!

            StatusFeatureNotes
            ✅Multiple indexersbased on fetch strategies
            ✅Fetch Strategiestimeout, retry, fallback, race, highestValue
            ✅Build time validations & optimizations
            ✅Client-Side Compositionwith improved execution planner (based on GraphQL-Mesh)
            ✅Cross-chain Subgraph HandlingUse similar subgraphs as a single source
            ✅Raw Execution (standalone mode)without a wrapping GraphQL client
            ✅Local (client-side) Mutations
            ✅Automatic Block Tracking⁠tracking block numbers as described here
            ✅Automatic Pagination⁠doing multiple requests in a single call to fetch more than the indexer limit
            ✅Integration with @apollo/client
            ✅Integration with urql
            ✅TypeScript supportwith built-in GraphQL Codegen and TypedDocumentNode
            ✅@live queriesBased on polling

            You can find an extended architecture design here

            Getting Started

            You can follow Episode 45 of graphql.wtf⁠ to learn more about Graph Client:

            GraphQL.wtf Episode 45
            ⁠

            To get started, make sure to install [The Graph Client CLI] in your project:

            1yarn add -D @graphprotocol/client-cli2# or, with NPM:3npm install --save-dev @graphprotocol/client-cli

            The CLI is installed as dev dependency since we are using it to produce optimized runtime artifacts that can be loaded directly from your app!

            Create a configuration file (called .graphclientrc.yml) and point to your GraphQL endpoints provided by The Graph, for example:

            1# .graphclientrc.yml2sources:3  - name: uniswapv24    handler:5      graphql:6        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2

            Now, create a runtime artifact by running The Graph Client CLI:

            1graphclient build

            Note: you need to run this with yarn prefix, or add that as a script in your package.json.

            This should produce a ready-to-use standalone execute function, that you can use for running your application GraphQL operations, you should have an output similar to the following:

            1GraphClient: Cleaning existing artifacts2GraphClient: Reading the configuration3🕸️: Generating the unified schema4🕸️: Generating artifacts5🕸️: Generating index file in TypeScript6🕸️: Writing index.ts for ESM to the disk.7🕸️: Cleanup8🕸️: Done! => .graphclient

            Now, the .graphclient artifact is generated for you, and you can import it directly from your code, and run your queries:

            1import { execute } from '../.graphclient'23const myQuery = gql`4  query pairs {5    pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {6      id7      token0 {8        id9        symbol10        name11      }12      token1 {13        id14        symbol15        name16      }17    }18  }19`2021async function main() {22  const result = await execute(myQuery, {})23  console.log(result)24}2526main()

            Using Vanilla JavaScript Instead of TypeScript

            GraphClient CLI generates the client artifacts as TypeScript files by default, but you can configure CLI to generate JavaScript and JSON files together with additional TypeScript definition files by using --fileType js or --fileType json.

            js flag generates all files as JavaScript files with ESM Syntax and json flag generates source artifacts as JSON files while entrypoint JavaScript file with old CommonJS syntax because only CommonJS supports JSON files as modules.

            Unless you use CommonJS(require) specifically, we’d recommend you to use js flag.

            graphclient --fileType js

            • An example for JavaScript usage in CommonJS syntax with JSON files⁠
            • An example for JavaScript usage in ESM syntax⁠

            The Graph Client DevTools

            The Graph Client CLI comes with a built-in GraphiQL, so you can experiment with queries in real-time.

            The GraphQL schema served in that environment, is the eventual schema based on all composed Subgraphs and transformations you applied.

            To start the DevTool GraphiQL, run the following command:

            1graphclient serve-dev

            And open http://localhost:4000/⁠ to use GraphiQL. You can now experiment with your Graph client-side GraphQL schema locally! 🥳

            Examples

            You can also refer to examples directory in this repo⁠, for more advanced examples and integration examples:

            • TypeScript & React example with raw execute and built-in GraphQL-Codegen⁠
            • TS/JS NodeJS standalone mode⁠
            • Client-Side GraphQL Composition⁠
            • Integration with Urql and React⁠
            • Integration with NextJS and TypeScript⁠
            • Integration with Apollo-Client and React⁠
            • Integration with React-Query⁠
            • Cross-chain merging (same Subgraph, different chains)
              • Parallel SDK calls⁠
              • Parallel internal calls with schema extensions⁠
            • Customize execution with Transforms (auto-pagination and auto-block-tracking)⁠

            Advanced Examples/Features

            Customize Network Calls

            You can customize the network execution (for example, to add authentication headers) by using operationHeaders:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        operationHeaders:7          Authorization: Bearer MY_TOKEN

            You can also use runtime variables if you wish, and specify it in a declarative way:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        operationHeaders:7          Authorization: Bearer {context.config.apiToken}

            Then, you can specify that when you execute operations:

            1execute(myQuery, myVariables, {2  config: {3    apiToken: 'MY_TOKEN',4  },5})

            You can find the complete documentation for the graphql handler here⁠.

            Environment Variables Interpolation

            If you wish to use environment variables in your Graph Client configuration file, you can use interpolation with env helper:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        operationHeaders:7          Authorization: Bearer {env.MY_API_TOKEN} # runtime

            Then, make sure to have MY_API_TOKEN defined when you run process.env at runtime.

            You can also specify environment variables to be filled at build time (during graphclient build run) by using the env-var name directly:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        operationHeaders:7          Authorization: Bearer ${MY_API_TOKEN} # build time

            You can find the complete documentation for the graphql handler here⁠.

            Fetch Strategies and Multiple Graph Indexers

            It’s a common practice to use more than one indexer in dApps, so to achieve the ideal experience with The Graph, you can specify several fetch strategies in order to make it more smooth and simple.

            All fetch strategies can be combined to create the ultimate execution flow.

            `retry`

            The retry mechanism allow you to specify the retry attempts for a single GraphQL endpoint/source.

            The retry flow will execute in both conditions: a netword error, or due to a runtime error (indexing issue/inavailability of the indexer).

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        retry: 2 # specify here, if you have an unstable/error prone indexer
            `timeout`

            The timeout mechanism allow you to specify the timeout for a given GraphQL endpoint.

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26        timeout: 5000 # 5 seconds
            `fallback`

            The fallback mechanism allow you to specify use more than one GraphQL endpoint, for the same source.

            This is useful if you want to use more than one indexer for the same Subgraph, and fallback when an error/timeout happens. You can also use this strategy in order to use a custom indexer, but allow it to fallback to The Graph Hosted Service.

            1sources:2  - name: uniswapv23    handler:4      graphql:5        strategy: fallback6        sources:7          - endpoint: https://bad-uniswap-v2-api.com8            retry: 29            timeout: 500010          - endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2
            `race`

            The race mechanism allow you to specify use more than one GraphQL endpoint, for the same source, and race on every execution.

            This is useful if you want to use more than one indexer for the same Subgraph, and allow both sources to race and get the fastest response from all specified indexers.

            1sources:2  - name: uniswapv23    handler:4      graphql:5        strategy: race6        sources:7          - endpoint: https://bad-uniswap-v2-api.com8          - endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2
            `highestValue`

            This strategy allows you to send parallel requests to different endpoints for the same source and choose the most updated.

            This is useful if you want to choose most synced data for the same Subgraph over different indexers/sources.

            1sources:2  - name: uniswapv23    handler:4      graphql:5        strategy: highestValue6        strategyConfig:7          selectionSet: |8            {9              _meta {10                block {11                  number12                }13              }14            }15          value: '_meta.block.number'16        sources:17          - endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2-118          - endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2-2

            Block Tracking

            The Graph Client can track block numbers and do the following queries by following this pattern with blockTracking transform;

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26    transforms:7      - blockTracking:8          # You might want to disable schema validation for faster startup9          validateSchema: true10          # Ignore the fields that you don't want to be tracked11          ignoreFieldNames: [users, prices]12          # Exclude the operation with the following names13          ignoreOperationNames: [NotFollowed]

            You can try a working example here⁠

            Automatic Pagination

            With most subgraphs, the number of records you can fetch is limited. In this case, you have to send multiple requests with pagination.

            1query {2  # Will throw an error if the limit is 10003  users(first: 2000) {4    id5    name6  }7}

            So you have to send the following operations one after the other:

            1query {2  # Will throw an error if the limit is 10003  users(first: 1000) {4    id5    name6  }7}

            Then after the first response:

            1query {2  # Will throw an error if the limit is 10003  users(first: 1000, skip: 1000) {4    id5    name6  }7}

            After the second response, you have to merge the results manually. But instead The Graph Client allows you to do the first one and automatically does those multiple requests for you under the hood.

            All you have to do is:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26    transforms:7      - autoPagination:8          # You might want to disable schema validation for faster startup9          validateSchema: true

            You can try a working example here⁠

            Client-side Composition

            The Graph Client has built-in support for client-side GraphQL Composition (powered by GraphQL-Tools Schema-Stitching⁠).

            You can leverage this feature in order to create a single GraphQL layer from multiple Subgraphs, deployed on multiple indexers.

            💡 Tip: You can compose any GraphQL sources, and not only Subgraphs!

            Trivial composition can be done by adding more than one GraphQL source to your .graphclientrc.yml file, here’s an example:

            1sources:2  - name: uniswapv23    handler:4      graphql:5        endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v26  - name: compoundv27    handler:8      graphql:9        endpoint: https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2

            As long as there a no conflicts across the composed schemas, you can compose it, and then run a single query to both Subgraphs:

            1query myQuery {2  # this one is coming from compound-v23  markets(first: 7) {4    borrowRate5  }6  # this one is coming from uniswap-v27  pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {8    id9    token0 {10      id11    }12    token1 {13      id14    }15  }16}

            You can also resolve conflicts, rename parts of the schema, add custom GraphQL fields, and modify the entire execution phase.

            For advanced use-cases with composition, please refer to the following resources:

            • Advanced Composition Example⁠
            • GraphQL-Mesh Schema transformations⁠
            • GraphQL-Tools Schema-Stitching documentation⁠

            TypeScript Support

            If your project is written in TypeScript, you can leverage the power of TypedDocumentNode⁠ and have a fully-typed GraphQL client experience.

            The standalone mode of The GraphQL, and popular GraphQL client libraries like Apollo-Client and urql has built-in support for TypedDocumentNode!

            The Graph Client CLI comes with a ready-to-use configuration for GraphQL Code Generator⁠, and it can generate TypedDocumentNode based on your GraphQL operations.

            To get started, define your GraphQL operations in your application code, and point to those files using the documents section of .graphclientrc.yml:

            1sources:2  -  # ... your Subgraphs/GQL sources here34documents:5  - ./src/example-query.graphql

            You can also use Glob expressions, or even point to code files, and the CLI will find your GraphQL queries automatically:

            1documents:2  - './src/**/*.graphql'3  - './src/**/*.{ts,tsx,js,jsx}'

            Now, run the GraphQL CLI build command again, the CLI will generate a TypedDocumentNode object under .graphclient for every operation found.

            Make sure to name your GraphQL operations, otherwise it will be ignored!

            For example, a query called query ExampleQuery will have the corresponding ExampleQueryDocument generated in .graphclient. You can now import it and use that for your GraphQL calls, and you’ll have a fully typed experience without writing or specifying any TypeScript manually:

            1import { ExampleQueryDocument, execute } from '../.graphclient'23async function main() {4  // "result" variable is fully typed, and represents the exact structure of the fields you selected in your query.5  const result = await execute(ExampleQueryDocument, {})6  console.log(result)7}

            You can find a TypeScript project example here⁠.

            Client-Side Mutations

            Due to the nature of Graph-Client setup, it is possible to add client-side schema, that you can later bridge to run any arbitrary code.

            This is helpful since you can implement custom code as part of your GraphQL schema, and have it as unified application schema that is easier to track and develop.

            This document explains how to add custom mutations, but in fact you can add any GraphQL operation (query/mutation/subscriptions). See Extending the unified schema article⁠ for more information about this feature.

            To get started, define a additionalTypeDefs section in your config file:

            1additionalTypeDefs: |2  # We should define the missing `Mutation` type3  extend schema {4    mutation: Mutation5  }67  type Mutation {8    doSomething(input: SomeCustomInput!): Boolean!9  }1011  input SomeCustomInput {12    field: String!13  }

            Then, add a pointer to a custom GraphQL resolvers file:

            1additionalResolvers:2  - './resolvers'

            Now, create resolver.js (or, resolvers.ts) in your project, and implement your custom mutation:

            1module.exports = {2  Mutation: {3    async doSomething(root, args, context, info) {4      // Here, you can run anything you wish.5      // For example, use `web3` lib, connect a wallet and so on.67      return true8    },9  },10}

            If you are using TypeScript, you can also get fully type-safe signature by doing:

            1import { Resolvers } from './.graphclient'23// Now it's fully typed!4const resolvers: Resolvers = {5  Mutation: {6    async doSomething(root, args, context, info) {7      // Here, you can run anything you wish.8      // For example, use `web3` lib, connect a wallet and so on.910      return true11    },12  },13}1415export default resolvers

            If you need to inject runtime variables into your GraphQL execution context, you can use the following snippet:

            1execute(2  MY_QUERY,3  {},4  {5    myHelper: {}, // this will be available in your Mutation resolver as `context.myHelper`6  },7)

            You can read more about client-side schema extensions here⁠

            You can also delegate and call Query fields as part of your mutation⁠

            License

            Released under the MIT license⁠.

            ⁠Edit on GitHub⁠

            Subgraph ID vs Deployment IDArchitecture
            On this page
            • Background
            • Features and Goals
            • Getting Started
            • Using Vanilla JavaScript Instead of TypeScript
            • Advanced Examples/Features
            • License
            The GraphStatusTestnetBrand AssetsForumSecurityPrivacy PolicyTerms of Service