BTC NOON
  • Home
  • Cryptocurrency
  • Bitcoin
  • Ethereum
  • Blockchain
  • Regulations
  • Altcoin
  • DeFi
  • Web 3.0
No Result
View All Result
BTC NOON
No Result
View All Result
Home Web 3.0

Web3 data querying with The Graph and subgraphs

Xiao Chen Sun by Xiao Chen Sun
March 10, 2023
in Web 3.0
0
Web3 data querying with The Graph and subgraphs
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


The Graph is an indexing protocol for organizing blockchain information. It makes use of a GraphQL API to offer simpler entry to on-chain info than the standard technique of sending an RPC name.

The community organizes the information with subgraphs; open-source APIs which are created by the group and are used for retrieving information 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 information querying.

Indexers function the community nodes

Indexers function the nodes of the community, which index information and serve the queries.

Because the Graph Community makes use of a proof-of-stake algorithm, indexers stake Graph Tokens (GRT) to offer indexing and question processing companies. In flip, Indexers can earn question charges and indexing rewards.

They choose subgraphs to index primarily based on the subgraph’s curation sign. Functions that devour the Indexers’ information can set parameters for which Indexers they wish to course of their queries, together with their preferences for question charge pricing.

Curators sign high-quality subgraphs

Curators arrange information 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 position 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.

Based on the Graph’s documentation, curating is taken into account dangerous and will solely be carried out after completely 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, together with the worth the Indexer fees 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 danger than being a Curator as a result of they aren’t uncovered to fluctuations within the worth of GRT, as a consequence of burning shares of GCS.

The Graph Basis

The Graph is developed and maintained by The Graph Basis. To ensure the community and bigger group proceed to enhance, the inspiration distributes grants (referred to as Graph Grants) to group members engaged on protocol infrastructure, tooling, dApps, subgraphs, and group constructing.

Three totally different graph companies

There are three other ways to work together with the Graph in case you are not internet hosting your personal subgraph:

  • Graph Explorer: Discover totally 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 other than Ethereum, comparable 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 comparable to MetaMask or Coinbase.

Create a venture on Hosted Service

After creating an account on the hosted service, click on “My Dashboard” on the navigation bar to see your dashboard.

Hosted Service My Dashboard

Click on “Add Subgraph” to create a subgraph.

Hosted Service 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”.

Hosted Service Name Install Deploy

With our subgraph setup on the hosted service, we are able to create our venture 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 out there in your venture 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/varieties/tsconfig.base.json"}' > tsconfig.json
echo '.DS_Storennode_modules' > .gitignore

Sensible contracts on the Ethereum blockchain expose an software binary interface (or ABI) as an interface between client-side purposes and the Ethereum blockchain. We are going to want this for our subgraph.

Obtain the contract’s ABI with cURL and reserve it to a file referred to as Token.json.

curl "http://api.etherscan.io/api?module=contract&motion=getabi&tackle=0xe7c29cba93ef8017c7824dd0f25923c38d08065c&format=uncooked" > Token.json

Create three venture information together with:

  • token.ts for AssemblyScript code that interprets Ethereum occasion information into the entities outlined within the scheme
  • subgraph.yaml for a YAML configuration of the subgraph’s manifest
  • schema.graphql for a GraphQL schema defining the information saved for the subgraph and how one can 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

sort Token @entity {}
sort Consumer @entity {}

The Token has a identify and different info comparable to when it was created, the content material URI, and the IPFS file path. It additionally contains details about the creator and proprietor.

# schema.graphql

