检测MetaMask插件是否安装

//原始方法
if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
}
//推荐方法
import detectEthereumProvider from '@metamask/detect-provider'
async function initWeb3 () {
  const provider = await detectEthereumProvider()
  if (provider) {
    // provider === window.ethereum
  } else {
    return false
  }
}
initWeb3()

MetaMask授权

//进行授权
window.ethereum.request({
    method: 'eth_requestAccounts'
}).then((res)=>{
    //授权成功
}).catch((err)=>{
    //取消授权
)

添加自定义网络

import Web3 from 'web3'
window.ethereum.request({
    method: 'wallet_addEthereumChain',
    params: [
                {
                    chainId: web3.utils.numberToHex(97),
                    chainName: 'bsc',
                    nativeCurrency: {
                      name: 'tbnb',
                      symbol: 'tbnb', // 2-6 characters long
                      decimals: 18
                    },
                    rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545'],
                    blockExplorerUrls: ['https://testnet.bscscan.com']
                }
            ]
    }).then((res)=>{
        //添加成功
    }).catch((err)=>{
        //添加失败
    })

注入web3

 const web3 = new Web3(window.ethereum)
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