Saturday, May 23, 2026
  • Login
SB Crypto Guru News- latest crypto news, NFTs, DEFI, Web3, Metaverse
No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS
CRYPTO MARKETCAP
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS
No Result
View All Result
SB Crypto Guru News- latest crypto news, NFTs, DEFI, Web3, Metaverse
No Result
View All Result

Easy methods to Construct a Polygon Portfolio Tracker

by SB Crypto Guru News
March 5, 2023
in Web3
Reading Time: 14 mins read
0 0
A A
0


On this article, we’ll show find out how to construct a Polygon portfolio tracker by following the steps within the video above. Though the video focuses on Ethereum, we’ll goal the Polygon community just by updating the chain ID worth. Additionally, with two highly effective endpoints from Moralis, we’ll fetch the required on-chain knowledge for our portfolio tracker. Let’s have a look at how easy it’s to make use of the 2 Web3 Information API endpoints protecting the blockchain-related facet of a Polygon portfolio tracker:

const response = await Moralis.EvmApi.token.getWalletTokenBalances({
  deal with,
  chain,
});
const tokenPriceResponse = await Moralis.EvmApi.token.getTokenPrice({
  deal with,
  chain,
});

To run the above two strategies, you additionally have to initialize Moralis utilizing your Web3 API key:

Moralis.begin({
  apiKey: MORALIS_API_KEY,
}

That’s it! It doesn’t must be extra sophisticated than that when working with Moralis! Now, the above strains of code are the gist of the blockchain-related backend functionalities of portfolio trackers throughout a number of chains. Due to the cross-chain interoperability of Moralis, whether or not you want to construct a Polygon portfolio tracker or goal every other EVM-compatible chain, the above-presented code snippets get the job accomplished!

Cross-Chain Networks for Crypto Portfolio Trackers

In fact, you have to implement the above strains of code correctly and add appropriate frontend parts. So, if you happen to want to learn to just do that and create a clear Polygon portfolio tracker, be sure to comply with our lead. However first, join with Moralis! In any case, your Moralis account is the gateway to utilizing the quickest Web3 APIs. 

Build a Polygon Portfolio Tracker - Sign Up with Moralis

Overview

Since Polygon continues to be one of the crucial common EVM-compatible chains, we wish to show find out how to construct a Polygon portfolio tracker with minimal effort. The core of immediately’s article is our Polygon portfolio tracker tutorial. That is the place you should have an opportunity to clone our completed code for the Ethereum tracker and apply some minor tweaks to focus on the Polygon community. On this tutorial, you’ll be utilizing NodeJS to cowl the backend and NextJS for the frontend. So far as the fetching of on-chain knowledge goes, Moralis will do the trick with the above-presented snippets of code. You simply have to retailer your Moralis Web3 API key in a “.env” file. 

Apart from guiding you thru these minor tweaks, we may also stroll you thru crucial elements of the code. When you full the tutorial, you’ll even have an opportunity to discover different Moralis instruments you should use to create all kinds of highly effective dapps (decentralized purposes). For instance, Moralis affords the Moralis Streams API, enabling you to stream real-time blockchain occasions straight into the backend of your decentralized utility by way of Web3 webhooks!

All in all, after finishing immediately’s article, you’ll be prepared to affix the Web3 revolution utilizing your legacy programming expertise!     

Polygon Network Logos

Now, earlier than you soar into the tutorial, keep in mind to enroll with Moralis. With a free Moralis account, you acquire free entry to a number of the market’s main Web3 growth sources. In flip, you’ll be capable to develop Web3 apps (decentralized purposes) and different Web3 initiatives smarter and extra effectively!

Tutorial: Easy methods to Construct a Polygon Portfolio Tracker

We determined to make use of MetaMask as inspiration. Our Polygon portfolio tracker may also show every coin’s portfolio proportion, worth, and steadiness in a related pockets. Right here’s how our instance pockets appears:

Landing Page of Our Polygon Portfolio Tracker

For the sake of simplicity, we’ll solely deal with the belongings desk on this article. With that stated, it’s time you clone our venture that awaits you on the “metamask-asset-table” GitHub repo web page:

Polygon Portfolio Tracker GitHub Repo Page

After cloning our repo into your “metamask-portfolio-table” venture listing, open that venture in Visible Studio Code (VSC). If we first deal with the “backend” folder, you may see it accommodates the “index.js”, “package-lock.json”, and “bundle.json” scripts. These scripts will energy your NodeJS backend dapp. 

Nonetheless, earlier than you may run your backend, you want to set up all of the required dependencies with the npm set up command. As well as, you additionally have to create a “.env” file and populate it with the MORALIS_API_KEY environmental variable. As for the worth of this variable, you want to entry your Moralis admin space and replica your Web3 API key:

By this level, you must’ve efficiently accomplished the venture setup. In flip, we are able to stroll you thru the primary backend script. That is additionally the place you’ll learn to change the chain ID to match Polygon.

Best Technique to Construct a Portfolio Tracker with Help for Polygon

In case you deal with the backend “index.js” script, you’ll see that it first imports/requires all dependencies and defines native port 5001. The latter is the place you’ll be capable to run your backend for the sake of this tutorial. So, these are the strains of code that cowl these features:

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

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

Subsequent, the script instructs the app to make use of CORS and Categorical and to fetch your Web3 API key from the “.env” file:

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

const MORALIS_API_KEY = course of.env.MORALIS_API_KEY;

On the backside of the script, the Moralis.begin perform makes use of your API key to initialize Moralis:

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

Between the strains that outline the MORALIS_API_KEY variable and initialize Moralis, the script implements the 2 EVM API strategies introduced within the intro. Listed here are the strains of code that cowl that correctly:

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

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

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

    modifiedResponse.push(totalWalletUsdValue);

    return res.standing(200).json(modifiedResponse);
  } catch (e) {
    console.log(`One thing went unsuitable ${e}`);
    return res.standing(400).json();
  }
});

