Aarc Cross-Chain API Tutorial

megabyte,AarcCross-Chain
Aarc Cross-Chain API Tutorial

gm! Since last year, web3 narrative has shifted towards Rollups and Rollapps. From a developer's POV, it's good to see the ecosystem growing and building decentralized applications that are scalable to the masses.

As good as this narrative is, it brings its complexities.
New rollups = (New Tokens + Same token) on new chains
Developers are getting frustrated with handling different tokens and chains and, most importantly, assuming which chain and token their users have with them.

There are some tedious solutions to solve these issues:

Aarc provides a single solution to help with these problems with relatively far-better solution.

Aarc Cross-Chain API (opens in a new tab) is a packed API that provides developers with

Also, it does not require changing the application's UI, which helps to provide the best user experience.

Application flow after Aarc Cross-Chain API Integration

Integration of Aarc Cross-Chain API will bring:

To enjoy the same experience, let's get started by building a cross-chain Swap Application.

LFG (🧱,🚀)

Prerequisites

It would be best if you had the understanding of the following before moving ahead with this tutorial:

Getting started

We will be building a Swapping application using Next.js while utilizing the following:

  1. Get the Aarc API Key from the dashboard (opens in a new tab).

    ℹ️ INFO
    Learn how to get the Aarc API Key here (opens in a new tab).
  2. Clone the repo.

    git clone https://github.com/megabyte0x/cross-chain-tutorial-ui

    This will get you the primary UI for a swapping application. UI Image

  3. Set up the environment variables.

    • Create a .env.local file in the root directory and add the following:
      AARC_API_KEY=YOUR_AARC_API_KEY
    • Get the Wallet Connect API Key and paste it into the _app.js file.

Building the API

