Skip to content

Using The Graph on Moonbeam

Introduction

Indexing protocols organize information so that applications can access it more efficiently. For example, Google indexes the entire Internet to provide information rapidly when you search for something.

The Graph is a decentralized and open-source indexing protocol for querying networks like Ethereum. In short, it provides a way to efficiently store data emitted by events from smart contracts so that other projects or dApps can access it easily.

Furthermore, developers can build APIs called subgraphs. Users or other developers can use subgraphs to query data specific to a set of smart contracts. Data is fetched with a standard GraphQL API. You can visit The Graph's documentation site to learn about The Graph protocol.

Due to the support of Ethereum tracing modules on Moonbeam, The Graph can index blockchain data on Moonbeam. This guide takes you through the creation of a subgraph based on the Exiled Racers Game Asset contract on Moonbeam.

The information presented herein is for informational purposes only and has been provided by third parties. Moonbeam does not endorse any project listed and described on the Moonbeam docs website (https://docs.moonbeam.network/).

Create a Subgraph

You can quickly create a subgraph from an existing contract. To get started, you'll follow these steps:

  1. Initialize your subgraph project
  2. Deploy your subgraph to the Subgraph Studio
  3. Publish your subgraph to The Graph's decentralized network
  4. Query your subgraph from your dApp

Note

You can query your subgraph via the free, rate-limited development query URL, which can be used for development and staging. The free plan includes 100,000 queries per month. If you need to make more queries or want a production-ready plan, please check out The Graph's documentation.

Create a Subgraph on Subgraph Studio

To initialize your subgraph, you must head to the Subgraph Studio and connect your wallet. After you've connected your wallet, you'll be prompted to add an email address, which will be used to send notifications about your account. You can only associate one account with your email address, so make sure you've connected the account you intend to continue to use.

After you get your email address set up and verified, you can create a subgraph from your dashboard by clicking Create a Subgraph.

Create a subgraph

Then, you can:

  1. Enter a name. Note that it is recommended to use title case for the name (i.e., Subgraph Name Chain Name); the name cannot be changed once it has been created
  2. Click Create Subgraph

Enter a name for your subgraph

You will then land on your subgraph's page. Here, you can add additional information about your subgraph, such as the description, source code URL, website URL, and categories your subgraph belongs to. You'll also find all the CLI commands you need to initialize and deploy your subgraph.

The landing page for your subgraph

Install Graph CLI⁠

To install Graph CLI on your local machine, run the following:

npm install -g @graphprotocol/graph-cli
yarn global add @graphprotocol/graph-cli

Initialize Your Subgraph⁠

Before you initialize your subgraph, you should verify the contract address from which you want to query data on Moonscan. This is so the Graph CLI can pull in the ABI directly from Moonscan for you. To learn how to verify your contracts, please refer to the Verify Contracts section of the docs.

You'll need to grab the initialization command from your subgraph's page on Subgraph Studio to initialize your subgraph. Or, if you know the name of your subgraph, you can use the following command:

graph init --studio INSERT_SUBGRAPH_NAME

To initialize your subgraph, you'll need to provide some additional information, which you will be prompted to provide in your terminal:

  1. For Protocol, select ethereum, as Moonbeam is an Ethereum-compatible chain
  2. Hit enter for Subgraph slug to use the default one provided, or change as needed
  3. Again, hit enter for Directory to create the subgraph in to use the default one provided, or change as needed
  4. For Ethereum network, scroll down and select the Moonbeam network you are working with. Note that the Moonbase Alpha TestNet is labeled as mbase
  5. Enter the contract address to index and query data from. The CLI will attempt to fetch the ABI from Moonscan. If it doesn't work, make sure that your contract has been verified and retry if needed. Otherwise, you will need to input it manually as a JSON file after your project has been successfully created
  6. Enter a start block. The start block allows you to save time by only indexing the necessary blocks. To get all of the data for this contract, you can use the block the contract was deployed
  7. Contract Name should be automatically populated for you, but if not, manually enter the name of the contract
  8. For Index contract events as entities, it is recommended to set this to true, as it will automatically add mappings to your subgraph for every event emitted. In other words, you'll be able to capture and store the data emitted by these events

The CLI will generate your project for you, and you can continue to add additional contracts as needed.

graph init --studio moonbeam-demo · ethereum · moonbeam-demo · moonbeam-demo · moonbeam · 0x515e20e6275CEeFe19221FC53e77E38cc32b80Fb ✖ Failed to fetch Start Block: Failed to fetch contract creation transaction hash · false · 1137478 · EXRGameAsset · true Generate subgraph Write subgraph to directory Create subgraph scaffold Initialize networks config Initialize subgraph repository Install dependencies with yarn Generate ABI and schema types with yarn codegen Subgraph moonbeam-demo created in moonbeam-demo

Your project will be created using the slug name you provided in step two. At this time, you can feel free to check out the project and modify the logic as needed for your project. For more information on how to write a subgraph, check out The Graph's documentation. Note that for this quick start example, if you selected to index contract events as entities, you don't need to modify anything; you can deploy the project as is.

Deploy a Subgraph

To deploy your subgraph to Subgraph Studio, change to the subgraph directory in your terminal and run the following commands:

  1. Generate types for your smart contract ABIs and the subgraph schema

    graph codegen
    

    graph codegen Skip migration: Bump mapping apiVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping apiVersion from 0.0.2 to 0.0.3 Skip migration: Bump mapping apiVersion from 0.0.3 to 0.0.4 Skip migration: Bump mapping specVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping specVersion from 0.0.2 to 0.0.4 ✔ Apply migrations ✔ Load subgraph from subgraph.yaml Load contract ABI from abis/EXRGameAsset.json ✔ Load contract ABIs Generate types for contract ABI: EXRGameAsset (abis/EXRGameAsset.json) Write types to generated/EXRGameAsset/EXRGameAsset.ts ✔ Generate types for contract ABIs ✔ Generate types for data source templates ✔ Load data source template ABIs ✔ Generate types for data source template ABIs ✔ Load GraphQL schema from schema.graphql Write types to generated/schema.ts ✔ Generate types for GraphQL schema

  2. Compile your subgraph to Wasm

    graph build
    

    graph build Skip migration: Bump mapping apiVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping apiVersion from 0.0.2 to 0.0.3 Skip migration: Bump mapping apiVersion from 0.0.3 to 0.0.4 Skip migration: Bump mapping specVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping specVersion from 0.0.2 to 0.0.4 ✔ Apply migrations ✔ Load subgraph from subgraph.yaml Compile data source: EXRGameAsset => build/EXRGameAsset/EXRGameAsset.wasm ✔ Compile subgraph Copy schema file build/schema.graphql Write subgraph file build/EXRGameAsset/abis/EXRGameAsset.json Write subgraph manifest build/subgraph.yaml ✔ Write compiled subgraph to build/

  3. Authenticate your subgraph with your deploy key. The exact command containing the deploy key can be found on your subgraph's page in Subgraph Studio

    graph auth --studio INSERT_DEPLOY_KEY
    

    graph auth --studio eb6... Deploy key set for https://api.studio.thegraph.com/deploy/

  4. Deploy your subgraph and specify the slug for it. Again, you can get the exact command from your subgraph's page in Subgraph Studio

    graph deploy --studio <SUBGRAPH_SLUG>
    

    You will be asked for a version label. You can enter something like v0.0.1, but you're free to choose the format

    graph deploy --studio moonbeam-demo v0.1 Skip migration: Bump mapping apiVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping apiVersion from 0.0.2 to 0.0.3 Skip migration: Bump mapping apiVersion from 0.0.3 to 0.0.4 Skip migration: Bump mapping specVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping specVersion from 0.0.2 to 0.0.4 ✔ Apply migrations ✔ Load subgraph from subgraph.yaml Compile data source: EXRGameAsset => build/EXRGameAsset/EXRGameAsset.wasm ✔ Compile subgraph Copy schema file build/schema.graphql Write subgraph file build/EXRGameAsset/abis/EXRGameAsset.json Write subgraph manifest build/subgraph.yaml ✔ Write compiled subgraph to build/ ✔ Compile subgraph ✔ Compile subgraph Add file to IPFS build/schema.graphql .. QmQfQiQLmtgpibjDDgP83YfczUzLbuXhKa8FevB58LLuP2 Add file to IPFS build/EXRGameAsset/abis/EXRGameAsset.json .. QmdXKywXz8MkUvbW5YrPiBzbGKgcMjZbbLjRjWtgGcruXT Add file to IPFS build/EXRGameAsset/EXRGameAsset.wasm .. QmSLqNWtL6Uvku5adann325ruz8AgjfqLmn1NFLpZ8JcKK ✔ Upload subgraph to IPFS
    Build completed: QmUHKw4sthmV6ve1YqFJMNvkviYf3sWzVA3qk4xjx5587q
    Deployed to https://thegraph.com/studio/subgraph/moonbeam-demo
    Subgraph endpoints: Queries (HTTP): https://api.studio.thegraph.com/query/80185/moonbeam-demo/v0.1

Once you've successfully deployed your subgraph, you can query it using the subgraph endpoint that was printed to your terminal.

Test Your Subgraph⁠

You can test your subgraph by making a query in the Playground section of your subgraph's page on Subgraph Studio.

The playground page for your subgraph

To test from your dApp, you can use the API endpoint that was printed to your terminal. You can also find the endpoint on your subgraph's page in Subgraph Studio under the Details tab.

The playground page for your subgraph

You can use the following example code to query your subgraph. First, you'll need to install Axios:

npm install axios
yarn add axios

Then, use the code snippet below. Be sure to insert your own query and endpoint:

import axios from 'axios';

const graphqlQuery = `query MyQuery {
  gameAssetMinteds {
    blockNumber
    transactionHash
    id
    tokenId
  }
}`;

const queryUrl =
  'https://api.studio.thegraph.com/query/80185/moonbeam-demo/version/latest';

const graphQLRequest = {
  method: 'post',
  url: queryUrl,
  data: {
    query: graphqlQuery,
  },
};

// Send the GraphQL query
axios(graphQLRequest)
  .then((response) => {
    // Handle the response here
    const data = response.data.data;
    console.log(data);
  })
  .catch((error) => {
    // Handle any errors
    console.error(error);
  });

Publish Your Subgraph to The Graph's Decentralized Network

Once your subgraph is ready for production, you can publish it to the decentralized network.

Note

Publishing requires Arbitrum ETH. When upgrading your subgraph, a small amount is airdropped to facilitate your initial protocol interactions.

For publishing instructions, please refer to The Graph's documentation.

Additional Resources

  • To explore all the ways you can optimize and customize your subgraph for better performance, read more about creating a subgraph
  • For more information on querying data from your subgraph, check out the Querying the Graph guide
The information presented herein has been provided by third parties and is made available solely for general information purposes. Moonbeam does not endorse any project listed and described on the Moonbeam Doc Website (https://docs.moonbeam.network/). Moonbeam Foundation does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Moonbeam Foundation disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Moonbeam Foundation. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Moonbeam Foundation has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Moonbeam Foundation harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.
Last update: December 10, 2024
| Created: April 12, 2021