Building a TokenSwap Subgraph

β€’7 min read
Cover Image for 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 emits GraphKitExchange__LiquidityAdded event.

  • removeLiquidity(uint256 _amount): This removes liquidity from the pool and emits GraphKitExchange__LiquidityRemoved event.

  • ethToTokenSwap(uint256 _minTokens): This swaps ETH to the Token and emits GraphKitExchange__ETHToTokenSwap event.

  • tokenToETHSwap(uint256 tokenSold, uint256 minTokens): This swaps Token to ETH and emits GraphKitExchange__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.

πŸ’‘
To learn more about Events in Solidity, check this out.

This is the Basic ERC20 Contract we will be using:


Deploy the Contracts

Now deploy these contracts using Remix on Polygon Munbai Testnet.

⚠
Make sure to deploy Token.sol first and then use that contract address and deploy GraphKitExchange.sol

Head to your Remix IDE and follow the steps:

  1. Connect with the Injected Provider and select Polygon Mumbai Testnet as the network.

  2. Get some TEST MATIC on Mumbai Testnet from the Faucet, here.

  3. Deploy Token.sol

    1. Copy the above contract and paste it into the Remix file.

    2. Then select the contract and enter the constructor parameters. I have entered MEGABYTE,MB and 100000000000000000000

    3. Hit Transact.

  1. Copy the above GraphKitExchange code and paste the content of GraphKitExchange.sol in the Remix File.

  2. Copy the Token.sol Contract Address

  3. Select the GraphKitExchange.sol, paste the Token Contract Address, and hit Transact.

  4. Verify the contracts on the Mumbai Scan

    Learn how to do it here.

  5. Keep both the contract addresses handy, we will be using them shortly.

    Here are mine though:
    Token Contract: 0xB2887fA56b2601cB5877A99188c3f23731F671F5

    Exchange 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

  1. Head to https://thegraph.com/studio

  2. Create Subgraph on Polygon Mumbai Testnet

  1. 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:

  1. Open up your terminal.

  2. 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:

  1. Create a new directory.

    mkdir tokenSwapSubgraph

  2. Initialize the subgraph [Paste your subgraph slug]

    graph init --studio <SUBGRAPH_SLUG>

  3. Choose ethereum as the protocol

  4. Enter the subgraph slug name

  5. Name the directory.

  6. Select mumbai as the Ethereum Network

  7. Enter the Contract Address for GraphKitExchange.sol contract.

  8. Use the default start block.

  9. Enter the name of the contract, here is GraphKitExchange

  10. Select true for the index contract event as entities

  11. Type y for entering a new contract address (for Token.sol)

  12. Type n for providing local ABI path.

  13. Enter the name of the contract, here is Token

Here's how it will look in your terminal πŸ‘‡πŸ»

  1. 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.

  1. Authenticate your Graph Studio Key [Get Deploy Key from your subgraph studio]

     graph auth --studio <DEPLOY KEY>
    
  2. Deploy your subgraph with your subgraph slug

     graph deploy --studio graphkitexchange
    
  3. Enter the v0.0.1 as the version for your subgraph

  4. In 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.

  1. Open your Token.sol contract on Mumbai Scan, and head towards the Contract Tab. Here's mine.

  2. Click on the Write tab below Contract tab. Since you have already verified the contract, you will be able to Write transactions on it using the Etherscan UI.

  3. Connect your Metamask with the Etherscan by clicking on Connect to Web3

  4. Now head to the approve function and open the modal.

  5. Enter the address of the GraphKitExchange contract address and the amount in wei

  6. Click on Write and confirm the transaction.

πŸ˜€
Since we have approved 5 MB to GraphKitExchange Contract it's time to add some Liquidity into the contract.

Follow these steps to create your first transaction on the GraphKitExchange Contract:

  1. Open your GraphKitExchange.sol contract on Mumbai Scan, and head towards the Contract Tab. Here's mine.

  2. Click on the Write tab below Contract tab. Since you have already verified the contract, you will be able to Write transactions on it using the Etherscan UI.

  3. Connect your Metamask with the Etherscan by clicking on Connect to Web3

  4. Click on addLiquidity and enter the 5 Matic and 5 MB (in wei) into the respective fields.

  5. Click on Write and confirm the transaction.

  6. You will see a View Transaction button, click on it and copy the transaction 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:

  1. Head to your deployed Subgraph and select the playground. Mine is https://thegraph.com/studio/subgraph/graphkitexchange/playground

  2. 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 πŸ˜‚

  3. 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.

  4. 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.

😁
To learn more about The Graph Protocol, join me with The Graph India Community

If you have any queries, DM me on Twitter, Lenster or LinkedIn.

Happy Learning πŸ™ŒπŸ»

Keep Building πŸ§±πŸš€