Q1 · 前端与链交互
写一段 JavaScript 代码连接 MetaMask,并显示钱包余额的大致步骤?
⚡ 速记答案(30 秒)
- 判断环境:
if (window.ethereum) - 请求连接:
await ethereum.request({ method: "eth_requestAccounts" })拿到accounts[0] - 创建 provider:
new ethers.BrowserProvider(window.ethereum) - 读余额:
provider.getBalance(address)→ 再用ethers.formatEther(balance)转成人类可读 ETH
🎮 交互 Demo
💡 提示:确保已安装 MetaMask 浏览器扩展。点击按钮后会弹出授权窗口。
📖 详细讲解
核心概念
连接 MetaMask 是 Web3 前端开发最基础的操作。流程分为三步:
1. 环境检测:检查浏览器是否安装了 MetaMask 扩展(window.ethereum)
2. 请求授权:调用 eth_requestAccounts 方法,弹出 MetaMask 授权弹窗
3. 读取数据:使用 Ethers.js 封装的 Provider 读取链上数据
关键 API
| API | 说明 |
|---|---|
window.ethereum | MetaMask 注入的全局对象 |
eth_requestAccounts | 请求用户授权连接 |
BrowserProvider | Ethers.js v6 的浏览器 Provider |
getBalance | 获取地址的 ETH 余额(单位:Wei) |
formatEther | 将 Wei 转换为 ETH |
面试要点
• 区分 Ethers.js v5 和 v6 的 API 差异(v5 用 Web3Provider,v6 用 BrowserProvider)
• 处理用户拒绝连接的情况
• 考虑网络切换和账户切换的事件监听
💻 代码示例
Ethers.js v6 连接钱包
import { ethers } from 'ethers';
async function connectWallet() {
// 1. 检查 MetaMask 是否安装
if (typeof window.ethereum === 'undefined') {
throw new Error('请先安装 MetaMask 扩展');
}
// 2. 请求用户授权连接
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
});
const address = accounts[0];
// 3. 创建 Provider 实例
const provider = new ethers.BrowserProvider(window.ethereum);
// 4. 获取余额并转换为 ETH
const balanceWei = await provider.getBalance(address);
const balanceEth = ethers.formatEther(balanceWei);
return {
address,
balance: balanceEth,
};
}监听账户和网络变化
// 监听账户切换
window.ethereum.on('accountsChanged', (accounts: string[]) => {
if (accounts.length === 0) {
console.log('用户断开连接');
} else {
console.log('切换到账户:', accounts[0]);
}
});
// 监听网络切换
window.ethereum.on('chainChanged', (chainId: string) => {
console.log('切换到链:', parseInt(chainId, 16));
// 建议刷新页面以重新加载状态
window.location.reload();
});面试技巧:回答时先给出核心结论,再展开细节。如果有实际项目经验,一定要结合具体案例说明。