-
Notifications
You must be signed in to change notification settings - Fork 454
/
index.html
43 lines (40 loc) · 1.78 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1 id="header">Connect to Metamask</h1>
<button class="connect"> Connect</button>
<h2>钱包地址: <span class="showAccount"></span></h2>
<h2>ChainID: <span class="showChainID"></span></h2>
<h2>ETH 余额: <span class="showETHBalance"></span></h2>
<script type="module">
import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/6.2.3/ethers.js"; const ethereumButton = document.querySelector('.connect');
const showAccount = document.querySelector('.showAccount');
const showChainID = document.querySelector('.showChainID');
const showETHBalance = document.querySelector('.showETHBalance');
ethereumButton.addEventListener(`click`, onClickHandler)
async function onClickHandler() {
console.log("连接钱包")
// 获得provider
const provider = new ethers.BrowserProvider(window.ethereum)
// 读取钱包地址
const accounts = await provider.send("eth_requestAccounts", []);
const account = accounts[0]
console.log(`钱包地址: ${account}`)
showAccount.innerHTML = account;
// 读取chainid
const { chainId } = await provider.getNetwork()
console.log(`chainid: ${chainId}`)
showChainID.innerHTML = chainId;
// 读取ETH余额
const signer = await provider.getSigner()
const balance = await provider.getBalance(signer.getAddress());
console.log(`以太坊余额: ${ethers.formatUnits(balance)}`)
showETHBalance.innerHTML = ethers.formatUnits(balance);
}
</script>
</body>
</html>