sort Token @entity {
  id: ID!
  tokenID: BigInt!
  contentURI: String
  tokenIPFSPath: String
  identify: 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

sort Consumer @entity {
  id: ID!
  tokens: [Token!]! @derivedFrom(discipline: "proprietor")
  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” aspect with the “many” aspect 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 information sources. dataSources.supply wants the tackle and ABI of the good contract.

# subgraph.yaml

dataSources:
  - sort: ethereum
    identify: Token
    community: mainnet
    supply:
      tackle: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
      abi: Token
      startBlock: 11648721

dataSources.mapping.entities defines the entities that the information supply writes to the shop and is specified by the schema in schema.graphql.

# subgraph.yaml

mapping:
  sort: ethereum/occasions
  apiVersion: 0.0.5
  language: wasm/assemblyscript
  entities:
    - Token
    - Consumer

dataSources.mapping.abis takes the identify and file location of the ABI for the supply contract.

# subgraph.yaml

abis:
  - identify: Token
    file: ./Token.json

dataSources.mapping.eventHandlers lists the good contract occasions the subgraph reacts to and the handlers within the mappings that rework these occasions into entities within the retailer.

# subgraph.yaml

eventHandlers:
  - occasion: TokenIPFSPathUpdated(listed uint256,listed string,string)
    handler: handleTokenIPFSPathUpdated
  - occasion: Switch(listed tackle,listed tackle,listed uint256)
    handler: handleTransfer
file: ./token.ts

Full subgraph.yaml file:

# subgraph.yaml

specVersion: 0.0.4
schema:
  file: ./schema.graphql
dataSources:
  - sort: ethereum
    identify: Token
    community: mainnet
    supply:
      tackle: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
      abi: Token
      startBlock: 11648721
    mapping:
      sort: ethereum/occasions
      apiVersion: 0.0.5
      language: wasm/assemblyscript
      entities:
        - Token
        - Consumer
      abis:
        - identify: Token
          file: ./Token.json
      eventHandlers:
        - occasion: TokenIPFSPathUpdated(listed uint256,listed string,string)
          handler: handleTokenIPFSPathUpdated
        - occasion: Switch(listed tackle,listed tackle,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 features: handleTransfer and handleTokenURIUpdated.

When a brand new token is created, transferred, or up to date, an occasion is fired and the mappings save the information 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 perform handleTransfer(occasion: TransferEvent): void {}

export perform handleTokenURIUpdated(occasion: TokenIPFSPathUpdatedEvent): void {}

handleTransfer hundreds the tokenId and units the proprietor.

// token.ts

export perform 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.tackle)
    token.contentURI = tokenContract.tokenURI(occasion.params.tokenId)
    token.tokenIPFSPath = tokenContract.getTokenIPFSPath(occasion.params.tokenId)
    token.identify = tokenContract.identify()
    token.createdAtTimestamp = occasion.block.timestamp
  }
  token.proprietor = occasion.params.to.toHexString()
  token.save()

  let consumer = Consumer.load(occasion.params.to.toHexString())
  if (!consumer) {
    consumer = new Consumer(occasion.params.to.toHexString())
    consumer.save()
  }
}

handleTokenURIUpdated updates the tokenIPFSPath anytime it adjustments.

// token.ts

export perform 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 venture for deployment:

yarn graph construct

Embrace your personal GitHub username adopted by the identify 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 https://thegraph.com/explorer/subgraph/ajcwebdev/logrocketgraph

Subgraph endpoints:
Queries (HTTP):     https://api.thegraph.com/subgraphs/identify/ajcwebdev/logrocketgraph

You’ll need 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 point out 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:

{
  "information": {
    "tokens": [
      {
        "id": "99999",
        "tokenID": "99999",
        "contentURI": "https://ipfs.foundation.app/ipfs/QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json",
        "tokenIPFSPath": "QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json"
      },
      {
        "id": "99998",
        "tokenID": "99998",
        "contentURI": "https://ipfs.foundation.app/ipfs/QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json",
        "tokenIPFSPath": "QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json"
      }
    ]
  }
}

Right here’s the question for the primary consumer and their related content material:

{
  customers(first: 1, orderBy: id, orderDirection: desc) {
    id
    tokens {
      contentURI
    }
  }
}

This can output the next:

