Web3Auth connection with WalletConnect issue using polygon

Hello there, I’m currently using web3auth with both WalletConnect and Metamask. However, I am experiencing some issues when trying to connect to Polygon through WalletConnect. After the connection is established, I receive an error message when using Next.js. Unfortunately, I haven’t been able to find a solution to this problem.

export const useWeb3Auth = () => {
  const [web3auth, setWeb3auth] = useState<Web3Auth | null>(null)
  const [provider, setProvider] = useState<IProvider | null>(null)
  const [isConnected, setIsConnected] = useState<boolean>(false)
  const [address, setAddress] = useState<addressType>(undefined)
  const [chainId, setChainId] = useState<number | null>(null)
  const [web3authStatus, setWeb3AuthStatus] = useState<string | null>(null)

  const initWeb3Auth = async (defaultConnection?: CustomChainConfig): Promise<Web3Auth> => {
    const web3AuthConfig = generateWeb3AuthConfig(defaultConnection)
    const web3AuthInstance = new Web3Auth(web3AuthConfig)
    web3AuthInstance.configureAdapter(openloginAdapter)

    const adapters = await getDefaultExternalAdapters({ options: web3AuthConfig })
    adapters.forEach((adapter) => {
      web3AuthInstance.configureAdapter(adapter)
    })

    await web3AuthInstance.initModal()
    setWeb3auth(web3AuthInstance)
    return web3AuthInstance
  }

  const login = useCallback(
    async (defaultChain?: CustomChainConfig, isSwap?: boolean) => {
      try {
        await (async () => {
          let web3AuthInstance = web3auth
          if ((!web3AuthInstance || defaultChain) && !isSwap) {
            console.info('[web3auth] starting')
            web3AuthInstance = await initWeb3Auth(defaultChain)
          }
          if (!web3AuthInstance) {
            console.warn('[web3auth] not initialized yet')
            return
          }

          const web3Provider = provider || (await web3AuthInstance.connect())
          if (web3Provider) {
            const ethersProvider = new ethers.providers.Web3Provider(web3Provider)
            await getAddress(ethersProvider)
            await getChainId(ethersProvider)
            setProvider(web3Provider)
            setIsConnected(true)
          }
        })()
      } catch (error) {
        console.error('Error during login process:', error)
      }
    },
    [provider, web3auth, setProvider, setIsConnected],
  )

  // Check current connection
  useEffect(() => {
    if (web3auth && web3auth.status === 'connected' && !provider) {
      login()
    }
  }, [web3auth, provider, login])

  const swapChain = useCallback(
    async (network: CustomChainConfig) => {
      try {
        if (!web3auth) return
        await web3auth.addChain(network)
        console.info('[web3auth] New Chain Added')
        await web3auth.switchChain({ chainId: network.chainId })
        await login(network, true)
      } catch (error: unknown) {
        const web3AuthError = error as Web3AuthError
        throw web3AuthError
      }
    },
    [web3auth, login],
  )

  const getAddress = async (ethersProvider: ethers.providers.Web3Provider) => {
    const signer = ethersProvider.getSigner()
    const address = await signer.getAddress()
    setAddress(address as addressType)
  }
  const getChainId = async (ethersProvider: ethers.providers.Web3Provider) => {
    const network = await ethersProvider.getNetwork()
    setChainId(network.chainId)
  }

  const clearStates = () => {
    setProvider(null)
    setIsConnected(false)
    setAddress(undefined)
    setChainId(null)
    setWeb3AuthStatus(null)
  }

  const logout = useCallback(async () => {
    if (!web3auth || !isConnected) {
      console.warn('[web3auth] not initialized yet or not connected')
      return
    }
    try {
      await web3auth.logout()
    } catch (error) {
      console.error('Error during logout:', error)
    }
    clearStates()
  }, [web3auth, isConnected])

  return { web3auth, provider, isConnected, address, chainId, web3authStatus, swapChain, login, logout }
}

Hi @julio,

It would be really helpful if you could share your Web3Auth configuration with me. A screenshot from the console captured at the moment you’re encountering the issue would be fine. Additionally, knowing the specific package you’re working with can give us a clearer picture of what might be going wrong.

