通过网页切换metamask主网
2023-3-24|2023-3-24
![夜火/xloong](https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2Fcc67b15a-b537-4c34-90ad-f3155862a85e%2F%25E5%25BE%25AE%25E4%25BF%25A1%25E5%259B%25BE%25E7%2589%2587_20221209214742.jpg?table=collection&id=9a0fbcf3-cd55-46c1-800f-30cbccc1569a)
夜火/xloong
type
Post
status
Published
date
Mar 24, 2023
slug
metamast-switch-mainnet
summary
通过网页切换metamask主网
tags
开发
区块链
metamask
category
技术分享
icon
password
URL
Property
Mar 24, 2023 01:05 AM
通过 ethereum.request 发起切换主网请求,metamask小狐狸钱包,通过点击接受或同意切换请求,即可切换到对应主网,无需用户一点点设置填写主网信息
function switch_network(network){ const bsc = { chainId: '0x38', // 币安主网的chainId是56 chainName: 'Smart Chain', nativeCurrency: { name: 'BNB', symbol: 'bnb', decimals: 18, }, rpcUrls: ['https://bsc-dataseed.binance.org/'], blockExplorerUrls: ['https://bscscan.com/'], }; const eth = { chainId: '0x1', // 以太坊主网的chainId是1 chainName: 'Ethereum Mainnet', nativeCurrency: { name: 'ETH', symbol: 'eth', decimals: 18, }, rpcUrls: ['https://eth.llamarpc.com','https://mainnet.infura.io/v3/'], blockExplorerUrls: ['https://etherscan.io/'], }; var main =''; if(network=='bsc'){ main = bsc; }else if(network=='eth'){ main = eth; }else{ alert('还不支持当前主网,请切换到币安或以太坊主网'); return false; } console.log(main) ethereum .request({ method: 'wallet_addEthereumChain', params: [main], }) .then((result) => { console.log(result); }) .catch((error) => { console.log(error); }) .finally(() => { console.log('finally'); }); }
各主网对应的填写信息可以在这里查到: https://chainlist.org