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

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

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:

Understanding DappsSO, what are decentralized applications?blog.etereo.io

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

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

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

How to read the balance of your MetaMask wallet with web3.js (2024)
Top Articles
How do I restore a card I had previously added to my device’s Wallet?
How can you evaluate financial risks in a lease agreement?
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
³µ¿Â«»ÍÀÇ Ã¢½ÃÀÚ À̸¸±¸ ¸íÀÎ, ¹Ì±¹ Ķ¸®Æ÷´Ï¾Æ ÁøÃâ - ¿ù°£ÆÄ¿öÄÚ¸®¾Æ
Gore Videos Uncensored
Craigslist Furniture Bedroom Set
Mr Tire Rockland Maine
Ecers-3 Cheat Sheet Free
123 Movies Babylon
Xm Tennis Channel
Walthampatch
Nebraska Furniture Tables
Best Nail Salon Rome Ga
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Average Salary in Philippines in 2024 - Timeular
Earl David Worden Military Service
Pjs Obits
Airtable Concatenate
Bolsa Feels Bad For Sancho's Loss.
Jesus Revolution Showtimes Near Regal Stonecrest
Wood Chipper Rental Menards
2011 Hyundai Sonata 2 4 Serpentine Belt Diagram
By.association.only - Watsonville - Book Online - Prices, Reviews, Photos
Skepticalpickle Leak
897 W Valley Blvd
The Bold and the Beautiful
Ripsi Terzian Instagram
A Man Called Otto Showtimes Near Carolina Mall Cinema
Goodwill Thrift Store & Donation Center Marietta Photos
No Hard Feelings Showtimes Near Tilton Square Theatre
Obsidian Guard's Skullsplitter
Ukg Dimensions Urmc
Game8 Silver Wolf
Wo ein Pfand ist, ist auch Einweg
Leena Snoubar Net Worth
Restored Republic May 14 2023
Gt500 Forums
Wal-Mart 140 Supercenter Products
Fool's Paradise Showtimes Near Roxy Stadium 14
Unitedhealthcare Community Plan Eye Doctors
Memberweb Bw
[Teen Titans] Starfire In Heat - Chapter 1 - Umbrelloid - Teen Titans
Best Conjuration Spell In Skyrim
Ehc Workspace Login
Walmart Careers Stocker
Gw2 Support Specter
25 Hotels TRULY CLOSEST to Woollett Aquatics Center, Irvine, CA
House For Sale On Trulia
Westport gun shops close after confusion over governor's 'essential' business list
300 Fort Monroe Industrial Parkway Monroeville Oh
Black Adam Showtimes Near Cinemark Texarkana 14
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6696

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.