The Graph: Indexing and querying step by step

Ahmed Castro - Oct 10 '23 - - Dev Community

Ethereum smart contract historic data is open and verifiable, however it's not easy to query and navigate through it. To solve this problem, The Graph team created an indexer platform that helps devs to easily collect and expose information about any smart contract on many chains. Having this information easily available opens the door to insightful dashboards, user experience improvements on dApps or even new blockchain use cases.

In this tutorial we'll cover how to store data by creating a subgraph using The Graph studio. And how to retrieve it by maying queries to the graphql exposed by the subgraph.

Before we start

For this tutorial you will need Metamask or other wallet of your choice, with Scroll Sepolia funds that you can get from a Sepolia faucet and then bridge them to L2 using the Scroll Sepolia bridge. Alternatively, you can use a Scroll Sepolia Faucet to get funds directly on L2.

On this guide we'll deploy on Scroll Sepolia, I'll explain the exact changes that are needed to deploy on any other EVM chain.

1. Launch a Smart Contract

Let's start by launching a sample smart contract, for this tutorial we'll launch a Greeter contract. Notice that we are emitting an event when the greet function is called. This is because is very easy for the The Graph to collect information of emitted events, but if you already deployed a contract that has no events, it is also possible for The Graph to index it.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

contract TheGraphGreeter
{
    string public greeting;
    event Greeted(string hello, address sender);

    function greet(string memory greeting_) public
    {
        greeting = greeting_;
        emit Greeted(greeting, msg.sender);
    }
}
Enter fullscreen mode Exit fullscreen mode

For this example I'll be using Scroll Sepolia testnet where I deployed and verified the contract on etherscan at:
0x111690a4468ba9b57d08280b2166aff2bac65248

For more information about launching on Scroll visit the deployment and verification guides.

2. Create a Subgraph

Next, we'll launch a subgraph from The Graph Studio. A subgraph is where you will signal The Graph protocol what information you want to index and how you want to package it.

Start by going to thegraph.com/studio, signing up and Clicking on Create a Subgraph.

Create Subgraph button on The Graph

Now set a name for your subgraph and select the chain where you will be deploying (in order to use The Graph Studio the chain has to be integrated on The Graph).

Subgraph creation form on The Graph

Now that you created a subgraph, let's deploy it by submitting your smart contract information.

3. Deploy a Subgraph

On your terminal, create a new folder and save your smart contract ABI on a file that we'll call MyABI.json.

This is the ABI for our Greeter contract example.

[
    {
        "inputs": [
            {
                "internalType": "string",
                "name": "greeting_",
                "type": "string"
            }
        ],
        "name": "greet",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": false,
                "internalType": "string",
                "name": "hello",
                "type": "string"
            },
            {
                "indexed": false,
                "internalType": "address",
                "name": "sender",
                "type": "address"
            }
        ],
        "name": "Greeted",
        "type": "event"
    },
    {
        "inputs": [],
        "name": "greeting",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
]
Enter fullscreen mode Exit fullscreen mode

If you deployed your contract using Remix, you can query your ABI on the compiler tab.

How to get the ABI from a Smart Contract on Remix

On the same directory where you stored your ABI run the following commands.

Notice you will have to set DEPLOYKEY that you can find on your subgraph studio.

Deploy Key on The Graph

# 1. Install The Graph CLI tool
npm install -g @graphprotocol/graph-cli
# 2. Init, authenticate and deploy your subgraph
graph init --studio my-subgraph
graph auth --studio DEPLOYKEY
cd my-subgraph
graph codegen && graph build
graph deploy --studio my-subgraph
Enter fullscreen mode Exit fullscreen mode

This will trigger a CLI prompt that you can fill the following way:

  • Protocol: ethereum
  • Subgraph slug: my-subgraph
  • Directory: my-subgraph
  • Ethereum Network: scroll-sepolia
  • Contract address: 0xYOURGREETINGADDRESS
  • ABI file (path): ../MyABI.json

4. Query the data

Once the subgraph is deployed it will generate a graphql that where you can make queries from the browser.

The Graph API url to use on Javascript

On the graphqli interface try submitting the following query:

{
  greeteds(arg: "value") {
    hello
  }
}
Enter fullscreen mode Exit fullscreen mode

Usually you will want to query your subgraph from the web. To do so you can send a POST request with your graphql query as a parameter the following way:

Notice: You will need to replace YOURAPIURL with the Production Query URL provided on The Graph Studio website.

The following javascript call should return all your data from the subgraph. Remember to call the greet function beforehand a few times to index some information.

await fetch('YOURAPIURL', {
  method: 'POST',
  body: JSON.stringify({
    query: `{
  greeteds(arg: "value") {
    hello
  }}`
  }),
  headers: {
      'content-type': 'application/json'
  }
}).then(async (data) => {
    // Console log our return data
    console.log(await data.json());
});
Enter fullscreen mode Exit fullscreen mode

Now you can display on-chain information on your website or in any backend service!

Official documentation: https://thegraph.com/docs/en/

Thanks for watching this tutorial!

Follows us on dev.to and in Youtube for everything related to Blockchain development.

. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player