{
  "information": {
    "customers": [
      {
        "id": "0xfffff449f1a35eb0facca8d4659d8e15cf2f77ba",
        "tokens": [
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmVkXqo2hmC2j18udhZG1KavxaTGrnEX7uuddEbghPKCUW/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmTSEgtJmptBCpEJKubK6xDZFiCMEHgGQjhrUAsJSXwzKZ/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmPzSJGhheyyA7MZMYz7VngnZWN8TinH75PTP7M1HAedti/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmeroC2cWfdN31hLd3JpBQMbbWqnQdUdGx94FGUR4AGBUP/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmQVkhqEsZvsstfDp6QAPXB4TkxFnpeAc9BWu2eQo6QvZD/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmRax3fw4skHp95i2v3BzroMoKQVHqAkwbov8FyPdesk3j/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmViGRnvHFBZ6CWHoxZGJoU9iwnoGwZfqj2vgDN3dgsGv4/metadata.json"
          },
          {
            "contentURI": "https://ipfs.foundation.app/ipfs/QmdRBPxDF1tUzm1Pczyme24vguUjW28cLwM4n9MvtxAWX6/metadata.json"
          }
        ]
      }
    ]
  }
}

The question for the 2 most just lately created NFTs.

{
  tokens(
    first: 2,
    orderBy: createdAtTimestamp,
    orderDirection: desc
  ) {
    id
    tokenID
    contentURI
    createdAtTimestamp
  }
}

This can output the next:

{
  "information": {
    "tokens": [
      {
        "id": "133012",
        "tokenID": "133012",
        "contentURI": "https://ipfs.foundation.app/ipfs/QmSmk85TjpaegCmHDRWZQqMz18vJtACZdugVx5a1tmfjpv/metadata.json",
        "createdAtTimestamp": "1656792769"
      },
      {
        "id": "133011",
        "tokenID": "133011",
        "contentURI": "https://ipfs.foundation.app/ipfs/QmU6RFcKFDteUTipg5tg4NFkWKApdVbo9oq9UYMtSmcWVe/metadata.json",
        "createdAtTimestamp": "1653825764"
      }
    ]
  }
}

You can too use the HTTP endpoint and ship GraphQL queries straight with cURL.

curl 
  --header 'content-type: software/json' 
  --url 'https://api.thegraph.com/subgraphs/identify/ajcwebdev/logrocketgraph' 
  --data '{"question":"{ tokens(first: 1) { contentURI tokenIPFSPath } }"}'

Conclusion

On this article, we’ve seen how one can create a GraphQL endpoint that exposes sure info contained on the Ethereum blockchain. By writing a schema containing our entities, we outlined the knowledge that can 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 purposes with better 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’ potential to activate and transact in your apps can drastically have an effect on your backside line. In case you’re excited about monitoring UX points, robotically surfacing JavaScript errors, and monitoring sluggish community requests and element load time, try LogRocket.LogRocket Dashboard Free Trial Bannerhttps://logrocket.com/signup/

LogRocket is sort of a DVR for internet and cell apps, recording all the things that occurs in your internet app or web site. As an alternative of guessing why issues occur, you’ll be able to mixture and report on key frontend efficiency metrics, replay consumer classes together with software state, log community requests, and robotically floor all errors.

Modernize the way you debug internet and cell apps — Start monitoring for free.



Source link

You might also like

Web3 for Frontend Developers – Getting Started With Moralis Web3UI Kit

What Is the Blockchain Trilemma? Blockchain Trilemma Explained

Web3 Privacy Guide – Creating an Anonymous Identity

Tags: dataGraphqueryingsubgraphsWeb3
Share30Tweet19
Xiao Chen Sun

Xiao Chen Sun

Recommended For You

Web3 for Frontend Developers – Getting Started With Moralis Web3UI Kit

by Xiao Chen Sun
March 27, 2023
0
Web3 for Frontend Developers – Getting Started With Moralis Web3UI Kit

