switchChain() not working

When asking for help in this category, please make sure to provide the following details:

  • SDK Version(package.json): “@web3auth/no-modal”: “^9.1.0”,
  • Platform: Web / nuxt
  • Browser Console Screenshots:

i call the switchChain method but its not working, it does not even return an error.

what am i doing wrong?
console


import { Web3AuthNoModal } from '@web3auth/no-modal'
import { CHAIN_NAMESPACES, type IProvider, WALLET_ADAPTERS, WEB3AUTH_NETWORK } from '@web3auth/base'
import { WalletConnector, type ChainId, numberToHex, ChainIds } from '@ryze-blockchain/ethereum'
import { AuthAdapter } from '@web3auth/auth-adapter'
import { EthereumPrivateKeyProvider } from '@web3auth/ethereum-provider'

const chainConfig = {
    chainNamespace: CHAIN_NAMESPACES.EIP155,
    chainId: numberToHex(ChainIds.BNB),
    rpcTarget: 'https://bsc-dataseed.binance.org/',
    displayName: 'Binance Smart Chain',
    blockExplorerUrl: 'https://bscscan.com/',
    ticker: 'BNB',
    tickerName: 'Binance Coin',
    logo: '/images/chains/binance.svg',
}

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

const web3auth = new Web3AuthNoModal({
    clientId: 'BPS1KO7rAWwv_KdX9df1aMZFpCnJW4PgnpG0i2yGz9esEGoJLklJPveg02gampc_nr4_fR1pJJQZGOtlS22-jcA',
    web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_DEVNET,
    privateKeyProvider,
})

const authAdapter = new AuthAdapter({ privateKeyProvider })

web3auth.configureAdapter(authAdapter)

export class Web3AuthConnector extends WalletConnector<IProvider> {
    public readonly id: string = 'web3auth'
    public readonly name: string = 'Login with Google'
    private static initialized = false

    public async getProvider() {
        if (!Web3AuthConnector.initialized) {
            Web3AuthConnector.initialized = true

            await web3auth.init()
        }

        if (!web3auth.connected)
            await web3auth.connectTo(WALLET_ADAPTERS.AUTH, { loginProvider: 'google' })

        const web3authProvider = web3auth.provider

        if (!web3authProvider)
            throw new Error('Failed to connect to Web3Auth')

        return web3authProvider
    }

    public async addChain(chainId: ChainId): Promise<void> {
        console.log('adding chain: ', chainId)

        if (chainId === ChainIds.BNB) {
            await web3auth.addChain({
                chainId: '0x38',
                displayName: 'Binance Smart Chain',
                chainNamespace: CHAIN_NAMESPACES.EIP155,
                tickerName: 'Binance Coin',
                ticker: 'BNB',
                decimals: 18,
                rpcTarget: 'https://bsc-dataseed.binance.org/',
                blockExplorerUrl: 'https://bscscan.com/',
                logo: '/images/chains/binance.svg',
                isTestnet: false,
            })
        }

        if (chainId === ChainIds.ARBITRUM) {
            console.log('adding arbitrum chain')

            try {
                await web3auth.addChain({
                    chainId: '0xa4b1',
                    displayName: 'Arbitrum',
                    chainNamespace: CHAIN_NAMESPACES.EIP155,
                    tickerName: 'Arbitrum',
                    ticker: 'ARB',
                    decimals: 18,
                    rpcTarget: 'https://arb1.arbitrum.io/rpc',
                    blockExplorerUrl: 'https://arbiscan.io/',
                    logo: '/images/chains/arbitrum.svg',
                    isTestnet: false,
                })
            }
            catch (error) {
                console.log('error adding arbitrum chain', error)
            }
        }
    }

    public async disconnect() {
        await web3auth.logout()
    }

    public async setChain(chain: ChainId): Promise<void> {
        console.log('chainId before switch: ', web3auth.provider?.chainId)

        try {
            await this.addChain(chain)
        }
        catch (error) {
            console.error('Failed to add chain', error)
        }

        try {
            await web3auth.switchChain({ chainId: numberToHex(chain) })
        }
        catch (error) {
            console.error('Failed to switch chain', error)
        }
        console.log('chainId after switch: ', web3auth.provider?.chainId)
    }
}

Hi Matheus!

Thanks for sharing your issue regarding the switchChain() method not working within the PnP Web SDK. I’ve gathered the necessary details to assist you:

Issue Summary:

  • SDK Details: PnP Web SDK
  • SDK Version: @web3auth/no-modal version 9.1.0
  • Platform: Web / Nuxt
  • Error: switchChain() method doesn’t return an error but is not functioning.

Additional Information:

  • Browser Console Screenshot: [Attached Image]

Code Snippet:

You provided a detailed code snippet that includes your implementation of the Web3AuthConnector class.

Suggested Next Steps:

  1. Ensure Chain Addition: It seems you are trying to add a chain before switching. Confirm that the chain is indeed being added successfully, and check the logs after the addChain method call.
  2. Inspect Chain IDs: Make sure the chain IDs being passed to the switchChain() method match the ones used when adding the chain (e.g., 0x38 for Binance).
  3. Add Logging: You might want to add additional logging right before and after the await web3auth.switchChain() call to see if it was reached in execution.

If the issue persists, could you please double-check the console for any hidden warnings or errors? You might also want to provide any relevant information regarding the specific chain you are trying to switch to.

Your detailed information will help the support team assist you better. Thank you for reaching out! If you have any further questions or updates, feel free to share.

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

Hey @matheussimasalves,

I recall we resolved this issue during office hours. The root cause was related to how you were retrieving the chain ID of the currently active chain. The chain switching was successful, but note that the Web3Auth object always retains the chain ID it was initialized with, even though the active chain ID may change when switching or adding chains. Marking this issue as resolved.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.