Monday, August 11, 2025
No Result
View All Result
Crypeto News
Smarter_way_USA
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos
CRYPTO MARKETCAP
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos
CRYPTO MARKETCAP
Crypeto News
No Result
View All Result

How to Build a Polygon Portfolio Tracker

by crypetonews
March 3, 2023
in Web3
Reading Time: 12 mins read
0 0
A A
0
Home Web3
Share on FacebookShare on Twitter


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:

const response = await Moralis.EvmApi.token.getWalletTokenBalances({
address,
chain,
});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!

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 APIToken APIBalances APITransaction APIEvents APIBlock APIDeFi APIResolve APIIPFS 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:



Source link

Tags: BuildPolygonportfolioTracker
Previous Post

Unity Gaming Engine Launches Blockchain and Web3 Integration Options – Blockchain Bitcoin News

Next Post

Bitcoin Long Liquidations Hit Highest Level Since August

Related Posts

Ronin API – Build on Ronin with Moralis
Web3

Ronin API – Build on Ronin with Moralis

May 28, 2025
How to Build NFT Apps on Solana
Web3

How to Build NFT Apps on Solana

May 23, 2025
Solana NFT API – Exploring the Top 2025 NFT API for Solana
Web3

Solana NFT API – Exploring the Top 2025 NFT API for Solana

May 21, 2025
Get Solana Whales – How to Fetch Top Whales of a Solana Token
Web3

Get Solana Whales – How to Fetch Top Whales of a Solana Token

May 19, 2025
Neobank App Development – How to Build a Web3 Neobank
Web3

Neobank App Development – How to Build a Web3 Neobank

May 16, 2025
How to Get Top Solana Token Holders
Web3

How to Get Top Solana Token Holders

May 14, 2025
Next Post
Bitcoin Long Liquidations Hit Highest Level Since August

Bitcoin Long Liquidations Hit Highest Level Since August

What Happened to Bitcoin-Why Did BTC Price Dropped by More Than 5% in Minutes?

What Happened to Bitcoin-Why Did BTC Price Dropped by More Than 5% in Minutes?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

RECOMMENDED

Tron’s Record-Breaking Reliability: Successful Transaction Ratio In 2025 Holding Near 100%
Crypto Updates

Tron’s Record-Breaking Reliability: Successful Transaction Ratio In 2025 Holding Near 100%

by crypetonews
August 11, 2025
0

Trusted Editorial content, reviewed by leading industry experts and seasoned editors. Ad Disclosure Amidst growing blockchain usage, Tron, a leading...

Beeple’s Punks Event Sends Nakamigos NFT Sales Up +3,000%

Beeple’s Punks Event Sends Nakamigos NFT Sales Up +3,000%

August 11, 2025
The Last Great Crypto Bull Run, Why This Alt Season Is Unlike Any Other | by Ben Fairbank | The Capital | Aug, 2025

The Last Great Crypto Bull Run, Why This Alt Season Is Unlike Any Other | by Ben Fairbank | The Capital | Aug, 2025

August 7, 2025
SWL Miner Lets XRP Holders Earn Daily BTC with No Hardware

SWL Miner Lets XRP Holders Earn Daily BTC with No Hardware

August 5, 2025
Corporate Bitcoin Holdings Surge as Adoption Spreads Globally, Report Shows

Corporate Bitcoin Holdings Surge as Adoption Spreads Globally, Report Shows

August 6, 2025
Bitcoin Futures Open Interest Nears B as Options Skew Bullish

Bitcoin Futures Open Interest Nears $79B as Options Skew Bullish

August 6, 2025

Please enter CoinGecko Free Api Key to get this plugin works.
  • Trending
  • Comments
  • Latest
Top 10 NFTs to Watch in 2025 for High-Return Investments

Top 10 NFTs to Watch in 2025 for High-Return Investments

November 22, 2024
Uniswap v4 Teases Major Updates for 2025

Uniswap v4 Teases Major Updates for 2025

