March 3, 2023

How to Build a Polygon Portfolio Tracker

Table of Contents

In this article, we will demonstrate how to build a Polygon portfolio tracker by following the steps in the video above. Although the video focuses on Ethereum, we’ll target the Polygon network simply by updating the chain ID value. Also, with two powerful endpoints from Moralis, we will fetch the necessary on-chain data for our portfolio tracker. Let’s look at how simple it is to use the two Web3 Data API endpoints covering the blockchain-related aspect of a Polygon portfolio tracker:

  • getWalletTokenBalances:
const response = await Moralis.EvmApi.token.getWalletTokenBalances({
  address,
  chain,
});
  • getTokenPrice:
const tokenPriceResponse = await Moralis.EvmApi.token.getTokenPrice({
  address,
  chain,
});

To run the above two methods, you also need to initialize Moralis using your Web3 API key:

Moralis.start({
  apiKey: MORALIS_API_KEY,
}

That’s it! It doesn’t have to be more complicated than that when working with Moralis! Now, the above lines of code are the gist of the blockchain-related backend functionalities of portfolio trackers across multiple chains. Thanks to the cross-chain interoperability of Moralis, whether you wish to build a Polygon portfolio tracker or target any other EVM-compatible chain, the above-presented code snippets get the job done!

Cross-Chain Networks for Crypto Portfolio Trackers

Of course, you must implement the above lines of code properly and add suitable frontend components. So, if you wish to learn how to do just that and create a clean Polygon portfolio tracker, make sure to follow our lead. But first, sign up with Moralis! After all, your Moralis account is the gateway to using the fastest Web3 APIs. 

Build a Polygon Portfolio Tracker - Sign Up with Moralis

Overview

Since Polygon continues to be one of the most popular EVM-compatible chains, we want to demonstrate how to build a Polygon portfolio tracker with minimum effort. The core of today’s article is our Polygon portfolio tracker tutorial. This is where you will have a chance to clone our finished code for the Ethereum tracker and apply some minor tweaks to target the Polygon network. In this tutorial, you’ll be using NodeJS to cover the backend and NextJS for the frontend. As far as the fetching of on-chain data goes, Moralis will do the trick with the above-presented snippets of code. You just need to store your Moralis Web3 API key in a “.env” file. 

Aside from guiding you through these minor tweaks, we will also walk you through the most important parts of the code. Once you complete the tutorial, you’ll also have a chance to explore other Moralis tools you can use to create all sorts of powerful dapps (decentralized applications). For example, Moralis offers the Moralis Streams API, enabling you to stream real-time blockchain events directly into the backend of your decentralized application via Web3 webhooks!

All in all, after completing today’s article, you’ll be ready to join the Web3 revolution using your legacy programming skills!     

Polygon Network Logos

Now, before you jump into the tutorial, remember to sign up with Moralis. With a free Moralis account, you gain free access to some of the market’s leading Web3 development resources. In turn, you’ll be able to develop Web3 apps (decentralized applications) and other Web3 projects smarter and more efficiently!

Tutorial: How to Build a Polygon Portfolio Tracker

We decided to use MetaMask as inspiration. Our Polygon portfolio tracker will also display each coin’s portfolio percentage, price, and balance in a connected wallet. Here’s how our example wallet looks:

Landing Page of Our Polygon Portfolio Tracker

For the sake of simplicity, we’ll only focus on the assets table in this article. With that said, it’s time you clone our project that awaits you on the “metamask-asset-table” GitHub repo page:

Polygon Portfolio Tracker GitHub Repo Page

After cloning our repo into your “metamask-portfolio-table” project directory, open that project in Visual Studio Code (VSC). If we first focus on the “backend” folder, you can see it contains the “index.js”, “package-lock.json”, and “package.json” scripts. These scripts will power your NodeJS backend dapp. 

However, before you can run your backend, you need to install all the required dependencies with the npm install command. In addition, you also need to create a “.env” file and populate it with the MORALIS_API_KEY environmental variable. As for the value of this variable, you need to access your Moralis admin area and copy your Web3 API key:

By this point, you should’ve successfully completed the project setup. In turn, we can walk you through the main backend script. This is also where you’ll learn how to change the chain ID to match Polygon.

Easiest Way to Build a Portfolio Tracker with Support for Polygon

If you focus on the backend “index.js” script, you’ll see that it first imports/requires all dependencies and defines local port 5001. The latter is where you’ll be able to run your backend for the sake of this tutorial. So, these are the lines of code that cover those aspects:

const express = require("express");
const app = express();
const port = 5001;
const Moralis = require("moralis").default;
const cors = require("cors");

require("dotenv").config({ path: ".env" });

Next, the script instructs the app to use CORS and Express and to fetch your Web3 API key from the “.env” file:

app.use(cors());
app.use(express.json());

const MORALIS_API_KEY = process.env.MORALIS_API_KEY;

At the bottom of the script, the Moralis.start function uses your API key to initialize Moralis:

Moralis.start({
  apiKey: MORALIS_API_KEY,
}).then(() => {
  app.listen(port, () => {
    console.log(`Listening for API Calls`);
  });
});

Between the lines that define the MORALIS_API_KEY variable and initialize Moralis, the script implements the two EVM API methods presented in the intro. Here are the lines of code that cover that properly:

app.get("/gettokens", async (req, res) => {
  try {
    let modifiedResponse = [];
    let totalWalletUsdValue = 0;
    const { query } = req;

    const response = await Moralis.EvmApi.token.getWalletTokenBalances({
      address: query.address,
      chain: "0x89",
    });

    for (let i = 0; i < response.toJSON().length; i++) {
      const tokenPriceResponse = await Moralis.EvmApi.token.getTokenPrice({
        address: response.toJSON()[i].token_address,
        chain: "0x89",
      });
      modifiedResponse.push({
        walletBalance: response.toJSON()[i],
        calculatedBalance: (
          response.toJSON()[i].balance /
          10 ** response.toJSON()[i].decimals
        ).toFixed(2),
        usdPrice: tokenPriceResponse.toJSON().usdPrice,
      });
      totalWalletUsdValue +=
        (response.toJSON()[i].balance / 10 ** response.toJSON()[i].decimals) *
        tokenPriceResponse.toJSON().usdPrice;
    }

    modifiedResponse.push(totalWalletUsdValue);

    return res.status(200).json(modifiedResponse);
  } catch (e) {
    console.log(`Something went wrong ${e}`);
    return res.status(400).json();
  }
});

Looking at the lines of code above, you can see that we replaced 0x1 with 0x89 for both chain parameters. The former is the chain ID in HEX formation for Ethereum and the latter for Polygon. So, if you aim to build a Polygon portfolio tracker, make sure to go with the latter. You can also see that the getWalletTokenBalances endpoint queries the connected wallet. Then, the getTokenPrice endpoint loops over the results provided by the getWalletTokenBalances endpoint. That way, it covers all the tokens in the connected wallet and fetches their USD prices. It also calculates the total value of the wallet by simply adding the USD values of all tokens. Finally, our backend script pushes the results to the frontend client.

Title - Polygon Portfolio Tracker NextJS

Frontend Code Walkthrough  

As mentioned above, you’ll create the frontend of your Polygon portfolio tracker dapp with NextJS. So, the “nextjs_moralis_auth” folder is essentially a NextJS app. To make it work, you need to install all dependencies using the npm install command. However, make sure you cd into the “nextjs_moralis_auth” folder before running the command. Once you install the dependencies, you can run your frontend and play around with your new Polygon portfolio tracker. But since we want you to get some additional insight from this article, let’s look at the most significant snippets of the code of the various frontend scripts. 

The “signin.jsx” script provides the “Connect MetaMask” button. Once users connect their wallets, the “user.jsx” script takes over. The latter offers a “Sign Out” button and renders the LoggedIn component, both inside the User function:

function User({ user }) {
  return (
    <section className={styles.main}>
      <section className={styles.header}>
        <section className={styles.header_section}>
          <h1>MetaMask Portfolio</h1>
          <button
            className={styles.connect_btn}
            onClick={() => signOut({ redirect: "/" })}
          >
            Sign out
          </button>
        </section>
        <LoggedIn />
      </section>
    </section>
  );
}

If you look at the “loggedIn.js” component, you’ll see that it contains two other components: “tableHeader.js” and “tableContent.js“. As such, these two components make sure the on-chain data fetched by the above-covered backend is neatly presented on the frontend. 

Portfolio Table Components

Here’s a screenshot that clearly shows you what “tableHeader.js” looks like in a browser:

Components and Code - Polygon Portfolio Tracker

As you can see, the “tableHeader.js” script mainly deals with formatting and styling, which is not the point of this tutorial. The same is true for the “tableContent.js” component, which ensures that the table columns match our goals. It also calls the “GetWalletTokens” component:

The “getWalletTokens.js” script gets the on-chain data fetched by the backend. So, are you wondering how to get blockchain data from the backend to frontend? The “getWalletTokens.js” script utilizes useAccount from the wagmi library. The latter extracts the connected address and prompts the backend server with that address via Axios:

  useEffect(() => {
    let response;
    async function getData() {
      response = await axios
        .get(`http://localhost:5001/gettokens`, {
          params: { address },
        })
        .then((response) => {
          console.log(response.data);
          setTokens(response.data);
        });
    }
    getData();
  }, []);

Looking at the above code snippet, you can see that the response variable stores all the on-chain data that the backend fetched. The script also saves response.data in the setTokens state variable. Then, the return function inside the “getWalletTokens.js” script renders the final component: “card.js“:

  return (
    <section>
      {tokens.map((token) => {
        return (
          token.usdPrice && (
            <Card
              token={token}
              total={tokens[3]}
              key={token.walletBalance?.symbol}
            />
          )
        );
      })}
    </section>
  );

While rendering “card.js“, “getWalletTokens.js” passes along some props. The “card.js” component then uses these props to render the details that finally populate the “Assets” table:

Final Build of Our Polygon Portfolio Tracker

Once you successfully run the above-presented backend and frontend, you’ll be able to test your tracker on “localhost:3000“:

As the above screenshot indicates, you must first connect your MetaMask wallet by clicking on the “Connect MetaMask” button.

Note: By default, MetaMask doesn’t include the Polygon network. Thus, make sure to add that network to your MetaMask and switch to it:

Once you connect your wallet, your instance of our portfolio tracker dapp will display your tokens in the following manner:

Finalized Build of Our Polygon Portfolio Tracker

Note: The “Tokens” section of our table is the only one currently active. However, we urge you to use the Moralis resources to add functionality to the “NFTs” and “Transactions” sections as well. 

Beyond Polygon Portfolio Tracker Development

If you took on the above tutorial, you probably remember that our example dapp only utilizes two Moralis Web3 Data API endpoints. However, many other powerful API endpoints are at your disposal when you opt for Moralis. While Moralis specializes in catering Web3 wallets and portfolio trackers, it can be used for all sorts of dapps. 

The entire Moralis fleet encompasses the Web3 Data API, Moralis Streams API, and Authentication API: 

Polygon Portfolio Tracker APIs from Moralis
  • The Web3 Data API contains the following APIs enabling you to fetch any on-chain data the easy way:
    • NFT API
    • Token API
    • Balances API
    • Transaction API
    • Events API
    • Block API
    • DeFi API
    • Resolve API
    • IPFS API
  • With the Moralis Streams API, you can listen to real-time on-chain events for any smart contract and wallet address. That way, you can use on-chain events as triggers for your dapps, bots, etc. Plus, you can use the power of Moralis Streams via the SDK or our user-friendly dashboard.
  • Thanks to the Moralis Web3 Authentication API, you can effortlessly unify Web3 wallets and Web2 accounts in your applications. 

Note: You can explore all of Moralis’ API endpoints and even take them for test rides in our Web3 documentation.

All these tools support all the leading blockchains, including non-EVM-compatible chains, such as Solana and Aptos. As such, you are never stuck to any particular chain when building with Moralis. Plus, thanks to Moralis’ cross-platform interoperability, you can use your favorite legacy dev tools to join the Web3 revolution! 

Aside from enterprise-grade Web3 APIs, Moralis also offers some other useful tools. Two great examples are the gwei to ether calculator and Moralis’ curated crypto faucet list. The former ensures you never get your gwei to ETH conversions wrong. The latter provides links to vetted testnet crypto faucets to easily obtain “test” cryptocurrency.

How to Build a Polygon Portfolio Tracker – Summary

In today’s article, you had an opportunity to follow our lead and create your own Polygon portfolio tracker dapp. By using our scripts, you were able to do so with minimum effort and in a matter of minutes. After all, you only had to create your Moralis account, obtain your Web3 API key and store it in a “.env” file, install the required dependencies, replace 0x1 with 0x89, and run your frontend and backend. You also had a chance to deepen your understanding by exploring the most important scripts behind our example portfolio tracker dapp. Last but not least, you also learned what Moralis is all about and how it can make your Web3 development journey a whole lot simpler.

If you have your own dapp ideas, dive straight into the Moralis docs and BUIDL a new killer dapp. However, if you need to expand your blockchain development knowledge first or get some interesting ideas, make sure to visit the Moralis YouTube channel and the Moralis blog. These places cover all sorts of topics and tutorials that can help you become a Web3 developer for free. For instance, you can explore the superior Alchemy NFT API alternative, the leading Ethereum scaling solutions, learn how to get started in DeFi blockchain development, and much more. Moreover, when it comes to tutorials, you can choose short and simple ones as the one herein, or you can tackle more extensive challenges. A great example of the latter would be to build a Web3 Amazon clone.

Nonetheless, if you and your team need assistance scaling your dapps, reach out to our sales team. Simply select the “For Business” menu option, followed by a click on the “Contact Sales” button:

Market Data API
Build amazing trading and portfolio dapps with this Market Data API. Keep users engaged with up-to-date data!
Market Data API
Related Articles
January 25, 2024

Why Did Crypto Go Up Today? Get Digital Currency Price Triggers via API

September 12, 2022

How to Build a Cronos Dapp in 5 Steps

February 17, 2023

Aptos NFT Tutorial – How to Mint NFTs on Aptos

October 26, 2022

How to Create an NFT Project – Get Started and Launch Successfully

December 30, 2022

Essential Web3 Programming Languages for 2023

October 16, 2023

What is ERC-4337? Full EIP-4337 Guide

December 9, 2022

How to Listen to the Blockchain with Ethers.js

March 8, 2023

Crypto Dashboard Project – Build a Cryptocurrency Portfolio Dashboard with a Template