Does addChain and switchChain function working on web3auth version 9.7.0 now ? I cannot switch change while using switchChain function

  • What’s on your mind?

    • after login with google (social) , when i can switchChain function form provider, it get this error
      “underlying network changed (event=“changed”, network={“chainId”:84532,“name”:“unknown”}, detectedNetwork={“name”:“sepolia”,“chainId”:11155111,“ensAddress”:null}, code=NETWORK_ERROR, version=providers/5.7.2)”

    • Because of my Apps now in using React v17 then cannot update web3auth to v10 (required React v18) .
      If you guy have any best example for using switchChain function of web3auth no modal version 9.7.0 , please help me for that

Hi Peter — thanks for the details, and sorry you’re hitting this. I pulled the important bits from your message and added a few suggestions and requests so the support team can reproduce and help quickly.

Summary of what I see

  • SDK: web3auth (no‑modal) — version 9.7.0 (you said you can’t upgrade because your app is on React 17)
  • Platform: Web (React v17)
  • Ethers/provider info: error message shows providers/5.7.2 (ethers v5.7.2)
  • Error observed when calling switchChain after Google (social) login:
    “underlying network changed (event="changed", network={"chainId":84532,"name":"unknown"}, detectedNetwork={"name":"sepolia","chainId":11155111,"ensAddress":null}, code=NETWORK_ERROR, version=providers/5.7.2)”

What this usually means

  • The provider’s network changed while ethers was using the old network — ethers throws NETWORK_ERROR when a network change is detected mid-request.
  • Common causes: using a decimal chainId instead of hex in wallet_switchEthereumChain params, not adding the chain first (error 4902), or not reinitializing your ethers/web3 provider after chain change.

