关于区块链:web3与Metamask同步切换链

7次阅读

共计 975 个字符,预计需要花费 3 分钟才能阅读完成。

以前遇到一个需要:跨链转换代币,可能从以太链转到本人的链。再从本人的链转回以太链。
冀望:当本地切换的时候,metamask 的网络也跟着切换

举荐一个网络 id 和链名称的 git 库:https://github.com/ethereum-l…

大家都是老码农了,废话就不多说了。间接上代码

最完满的形式:

// 增加网络 chainId 你须要切换的 id
addOrChangeNetWork(chainId) {const toHex = (num) => {return '0x' + num.toString(16)
        }
        let chain = import web3json from `@/moke/json/eip155-${chainId}.json` 
        let net_data = {chainId: toHex(chain.chainId),
            chainName: chain.name,
            nativeCurrency: {
                name: chain.nativeCurrency.name,
                symbol: chain.nativeCurrency.symbol,
                decimals: chain.nativeCurrency.decimals
            },
            rpcUrls: chain.rpc,
            blockExplorerUrls: [chain.explorers && chain.explorers.length > 0 && chain.explorers[0].url ? chain.explorers[0].url : chain.infoURL]
        }
        web3.eth.getAccounts((error, accounts) => {
            window.ethereum
                .request({
                    method: 'wallet_addEthereumChain',
                    params: [net_data, accounts[0]]
                })
                .then((result) => {console.log(result, '返回数据')
                })
                .catch((error) => {console.log(error,'谬误数据')
                })
        })
    }

简略的形式:

window.ethereum.request({
    method: 'wallet_switchEthereumChain',
    params: [
        {chainId: Web3.utils.numberToHex(1) // 链 id
        }
    ]
})

出工!

正文完
 0