January 2, 2025
Enforceable Human-Readable Transactions: Can They Prevent Bybit-Style Hacks?

Enforceable Human-Readable Transactions: Can They Prevent Bybit-Style Hacks?

February 27, 2025
Best Cryptocurrency Portfolio Tracker Apps to Use in 2025

Best Cryptocurrency Portfolio Tracker Apps to Use in 2025

April 24, 2025
What’s the Difference Between Polygon PoS vs Polygon zkEVM?

What’s the Difference Between Polygon PoS vs Polygon zkEVM?

November 20, 2023
FTT jumps 7% as Backpack launches platform to help FTX victims liquidate claims

FTT jumps 7% as Backpack launches platform to help FTX victims liquidate claims

July 18, 2025
XRP Official CRYPTO VOTE LIVE NEWS!🔴GENIUS, CLARITY Act

XRP Official CRYPTO VOTE LIVE NEWS!🔴GENIUS, CLARITY Act

46
IMP UPDATE : BILLS PASSED || BITCOIN DOMINANCE FALLING

IMP UPDATE : BILLS PASSED || BITCOIN DOMINANCE FALLING

38
🚨BIG UPDATE ON WAZIRX || ALT COIN PORTFOLIO NO 1

🚨BIG UPDATE ON WAZIRX || ALT COIN PORTFOLIO NO 1

37
BITCOIN: IT'S HAPPENING NOW (Urgent Update)!!! Bitcoin News Today, Ethereum, Solana, XRP & Chainlink

BITCOIN: IT'S HAPPENING NOW (Urgent Update)!!! Bitcoin News Today, Ethereum, Solana, XRP & Chainlink

33
JUST IN XRP RIPPLE DUBAI NEWS!

JUST IN XRP RIPPLE DUBAI NEWS!

25
Flash USDT | How It Became the Biggest Crypto Scam Worldwide

Flash USDT | How It Became the Biggest Crypto Scam Worldwide

31
штурм 0 000 откроет путь к историческим высотам

штурм $120 000 откроет путь к историческим высотам

August 11, 2025
Tron’s Record-Breaking Reliability: Successful Transaction Ratio In 2025 Holding Near 100%

Tron’s Record-Breaking Reliability: Successful Transaction Ratio In 2025 Holding Near 100%

August 11, 2025
Bitcoin Price Watch: Bulls Eye 5K as Key Resistance Looms

Bitcoin Price Watch: Bulls Eye $125K as Key Resistance Looms

August 11, 2025
Tezos (XTZ) Breaks Above Key Resistance as Bulls Target .03 Level

Tezos (XTZ) Breaks Above Key Resistance as Bulls Target $1.03 Level

August 11, 2025
Revealed: the long-suppressed stories of the world’s oldest slave ship – The Art Newspaper

Revealed: the long-suppressed stories of the world’s oldest slave ship – The Art Newspaper

August 11, 2025
Embargo’s Double Extortion Play Bags M From US Victims

Embargo’s Double Extortion Play Bags $34M From US Victims

August 11, 2025
Crypeto News

Find the latest Bitcoin, Ethereum, blockchain, crypto, Business, Fintech News, interviews, and price analysis at Crypeto News.

CATEGORIES

  • Altcoin
  • Analysis
  • Bitcoin
  • Blockchain
  • Crypto Exchanges
  • Crypto Updates
  • DeFi
  • Ethereum
  • Metaverse
  • Mining
  • NFT
  • Regulations
  • Scam Alert
  • Uncategorized
  • Videos
  • Web3

LATEST UPDATES

  • штурм $120 000 откроет путь к историческим высотам
  • Tron’s Record-Breaking Reliability: Successful Transaction Ratio In 2025 Holding Near 100%
  • Bitcoin Price Watch: Bulls Eye $125K as Key Resistance Looms
  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 Crypeto News.
Crypeto News is not responsible for the content of external sites.

No Result
View All Result
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos

Copyright © 2022 Crypeto News.
Crypeto News is not responsible for the content of external sites.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In