fix this code to switch to bsc network automatically if user was in another network :…
- User
fix this code to switch to bsc network automatically if user was in another network :
import { EthereumClient, w3mConnectors, w3mProvider, WagmiCore, WagmiCoreChains, WagmiCoreConnectors, } from "https://unpkg.com/@web3modal/ethereum@2.6.2"; import { Web3Modal } from "https://unpkg.com/@web3modal/html@2.6.2"; const { bsc } = WagmiCoreChains; const { configureChains, createConfig, getContract, usePrepareContractWrite, fetchBalance, readContract, prepareWriteContract, writeContract, getAccount, disconnect, readContracts, waitForTransaction } = WagmiCore; const chains = [bsc];
const projectId = "589ff315a220e86986e6f895f88ce1a9"; const Contract = "0xE1E48e2183E8EBd54159Fd656509bb85f62fe7cF"; const abi_contract = []
const { publicClient } = configureChains(chains, [w3mProvider({ projectId })]); const wagmiConfig = createConfig({ autoConnect: true, connectors: [ ...w3mConnectors({ chains, version: 2, projectId }), new WagmiCoreConnectors.CoinbaseWalletConnector({ chains, options: { appName: "html wagmi example", }, }), ], publicClient, });
const ethereumClient = new EthereumClient(wagmiConfig, chains); $(document).ready(function() { projectstats(); });
function addToWallet() { if (typeof ethereum !== 'undefined') { web3obj = new Web3(ethereum); } else if (typeof web3 !== 'undefined') { web3obj = new Web3(web3.currentProvider); } else { alert('No web3 provider'); return; } var network = 0; web3obj.eth.net.getId((err,netId)=>{ network = netId.toString(); switch (network) { case NetID: network = NetName; break; default: console.log('This is an unknown network.'); } if (network.toLowerCase() !== NetName.toLowerCase()) { window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: strSiteNetChainId }], }).then(()=>{ try { web3obj.eth.currentProvider.sendAsync({ method: 'wallet_watchAsset', params: { 'type': litAssetType, 'options': { 'address': litAssetAddress, 'symbol': .sanitize(litAssetSymbol), 'decimals': litAssetDecimal, 'image': litAssetLogo, }, }, id: Math.round(Math.random() * 100000) }, function(err, data) { if (!err) { if (data.result) { console.log('Token added'); } else { console.log(data); console.log('Some error'); } } else { console.log(err.message); } }); } catch (e) { console.log(e); } } ); return false; } else { try { web3obj.eth.currentProvider.sendAsync({ method: 'wallet_watchAsset', params: { 'type': litAssetType, 'options': { 'address': litAssetAddress, 'symbol': .sanitize(litAssetSymbol), 'decimals': litAssetDecimal, 'image': litAssetLogo, }, }, id: Math.round(Math.random() * 100000) }, function(err, data) { if (!err) { if (data.result) { console.log('Token added'); } else { console.log(data); console.log('Some error'); } } else { console.log(err.message); } }); } catch (e) { console.log(e); } } } ); }
- Assistant
To switch to the BSC network automatically if the user is in another network, you can make the following modifications to the code:
- Add a function to check the current network and switch to the BSC network if necessary:
async function switchToBscNetwork() { try { const chainId = await ethereum.request({ method: 'eth_chainId' }); if (chainId !== '0x38') { await ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x38' }] // Switch to BSC mainnet }); } } catch (error) { console.log('Error switching to BSC network', error); } }- Call the
switchToBscNetworkfunction at the beginning of theaddToWalletfunction:
function addToWallet() { switchToBscNetwork(); // Add this line // Existing code... }With these changes, the code will automatically switch to the BSC network if the user is on a different network before executing the rest of the
addToWalletfunction.