MetaMask文档 https://docs.metamask.io/guide/ethereum-provider.html
MetaMask下载 https://metamask.io/download.html
连接MetaMask
import React from 'react'
export default function Demo() {
const connectWall = () => {
//判断用户是否安装MetaMask钱包插件
if (typeof window.ethereum === "undefined") {
//没安装MetaMask钱包进行弹框提示
alert("请安装MetaMask")
} else {
//如果用户安装了MetaMask,你可以要求他们授权应用登录并获取其账号
window.ethereum.enable()
.then(function (accounts) {
// 判断是否连接以太
if (window.ethereum.networkVersion !== "1") {
console.log('当前网络不在以太坊')
}
//如果用户同意了登录请求,你就可以拿到用户的账号
console.log('用户钱包地址', accounts[0])
})
.catch(function (reason) {
// 如果用户拒绝了登录请求
if (reason === "User rejected provider access") {
console.log('用户拒绝了登录请求')
} else {
console.log("其他情况");
}
});
}
}
return (
<div>
<button onClick={
connectWall}>连接钱包</button>
</div>
)
}
使用ethereum连接与web3连接的使用场景
方式1
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
这样可以指定连接的地址,且可以同时连接N个区块链(声明且new多次)
方式2
window.ethereum
window.ethereum为当前链地址,可以调用钱包的一些方法,它主要用来监听钱包的事件[网络、账号、发送RPC请求、、、]
方式3
var web3 = new Web3(window.ethereum);
这样通过web3连接当前链地址,多个new也可以同时连多个不同的链
ethereum常用API
更全面的文档请看官方文档:https://docs.metamask.io/guide/ethereum-provider.html
Web3 浏览器检测
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
}
连接到 MetaMask,并且获取到账户
const accounts = await ethereum.request({
method: 'eth_requestAccounts' });
const account = accounts[0];//账户被锁定是获取不到的
链 ID
十六进制 | 十进制 | 网络 |
---|---|---|
0x1 | 1 | 以太坊主网(Mainnet) |
0x3 | 3 | Ropsten 测试网络 |
0x4 | 4 | Rinkeby 测试网络 |
0x5 | 5 | 歌尔力测试网 |
0x2a | 42 | 科文测试网 |
ethereum.isConnected
true如果提供者连接到当前链,则返回,false否则返回
var isConnected = ethereum.isConnected()
ethereum.request
发送一个RPC请求
例 切换网络:https://web03.cn/blog/257
监听连接
ethereum.on('connect', (connectInfo) => {
if(ethereum.isConnected()){
// 确定提供程序何时/是否连接。
}
});
监听断开
ethereum.on('disconnect', (error) => {
});
如果 MetaMask 提供程序变得无法向任何链提交 RPC 请求,则会发出此事件。通常,这只会由于网络连接问题或一些不可预见的错误而发生。
一旦disconnect发出,提供者将不会接受任何新请求,直到重新建立与链的连接,这需要重新加载页面。您还可以使用该ethereum.isConnected()方法来确定提供程序是否已断开连接。
监听帐户更改
ethereum.on('accountsChanged', (accounts) => {
});
监听链改变
ethereum.on('chainChanged', (chainId) => {
});
监听信息
ethereum.on('message', (message) => {
});
当 MetaMask 提供者收到一些应该通知消费者的消息时,它会发出此事件。消息的种类由type字符串标识。
RPC 订阅更新是message事件的常见用例。例如,如果您使用的是创建一个订阅eth_subscribe,每个订阅更新将被发射作为message一个事件type的eth_subscription。
错误
ethereum.request(args)方法抛出的错误
{
message: string;
code: number;
data?: unknown;
}
code | 描述 |
---|---|
4001 | 请求被用户拒绝 |
-32602 | 参数无效 |
-32603 | 内部错误 |