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

**URL:** <https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565>\
**Category:** Embedded Wallets (Web3Auth)\
**Created:** [October 22, 2025, 4:47pm UTC](https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565 "2025-10-22T16:47:19Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Peter\_Pham](https://yyz1.discourse-cdn.com/flex011/user_avatar/builder.metamask.io/peter_pham/32/1628_2.png) [@Peter\_Pham](https://builder.metamask.io/u/Peter_Pham)\
**Post date:** [October 22, 2025, 4:47pm UTC](https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565/1 "2025-10-22T16:47:19Z")

</div>

- **What’s on your mind?**

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex011/uploads/metamaskbuilderhub/original/1X/082cfc3a14103b01cfa5ef7d85f1121a23fa3e81.png) [@system](https://builder.metamask.io/u/system)\
**Post date:** [October 22, 2025, 4:49pm UTC](https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565/2 "2025-10-22T16:49:22Z")

</div>

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](https://your-rpc.example)’],  
blockExplorerUrls: [‘[https://explorer.example](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](https://builder.metamask.io/t/metamask-developer-office-hours/2544/1)

---

<div class="post-metadata">

**Author:** ![Peter\_Pham](https://yyz1.discourse-cdn.com/flex011/user_avatar/builder.metamask.io/peter_pham/32/1628_2.png) [@Peter\_Pham](https://builder.metamask.io/u/Peter_Pham)\
**Post date:** [October 23, 2025, 12:15am UTC](https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565/3 "2025-10-23T00:15:23Z")

</div>

```auto
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](https://ethereum-sepolia-rpc.publicnode.com)’,

symbol: ‘ETH’,

explorerUrl: ‘[https://sepolia.etherscan.io](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](https://base-sepolia-rpc.publicnode.com)’,

symbol: ‘ETH’,

explorerUrl: ‘[https://sepolia.basescan.org/](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](https://endpoints.omniatech.io/v1/bsc/testnet/public)’,

symbol: ‘BSC’,

explorerUrl: ‘[https://testnet.bscscan.com](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

 ![Screen Shot 2025-10-23 at 07.12.38](https://canada1.discourse-cdn.com/flex011/uploads/metamaskbuilderhub/original/2X/1/124cf837a8de4597ec7f44e48b2f8dd3bf47cda8.png)

---

<div class="post-metadata">

**Author:** ![shana](https://avatars.discourse-cdn.com/v4/letter/s/3bc359/32.png) [@shana](https://builder.metamask.io/u/shana)\
**Post date:** [October 27, 2025, 9:34am UTC](https://builder.metamask.io/t/does-addchain-and-switchchain-function-working-on-web3auth-version-9-7-0-now-i-cannot-switch-change-while-using-switchchain-function/2565/4 "2025-10-27T09:34:50Z")

</div>

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