Thanks a lot for taking the time to gather this information. I’m here to assist you every step of the way, so please feel free to share these details at your convenience.

Hey Tom.

Thank you for guiding me through this. Here is the information you requested:

  1. Package Versions:
  • @web3auth/base: ^8.0.0
  • @web3auth/default-evm-adapter: ^8.0.1
  • @web3auth/ethereum-provider: ^8.0.1
  • @web3auth/modal: ^8.0.1
  • @web3auth/openlogin-adapter: ^8.0.1

These are the current versions of the packages I’m using in my project.

  1. Web3Auth Configuration: I’ve used the following configuration to initialize Web3Auth in my Next.js application:
import { CustomChainConfig, OPENLOGIN_NETWORK_TYPE } from '@web3auth/base'
import { EthereumPrivateKeyProvider } from '@web3auth/ethereum-provider'
import { Web3AuthOptions } from '@web3auth/modal'
import { OpenloginAdapter } from '@web3auth/openlogin-adapter'
import { WEB3_AUTH_CHAINS } from './utils/networkEnvironments'

// Web3 AuthModal
const WEB3_AUTH_CLIENT_ID = process.env.NEXT_PUBLIC_WEB3_AUTH_CLIENT_ID
const WEB3_AUTH_NETWORK = process.env.NEXT_PUBLIC_WEB3_AUTH_NETWORK

if (!WEB3_AUTH_CLIENT_ID) {
  throw new Error('[Missing ENV] - NEXT_PUBLIC_WEB3_AUTH_CLIENT_ID')
}
if (!WEB3_AUTH_NETWORK) {
  throw new Error('[Missing ENV] - WEB3_AUTH_NETWORK')
}

export const generateWeb3AuthConfig = (defaultNetwork?: CustomChainConfig): Web3AuthOptions => {
  const defaultChainConfig = defaultNetwork ?? WEB3_AUTH_CHAINS[0]
  const ethereumPrivateKeyProvider = new EthereumPrivateKeyProvider({
    config: {
      chainConfig: defaultChainConfig,
    },
  })
  return {
    clientId: WEB3_AUTH_CLIENT_ID,
    web3AuthNetwork: WEB3_AUTH_NETWORK as OPENLOGIN_NETWORK_TYPE,
    chainConfig: defaultChainConfig,
    uiConfig: {
      appName: 'Perpetual',
      theme: {
        primary: 'rgba(0, 172, 134, 0.60)',
      },
      modalZIndex: '9998',
      mode: 'dark',
      logoLight: '/assets/icons/cipherem.svg',
      logoDark: '/assets/icons/cipherem.svg',
      defaultLanguage: 'en', // en, de, ja, ko, zh, es, fr, pt, nl
      loginGridCol: 3,
      primaryButton: 'externalLogin', // "externalLogin" | "socialLogin" | "emailLogin"
    },
    privateKeyProvider: ethereumPrivateKeyProvider,
  }
}

export const openloginAdapter = new OpenloginAdapter({
  loginSettings: {
    mfaLevel: 'optional',
  },
  adapterSettings: {
    uxMode: 'popup', // "redirect" | "popup"
    whiteLabel: {
      logoLight: '/assets/icons/cipherem.svg',
      logoDark: '/assets/icons/cipherem.svg',
      defaultLanguage: 'en', // en, de, ja, ko, zh, es, fr, pt, nl
      mode: 'dark', // whether to enable dark, light or auto mode. defaultValue: auto [ system theme]
    },
    mfaSettings: {
      deviceShareFactor: {
        enable: true,
        priority: 1,
        mandatory: true,
      },
      backUpShareFactor: {
        enable: true,
        priority: 2,
        mandatory: true,
      },
      socialBackupFactor: {
        enable: true,
        priority: 3,
        mandatory: true,
      },
      passwordFactor: {
        enable: true,
        priority: 4,
        mandatory: true,
      },
    },
  },
})

image

Additionally, I’ve attached the requested screenshots showing the error in the console.

I hope this information helps in diagnosing the issue. Please let me know if there’s anything else I can provide or do to assist further.

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