以下是如何实现钱包连接的基本步骤:
1. 选择一个钱包库
最常见的钱包是 MetaMask,它是一个浏览器插件,可以与 DApp(去中心化应用)进行交互。常用的 JavaScript 库有:
• Web3.js
• Ethers.js
• Wagmi(对于 React 项目)
这两者中,Ethers.js 更轻量并且功能更强大,所以我们会以它为例。
2. 检查钱包是否安装
首先,需要判断用户是否安装了钱包(如 MetaMask)。你可以通过检测 window.ethereum 对象来确认。
if (typeof window.ethereum !== 'undefined') {
console.log("MetaMask is installed!");
} else {
console.log("Please install MetaMask!");
}
3. 连接钱包
用户点击连接按钮时,可以通过 window.ethereum 请求钱包连接。你需要调用 ethereum.request 来请求连接。
const connectWallet = async () => {
try {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
});
console.log('Connected account:', accounts[0]);
} catch (error) {
console.error("User denied account access");
}
};
这段代码会弹出 MetaMask 钱包提示,用户同意后返回账户信息。
4. 获取用户账户和网络信息
连接成功后,通常你需要获取用户的地址(公钥)以及网络信息(如以太坊主网、测试网等)。
const getAccountAndNetwork = async () => {
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
const networkId = await window.ethereum.request({ method: 'net_version' });
console.log('User account:', accounts[0]);
console.log('Network ID:', networkId);
};
5. 监听账户或网络变化
你可以监听账户或网络变化事件,以便在用户更改了钱包账户或切换了网络时,自动更新界面。
window.ethereum.on('accountsChanged', (accounts) => {
console.log('Account changed:', accounts[0]);
});
window.ethereum.on('chainChanged', (chainId) => {
console.log('Network changed:', chainId);
});
6. 发起交易
你也可以通过钱包发起交易,例如发送以太币或调用智能合约方法。通过 ethereum.request 方法发起交易。
const sendTransaction = async () => {
try {
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [{
from: '用户地址',
to: '接收方地址',
value: '0x29a2241af62c0000', // 发送金额(单位:wei)
}],
});
console.log('Transaction hash:', txHash);
} catch (error) {
console.error('Transaction failed:', error);
}
};
7. 使用 Ethers.js (可选)
如果使用 Ethers.js,你可以更方便地与智能合约进行交互并管理钱包。以下是一个简单的示例,如何用 Ethers.js 与钱包交互:
import { ethers } from 'ethers';
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const getBalance = async () => {
const address = await signer.getAddress();
const balance = await provider.getBalance(address);
console.log('Balance:', ethers.utils.formatEther(balance));
};
const sendTransaction = async () => {
const tx = await signer.sendTransaction({
to: '接收方地址',
value: ethers.utils.parseEther('0.1'), // 发送0.1 ETH
});
console.log('Transaction hash:', tx.hash);
};
总结
• 首先,你需要检查用户是否安装了钱包(如 MetaMask)。
• 然后,使用 window.ethereum.request 方法来请求用户连接钱包。
• 获取钱包中的账户信息以及网络信息,确保正确与区块链网络交互。
• 监听钱包账户和网络变化,以便于 UI 自动更新。
• 使用 eth_sendTransaction 方法发送交易,或使用 Ethers.js 与智能合约交互。