直接上代码,我这里吧所有配置都改成正式的链56,一旦用户的小狐狸钱包现在的链不一致,就询问切换网络,没有就创建网络,网络切换成功后,收到监听,重新连接一下web3,就是重新调用一些connectWeb3这个方法,再连接合约
connectWeb3: async function () {
// 判断链对不,链不对就请求切换网络,或者添加网络,
if (window.ethereum) {
try {
await (window.ethereum as any).request({
method: 'wallet_switchEthereumChain',
params: [{
chainId: Web3.utils.numberToHex(56) // 目标链ID
}]
})
} catch (e) {
if ((e as any).code === 4902) {
try {
await (window.ethereum as any).request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: Web3.utils.numberToHex(56), // 目标链ID
chainName: 'Binance Smart Chain Mainnet',
nativeCurrency: {
name: 'bnb',