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
Frontiers | Prediction of problem gambling by demographics, gaming behavior and psychological correlates among gacha gamers: A cross-sectional online survey in Chinese young adults
Photon on SOL | Photon Trading
Antisis City/Antisis City Gym
Average Jonas Wife
Melson Funeral Services Obituaries
Fat Hog Prices Today
Horoscopes and Astrology by Yasmin Boland - Yahoo Lifestyle
Soap2Day Autoplay
Sinai Web Scheduler
Southland Goldendoodles
Youtube Combe
LA Times Studios Partners With ABC News on Randall Emmett Doc Amid #Scandoval Controversy
Ave Bradley, Global SVP of design and creative director at Kimpton Hotels & Restaurants | Hospitality Interiors
What Is A Good Estimate For 380 Of 60
Rainfall Map Oklahoma
Current Time In Maryland
Panorama Charter Portal
Log in or sign up to view
Rachel Griffin Bikini
Star Wars: Héros de la Galaxie - le guide des meilleurs personnages en 2024 - Le Blog Allo Paradise
Comics Valley In Hindi
How To Cancel Goodnotes Subscription
Andhrajyothy Sunday Magazine
Ruben van Bommel: diepgang en doelgerichtheid als wapens, maar (nog) te weinig rendement
Labby Memorial Funeral Homes Leesville Obituaries
bode - Bode frequency response of dynamic system
Iroquois Amphitheater Louisville Ky Seating Chart
Ecampus Scps Login
Bfsfcu Truecar
Housing Intranet Unt
Street Fighter 6 Nexus
Eaccess Kankakee
Autotrader Bmw X5
MethStreams Live | BoxingStreams
Southern Democrat vs. MAGA Republican: Why NC governor race is a defining contest for 2024
Poster & 1600 Autocollants créatifs | Activité facile et ludique | Poppik Stickers
Bee And Willow Bar Cart
Bismarck Mandan Mugshots
Poe Flameblast
Mohave County Jobs Craigslist
Uc Santa Cruz Events
Anguilla Forum Tripadvisor
Best Restaurants Minocqua
Letter of Credit: What It Is, Examples, and How One Is Used
The best specialist spirits store | Spirituosengalerie Stuttgart
60 Days From May 31
Pgecom
Playboi Carti Heardle
Union Supply Direct Wisconsin
Walmart Front Door Wreaths
O.c Craigslist
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.