Building a Subgraph with The Graph

The Graph and Google

The Graph is a lot like Google- all it does is index specific data sets (specified by indexers), and allows people to search those sets. Now the model is a bit different, but they are also focused on organizing information. As the blockchains and networks surrounding them grow, this information becomes exponentially more valuable as time goes on and more apps are built on them.

This is more-so some commentary to a video tutorial on deploying subgraphs. When creating one for an already deployed contract, we faced a bunch of errors with type conversion generated from The Graph's init function.

So, how does one build a subgraph? What do you need to build one?

All you need is a smart contract, some events in that contract, and an EVM compatible network.

To start, deploy your contract to whatever EVM compatible chain you want your contract to run on. Next, you'll run the graph init command-line function and fill in the fields when prompted.

After, there will be a folder called `generated` that will contain the contract `abis,` `src/mappings.ts,` `schema.graphql,` and the `subgraph.yaml.` The `subgraph.yaml`

The `schema.ts` is autogenerated when you run `yarn deploy` or `graph codegen`. The s`chema.graphql` and `src/mappings.ts` are connected, in that you need them to generate the `generated` folder. Any data type and name change you make in the `schema.graphql` needs to be reflected in the `mappings.ts.` For instance, if you have a BigInt[] array that is emitted as a return value from the contract, you'll need to do some type casting somewhere throughout the logic, since conversion from Solidity to GraphQL and JS/TS have casting issues.

Event on contract in EVM -> GraphQL -> mappings.ts -> frontend updates

Testing your subgraph

Once you have deployed the subgraph to the studio through the deploy command, you will need to test your schemas against the activity of the smart contract. There are two ways to do this: one, you spin up a local graph node and a local hardhat environment, mimic some smart contract actions, then query locally based on that. Or, two, you can query the deployed contract on a testnet.

Should you choose the latter, you'll get access to an interface like this after deploying to the studio. You'll still need to test on the network, so make sure you have done all of your schema and type checks beforehand.

From here, The Graph will be picking up and indexing events from the deployed smart contract that you can now interact with.

Tired of doing the same activities over and over again?

Get Started