Building a TokenSwap Subgraph
gm gm gm!!!
Indexing Blockchain Data is really really hard and indexing transactions of something like Uniswap is a lethal task. But The Graph Protocol greatly reduces the complexity of this.
We will be learning how to build, deploy, and play with Subgraph for a simple Token Swapping Contract.
The following are the prerequisites for this tutorial:
Building the Token Swap Contract
This is the Token Swap Contract we will be using for our example.
The following are the main functions we will be focusing on in our subgraph:
addLiquidity(uint256 _tokenAmount)
: This adds liquidity to the pool and emitsGraphKitExchange__LiquidityAdded
event.removeLiquidity(uint256 _amount)
: This removes liquidity from the pool and emitsGraphKitExchange__LiquidityRemoved
event.ethToTokenSwap(uint256 _minTokens)
: This swaps ETH to the Token and emitsGraphKitExchange__ETHToTokenSwap
event.tokenToETHSwap(uint256 tokenSold, uint256 minTokens)
: This swaps Token to ETH and emitsGraphKitExchange__TokenToETHSwap
event.
Having these above events is important as the Graph Nodes will be listening to these events and storing the data (defined in schema) as it gets emitted.
This is the Basic ERC20 Contract we will be using:
Deploy the Contracts
Now deploy these contracts using Remix on Polygon Munbai Testnet.
Token.sol
first and then use that contract address and deploy GraphKitExchange.sol
Head to your Remix IDE and follow the steps:
Connect with the Injected Provider and select Polygon Mumbai Testnet as the network.
Get some TEST MATIC on Mumbai Testnet from the Faucet, here.
Deploy
Token.sol
Copy the above contract and paste it into the Remix file.
Then select the contract and enter the constructor parameters. I have entered
MEGABYTE
,MB
and100000000000000000000
Hit Transact.
Copy the above GraphKitExchange code and paste the content of
GraphKitExchange.sol
in the Remix File.Copy the
Token.sol
Contract AddressSelect the GraphKitExchange.sol, paste the Token Contract Address, and hit Transact.
Verify the contracts on the Mumbai Scan
Learn how to do it here.
Keep both the contract addresses handy, we will be using them shortly.
Here are mine though:
Token Contract: 0xB2887fA56b2601cB5877A99188c3f23731F671F5Exchange Contract: 0xd8F178e60F3A7434F0F4E2519e6C2B89575f8123
Congrats your contracts are ready π₯
Let's deploy the Subgraph for the same π
Build the Subgraph
To build the Subgraph, these are the steps that need to be followed:
Create a Subgraph on Subgraph Studio.
Install the Graph Protocol CLI
Initialize your Subgraphβ
Deploying a Subgraph to Subgraph Studio
Before building the subgraph, if you wanna revisit the concepts of Subgraph check this out ππ»
Create a subgraph on Subgraph Studio
Head to https://thegraph.com/studio
Create Subgraph on Polygon Mumbai Testnet
- Keep the Subgraph Slug and Deploy Key handy.
Install the Graph Protocol CLI
You need to install graph-cli
to use the Subgraph Studio from your system.
Follow the steps for installing it:
Open up your terminal.
Paste the following command and hit ENTER:
yarn global add @graphprotocol/graph-cli
Initialize your Subgraphβ
It's time to start working on your Subgraph:
Create a new directory.
mkdir tokenSwapSubgraph
Initialize the subgraph [Paste your subgraph slug]
graph init --studio <SUBGRAPH_SLUG>
Choose
ethereum
as the protocolEnter the subgraph slug name
Name the directory.
Select
mumbai
as the Ethereum NetworkEnter the Contract Address for
GraphKitExchange.sol
contract.Use the default start block.
Enter the name of the contract, here is
GraphKitExchange
Select
true
for the index contract event as entitiesType
y
for entering a new contract address (forToken.sol
)Type
n
for providing local ABI path.Enter the name of the contract, here is
Token
Here's how it will look in your terminal ππ»
Go to your subgraph directory
cd graphkitexchange
In the directory, you can see the following files:
In the
src
directory you will see that it auto-generated the mappings for your subgraph as per the events in your contracts.
Your Subgraph is ready now. It's time to deploy it.
Deploy the Subgraph
We are almost done! Let's deploy our subgraph.
Authenticate your Graph Studio Key [Get Deploy Key from your subgraph studio]
graph auth --studio <DEPLOY KEY>
Deploy your subgraph with your
subgraph slug
graph deploy --studio graphkitexchange
Enter the
v0.0.1
as the version for your subgraphIn the end, you will see this ππ»
Here you got the subgraph endpoint, https://api.studio.thegraph.com/query/48418/graphkitexchange/v0.0.1
Whoo!!! That's a lot of work! But congrats π€© You deployed your subgraph for a Token Swapping Contract.
Play with the Subgraph using Subgraph Studio
So, it's time to use a decentralized, most effective and inexpensive way of querying the blockchain data.
I'll be using a Subgraph Playground for the same. [Not a frontend dev... hehe]
Creating Txn on the contracts
Before using the subgraph we need to create some transactions so we can query them.
Follow the steps to approve GraphKitExchange
's contract address on Token
Contract.
Open your
Token.sol
contract on Mumbai Scan, and head towards theContract
Tab. Here's mine.Click on the
Write
tab belowContract
tab. Since you have already verified the contract, you will be able to Write transactions on it using the Etherscan UI.Connect your Metamask with the Etherscan by clicking on
Connect to Web3
Now head to the
approve
function and open the modal.Enter the address of the
GraphKitExchange
contract address and the amount inwei
Click on
Write
and confirm the transaction.
Follow these steps to create your first transaction on the GraphKitExchange
Contract:
Open your
GraphKitExchange.sol
contract on Mumbai Scan, and head towards theContract
Tab. Here's mine.Click on the
Write
tab belowContract
tab. Since you have already verified the contract, you will be able to Write transactions on it using the Etherscan UI.Connect your Metamask with the Etherscan by clicking on
Connect to Web3
Click on
addLiquidity
and enter the 5 Matic and 5 MB (in wei) into the respective fields.Click on
Write
and confirm the transaction.You will see a
View Transaction
button, click on it and copy thetransaction hash
Voila! We are good to go with our subgraph.
Querying the Subgraph
Now we have a transaction ready in your GraphKitExchange Contract waiting to be queried by us.
Let's do this, by following these steps:
Head to your deployed Subgraph and select the playground. Mine is https://thegraph.com/studio/subgraph/graphkitexchange/playground
Now paste this into the query
query MyQuery { graphKitExchangeLiquidityAddeds (where: {transactionHash: "Your Transaction Hash"}){ _ethAmount _lpAmount _tokenAmount _user } }
π’In "Your Transaction Hash" be sensible and paste your transaction hash πNow click on that YOUTUBE PLAY BUTTON
As you can see on the right side we got this ππ»
{ "data": { "graphKitExchangeLiquidityAddeds": [{ "_ethAmount": "5000000000000000000", "_lpAmount": "5000000000000000000", "_tokenAmount": "5000000000000000000", "_user": "0x1cb30cb181d7854f91c2410bd037e6f42130e860" }] } }
It has the same data we emitted in our
GraphKitExchange__LiquidityAdded
but we didn't require to have the node setup or to some centralised node provided for this query.Querying with The Graph Protocol is superfast, decentralized and inexpensive.
TASK: Use the rest of the functions and query the subgraph for the events they emit.
Reference Links
I hope you have learned something today with this quite long blog.
If you have any queries, DM me on Twitter, Lenster or LinkedIn.
Happy Learning ππ»
Keep Building π§±π