This repo is your starting point to work on The Graph during Workshop.
This repo contains step-by-step instructions on building a subgraph and using it's endpoint to showcase the data.
Let's Dive into Google of Blockchain for Data Indexing!
Deploy a simple smart contract on the Polygon Mumbai testnet and deploy a subgraph for it.
Open Remix IDE. Create a Solidity file
GraphGuru.soland paste the following code.//SPDX-License-Identifier: MITpragma solidity^0.8.7; contractGraphGuru { event ChangeNameEvent (stringname); event ChangeTwitterNameEvent (stringname); event TransferEvent(addressfrom, addressto, uintamount); stringpublic name ="The Graph"; stringpublic twitterName ="graphprotocol"; function changeName(stringcalldata_name) public { name = _name; emitChangeNameEvent(_name); } function changeTwitterName(stringcalldata_twitterName) public { twitterName = _twitterName; emitChangeTwitterNameEvent(_twitterName); } function transfer(address payableto) publicpayable { to.transfer(msg.value); emitTransferEvent(msg.sender, to, msg.value); } }
Compile the contract and deploy it to Mumbai testnet using
Injected Provideras the environment. Note down the contract address.Verify and publish your smart contract (Don't know how? See this)
Go to the Subgraph studio and connect your wallet.
Click on
Create a Subgraph. Name your subgraph and select 'Polygon Mumbai' as the blockchain network. Your subgraph is created 🤩.You need to install The Graph protocol CLI to work with the subgraph.
npm install -g @graphprotocol/graph-cliOR
yarn global add @graphprotocol/graph-cliCreate an empty folder and open it in your code editor (I love VSCode ❤️). Change the directory to that folder and fire up your terminal pointing to that folder.
Now we will initialize the subgraph using the following command
graph init --studio SUBGRAPH_NAMESelect
ethereumas ProtocolPress Enter for
subgraph slugandDirectory to create subgraph in.Select
mumbaias our network.Enter the contract address of your deployed contract from above. It will automatically fetch the ABI as we have verified our contract.
Enter the block number in which the contract is created.
Enter
GraphGuruas the contract name.Press Enter for
Index contract events as entities.You have successfully created your first Subgraph. (YOU ARE AWESOMEEE! 🙇🏻♂️)
You need to authenticate your subgraph. Refer dashboard for the key.
graph auth --studio 5a6288af6001705f65d514e5423b018dChange the directory to your deployed subgraph folder
cd GraphGuruNow we build our subgraph using the following command
graph codegen && graph buildFinal Step - Deploy your subgraph. 🥳🥳🥳
graph deploy --studio GraphGuruYou can give the version as
v0.1Play around with your contract. Transfer some ETH / MATIC or change your name or Twitter username using the Remix IDE.
Congrats!!! You have created and deployed your subgraph endpoint.
Since you deployed your subgraph now it's time to use it. To start using follow these steps:
Create a folder/directory and open it in your code editor.
We will create a React app. Open your terminal pointing towards the directory and run the following command
npm create vite@latestEnter the Project Name as
frontendorclient.Select
Reactas the framework and then selectJavaScript(without SWC ❌).Run the following commands to start. (You can refer to your terminal)
cd clientnpm installnpm run devWe will also need to install
graphqlto query the data andurqlwhich is a highly customizable and versatile GraphQL client for React.npm install graphql urql@3.0.3Inside the directory, go to the
src/App.jsxand replace the existing code withimport{useState,useEffect}from'react';import'./App.css';functionApp(){return(<><div></div></>)}exportdefaultApp;
We are going to make use of the deployed subgraph for this. See it on your dashboard.
Click on
Querybutton on the right and copy the Query URL to access the subgraph.Go back to our
App.jsxand store the URL in a variable inside the App function.constQueryURL="https://api.studio.thegraph.com/query/39471/GraphGuru/version/latest"
You need an API Key to query the data. Under the Query URL you can see the option to
Manage API Keys. Click on that and it will take you to create it. You can also create it using this link.
Click on
Create API Key.You get 1,000 free queries for the API key. Enter your email address and claim your queries.
Copy the generated API key and paste it into our query URL.
Add the data you want to query below the
QueryURLvariable. Here we will get the data about the first 5 token details of Uniswap.constquery=`{ changeNameEvents(first: 5) { id name blockNumber blockTimestamp }}`
Create a client to access Uniswap. We will make of
urqlfor this. Add the following import statement at the topimport{createClient}from'urql';
To create the client add the following code after the
queryvariableconstclient=createClient({url: QueryURL})
We will make use of useEffect and useState to track the state. Add the following code in the App function
const[names,setNames]=useState([]);
useEffect(()=>{constgetNames=async()=>{const{ data }=awaitclient.query(query).toPromise();console.log(data);setNames(data.names);}getNames();},[])
To display the data on the frontend, we will return the following.
return(<><div><h1>Information</h1>{names!==null&&names.length>0&&names.map((name)=>{return(<divkey={name.id}><div>{name.id}</div><div>{name.name}</div></div>);})}</div></>);
Your final
App.jsxshould look like this 👇🏻 -:import{useEffect,useState}from'react';import{createClient}from'urql';import'./App.css';functionApp(){const[names,setNames]=useState([]);constQueryURL="https://api.studio.thegraph.com/query/39471/GraphGuru/version/latest";constclient=createClient({url: QueryURL});constquery=`{ changeNameEvents(first: 5) { id name blockNumber blockTimestamp }}`useEffect(()=>{constgetNames=async()=>{const{ data }=awaitclient.query(query).toPromise();console.log(data);setNames(data.names);}getNames();},[])return(<><div><h1>Information</h1>{names!==null&&names.length>0&&names.map((name)=>{return(<divkey={name.id}><div>{name.id}</div><div>{name.name}</div></div>);})}</div></>);}exportdefaultApp;
Run
npm run devto view the frontend.Make use of The Graph Playground in the dashboard to use different queries and display that data.= (SKY IS THE LIMIT 🌌)
Wohooo! You did it. 🥳 Congratulationssss! Share it with the world.
FOR ANY QUERIES JOIN THE 👉🏻TELEGRAM GROUP👈🏻