Quick troubleshooting & fixes to try (worked patterns for web3auth v9.x + ethers v5)

  1. Use provider.request with a hex chainId. Example (no-modal web3auth provider):
    await web3auth.provider.request({
    method: ‘wallet_switchEthereumChain’,
    params: [{ chainId: ‘0x14A34’ }] // hex for decimal 84532
    })

  2. If the chain is not added (error code 4902), call wallet_addEthereumChain first (example skeleton):
    await web3auth.provider.request({
    method: ‘wallet_addEthereumChain’,
    params: [{
    chainId: ‘0x14A34’,
    chainName: ‘MyChain’,
    nativeCurrency: { name: ‘ETH’, symbol: ‘ETH’, decimals: 18 },
    rpcUrls: [‘https://your-rpc.example’],
    blockExplorerUrls: [‘https://explorer.example’]
    }]
    })

  3. Recreate your ethers provider after switching chains. For example:
    // after switch/chainChanged
    const ethersProvider = new ethers.providers.Web3Provider(web3auth.provider);
    const signer = ethersProvider.getSigner();

  4. Listen for chain changes and update state/provider:
    web3auth.provider.on && web3auth.provider.on(‘chainChanged’, (chainIdHex) => {
    // rebuild provider/signer and update app state
    });

  5. Avoid firing other requests during the switch. The NETWORK_ERROR often happens when something is mid-request while the network flips.

What I need from you to help further (only if you can share — no spam):

  • Your code snippet that initializes web3auth and your provider (the login snippet) and the exact switchChain/addChain call you’re using.
  • Are you using ethers.js or web3.js in your app? If ethers, which version (the error suggests v5.7.2).
  • Browser console logs (full stack trace) or a screenshot of the console error.
  • Which chain are you attempting to switch to (name, decimal chainId and RPC URL) so we can verify the exact chainId hex to use.

If you want, paste your init + switch code and I’ll point out exactly what to change. If you just want a quick test: try calling wallet_switchEthereumChain with a hex chainId and recreate the ethers provider after the switch — that often resolves the underlying network changed error.

I’ll wait for your code/console output and can give an exact patch for v9.7.0.

Note: This response was generated by an AI bot and may require further verification. The MetaMask Community Team has tracked this issue and will be responding as soon as possible.

Additionally, we would recommend you to join our biweekly Office Hours to get this resolved even faster. MetaMask Developer Office Hours

import { ethers } from 'ethers'

import { web3auth } from '~/components/navigation/Navigation'
import { getNetworkByChainId } from '~/helpers/web3'
import { useAppDispatch, useAppSelector } from '~/store/hooks'
import { selectors } from '~/store/selectors'
import { NetworkUseType } from '../types'
import { actions } from '~/store/actions'
import { getActiveConnectionMethod } from '~/web3/walletProviderService'

export const WalletProvider = () => {
  const dispatch = useAppDispatch()

  const context = useAppSelector(selectors.wallet.getContext)
  const isAuth = useAppSelector(selectors.wallet.getIsAuth)
  const activeMethod = getActiveConnectionMethod()
  const isWeb3authConnected = activeMethod === 'web3auth'

  let provider: any

  const switchChain = async (network: NetworkUseType | undefined) => {
    if (!web3auth || !network) return

    await web3auth.addChain({
      chainNamespace: 'eip155',
      chainId: network?.hexChainId,
      rpcTarget: network.rpc,
      displayName: network.name,
      blockExplorerUrl: network.explorerUrl,
      ticker: network.symbol,
      tickerName: network.typeNetwork.toLocaleUpperCase(),
    })

    try {
      await web3auth.switchChain({ chainId: network.hexChainId })

      dispatch(actions.bridge.setNetwork(network))
      console.log(`Switched to chainId: ${network.id}`)
    } catch (error) {
      console.error('Error switching chain:', error)
    }
  }

  const getNetworkInfo = async () => {
    if (!isAuth) return

    if (!isWeb3authConnected) {
      if (!context || !context?.library) return

      dispatch(actions.bridge.setNetwork(getNetworkByChainId(context.chainId)))
      provider = context?.library
    } else {
      if (!web3auth?.provider) return

      provider = new ethers.providers.Web3Provider(web3auth?.provider) // web3Provider

      try {
        const networkInfo = await provider.getNetwork()
        dispatch(
          actions.bridge.setNetwork(getNetworkByChainId(networkInfo.chainId)),
        )
      } catch (error) {
        console.error('Error getting network info:', error)
      }
    }
  }

  getNetworkInfo()

  return {
    provider,
    switchChain,
  }
}











// @ts-nocheck

import { Web3AuthNoModal } from '@web3auth/no-modal'
import { EthereumPrivateKeyProvider } from '@web3auth/ethereum-provider'
import { AuthAdapter } from "@web3auth/auth-adapter";
import { CHAIN_NAMESPACES } from '@web3auth/base'
import useAction from './useAction'
import { actions } from '~/store/actions'
import { useAppDispatch, useAppSelector } from '~/store/hooks'
import { selectors } from '~/store/selectors'
import {
  connectWallet,
  linkToSocial,
  loginBySocial,
} from '~/store/modules/wallet'
import { useEffect } from 'react'
import { WALLET_TYPES } from '~/constants/wallet'
import { getPublicCompressed } from '@toruslabs/eccrypto'
import {
  LinkToSocialStatuses,
  SignInWithSocialStatuses,
} from '~/store/modules/wallet/types'

const web3AuthClientId = process.env.NEXT_PUBLIC_WEB3AUTH_CLIENT_ID
const web3AuthVerifier = process.env.NEXT_PUBLIC_WEB3AUTH_VERIFIER
const web3AuthNetwork = process.env.NEXT_PUBLIC_WEB3AUTH_AUTH_NETWORK
const web3AuthChainId = process.env.NEXT_PUBLIC_WEB3AUTH_AUTH_CHAIN_ID
const web3AuthRPC = process.env.NEXT_PUBLIC_WEB3AUTH_RPC
const web3AuthExplorer = process.env.NEXT_PUBLIC_WEB3AUTH_EXPLORER
const web3AuthDisplayName = process.env.NEXT_PUBLIC_WEB3AUTH_DISPLAY_NAME

const initWeb3AuthConfig = () => {
  const chainConfig = {
    chainNamespace: CHAIN_NAMESPACES.EIP155,
    chainId: web3AuthChainId,
    rpcTarget: web3AuthRPC,
    displayName: web3AuthDisplayName,
    blockExplorer: web3AuthExplorer,
    ticker: 'ETH',
    tickerName: 'Ethereum',
  }

  const privateKeyProvider = new EthereumPrivateKeyProvider({
    config: { chainConfig },
  })

  const web3auth = new Web3AuthNoModal({
    clientId: web3AuthClientId,
    web3AuthNetwork, // Web3Auth Network
    chainConfig,
    useCoreKitKey: false,
    sessionTime: 7 * 86400,
    privateKeyProvider
  })

  
  const openloginAdapter = new AuthAdapter({
    privateKeyProvider,
    loginSettings: {
      mfaLevel: 'none',
    },
    adapterSettings: {
      uxMode: 'redirect',
      loginConfig: {
        jwt: {
          name: 'Heroes of Mavia',
          verifier: web3AuthVerifier,
          typeOfLogin: 'jwt',
          clientId: web3AuthClientId,
        },
      },
    },
  })
  web3auth.configureAdapter(openloginAdapter)
  return web3auth
}

export const web3auth = initWeb3AuthConfig()

export const useWeb3auth = () => {
  const dispatch = useAppDispatch()
  const setWeb3Auth = useAction(actions?.wallet?.setWeb3Auth)
  const setWeb3AuthStatus = useAction(actions?.wallet?.setWeb3AuthStatus)
  const account = useAppSelector(selectors.wallet.getAccount)
  const isAuth = useAppSelector(selectors.wallet.getIsAuth)
  const linkSocialStatus = useAppSelector(selectors.wallet.getLinkSocialStatus)
  const loginBySocialStatus = useAppSelector(
    selectors.wallet.getLoginBySocialStatus,
  )

  const linkedToSocial = useAction(linkToSocial)
  const loginedBySocial = useAction(loginBySocial)

  useEffect(() => {
    const initWeb3Auth = async () => {
      try {
        await web3auth.init()
        dispatch(setWeb3Auth({ data: web3auth }))

        if (web3auth.connected) {
          dispatch(actions.wallet.setWeb3AuthStatus(true))
          // Trigger web3auth provider in case no current injected provider
          if (!account) {

            
            dispatch(actions.wallet.setWeb3AuthProvider(web3auth.provider))
            dispatch(connectWallet(WALLET_TYPES.WEB3AUTH))
          }

          const app_scoped_privkey = await web3auth.provider?.request({
            method: 'eth_private_key', // use "private_key" for other non-evm chains
          })
          // @ts-ignore
          const app_pub_key1 = app_scoped_privkey
            ? getPublicCompressed(
                Buffer.from(app_scoped_privkey.padStart(64, '0'), 'hex'),
              ).toString('hex')
            : ''
          const walletInfo = await web3auth.getUserInfo()
          try {
            if (
              isAuth &&
              linkSocialStatus === LinkToSocialStatuses.Loading &&
              !account?.account
            ) {
              linkedToSocial({
                idToken: walletInfo?.idToken,
                oAuthIdToken: walletInfo?.oAuthIdToken,
                appPubKey: app_pub_key1,
              })
            }
            if (loginBySocialStatus === SignInWithSocialStatuses.Loading) {
              loginedBySocial({
                idToken: walletInfo?.idToken,
                oAuthIdToken: walletInfo?.oAuthIdToken,
                appPubKey: app_pub_key1,
              })
            }
          } catch (error) {
            console.error(error)
          }
        }
      } catch (error) {
        console.error(error)
      }
    }
    if (!web3auth.connected) {
      initWeb3Auth()
    }
  }, [
    account,
    dispatch,
    isAuth,
    linkSocialStatus,
    linkedToSocial,
    loginBySocialStatus,
    loginedBySocial,
    setWeb3Auth,
    setWeb3AuthStatus,
  ])
}



this code is about switchChain and the initializes web3auth on my Apps, i use ethers version 5.7.2.
Chains

switch is
ETH_SEPOLIA: {

providerType: PROVIDER_TYPE.Ethereum,

name: ‘Ethereum Sepolia’,

id: 11155111,

rpc:

process.env.NEXT_PUBLIC_RPC_ETH_SEPOLIA ??

https://ethereum-sepolia-rpc.publicnode.com’,

symbol: ‘ETH’,

explorerUrl: ‘https://sepolia.etherscan.io’,

icon: ‘images/wallet/ethereum.png’,

typeNetwork: NETWORK_TYPE.ethereum,

hexChainId: ‘0xaa36a7’, // testnet

},

BASE_SEPOLIA: {

providerType: PROVIDER_TYPE.Base,

name: ‘Base Sepolia’,

id: 84532,

rpc:

process.env.NEXT_PUBLIC_RPC_BASE_SEPOLIA ??

https://base-sepolia-rpc.publicnode.com’,

symbol: ‘ETH’,

explorerUrl: ‘https://sepolia.basescan.org/’,

icon: ‘images/wallet/ethereum.png’,

typeNetwork: NETWORK_TYPE.base,

hexChainId: ‘0x14a34’, // testnet

},

BSC_TESTNET: {

providerType: PROVIDER_TYPE.BSC,

name: ‘Binance Smart Chain Testnet’,

id: 97,

rpc: ‘https://endpoints.omniatech.io/v1/bsc/testnet/public’,

symbol: ‘BSC’,

explorerUrl: ‘https://testnet.bscscan.com’,

icon: ‘images/bridge/token_bnb.png’,

typeNetwork: NETWORK_TYPE.bsc,

hexChainId: ‘0x61’,

},

And sometime i get this error when switch to BSC network ? please help me for that

Hi where did you get parameters for Binance chain? And you said sometimes you get the error could you share when