【区块链】走进web3的世界-RPC切换功能记录

1、switchNetwork组件

import { ethers } from 'ethers'
/**
 * 切换网络方法
 * @param chainId 网络ID
 * @param RpcInfo rpc信息
 *  @chainName String  网络名称
 *  @Nodes String  新的 RPC URL
 *  @BlockExplorerUrls String  区块浏览器 URL(可选)
 * @param nativeCurrency 货币信息
 *  @name 货币名称
 *  @decimals 位数
 */
export const switchNetwork = async (netInfo) => {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    // 当前网络信息
    const network = await provider.getNetwork();
    // 当前网络和域名网络一致
    if (netInfo.chainId && network.chainId == netInfo.chainId) {
        console.log('当前网络和域名网络一致');
        return true;
    }
    let hex_chainId = ethers.utils.hexValue(netInfo.chainId);
    console.log('hex_chainId :' + hex_chainId);
    try {
        // 切换到传入的网络
        await provider.send('wallet_switchEthereumChain', [
            { chainId: hex_chainId }
        ]);
        console.log('切换成功')
        return true;
    } catch (e) {
        const provider = (window as any).ethereum;
        // 当缺少该网络时,自动添加
        if (e.code === 4902) {
            await provider.request({
                method: 'wallet_addEthereumChain',
                params: [
                    {
                        chainId: `0x${parseFloat(netInfo.chainId).toString(16)}`,
                        chainName: netInfo.rpcInfo.chainName,
                        nativeCurrency: {
                            name: netInfo.nativeCurrency.name,
                            symbol: netInfo.nativeCurrency.symbol,
                            decimals: netInfo.nativeCurrency.decimals
                        },
                        rpcUrls: [netInfo.rpcInfo.Nodes],
                        blockExplorerUrls: [netInfo.rpcInfo.BlockExplorerUrls]
                    }
                ]
            });
            return true;
        }
        throw e;
    }
};

 2、rpc网络配置


{
    "ethMain": {
        "chainId": 1,
        "netInfo": {
            "chainName": "以太坊主网",
            "Nodes": "https://mainnet.infura.io/v3/",
            "BlockExplorerUrls": "https://etherscan.io"
        },
        "nativeCurrency": {
            "name": "ETH",
            "symbol": "ETH",
            "decimals": 18
        }
    },
    "bnbMain": {
        "chainId": 56,
        "netInfo": {
            "chainName": "BSC MAINNET",
            "Nodes": "https://bsc-dataseed.binance.org",
            "BlockExplorerUrls": ""
        },
        "nativeCurrency": {
            "name": "UNKNOWN",
            "symbol": "UNKNOWN",
            "decimals": 18
        }
    },
    "doMain": {
        "chainId": 137,
        "netInfo": {
            "chainName": "BSC MAINNPolygon Mainnet",
            "Nodes": "https://polygon-mainnet.infura.io",
            "BlockExplorerUrls": "https://polygonscan.com/"
        },
        "nativeCurrency": {
            "name": "MATIC",
            "symbol": "MATIC",
            "decimals": 18
        }
    }
}

3、调用切换rpc网络


import React, { FC, useEffect} from 'react'
import { switchNetwork } from '@/web3/common/switchNetwork'
import netInfo from '@/web3/common/rpc.config.json'

const RegisterDomain: FC = () => {
    /**
     * @param netInfo
     *  @param chainId 链ID(需要切换的链ID)
     *  @param RpcInfo {} rpc信息
     *  @param nativeCurrency {} 货币信息
     *
     */
    const switchNet = async () => {
        await switchNetwork(netInfo.ethMain).catch(e => {
            const { message } = e
            console.log('======message======', message)
        })
    }

    useEffect(() => {
        // 切换网络测试
        switchNet()
    }, [])
    return (
        <>
            <DomainComponents />
        </>
    )
}
export default RegisterDomain

猜你喜欢

转载自blog.csdn.net/qq_23334071/article/details/130180045