Skip to content

Instantly share code, notes, and snippets.

@Ajinkgupta
Created December 19, 2022 10:42
Show Gist options
  • Save Ajinkgupta/19184710aee1941a5f41ffc37e2c193c to your computer and use it in GitHub Desktop.
Save Ajinkgupta/19184710aee1941a5f41ffc37e2c193c to your computer and use it in GitHub Desktop.
connect metamask
import { useState, useEffect } from 'react';
import { ethers } from 'ethers';
import { QRCodeCanvas } from "qrcode.react";
import { randomBytes } from 'ethers/lib/utils';
function App() {
const [haveMetamask, sethaveMetamask] = useState(true);
const [accountAddress, setAccountAddress] = useState('');
const [accountBalance, setAccountBalance] = useState('');
const [isConnected, setIsConnected] = useState(false);
const { ethereum } = window;
const provider = new ethers.providers.Web3Provider(window.ethereum);
useEffect(() => {
const { ethereum } = window;
const checkMetamaskAvailability = async () => {
if (!ethereum) {
sethaveMetamask(false);
}
sethaveMetamask(true);
};
checkMetamaskAvailability();
}, []);
const connectWallet = async () => {
try {
if (!ethereum) {
sethaveMetamask(false);
}
const accounts = await ethereum.request({
method: 'eth_requestAccounts',
});
let balance = await provider.getBalance(accounts[0]);
let bal = ethers.utils.formatEther(balance);
setAccountAddress(accounts[0]);
setAccountBalance(bal);
setIsConnected(true);
} catch (error) {
setIsConnected(false);
}
};
return (
<div className="App">
<div class="flex items-center justify-center h-screen">
<div class="bg-indigo-800 text-white font-bold rounded-lg border shadow-lg p-10">
<header className="App-header">
{haveMetamask ? (
<div className="App-header">
{isConnected ? (
<div className="card">
<div className="card-row">
<h3>Wallet Address:</h3>
<p>
{accountAddress.slice(0, 4)}...
{accountAddress.slice(38, 42)}
</p>
<QRCodeCanvas
id="qrCode"
value={accountAddress}
size={300}
bgColor={"#00ff00"}
level={"H"}
/>
</div>
<div className="card-row">
<h3>Wallet Balance:</h3>
<p>{accountBalance}</p>
</div>
</div>
) : (
<h1>By Ram</h1>
)}
{isConnected ? (
<p className="info">🎉 Connected Successfully</p>
) : (
<button className="btn" onClick={connectWallet}>
Connect
</button>
)}
</div>
) : (
<p>Please Install MataMask</p>
)}
</header>
</div>
</div>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment