-
Notifications
You must be signed in to change notification settings - Fork 0
/
etherium.js
49 lines (44 loc) · 1.27 KB
/
etherium.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
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { useEffect } from "react";
import web3 from "../ethereum/web3";
export default function Home() {
let currentAccount;
useEffect(() => {
if (typeof window !== "undefined" && window.ethereum)
window.ethereum.on("accountsChanged", handleAccountsChanged);
}, []);
const handleAccountsChanged = (accounts) => {
if (accounts.length === 0) {
// MetaMask is locked or the user has not connected any accounts
console.log('Please connect to MetaMask.');
} else if (accounts[0] !== currentAccount) {
currentAccount = accounts[0];
console.log("current account", currentAccount);
}
}
const connect = async () => {
try {
const accounts = await ethereum.request({
method: "eth_requestAccounts",
});
console.log("received eth wallets", accounts);
currentAccount = accounts[0];
const ether = await web3.eth.getBalance(currentAccount);
console.log("ether in account", ether);
} catch (e) {
if (e.code === 4001) {
console.log("Please connect to metamask");
} else {
console.error(e.message);
}
}
};
return (
<>
<h1>Connect to metamask</h1>
<button onClick={connect}> Connect </button>
</>
);
}