当前位置:网站首页>Metamask插件中-添加网络和切换网络
Metamask插件中-添加网络和切换网络
2022-08-08 15:33:00 【JackieDYH】
Dapp中,自动给用户Metamask添加一个网络(比如BNB主网或BNB测试网),程序主动切换用户Metamask的网络为指定网络(比如BNB主网)
Metamask新增了一个AddEthereumChainParameter 的api,可以自动给用户Metamask添加一个网络,并把当前页面连接到这个网络。
执行这个api时,如果用户的Metamask还没有添加参数指定的网络,则Metamask会弹出一个提示框,提示用户当前页面要给Metamask添加一个网络,并显示要添加网络的信息。如果用户点确定,Metamask就会添加这个网络到用户的钱包。
如果用户的Metamask已经添加了参数指定的网络,但是当前钱包连接的网络不是这个网络,则Metamask会弹出一个提示框,提示用户当前页面要把Metamask的网络切换到指定网络,如果用户点确定,Metamask当前连接的网络就会切换到指定网络。
以上判断Metamask是否添加了指定网络,是根据参数中的ChainID来判断,网络id一样就认为是同一个网络。
如果执行时Metamask已经添加了指定网络,当前也正好连接的是这个网络,则什么也不会执行,不会有任何提示。
在官方文档中,说这个api必须由用户主动操作来触发(点某个按钮),但是实测并不需要,在页面加载时,程序自动执行这个api也是可以的。所以可以在应用初始化的地方,固定执行这个api,这样当用户没有添加网络时,会自动添加;用户没有连接到网络时,会自动连接;用户已连接网络时,什么也不会做。
演示
添加节点
// 添加链节点
async changeNetwork(id) {
let cfg = chainBase[id];
// console.log(cfg);
if (!window.ethereum) {
return false;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const request = (window.ethereum).request;
// 获取当前链id
const chainId = await request({ method: "eth_chainId" });
console.log(`chainId:${chainId}`);
if (chainId == cfg.chainId) {
message.warning(`当前链已经是:${cfg.chainName}`);
} else {
message.warning(`正在切换链为:${cfg.chainName}`);
}
try {
// 切换
await request({
method: "wallet_switchEthereumChain",
params: [{ chainId: cfg.chainId }],
});
return true;
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const err = e;
console.log(err);
if (err.code === 4902) {
try {
// 添加
await request({
method: "wallet_addEthereumChain",
params: [cfg],
});
} catch (addError) {
console.error(addError);
}
} else {
message.error(`ERROR:${err.message}`);
}
return true;
}
},常用链节点信息
const ChainCfg = {
1: {
chainId: '0x1',
chainName: 'Ethereum Mainnet',
nativeCurrency: {
name: 'ETH',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'],
blockExplorerUrls: ['https://etherscan.io'],
},
3: {
chainId: '0x3',
chainName: 'Ropsten testNet',
nativeCurrency: {
name: 'ETH',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'],
blockExplorerUrls: ['https://ropsten.etherscan.io'],
},
42: {
chainId: '0x2a',
chainName: 'Kovan testNet',
nativeCurrency: {
name: 'ETH',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'],
blockExplorerUrls: ['https://kovan.etherscan.io'],
},
56: {
chainId: '0x38',
chainName: 'Binance Smart Chain',
nativeCurrency: {
name: 'BNB',
symbol: 'BNB',
decimals: 18,
},
rpcUrls: ['https://bsc-dataseed.binance.org/'],
blockExplorerUrls: ['https://bscscan.com/'],
},
97: {
chainId: '0x61',
chainName: 'Binance Smart Chain - TestNet',
nativeCurrency: {
name: 'BNB',
symbol: 'BNB',
decimals: 18,
},
rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
blockExplorerUrls: ['https://testnet.bscscan.com/'],
},
1088: {
chainId: '0x440',
chainName: 'Maas - TestNet',
nativeCurrency: {
name: 'Maas',
symbol: 'Maas',
decimals: 18,
},
rpcUrls: ['https://maas-test-node.onchain.com/'],
blockExplorerUrls: ['https://maas-test-explorer.onchain.com/'],
},
2088: {
chainId: '0x828',
chainName: 'Maas',
nativeCurrency: {
name: 'Maas',
symbol: 'Maas',
decimals: 18,
},
rpcUrls: ['https://maas-node.onchain.com/'],
blockExplorerUrls: ['https://maas-explorer.onchain.com/'],
},
};
export default ChainCfg;代码
const addNetwork = () => {
window.ethereum.request({
method: 'wallet_addEthereumChain', // Metamask的api名称
params: [{
chainId: "0x80", // 网络id,16进制的字符串
chainName: "HecoMain", // 添加到钱包后显示的网络名称
rpcUrls: [
'https://http-mainnet-node.huobichain.com', // rpc地址
],
iconUrls: [
'https://testnet.hecoinfo.com/favicon.png' // 网络的图标,暂时没看到在哪里会显示
],
blockExplorerUrls: [
'https://hecoinfo.com' // 网络对应的区块浏览器
],
nativeCurrency: { // 网络主币的信息
name: 'HT',
symbol: 'HT',
decimals: 18
}
}]
})
}
addNetwork()边栏推荐
猜你喜欢

JS-BOM-factorial calculation

带你玩转“超大杯”ECS特性及实验踩坑【华为云至简致远】

Streamsets Data Collector 3.12

761. 特殊的二进制序列 : 经典构造题

全网首发!消息中间件神仙笔记,涵盖阿里十年技术精髓

Introduction to Power BI
![[Unity Starter Plan] Making RubyAdventure02 - Handling Tile Maps & Collision](/img/e9/2fd665da5ef8ce6f350a338ab1e81e.png)
[Unity Starter Plan] Making RubyAdventure02 - Handling Tile Maps & Collision

A16z:为什么 NFT 创作者要选择 cc0?

Iptables防火墙iprange模块扩展匹配规则

解决Redis、MySQL缓存双写不一致问题
随机推荐
兆骑科创创业赛事活动举办平台,投融资对接,线上直播路演
JS加法器(DOM)
leetcode/number of palindromic substrings
幂等性~~
查询接口 - 树形菜单查询接口实现
循环神经网络RNN入门介绍
Notes on the development of kindergarten enrollment registration system based on WeChat applet
携手数字创新 共筑国产生态 7月份AntDB与5款产品完成互认证
线程本地存储 ThreadLocal
本机Redis Desktop Manager连不上vmware的redis
你真的会软件测试bug分析定位嘛
【Unity入门计划】用双血条方法控制伤害区域减血速度
消除游戏中宝石下落的原理和实现
投资一个约20台桩的充电站需要多少钱?多久可以实现盈利?
并发请求如何优雅地处理重复请求
bzoj3693 round table hall theorem + segment tree
解决Redis、MySQL缓存双写不一致问题
CS231n: 6 training neural network (2)
[Online interviewer] How to achieve deduplication and idempotency
bzoj3693 圆桌会议 hall定理+线段树
