forked from ShreyaVishesh/P2P_Express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwallet.js
103 lines (78 loc) · 2.61 KB
/
wallet.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import {React, useState, useEffect} from 'react'
import {ethers} from 'ethers'
import styles from './Wallet.module.css'
import electo_token_abi from './electo_token_abi.json'
import Interaction from './Interaction';
const Wallet = () => {
// ganache-cli address
const contractAddress = '0x9C6bA4D61Cd0696a865A439Fc569c556326Eb984';
const [tokenName, setTokenName] = useState("Token");
const [connButtonText, setConnButtonText] = useState("Connect Wallet");
const [errorMessage, setErrorMessage] = useState(null);
const [defaultAccount, setDefaultAccount] = useState(null);
const [balance, setBalance] = useState(null);
const [provider, setProvider] = useState(null);
const [signer, setSigner] = useState(null);
const [contract, setContract] = useState(null);
const connectWalletHandler = () => {
if (window.ethereum && window.ethereum.isMetaMask) {
window.ethereum.request({method: 'eth_requestAccounts'})
.then(result => {
accountChangedHandler(result[0]);
setConnButtonText('Wallet Connected');
})
.catch(error => {
setErrorMessage(error.message);
})
} else {
console.log('need to install metamask');
setErrorMessage('Please install MetaMask');
}
}
const accountChangedHandler = (newAddress) => {
setDefaultAccount(newAddress);
updateEthers();
}
const updateEthers = () => {
let tempProvider = new ethers.providers.Web3Provider(window.ethereum);
let tempSigner = tempProvider.getSigner();
let tempContract = new ethers.Contract(contractAddress, electo_token_abi, tempSigner)
setProvider(tempProvider);
setSigner(tempSigner);
setContract(tempContract);
}
useEffect(() => {
if (contract != null) {
updateBalance();
updateTokenName();
}
}, [contract])
const updateBalance = async () => {
let balanceBigN = await contract.balanceOf(defaultAccount);
let balanceNumber = balanceBigN.toNumber();
let decimals = await contract.decimals();
let tokenBalance = balanceNumber / Math.pow(10, decimals);
setBalance(tokenBalance);
console.log(tokenBalance);
}
const updateTokenName = async () => {
setTokenName(await contract.name());
}
return (
<div>
<h2> {tokenName + " ERC-20 Wallet"} </h2>
<button className={styles.button6} onClick={connectWalletHandler}>{connButtonText}</button>
<div className = {styles.walletCard}>
<div>
<h3>Address: {defaultAccount}</h3>
</div>
<div>
<h3>{tokenName} Balance: {balance}</h3>
</div>
{errorMessage}
</div>
<Interaction contract={contract}/>
</div>
);
}
export default Wallet;