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

Rafael Etereo
Etéreo
Published in
4 min readMar 28, 2021

--

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 is Ethereum, we recommend checking out this blog post:

You will be able to find the source code for this example at https://github.com/etereo-io/web3-example

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:

First of all, we will install 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
yarn add web3

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!');
}

After detecting that the user has MetaMask installed what we are going to do is 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 did that, we are already connected to the wallet, which means that we can access the current balance.

In order to list the wallet accounts, we will use web3.eth.getAccounts

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 also can be used to identify a user.

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

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

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

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

Well, that’s great! We already can see our Ethereum balance. Let’s try now to get our ERC20 tokens and the balance of each of them.

In Ethereum in order to get a balance of a token we need to know two different things:

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

We can see both things in Etherscan, as an example for the HEX token

https://etherscan.io/token/0x2b591e99afe9f32eaa6214f7b7629768c40eeb39#readContract

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

The ERC20 is a standard for smart contracts that defines a common interface. So, as long as we are dealing with ERC20 tokens, we are going to find this method available in all of them. For this example, we will use this ABI JSON.

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

In our case, we just need to create a list of tokens that we want to see the balance of (unfortunately we can not get all the tokens the wallet has access to, we need to know first the smart contract addresses), and for each of them, we get the balance.

For example, the following list shows the addresses of the smart contracts for HEX, COVAL and DAI ERC20 tokens.

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

And for each of them we can do :

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

Where “address” is the MetaMask wallet address that we extracted at the beginning.

And, that’s it!

  • We 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:

If you are looking for a software team that can help you build DApps. Take a look at Etéreo

--

--