How to connect and get the balance from a Metamask wallet on the Polygon chain in React.js

Viewed 1281

What is the best way to do the following actions on a DAAP developed with React.js?

Actions:

  • connect/disconnect... on Metamask wallet
  • get accounts
  • get balance on MATIC from this account
  • get ERC720 tokens from this account

Minimum requirements (objetives):

  • built-in on react.js
  • just need metamask integration
  • need to run on the Polygon chain network

I am very confused becasue I have tried a lot of libraries like web3.js, ether.js, web3-react... and I did not find a proper solution. Anyone can ilustrate me and tell me the best approach?

1 Answers

You can use basic metamask functions to connect with metamask and getting the account details, and for balance part you can either use the web3 calls from web3js library or for ease use the maticjs library from polygon. Writing this quick snippet for fetching balance using maticjs. Checkout the full POC for react DApp at https://github.com/ankitboghra/polygon-dapp-poc

import { POSClient, use } from "@maticnetwork/maticjs"
import { Web3ClientPlugin } from '@maticnetwork/maticjs-web3'

use(Web3ClientPlugin)

await posClient.init({
      network: networkName,  // 'testnet' or 'mainnet'
      version: networkVersion, // 'mumbai' or 'v1'
      parent: {
        provider: mainProvider,
        defaultConfig: {
          from: currentAccount
        }
      },
      child: {
        provider: maticProvider,
        defaultConfig: {
          from: currentAccount
        }
      }
    });


const erc20Token = posClient.erc20(tokenAddress, false);
const balance = await erc20Token.getBalance(currentAccount)
Related