We already have most of our UI, so let's start building with the Aarc Cross-Chain API.

  1. Initialize the directory.

    Nextjs provides serverless functions to make API integration more accessible and more convenient. So, enter the following command in your terminal.

    mkdir pages/api && cd pages/api 
  2. Fetch the Quotes as the parameters.

    Create a new file named index.ts in the pages/api/quote directory and add the following code:

    import { NextApiRequest, NextApiResponse } from 'next';
     
    const BASE_URL = "https://bridge-swap.aarc.xyz/bridge-swap"; // base url for the cross-chain end point.
     
    const AARC_API_KEY = process.env.AARC_API_KEY ? process.env.AARC_API_KEY : "";
     
    export default async function handler(req: NextApiRequest, res: NextApiResponse) {
      const {
          recipient, routeType, fromChainId, fromTokenAddress, toChainId, toTokenAddress, fromAmount, userAddress
      } = req.query;
     
      const queryParams = new URLSearchParams({
          recipient: recipient as string, // receiver address
          routeType: routeType as string, // criteria to sort the routes
          fromChainId: fromChainId as string, // source network chainId
          fromTokenAddress: fromTokenAddress as string, // source token address on the source network
          toChainId: toChainId as string, // destination network chainId
          toTokenAddress: toTokenAddress as string, // destination token address on the destination network
          fromAmount: fromAmount as string, // amount of token of `fromTokenAddress`
          userAddress: userAddress as string // the owner of the token of `fromTokenAddress`
      });
     
      const endPoint = `${BASE_URL}/quote?${queryParams}`; // final end point for the API
     
      let response;
      let responseInJson;
      let route;
     
      try {
          response = await fetch(endPoint, {
              method: "GET",
              headers: {
                  "x-api-key": AARC_API_KEY,
                  Accept: "application/json",
                  "Content-Type": "application/json",
              },
          });
      } catch (error) {
          console.error("Error fetching Quote data:", error);
      }
     
      if (response != undefined) {
          try {
              responseInJson = await response.json();
              if (responseInJson.success === true)
                  // selecting the first route from the array of routes
                  route = responseInJson.result.routes[0]; 
              else
                  console.error("Error fetching Quote data:", responseInJson);
          } catch (error) {
              console.error("Error parsing JSON response:", error);
          }
      }
     
      res.status(200).json({ route });
    }

    This will fetch the routes available for the cross-chain transactions, and for our tutorial purposes we are returning the first route.

    The response to the above request:
    {
      route: {
        routeId: '84b3df97-6a1a-42c2-8cbc-fd1f2df93bf5',
        isOnlySwapRoute: false,
        fromAmount: '100000000',
        toAmount: '99681045402569142255',
        usedBridgeNames: [ 'hyphen' ],
        minimumGasBalances: { '56': '2800000000000000', '137': '60000000000000000' },
        chainGasBalances: { '56': [Object], '137': [Object] },
        totalUserTx: 1,
        sender: '0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE',
        recipient: '0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE',
        totalGasFeesInUsd: 0.03151520794860174,
        receivedValueInUsd: 99.6495247920514,
        inputValueInUsd: 99.95,
        outputValueInUsd: 99.68104,
        userTxs: [ [Object] ],
        serviceTime: 300,
        maxServiceTime: 7200,
        integratorFee: { amount: '0', asset: [Object] },
        extraData: { rewards: [] }
      }
    }
  3. Fetch the Route Transaction Data

    Create a new file named index.ts in the pages/api/routeTxData directory and add the following code:

    import { NextApiRequest, NextApiResponse } from 'next';
     
    // base url for the cross-chain end point.
    const BASE_URL = "https://bridge-swap.aarc.xyz/bridge-swap";
     
    // AARC API Key. Get it from here: https://dashboard.aarc.xyz/
    const AARC_API_KEY = process.env.AARC_API_KEY ? process.env.AARC_API_KEY : "";
     
    export default async function handler(req: NextApiRequest, res: NextApiResponse) {
      const {
          route
      } = req.body;
     
      const endPoint = `${BASE_URL}/route-transaction-data/`;
     
      let response;
      let responseInJson;
     
      try {
          response = await fetch(endPoint, {
              method: "POST",
              headers: {
                  "x-api-key": AARC_API_KEY,
                  Accept: "application/json",
                  "Content-Type": "application/json",
              },
              body: JSON.stringify({ route: route }),
          });
      } catch (error) {
          console.error("Error fetching Quote data:", error);
      }
     
      if (response != undefined) {
          try {
              responseInJson = await response.json();
          } catch (error) {
              console.error("Error parsing JSON response:", error);
          }
      }
     
      res.status(200).json({ responseInJson });
    }

    This will fetch the route txn data and approval data for the cross-chain transactions.

    • Approval Data: This will be used to provide approval to the bridge to spend the user's tokens.
    • Route Txn Data: This will be used to execute the cross-chain transaction.
    The response to the above request:
    {
      success: true,
      result: {
        userTxType: 'fund-movr',
        txType: 'eth_sendTransaction',
        txData: '0x0000000346e0f5dc000....0000000000000000000000',
        txTarget: '0x3a23F943181408EAC424116Af7b7790c94Cb97a5',
        chainId: 137,
        userTxIndex: 0,
        value: '0x00',
        approvalData: {
          minimumApprovalAmount: '100000000',
          approvalTokenAddress: '0xc2132d05d31c914a87c6611c10748aeb04b58e8f',
          allowanceTarget: '0x3a23F943181408EAC424116Af7b7790c94Cb97a5',
          owner: '0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE'
        }
      },
      statusCode: 200
    }
  4. Generate Approval Transaction Data

    Create a new file named index.ts in the pages/api/generateApprovalTxData directory and add the following code:

    // API for generating the approval transaction data.
    import { NextApiRequest, NextApiResponse } from 'next';
     
    // base url for the cross-chain end point.
    const BASE_URL = "https://bridge-swap.aarc.xyz/bridge-swap";
     
    // AARC API Key. Get it from here: https://dashboard.aarc.xyz/
    const AARC_API_KEY = process.env.AARC_API_KEY ? process.env.AARC_API_KEY : "";
     
    export default async function handler(req: NextApiRequest, res: NextApiResponse) {
      const {
          chainId, owner, allowanceTarget, tokenAddress, amount
      } = req.query;
     
      const queryParams = new URLSearchParams({
          chainId: chainId as string, // Source network chainId
          owner: owner as string, // Address of the owner of the token
          allowanceTarget: allowanceTarget as string, // Address of the spender
          tokenAddress: tokenAddress as string, // Address of the token
          amount: amount as string // The amount of token allowance to be set
      });
     
      // The final endpoint
      const endPoint = `${BASE_URL}/approval-transaction-data?${queryParams}`;
     
      let response;
      let responseInJson;
      let approvalTxData;
     
      try {
          response = await fetch(endPoint, {
              method: "GET",
              headers: {
                  "x-api-key": AARC_API_KEY,
                  Accept: "application/json",
                  "Content-Type": "application/json",
              },
          });
      } catch (error) {
          console.error("Error fetching Approval Tx data:", error);
      }
     
      if (response != undefined) {
          try {
              responseInJson = await response.json();
              if (responseInJson.success === true) {
                  approvalTxData = responseInJson.result;
              }
              else
                  console.error("Error fetching Approval tx data:", responseInJson);
          } catch (error) {
              console.error("Error parsing JSON response:", error);
          }
      }
     
      res.status(200).json({ approvalTxData });
    }

    This will generate the Approval Transaction Data for approving the bridge to spend the user's tokens.

    The response to the above request:
    {
      data: '0x095ea7b30000.....5e100',
      to: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',
      from: '0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE'
    }

We are done with the API integration!


Thanks for building with us!

You can check the complete code here: https://github.com/megabyte0x/aarc-cross-chain-tutorial (opens in a new tab)

Aarc provides several other solutions to improve web3 UX and developer experience. Check out the Aarc Developer Docs (opens in a new tab) for more information.

If you have any doubts or wanna discuss something:

© megabyte.RSS