Web3 data querying with The Graph and subgraphs

The Graph is an indexing protocol for organizing blockchain data. It makes use of a GraphQL API to supply simpler entry to on-chain info than the standard technique of sending an RPC name.
The community organizes the data with subgraphs; open-source APIs which might be created by the neighborhood and are used for retrieving data from Indexers, Curators, and Delegators.
On this article, we’re going to be having a look at how you should use The Graph and subgraphs for Web3 data querying.
Indexers function the community nodes
Indexers function the nodes of the community, which index data and serve the queries.
For the reason that Graph Community makes use of a proof-of-stake algorithm, indexers stake Graph Tokens (GRT) to supply indexing and question processing providers. In flip, Indexers can earn question charges and indexing rewards.
They choose subgraphs to index primarily based on the subgraph’s curation sign. Purposes that eat the Indexers’ data can set parameters for which Indexers they wish to course of their queries, alongside with their preferences for question charge pricing.
Curators sign high-quality subgraphs
Curators manage data from the subgraphs by signaling the subgraphs that ought to be listed by the Graph Community.
They do that utilizing Graph Curation Shares (GCS), which permit them to put the equal of an funding on a subgraph.
Curators stake GRT, which permits them to mint GCS. Every subgraph has a bonding curve that determines the connection between the worth of GRT and the variety of shares that may be minted.
In keeping with the Graph’s documentation, curating is taken into account dangerous and ought to solely be carried out after totally researching and investigating the trade-offs concerned.
Delegators safe the community by staking
Delegators stake GRT to a number of Indexers to assist safe the community with out having to run a node themselves.
Delegators earn parts of the Indexer’s question charges and rewards, that are depending on the Indexer’s and Delegator’s stake, alongside with the worth the Indexer expenses for every question.
Allocating extra stake to an Indexer permits extra potential queries to be processed. The Graph’s documentation claims that being a Delegator carries much less threat than being a Curator as a result of they aren’t uncovered to fluctuations within the value of GRT, resulting from burning shares of GCS.
The Graph Basis
The Graph is developed and maintained by The Graph Basis. To verify the community and bigger neighborhood proceed to enhance, the muse distributes grants (known as Graph Grants) to neighborhood members engaged on protocol infrastructure, tooling, dApps, subgraphs, and neighborhood constructing.
Three completely different graph providers
There are three alternative ways to work together with the Graph if you’re not internet hosting your individual subgraph:
- Graph Explorer: Discover completely different subgraphs and work together with the Graph protocol
- Subgraph Studio: Create, handle, and publish subgraphs and API keys utilizing Ethereum Mainnet
- Hosted Service: Create, handle, and publish subgraphs and API keys utilizing different networks except for Ethereum, equivalent to Avalanche, Concord, Fantom, and Celo
The hosted service doesn’t require a crypto pockets and can be utilized with a GitHub account. The Graph Explorer and Subgraph Studio will each ask you to attach a pockets equivalent to MetaMask or Coinbase.
Create a undertaking on Hosted Service
After creating an account on the hosted service, click on “My Dashboard” on the navigation bar to see your dashboard.
Click on “Add Subgraph” to create a subgraph.
Add a reputation and subtitle on your subgraph. When you’ve crammed in your subgraph’s info, scroll all the way down to the underside of the web page and click on “Create subgraph”.
With our subgraph setup on the hosted service, we are able to create our undertaking information. Create a brand new listing, initialize a bundle.json
, and set up dependencies.
mkdir graphrocket cd graphrocket yarn init -y yarn add -D @graphprotocol/graph-cli @graphprotocol/graph-ts
Copy the entry token accessible in your undertaking dashboard on Hosted Service. Paste the token after the yarn graph auth --product hosted-service
command.
yarn graph auth --product hosted-service YOURTOKEN
Create configuration information for TypeScript and Git.
Extra nice articles from LogRocket:
echo '{"extends": "@graphprotocol/graph-ts/types/tsconfig.base.json"}' > tsconfig.json echo '.DS_Storennode_modules' > .gitignore
Good contracts on the Ethereum blockchain expose an software binary interface (or ABI) as an interface between client-side functions and the Ethereum blockchain. We’ll want this for our subgraph.
Obtain the contract’s ABI with cURL and reserve it to a file known as Token.json
.
curl " > Token.json
Create three undertaking information together with:
token.ts
for AssemblyScript code that interprets Ethereum occasion data into the entities outlined within the schemesubgraph.yaml
for a YAML configuration of the subgraph’s manifestschema.graphql
for a GraphQL schema defining the data saved for the subgraph and learn how to question it through GraphQL
echo > token.ts echo > schema.graphql echo > subgraph.yaml
Outline Token
and Consumer
entities
In schema.graphql
we’ve outlined two varieties, Token
and Consumer
.
# schema.graphql kind Token @entity {} kind Consumer @entity {}
The Token
has a title
and different info equivalent to when it was created, the content material URI, and the IPFS file path. It additionally consists of details about the creator
and proprietor
.
# schema.graphql kind Token @entity { id: ID! tokenID: BigInt! contentURI: String tokenIPFSPath: String title: String! createdAtTimestamp: BigInt! creator: Consumer! proprietor: Consumer! }
The creator
and proprietor
are Consumer
varieties. They’ve an id
, an array of tokens
they personal, and an array of tokens
they’ve created
.
# schema.graphql kind Consumer @entity { id: ID! tokens: [Token!]! @derivedFrom(discipline: "owner") created: [Token!]! @derivedFrom(discipline: "creator") }
@derivedFrom
allows reverse lookups, which implies we don’t retailer either side of the connection to enhance indexing and question efficiency. For one-to-many relationships, the connection ought to be saved on the “one” facet with the “many” facet derived from it.
Create subgraph
The subgraph.yaml
file will comprise the definition of our subgraph. Begin with the model of the specification used and a file path to the entity varieties in schema.graphql
.
# subgraph.yaml specVersion: 0.0.4 schema: file: ./schema.graphql
Subsequent is the community containing our data sources. dataSources.supply
wants the deal with and ABI of the good contract.
# subgraph.yaml dataSources: - type: ethereum title: Token community: mainnet supply: deal with: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405" abi: Token startBlock: 11648721
dataSources.mapping.entities
defines the entities that the data supply writes to the shop and is specified by the schema in schema.graphql
.
# subgraph.yaml mapping: type: ethereum/occasions apiVersion: 0.0.5 language: wasm/assemblyscript entities: - Token - Consumer
dataSources.mapping.abis
takes the title
and file
location of the ABI for the supply contract.
# subgraph.yaml abis: - title: Token file: ./Token.json
dataSources.mapping.eventHandlers
lists the good contract occasions the subgraph reacts to and the handlers within the mappings that remodel these occasions into entities within the retailer.
# subgraph.yaml eventHandlers: - occasion: TokenIPFSPathUpdated(listed uint256,listed string,string) handler: handleTokenIPFSPathUpdated - occasion: Switch(listed deal with,listed deal with,listed uint256) handler: handleTransfer file: ./token.ts
Full subgraph.yaml
file:
# subgraph.yaml specVersion: 0.0.4 schema: file: ./schema.graphql dataSources: - type: ethereum title: Token community: mainnet supply: deal with: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405" abi: Token startBlock: 11648721 mapping: type: ethereum/occasions apiVersion: 0.0.5 language: wasm/assemblyscript entities: - Token - Consumer abis: - title: Token file: ./Token.json eventHandlers: - occasion: TokenIPFSPathUpdated(listed uint256,listed string,string) handler: handleTokenIPFSPathUpdated - occasion: Switch(listed deal with,listed deal with,listed uint256) handler: handleTransfer file: ./token.ts
Generate varieties
Generate AssemblyScript varieties for the ABI and the subgraph schema.
yarn graph codegen
Write mappings
Import the generated varieties and generated schema and create two capabilities: handleTransfer
and handleTokenURIUpdated
.
When a brand new token is created, transferred, or up to date, an occasion is fired and the mappings save the data into the subgraph.
// token.ts import { TokenIPFSPathUpdated as TokenIPFSPathUpdatedEvent, Switch as TransferEvent, Token as TokenContract, } from "./generated/Token/Token" import { Token, Consumer } from './generated/schema' export operate handleTransfer(occasion: TransferEvent): void {} export operate handleTokenURIUpdated(occasion: TokenIPFSPathUpdatedEvent): void {}
handleTransfer
masses the tokenId
and units the proprietor
.
// token.ts export operate handleTransfer(occasion: TransferEvent): void { let token = Token.load(occasion.params.tokenId.toString()) if (!token) { token = new Token(occasion.params.tokenId.toString()) token.creator = occasion.params.to.toHexString() token.tokenID = occasion.params.tokenId let tokenContract = TokenContract.bind(occasion.deal with) token.contentURI = tokenContract.tokenURI(occasion.params.tokenId) token.tokenIPFSPath = tokenContract.getTokenIPFSPath(occasion.params.tokenId) token.title = tokenContract.title() token.createdAtTimestamp = occasion.block.timestamp } token.proprietor = occasion.params.to.toHexString() token.save() let person = Consumer.load(occasion.params.to.toHexString()) if (!person) { person = new Consumer(occasion.params.to.toHexString()) person.save() } }
handleTokenURIUpdated
updates the tokenIPFSPath
anytime it adjustments.
// token.ts export operate handleTokenURIUpdated(occasion: TokenIPFSPathUpdatedEvent): void { let token = Token.load(occasion.params.tokenId.toString()) if (!token) return token.tokenIPFSPath = occasion.params.tokenIPFSPath token.save() }
Deploy subgraph
Construct your undertaking for deployment:
yarn graph construct
Embody your individual GitHub username adopted by the title of your subgraph:
yarn graph deploy --product hosted-service USERNAME/logrocketgraph
The terminal will return a URL with an explorer for the subgraph and an API endpoint for sending queries.
Deployed to Subgraph endpoints: Queries (HTTP):
You have to to attend on your subgraph to sync with the present state of the blockchain. As soon as the syncing is full, run the next question to indicate the primary two tokens ordered by id
in descending order.
{ tokens(first: 2, orderBy: id, orderDirection: desc) { id tokenID contentURI tokenIPFSPath } }
This can output the next:
{ "data": { "tokens": [ { "id": "99999", "tokenID": "99999", "contentURI": " "tokenIPFSPath": "QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json" }, { "id": "99998", "tokenID": "99998", "contentURI": " "tokenIPFSPath": "QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json" } ] } }
Right here’s the question for the primary person and their related content material:
{ customers(first: 1, orderBy: id, orderDirection: desc) { id tokens { contentURI } } }
This can output the next:
{ "data": { "users": [ { "id": "0xfffff449f1a35eb0facca8d4659d8e15cf2f77ba", "tokens": [ { "contentURI": " }, { "contentURI": " }, { "contentURI": " }, { "contentURI": " }, { "contentURI": " }, { "contentURI": " }, { "contentURI": " }, { "contentURI": " } ] } ] } }
The question for the 2 most not too long ago created NFTs.
{ tokens( first: 2, orderBy: createdAtTimestamp, orderDirection: desc ) { id tokenID contentURI createdAtTimestamp } }
This can output the next:
{ "data": { "tokens": [ { "id": "133012", "tokenID": "133012", "contentURI": " "createdAtTimestamp": "1656792769" }, { "id": "133011", "tokenID": "133011", "contentURI": " "createdAtTimestamp": "1653825764" } ] } }
You too can use the HTTP endpoint and ship GraphQL queries straight with cURL.
curl --header 'content-type: software/json' --url '' --data '{"query":"{ tokens(first: 1) { contentURI tokenIPFSPath } }"}'
Conclusion
On this article, we have now seen learn how to create a GraphQL endpoint that exposes sure info contained on the Ethereum blockchain. By writing a schema containing our entities, we outlined the data that will probably be listed by the subgraph.
The amount and variety of blockchain networks proceed to proliferate in Web3. Having a standardized and broadly adopted question language will allow builders to iterate and check their functions with larger effectivity.
Be a part of organizations like Bitso and Coinsquare who use LogRocket to proactively monitor their Web3 apps
Consumer-side points that impression customers’ capacity to activate and transact in your apps can drastically have an effect on your backside line. In the event you’re taken with monitoring UX points, routinely surfacing JavaScript errors, and monitoring sluggish community requests and part load time, try LogRocket.https://logrocket.com/signup/
LogRocket is sort of a DVR for net and cell apps, recording every thing that occurs in your net app or web site. As a substitute of guessing why issues occur, you may combination and report on key frontend efficiency metrics, replay person classes alongside with software state, log community requests, and routinely floor all errors.
Modernize the way you debug net and cell apps — Start monitoring for free.