Trying on the strains of code above, you may see that we changed 0x1 with 0x89 for each chain parameters. The previous is the chain ID in HEX formation for Ethereum and the latter for Polygon. So, if you happen to purpose to construct a Polygon portfolio tracker, be sure to go together with the latter. You can even see that the getWalletTokenBalances endpoint queries the related pockets. Then, the getTokenPrice endpoint loops over the outcomes supplied by the getWalletTokenBalances endpoint. That manner, it covers all of the tokens within the related pockets and fetches their USD costs. It additionally calculates the full worth of the pockets by merely including the USD values of all tokens. Lastly, our backend script pushes the outcomes to the frontend shopper.

Title - Polygon Portfolio Tracker NextJS

Frontend Code Walkthrough  

As talked about above, you’ll create the frontend of your Polygon portfolio tracker dapp with NextJS. So, the “nextjs_moralis_auth” folder is actually a NextJS app. To make it work, you want to set up all dependencies utilizing the npm set up command. Nonetheless, be sure you cd into the “nextjs_moralis_auth” folder earlier than working the command. As soon as you put in the dependencies, you may run your frontend and mess around along with your new Polygon portfolio tracker. However since we would like you to get some further perception from this text, let’s have a look at essentially the most vital snippets of the code of the assorted frontend scripts. 

The “signin.jsx” script offers the “Join MetaMask” button. As soon as customers join their wallets, the “consumer.jsx” script takes over. The latter affords a “Signal Out” button and renders the LoggedIn element, each contained in the Consumer perform:

perform Consumer({ consumer }) {
  return (
    <part className={kinds.foremost}>
      <part className={kinds.header}>
        <part className={kinds.header_section}>
          <h1>MetaMask Portfolio</h1>
          <button
            className={kinds.connect_btn}
            onClick={() => signOut({ redirect: "/" })}
          >
            Signal out
          </button>
        </part>
        <LoggedIn />
      </part>
    </part>
  );
}

In case you have a look at the “loggedIn.js” element, you’ll see that it accommodates two different parts: “tableHeader.js” and “tableContent.js“. As such, these two parts be sure the on-chain knowledge fetched by the above-covered backend is neatly introduced on the frontend. 

Portfolio Desk Parts

Right here’s a screenshot that clearly reveals you what “tableHeader.js” appears like in a browser:

