import { providers } from "ethers" ; import { AVALANCHE_MAINNET_PARAMS , AVALANCHE_TESTNET_PARAMS } from "../constants/chainParameters" ; import { isAvaxNetwork } from "../constants/constants" ; import { CHAINID } from "./env" ; const UNAVAILABLE_CHAIN_CODE = 4902 ; /**
 * Function copied and modified from https://docs.metamask.io/guide/rpc-api.html#other-rpc-methods
 * error code 4902 refers to chain being available in the wallet
 */ export const switchChains = async ( provider , chainId ) => { const hexChainId = "0x" + chainId . toString ( 16 ) ; if ( ! provider . provider . request ) return ; try { await provider . provider . request ( { method : "wallet_switchEthereumChain" , params : [ { chainId : hexChainId } ] , } ) ; } catch ( switchError ) { if ( switchError . code === UNAVAILABLE_CHAIN_CODE || ( switchError . data && switchError . data . originalError && switchError . data . originalError . code === UNAVAILABLE_CHAIN_CODE ) ) { if ( isAvaxNetwork ( chainId ) ) { try { await provider . provider . request ( { method : "wallet_addEthereumChain" , params : [ chainId === CHAINID . AVAX_MAINNET ? AVALANCHE_MAINNET_PARAMS : AVALANCHE_TESTNET_PARAMS ] , } ) ; } catch ( addError ) { console . error ( "Add network error" ) ; } } else { throw new Error ( "Network not found" ) ; } } } } ;