-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
60 lines (53 loc) · 1.62 KB
/
App.js
1
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
import { useState, useEffect } from 'react';
import {ethers} from "ethers";
import {contractAbi, contractAddress} from './Constant/constants.js';
import Login from './Components/Login';
import Connected from './Components/Connected'
import './App.css';
function App() {
const [provider,setProvider] = useState(null);
const [account,setAccount] = useState(null);
const[isConnected,setIsConnected] = useState(false);
useEffect( () => {
if(window.ethereum){
window.ethereum.on("accountsChanged", handleAccountsChanged);
}
return() => {
if(window.ethereum){
window.ethereum.removeListener("accountsChanged",handleAccountsChanged);
}
}
});
function handleAccountsChanged(accounts){
if(accounts.length > 0 && account != accounts[0]){
setAccount(accounts[0]);
}else{
setIsConnected(false);
setAccount(null);
}
}
async function connectMetamask(){
if(window.ethereum){
try{
const provider = new ethers.providers.Web3Provider(window.ethereum);
setProvider(provider);
await provider.send("eth_requestAccounts",[]);
const signer = provider.getSigner();
const address = await signer.getAddress();
setAccount(address);
console.log("Metamask Connected : ",address);
setIsConnected(true);
}catch(err){
console.error(err);
}
}else{
console.error("Metamask is not detected in the browser");
}
}
return (
<div className="App">
{isConnected ? (<Connected account = {account}/>):(<Login connectWallet = {connectMetamask}/>)}
</div>
);
}
export default App;