夜火笔记

通过网页切换metamask主网

2023-03-24
笔记 metamask区块链web3
2分钟
225字

和前面的文章类似:metamask小狐狸钱包 eth_sendTransaction接口发起指定币种交易

通过 ethereum.request 发起切换主网请求,metamask小狐狸钱包,通过点击接受或同意切换请求,即可切换到对应主网,无需用户一点点设置填写主网信息

1
function switch_network(network){
2
const bsc = {
3
chainId: '0x38', // 币安主网的chainId是56
4
chainName: 'Smart Chain',
5
nativeCurrency: {
6
name: 'BNB',
7
symbol: 'bnb',
8
decimals: 18,
9
},
10
rpcUrls: ['https://bsc-dataseed.binance.org/'],
11
blockExplorerUrls: ['https://bscscan.com/'],
12
};
13
const eth = {
14
chainId: '0x1', // 以太坊主网的chainId是1
15
chainName: 'Ethereum Mainnet',
33 collapsed lines
16
nativeCurrency: {
17
name: 'ETH',
18
symbol: 'eth',
19
decimals: 18,
20
},
21
rpcUrls: ['https://eth.llamarpc.com','https://mainnet.infura.io/v3/'],
22
blockExplorerUrls: ['https://etherscan.io/'],
23
};
24
var main ='';
25
if(network=='bsc'){
26
main = bsc;
27
}else if(network=='eth'){
28
main = eth;
29
}else{
30
alert('还不支持当前主网,请切换到币安或以太坊主网');
31
return false;
32
}
33
console.log(main)
34
ethereum
35
.request({
36
method: 'wallet_addEthereumChain',
37
params: [main],
38
})
39
.then((result) => {
40
console.log(result);
41
})
42
.catch((error) => {
43
console.log(error);
44
})
45
.finally(() => {
46
console.log('finally');
47
});
48
}

各主网对应的填写信息可以在这里查到: https://chainlist.org

本文标题:通过网页切换metamask主网
文章作者:夜火/xloong
发布时间:2023-03-24
Copyright 2026
站点地图