The Graph: Indexing and querying step by step
Published: 2023-10-10 00:02:52

---
title: The Graph: Indexing and querying step by step
published: true
description: 
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2yf1y96kh47b0f0knzn.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-09-25 19:27 +0000
---

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](https://metamask.io/) or other wallet of your choice, with Scroll Sepolia funds that you can get from a [Sepolia faucet](https://sepoliafaucet.com/) and then bridge them to L2 using the [Scroll Sepolia bridge](https://scroll.io/bridge). Alternatively, you can use a [Scroll Sepolia Faucet](https://docs.scroll.io/en/user-guide/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.

```solidity
// 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);
    }
}
```

For this example I'll be using Scroll Sepolia testnet where I deployed and verified the contract on etherscan at:
[0x111690a4468ba9b57d08280b2166aff2bac65248](https://sepolia.scrollscan.dev/address/0x111690a4468ba9b57d08280b2166aff2bac65248)

For more information about launching on Scroll visit the [deployment](https://docs.scroll.io/en/developers/guides/contract-deployment-tutorial/) and [verification](https://docs.scroll.io/en/developers/verifying-smart-contracts/) 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](https://thegraph.com/studio/subgraph/tribilin/), signing up and Clicking on `Create a Subgraph`.

![Create Subgraph button on The Graph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mn0j33jiqqziq5kl87m.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4qh2h9o9mm0hlv442qv.png)

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.

```json
[
	{
		"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"
	}
]
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pf5hfrifcy2ovmklqgfl.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojjzmvjquhwzxehtksup.png)

```
# 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
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkvf01yiyewx92883n4o.png)

On the graphqli interface try submitting the following query:

```
{
  greeteds(arg: "value") {
    hello
  }
}
```

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.

```javascript
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());
});
```

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

Official documentation: [https://thegraph.com/docs/en/](https://thegraph.com/docs/en/quick-start/)

**Thanks for watching this tutorial!**

Follows us on dev.to and in [Youtube]( https://www.youtube.com/channel/UCbF5CFuXv2vTkcGfepWV2nA) for everything related to Blockchain development.