The Graph – Subgraph Workshop

Dec 25, 2022 | Blockchain

Welcome to this enlightening workshop where you’ll embark on a journey to build a GraphQL API on top of the Ethereum blockchain. You’ll be able to query exciting data from Foundation by constructing a subgraph using the Foundation NFT smart contract.

Subgraph Workshop

Prerequisites

Before diving into the magic of subgraphs, ensure you have Node.js installed on your machine. This is essential for running the commands we’ll use throughout the workshop.

Getting Started

To kick off this adventure, open the The Graph Hosted Service and either sign in or create a new account.

Hosted studio dashboard

On the dashboard, click on Add Subgraph to make a new subgraph.

Hosted studio dashboard

Configure your subgraph by giving it the following properties:

  • Subgraph Name – Foundationsubgraph
  • Subtitle – A subgraph for querying NFTs
  • Optional – You can fill in the description and GITHUB URL fields if desired.
Hosted studio dashboard

Initializing a New Subgraph Using the Graph CLI

After creating the subgraph, we’ll initialize it locally using the Graph CLI.

Start by installing the Graph CLI:

npm install -g @graphprotocol/graph-cli

After the installation, you can initialize your new subgraph with the Graph CLI init command. There are two methods for initialization:

  1. From an example subgraph (This is an example command; please don’t run it):
  2. graph init --from-example GITHUB_USERNAME SUBGRAPH_NAME [DIRECTORY]
  3. From an existing smart contract (This is another example command; please don’t run it):
  4. graph init --from-contract CONTRACT_ADDRESS [--network ETHEREUM_NETWORK] [--abi FILE] GITHUB_USERNAME SUBGRAPH_NAME [DIRECTORY]

In our case, we’ll be starting with the Foundation proxy contract. You can initialize from that contract address with the following command:

graph init --from-contract 0xc9fe4ffc4be41d93a1a7189975cd360504ee361a --protocol ethereum --network mainnet --contract-name Token

This command will set up the foundational elements of your subgraph based on the provided contract address.

The Subgraph Configuration

The core configuration for the subgraph resides in the subgraph.yaml file. This file comprises several segments including the description, repository details, data sources, mappings, and entities.

You’ll be incorporating the Token and User entities, which will enable you to index the Tokens created by users, as well as the users themselves. Modify the schema.graphql file to be like this:

type Token @entity {
    id: ID!
    tokenID: BigInt!
    contentURI: String
    tokenIPFSPath: String
    name: String!
    createdAtTimestamp: BigInt!
    creator: User!
    owner: User!
}
type User @entity {
    id: ID!
    tokens: [Token!]! @derivedFrom(field: owner)
    created: [Token!]! @derivedFrom(field: creator)
}

Defining the Relationships

In this workshop, we’ll also explore how relationships work between entities. The @derivedFrom field helps establish reverse lookups, optimizing performance for querying complex relationships.

Mappings and Building

After defining your schema, next comes writing the AssemblyScript mappings in src/mappings.ts. Here you’ll handle events such as token creation and transfers:

import { TokenIPFSPathUpdated as TokenIPFSPathUpdatedEvent, Transfer as TransferEvent, Token as TokenContract } from ..generated/Token/Token;
import { Token, User } from ..generated/schema;

export function handleTransfer(event: TransferEvent): void {
    let token = Token.load(event.params.tokenId.toString());
    if (!token) {
        token = new Token(event.params.tokenId.toString());
        token.owner = event.params.to.toHexString();
    }
    // Additional token mappings
    token.save();

    let user = User.load(event.params.to.toHexString());
    if (!user) {
        user = new User(event.params.to.toHexString());
    }
    user.save();
}

These mappings will trigger whenever a token is created, transferred, or modified, ensuring your subgraph stays up-to-date.

Running a Build

To verify that everything is configured optimally, run:

graph build

Upon a successful build, you’ll observe a newly generated build folder in your directory.

Deploying the Subgraph

Deploying your subgraph is the next crucial step in this workshop. For this, ensure you copy the Access token from your account in the Graph Explorer.

Run the following commands to deploy:

graph auth hosted-service YOUR_ACCESS_TOKEN
yarn deploy

Once deployed successfully, your subgraph will appear in your dashboard.

Graph Dashboard

Querying for Data

With your subgraph alive and active, it’s time to query data! Use the following GraphQL to retrieve your tokens:

tokens {
    id
    tokenID
    contentURI
    tokenIPFSPath
}

Other query examples include ordering and pagination:

tokens(orderBy: id, orderDirection: desc) {
    id
    tokenID
    contentURI
    tokenIPFSPath
}

Troubleshooting

If you encounter any issues during the process, consider the following troubleshooting ideas:

  • Double-check your Node.js installation and ensure that all required packages are properly installed.
  • Ensure that the contract address used in the Graph CLI initialization commands is correct and valid on the Ethereum network.
  • Verify the correctness of your YAML configurations and GraphQL schema.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Next Steps

If you’re eager to dive deeper into Web3, Dapps, or building subgraphs, check out the following resources:

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox