Connect your Dapp to Metamask wallet
Using Metamask, Web3.js, and React.js
Getting Started with Metamask
Below are the main functions that allow us to connect to Metamask:
- connectWalletHandler - To connect to the Metamask wallet
- accountChangedHandler - Changing account from Metamask causes this function work
- getAccountBalance - Get the Balance of the token/coin in your metamask wallet
- chainChangedHandler - Changing the blockchain network in the Metamask causes this function to work
Set Up with GitPod
You can use GitPod for a clean environment with everything set up for you. Just click here:
Set Up Locally
Prefer to run locally? No problem.
Check out the Github Code
Run below commands to install and run the script
bash1 2 3 4
$ npm install $ npm start navigate browser to localhost:3000
javascript1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
import React, {useState} from 'react' import {ethers} from 'ethers' import './WalletCard.css' const WalletCard = () => { const [errorMessage, setErrorMessage] = useState(null); const [defaultAccount, setDefaultAccount] = useState(null); const [userBalance, setUserBalance] = useState(null); const [connButtonText, setConnButtonText] = useState('Connect Wallet'); const connectWalletHandler = () => { if (window.ethereum && window.ethereum.isMetaMask) { console.log('MetaMask Here!'); window.ethereum.request({ method: 'eth_requestAccounts'}) .then(result => { accountChangedHandler(result[0]); setConnButtonText('Wallet Connected'); getAccountBalance(result[0]); }) .catch(error => { setErrorMessage(error.message); }); } else { console.log('Need to install MetaMask'); setErrorMessage('Please install MetaMask browser extension to interact'); } } // update account, will cause component re-render const accountChangedHandler = (newAccount) => { setDefaultAccount(newAccount); getAccountBalance(newAccount.toString()); } const getAccountBalance = (account) => { window.ethereum.request({method: 'eth_getBalance', params: [account, 'latest']}) .then(balance => { setUserBalance(ethers.utils.formatEther(balance)); }) .catch(error => { setErrorMessage(error.message); }); }; const chainChangedHandler = () => { // reload the page to avoid any errors with chain change mid use of application window.location.reload(); } // listen for account changes window.ethereum.on('accountsChanged', accountChangedHandler); window.ethereum.on('chainChanged', chainChangedHandler); return ( <div className='walletCard'> <h4> {"Connect Metamask"} </h4> <button onClick={connectWalletHandler}>{connButtonText}</button> <div className='accountDisplay'> <h3>Address: {defaultAccount}</h3> </div> <div className='balanceDisplay'> <h3>Balance: {userBalance}</h3> </div> {errorMessage} </div> ); } export default WalletCard;