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
方式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
监听连接
ethereum.on('connect', (connectInfo) => {
if(ethereum.isConnected()){
// 确定提供程序何时/是否连接。 } });
监听断开
ethereum.on('disconnect', (error) => {
});
监听帐户更改
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 | 内部错误 |
有关完整的错误列表,请参阅EIP-1193 和 EIP-1474
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214100.html原文链接:https://javaforall.net