Introduction The web3 ecosystem has prioritized back-end development of blockchain-based projects, while giving little to no contribution to the front-end stack. The frontend is the development of the...

Read more

What Is the Blockchain Trilemma? Blockchain Trilemma Explained

by Xiao Chen Sun
March 27, 2023
0
What Is the Blockchain Trilemma? Blockchain Trilemma Explained

There are a whole lot of trilemmas out there. We've all struggled with the classic student trilemma, balancing good grades with social life, and sleep. But now we've...

Read more

Web3 Privacy Guide – Creating an Anonymous Identity

by Xiao Chen Sun
March 26, 2023
0
Web3 Privacy Guide – Creating an Anonymous Identity

Privacy is a right, not a privilege. This article is for web3 developers, founders, and builders who prefer to operate anonymously for a variety of reasons. The first...

Read more

What Is a Fork? Crypto Forks Explained

by Xiao Chen Sun
March 26, 2023
0
What Is a Fork? Crypto Forks Explained

We're not talking about cutlery today, instead, we're talking about what some crypto projects decide to do in the face of disaster or when attempting to upgrade. Let...

Read more

Contribute to the Web3 Blog and Get Paid

by Xiao Chen Sun
March 26, 2023
0
Contribute to the Web3 Blog and Get Paid

A few months ago, we launched the Web3 blog. It’s been an awesome success. With hundreds of thousands of views, 10+ awesome contributing expert writers, and with a...

Read more
Next Post
US House Republicans Blast Biden Administration’s Attack on the Crypto Ecosystem

US House Republicans Blast Biden Administration’s Attack on the Crypto Ecosystem

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Edelweiss Interop Recap | Ethereum Foundation Blog

Edelweiss Interop Recap | Ethereum Foundation Blog

March 15, 2023
Regulation still key for the evolution of CeFi: Paris Blockchain Week

Regulation still key for the evolution of CeFi: Paris Blockchain Week

March 23, 2023
Oh Circle | Financial Times

Oh Circle | Financial Times

March 26, 2023

Browse by Category

  • Altcoin
  • Artificial Intelligence
  • Bitcoin
  • Blockchain
  • Business
  • Cryptocurrencies
  • Cryptocurrency
  • Culture
  • DeFi
  • Education
  • Ethereum
  • Featured
  • News
  • Regulations
  • Uncategorized
  • Web 3.0

Recent News

Grindr Alerts Egyptian Users of Police-Operated Profiles

Grindr Alerts Egyptian Users of Police-Operated Profiles

March 27, 2023
Coinbase Chief Legal Officer Says SEC’s Wells Notice a Massive Overreach on Part of Regulator

Coinbase Chief Legal Officer Says SEC’s Wells Notice a Massive Overreach on Part of Regulator

March 27, 2023
Web3 for Frontend Developers – Getting Started With Moralis Web3UI Kit

Web3 for Frontend Developers – Getting Started With Moralis Web3UI Kit

March 27, 2023

Categories

  • Altcoin
  • Artificial Intelligence
  • Bitcoin
  • Blockchain
  • Business
  • Cryptocurrencies
  • Cryptocurrency
  • Culture
  • DeFi
  • Education
  • Ethereum
  • Featured
  • News
  • Regulations
  • Uncategorized
  • Web 3.0

Follow Us

Find Via Tags

Bank banks Binance Bitcoin Blockchain Blog BTC Chain Circle coin Coinbase Crypto data decentralized DeFi digital ETH Ethereum Exchange Fed finance Financial Foundation FTX Heres high hits IBM Launches market Network Platform Polygon Price Project Report SEC Shanghai Stablecoin Supply Token Top Trading USDC Web3

© 2023 BTC NOON | All Rights Reserved

No Result
View All Result
  • Home
  • Cryptocurrency
  • Bitcoin
  • Ethereum
  • Blockchain
  • Regulations
  • Altcoin
  • DeFi
  • Web 3.0

© 2023 BTC NOON | All Rights Reserved

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?