Components and Code - Polygon Portfolio Tracker

As you may see, the “tableHeader.js” script primarily offers with formatting and styling, which isn’t the purpose of this tutorial. The identical is true for the “tableContent.js” element, which ensures that the desk columns match our targets. It additionally calls the “GetWalletTokens” element:

The “getWalletTokens.js” script will get the on-chain knowledge fetched by the backend. So, are you questioning find out how to get blockchain knowledge from the backend to frontend? The “getWalletTokens.js” script makes use of useAccount from the wagmi library. The latter extracts the related deal with and prompts the backend server with that deal with by way of Axios:

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

Trying on the above code snippet, you may see that the response variable shops all of the on-chain knowledge that the backend fetched. The script additionally saves response.knowledge within the setTokens state variable. Then, the return perform contained in the “getWalletTokens.js” script renders the ultimate element: “card.js“:

  return (
    <part>
      {tokens.map((token) => {
        return (
          token.usdPrice && (
            <Card
              token={token}
              whole={tokens[3]}
              key={token.walletBalance?.image}
            />
          )
        );
      })}
    </part>
  );

Whereas rendering “card.js“, “getWalletTokens.js” passes alongside some props. The “card.js” element then makes use of these props to render the main points that lastly populate the “Property” desk:

Ultimate Construct of Our Polygon Portfolio Tracker

When you efficiently run the above-presented backend and frontend, you’ll be capable to take a look at your tracker on “localhost:3000“:

Because the above screenshot signifies, you have to first join your MetaMask pockets by clicking on the “Join MetaMask” button.

Notice: By default, MetaMask doesn’t embody the Polygon community. Thus, be sure so as to add that community to your MetaMask and change to it:

When you join your pockets, your occasion of our portfolio tracker dapp will show your tokens within the following method:

Finalized Build of Our Polygon Portfolio Tracker

Notice: The “Tokens” part of our desk is the one one presently energetic. Nonetheless, we urge you to make use of the Moralis sources so as to add performance to the “NFTs” and “Transactions” sections as properly. 

Past Polygon Portfolio Tracker Growth

In case you took on the above tutorial, you most likely keep in mind that our instance dapp solely makes use of two Moralis Web3 Information API endpoints. Nonetheless, many different highly effective API endpoints are at your disposal while you go for Moralis. Whereas Moralis makes a speciality of catering Web3 wallets and portfolio trackers, it may be used for all kinds of dapps. 

All the Moralis fleet encompasses the Web3 Information API, Moralis Streams API, and Authentication API: 

Polygon Portfolio Tracker APIs from Moralis
  • The Web3 Information API accommodates the next APIs enabling you to fetch any on-chain knowledge the straightforward manner:
    • NFT API
    • Token API
    • Balances API
    • Transaction API
    • Occasions API
    • Block API
    • DeFi API
    • Resolve API
    • IPFS API
  • With the Moralis Streams API, you may take heed to real-time on-chain occasions for any good contract and pockets deal with. That manner, you should use on-chain occasions as triggers to your dapps, bots, and many others. Plus, you should use the ability of Moralis Streams by way of the SDK or our user-friendly dashboard.
  • Due to the Moralis Web3 Authentication API, you may effortlessly unify Web3 wallets and Web2 accounts in your purposes. 

Notice: You may discover all of Moralis’ API endpoints and even take them for take a look at rides in our Web3 documentation.

All these instruments assist all of the main blockchains, together with non-EVM-compatible chains, similar to Solana and Aptos. As such, you’re by no means caught to any explicit chain when constructing with Moralis. Plus, because of Moralis’ cross-platform interoperability, you should use your favourite legacy dev instruments to affix the Web3 revolution! 

Apart from enterprise-grade Web3 APIs, Moralis additionally affords another helpful instruments. Two nice examples are the gwei to ether calculator and Moralis’ curated crypto faucet checklist. The previous ensures you by no means get your gwei to ETH conversions unsuitable. The latter offers hyperlinks to vetted testnet crypto taps to simply receive “take a look at” cryptocurrency.

Easy methods to Construct a Polygon Portfolio Tracker – Abstract

