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
Shell
$ npm install
$ npm start
navigate browser to localhost:3000
Javascript
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;
Comments
Post a Comment