Read the balance of your MetaMask wallet with web3.js

RafaelRafaelMarch 28, 2021
Read the balance of your MetaMask wallet with web3.js

How to read the balance of your MetaMask wallet with web3.js

Today we are going to do a simple tutorial on how to connect to your MetaMask wallet in a JavaScript browser application and show the balance of your wallet and tokens.

If you don't know what Ethereum is, we recommend checking out this blog post:

Understanding Dapps

You will be able to find the source code for this example at GitHub.

For this tutorial, we are going to use NextJS to build a front-end application and Web3.js to connect to our wallet. We are going to skip the steps to set up the project. If you want to kick-start a NextJS project, please take a look at this post:

How to setup a NextJS Project with TypeScript

Installing Web3

Web3.js is a library that offers many capabilities to interact with the Ethereum network. Some of the things you can do with Web3.js are:

  • Sign transactions
  • Read balances
  • Create wallets
  • Estimate gas costs
  • Subscribe to smart contract events
  • Invoke smart contract methods

To install it, run:

yarn add web3

Detecting MetaMask

MetaMask is going to inject an ethereum object into the browser. We can, and should, use this to detect if MetaMask is installed. Otherwise, we can prompt the user to install it.

if (typeof window.ethereum !== "undefined") {
  console.log("MetaMask is installed!");
}

Connecting to MetaMask

After detecting that the user has MetaMask installed, we will instantiate our version of Web3 with the provider information from the global object.

if (typeof window.ethereum !== "undefined") {
  // Instance web3 with the provided information
  web3 = new Web3(window.ethereum);
  try {
    // Request account access
    await window.ethereum.enable();
    return true;
  } catch (e) {
    // User denied access
    return false;
  }
}

Once we do that, we are already connected to the wallet, which means that we can access the current balance.

Getting Wallet Accounts

To list the wallet accounts, we use:

var accounts = await web3.eth.getAccounts();

This will return a list of addresses. The Ethereum address is the first 20 bytes of the SHA3 hashed public key. You can use this address to send funds to an account or to read the internal state. It can also be used to identify a user.

Reading ETH Balance

We can read the balance of an address by using the following method:

web3.eth
  .getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
  .then(console.log);

Output:

"1000000000000"

This will return the balance in wei. wei is the smallest unit in the ether values scale. It will be used for calculations, but it's recommended to transform the value into ether to represent it to the user.

web3.utils.fromWei(number [, unit]);

Getting ERC20 Token Balances

To get the balance of a token, we need to know two things:

  • The smart contract address
  • The contract ABI (Application Binary Interface) describing the available methods for the contract

You can find both in Etherscan. For example, for the HEX token:

HEX Token on Etherscan

We do not need to use the full ABI definition to interact with a smart contract. In this case, we will use only the balanceOf method to extract the balance of a certain token.

[
  {
    "constant": true,
    "inputs": [
      {
        "name": "_owner",
        "type": "address"
      }
    ],
    "name": "balanceOf",
    "outputs": [
      {
        "name": "balance",
        "type": "uint256"
      }
    ],
    "payable": false,
    "type": "function"
  }
]

We need to create a list of tokens we want to check the balance of (unfortunately, we cannot get all the tokens in the wallet automatically; we must know the smart contract addresses first).

Example list of token smart contract addresses for HEX, COVAL, and DAI ERC20 tokens:

const tokenAddresses = [
  {
    address: "0x2b591e99afe9f32eaa6214f7b7629768c40eeb39",
    token: "HEX",
  },
  {
    address: "0x3d658390460295fb963f54dc0899cfb1c30776df",
    token: "COVAL",
  },
  {
    address: "0x6b175474e89094c44da98b954eedeac495271d0f",
    token: "DAI",
  },
];

For each token, we can retrieve the balance using:

const tokenInst = new web3.eth.Contract(tokenABI, token.address);
const balance = await tokenInst.methods.balanceOf(address).call();

Where address is the MetaMask wallet address we extracted at the beginning.

Summary

  • Connected to our Wallet
  • Extracted the ETH available
  • Extracted the balance of our ERC20 tokens

If you want to see the full working example, take a look at the repository:

etereo-io/web3-example