In immediately’s article, you had a chance to comply with our lead and create your individual Polygon portfolio tracker dapp. By utilizing our scripts, you had been in a position to take action with minimal effort and in a matter of minutes. In any case, you solely needed to create your Moralis account, receive your Web3 API key and retailer it in a “.env” file, set up the required dependencies, change 0x1 with 0x89, and run your frontend and backend. You additionally had an opportunity to deepen your understanding by exploring crucial scripts behind our instance portfolio tracker dapp. Final however not least, you additionally discovered what Moralis is all about and the way it could make your Web3 growth journey an entire lot easier.

When you have your individual dapp concepts, dive straight into the Moralis docs and BUIDL a brand new killer dapp. Nonetheless, if you want to develop your blockchain growth data first or get some attention-grabbing concepts, be sure to go to the Moralis YouTube channel and the Moralis weblog. These locations cowl all kinds of matters and tutorials that may enable you to change into a Web3 developer without cost. For example, you may discover the superior Alchemy NFT API various, the main Ethereum scaling options, learn to get began in DeFi blockchain growth, and way more. Furthermore, relating to tutorials, you may select quick and easy ones because the one herein, or you may deal with extra in depth challenges. An important instance of the latter could be to construct a Web3 Amazon clone.

Nonetheless, if you happen to and your group want help scaling your dapps, attain out to our gross sales group. Merely choose the “For Enterprise” menu choice, adopted by a click on on the “Contact Gross sales” button:



Source link

Tags: Bitcoin NewsBuildCrypto NewsCrypto UpdatesLatest News on CryptoPolygonPortfolioSB Crypto Guru NewsTracker
Previous Post

Unity Gaming Engine Launches Blockchain and Web3 Integration Choices – Blockchain Bitcoin Information

Next Post

Bitcoin Lengthy Liquidations Hit Highest Stage Since August

Related Posts

Exploring Moonbeam – Why Build on Moonbeam? – Moralis Web3

Exploring Moonbeam – Why Build on Moonbeam? – Moralis Web3

by SB Crypto Guru News
September 11, 2024
0

In today’s tutorial, we’ll explore Moonbeam and the network’s benefits to explain why you might want to build on the...

Chiliz Chain Deep Dive – Why Build on Chiliz Chain? – Moralis Web3

Chiliz Chain Deep Dive – Why Build on Chiliz Chain? – Moralis Web3

by SB Crypto Guru News
September 10, 2024
0

In today’s article, we’ll explore the benefits of Chiliz to explain why you might want to build on this network....

NFT Rarity API – How to Get an NFT’s Rarity Ranking – Moralis Web3

NFT Rarity API – How to Get an NFT’s Rarity Ranking – Moralis Web3

by SB Crypto Guru News
September 6, 2024
0

Looking for the easiest way to get an NFT’s rarity ranking? If so, you’ve come to the right place. In...

How to Get Token Prices with an RPC Node – Moralis Web3

How to Get Token Prices with an RPC Node – Moralis Web3

by SB Crypto Guru News
September 3, 2024
0

Are you looking for an easy way to get token prices with an RPC node? If so, you’ve come to...

How to Get NFT Balances with One RPC Call – Moralis Web3

How to Get NFT Balances with One RPC Call – Moralis Web3

by SB Crypto Guru News
August 30, 2024
0

Did you know that with Moralis’ next-generation nodes, you can get NFT balances with just one RPC call? Our Extended...

Load More
Next Post
Bitcoin Lengthy Liquidations Hit Highest Stage Since August

Bitcoin Lengthy Liquidations Hit Highest Stage Since August

Funding Fund Targeted on Crypto Mining to Be Created in Russia – Mining Bitcoin Information

Funding Fund Targeted on Crypto Mining to Be Created in Russia – Mining Bitcoin Information

Facebook Twitter LinkedIn Tumblr RSS

CATEGORIES

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

SITE MAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 - SB Crypto Guru News.
SB Crypto Guru 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
No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • WEB3
  • METAVERSE
  • REGULATIONS
  • SCAM ALERT
  • ANALYSIS

Copyright © 2022 - SB Crypto Guru News.
SB Crypto Guru News is not responsible for the content of external sites.