如何给MetaMask添加自定义网络

检测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)

你可能感兴趣的:(区块链笔记,web3,MetaMask)