How to create an OpenSea GraphQL subgraph

To create an OpenSea GraphQL subgraph, you need to follow several steps, including defining
the schema, writing mapping functions, and deploying the subgraph. The following instructions
will guide you through this process:

1. Set up your environment:
Before you start, make sure you have the following installed:
– Node.js (version 14.x or higher)
– Yarn (version 1.x)
– The Graph CLI (`yarn global add @graphprotocol/graph-cli`)

2. Create a new subgraph project:
Run `graph init –from-example /` to create a
new subgraph project using an example template.

3. Define your schema:
Navigate to the `schema.graphql` file in the `subgraph` directory. Replace the example content
with the schema for your OpenSea subgraph. Here’s a basic example:

type Token @entity {
owner: Bytes!
metadataURI: String

type Transfer @entity {
token: Token!
from: Bytes!
to: Bytes!
timestamp: BigInt!

4. Define the data sources:
In the `subgraph.yaml` file, specify the Ethereum smart contracts you want to track. You’ll
need the contract addresses and the ABI files. For example:

specVersion: 0.0.2
description: OpenSea NFT Subgraph
repository: https://github.com//
file: ./schema.graphql

dataSources:
– kind: ethereum/contract
name: NFTContract
network: mainnet
address: “0xCONTRACT_ADDRESS”
abi: NFTContract
startBlock: START_BLOCK
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
– Transfer
– name: NFTContract
file: ./abis/NFTContract.json
eventHandlers:
– event: Transfer(address,address,uint256)
handler: handleTransfer
file: ./src/mapping.ts

5. Write mapping functions:
In the `src/mapping.ts` file, write the mapping functions to process the events and update the
entities in the store. For example:

import { BigInt } from
import { Transfer } from “../generated/NFTContract/NFTContract”;
import { Token, Transfer as TransferEntity } from “../generated/schema”;

export function handleTransfer(event: Transfer): void {
let token = Token.load(event.params.tokenId.toString());
if (token == null) {
token = new Token(event.params.tokenId.toString());
token.metadataURI = “”;
token.owner = event.params.to;
token.save();

let transfer = new TransferEntity(
event.transaction.hash.toHex() + “-” + event.logIndex.toString()

transfer.token = token.id;
transfer.from = event.params.from;
transfer.to = event.params.to;
transfer.timestamp = event.block.timestamp;
transfer.save();

6. Build and deploy the subgraph:
In the terminal, run the following commands:

yarn codegen
yarn build
graph auth https://api.thegraph.com/deploy/
graph deploy –node https://api.thegraph.com/deploy/ –ipfs https://api.thegraph.com/ip