Walletconnect v2 chains not supported with web3-react

63 Views Asked by At

I'm upgrading from the 6.x library to 8x and I'm having problems with the walletconnectv2 connector.

I get this error:

Error connecting to wallet: Error: Invalid chainId 5. Make sure the default chain is included in "chains" - chains specified in "optionalChains" may not be selected as default, as they may not be supported by the wallet.

Connector code:

import { initializeConnector } from '@web3-react/core'
import { WalletConnect as WalletConnectV2 } from '@web3-react/walletconnect-v2'

export const [walletConnectV2, hooks] = initializeConnector<WalletConnectV2>(
  (actions) =>
    new WalletConnectV2({
      actions,
      options: {
        projectId:"......",
        chains: [1, 56, 43114, 106, 137],
        optionalChains: [5, 80001, 421613, 97, 43113, 111],
        showQrModal: true,
      },
    })
)

Hook code:

const connect = useCallback(
    async (walletName, chainId) => {
      let chain: IChainState | null = null;
      let connector: MetaMask | WalletConnect;

      // Metamask NOT found
      if (walletName === 'Metamask' && typeof window?.ethereum === 'undefined') {
        console.warn('Web3 injection not found!');
        notifyError({
          title: 'Provider not found',
          message: 'Provider was not found, please try again',
        });
        return;
      }

      // Connect to metamask and recover chain state
      if (walletName === 'Metamask') {
        connector = metaMask;
        await switchChainOrAdd([getAddChainParameters(chainId.id)]);
        chain = { ...recoverChainState(chainId.id), provider: Web3?.givenProvider };
      }

      // Connect to walletconnect and recover chain state
      if (walletName === 'Trust Wallet') {
        connector = walletConnectV2;
        const params = getAddChainParameters(chainId.id);
        chain = {
          id: params?.chainId,
          name: params?.chainName,
          icon: params?.iconUrls?.[0] ?? '<icon>',
          chainRsp: '<ChainRsp>',
          currency: params?.nativeCurrency?.symbol,
          provider: Web3?.givenProvider,
          txScan: '<ScanuRL>',
          rpcUrl: 'https://gateway.tenderly.co/public/goerli',
          defaultChainId: params?.chainId,
        };
      }
      console.log(chainId, 'chainId')

      try {
        localStorage.setItem(
          'Wallet',
          JSON.stringify({ name: walletName, chainId: network.provider, expireDate: dayjs().add(2, 'hour').format() })
        );
        chainDispatch({ type: 'chainSwitch', payload: chain });
        await connector.activate(chainId.id);
      } catch (e) {
        console.error('Error connecting to wallet:', e);
        setError(e instanceof Error ? e : new Error('Failed to connect to the wallet'));
      }
    },
    [chainDispatch]
  );

chains.ts

import type { AddEthereumChainParameter } from '@web3-react/types'

const ETH: AddEthereumChainParameter['nativeCurrency'] = {
  name: 'Ether',
  symbol: 'ETH',
  decimals: 18,
}

const MATIC: AddEthereumChainParameter['nativeCurrency'] = {
  name: 'Matic',
  symbol: 'MATIC',
  decimals: 18,
}

const CELO: AddEthereumChainParameter['nativeCurrency'] = {
  name: 'Celo',
  symbol: 'CELO',
  decimals: 18,
}

interface BasicChainInformation {
  urls: string[]
  name: string
}

interface ExtendedChainInformation extends BasicChainInformation {
  nativeCurrency: AddEthereumChainParameter['nativeCurrency']
  blockExplorerUrls: AddEthereumChainParameter['blockExplorerUrls']
}

function isExtendedChainInformation(
  chainInformation: BasicChainInformation | ExtendedChainInformation
): chainInformation is ExtendedChainInformation {
  return !!(chainInformation as ExtendedChainInformation).nativeCurrency
}

export function getAddChainParameters(chainId: number): AddEthereumChainParameter | number {
  const chainInformation = CHAINS[chainId]
  if (isExtendedChainInformation(chainInformation)) {
    return {
      chainId,
      chainName: chainInformation.name,
      nativeCurrency: chainInformation.nativeCurrency,
      rpcUrls: chainInformation.urls,
      blockExplorerUrls: chainInformation.blockExplorerUrls,
    }
  }
    return chainId

}

const getInfuraUrlFor = (network: string) =>
  process.env.infuraKey ? `https://${network}.infura.io/v3/${process.env.infuraKey}` : undefined
const getAlchemyUrlFor = (network: string) =>
  process.env.alchemyKey ? `https://${network}.alchemyapi.io/v2/${process.env.alchemyKey}` : undefined

type ChainConfig = { [chainId: number]: BasicChainInformation | ExtendedChainInformation }

export const MAINNET_CHAINS: ChainConfig = {
  1: {
    urls: [getInfuraUrlFor('mainnet'), getAlchemyUrlFor('eth-mainnet'), 'https://cloudflare-eth.com'].filter(Boolean),
    name: 'Mainnet',
  },
  10: {
    urls: [getInfuraUrlFor('optimism-mainnet'), 'https://mainnet.optimism.io'].filter(Boolean),
    name: 'Optimism',
    nativeCurrency: ETH,
    blockExplorerUrls: ['https://optimistic.etherscan.io'],
  },
  42161: {
    urls: [getInfuraUrlFor('arbitrum-mainnet'), 'https://arb1.arbitrum.io/rpc'].filter(Boolean),
    name: 'Arbitrum One',
    nativeCurrency: ETH,
    blockExplorerUrls: ['https://arbiscan.io'],
  },
  137: {
    urls: [getInfuraUrlFor('polygon-mainnet'), 'https://polygon-rpc.com'].filter(Boolean),
    name: 'Polygon Mainnet',
    nativeCurrency: MATIC,
    blockExplorerUrls: ['https://polygonscan.com'],
  },
  42220: {
    urls: ['https://forno.celo.org'],
    name: 'Celo',
    nativeCurrency: CELO,
    blockExplorerUrls: ['https://explorer.celo.org'],
  },
}

export const TESTNET_CHAINS: ChainConfig = {
  5: {
    urls: [getInfuraUrlFor('goerli')].filter(Boolean),
    name: 'Görli',
  },
  420: {
    urls: [getInfuraUrlFor('optimism-goerli'), 'https://goerli.optimism.io'].filter(Boolean),
    name: 'Optimism Goerli',
    nativeCurrency: ETH,
    blockExplorerUrls: ['https://goerli-explorer.optimism.io'],
  },
  421613: {
    urls: [getInfuraUrlFor('arbitrum-goerli'), 'https://goerli-rollup.arbitrum.io/rpc'].filter(Boolean),
    name: 'Arbitrum Goerli',
    nativeCurrency: ETH,
    blockExplorerUrls: ['https://testnet.arbiscan.io'],
  },
  80001: {
    urls: [getInfuraUrlFor('polygon-mumbai')].filter(Boolean),
    name: 'Polygon Mumbai',
    nativeCurrency: MATIC,
    blockExplorerUrls: ['https://mumbai.polygonscan.com'],
  },
  44787: {
    urls: ['https://alfajores-forno.celo-testnet.org'],
    name: 'Celo Alfajores',
    nativeCurrency: CELO,
    blockExplorerUrls: ['https://alfajores-blockscout.celo-testnet.org'],
  },
}

export const CHAINS: ChainConfig = {
  ...MAINNET_CHAINS,
  ...TESTNET_CHAINS,
}

export const URLS: { [chainId: number]: string[] } = Object.keys(CHAINS).reduce<{ [chainId: number]: string[] }>(
  (accumulator, chainId) => {
    const validURLs: string[] = CHAINS[Number(chainId)].urls

    if (validURLs.length) {
      accumulator[Number(chainId)] = validURLs
    }

    return accumulator
  },
  {}
)

With Metamask I have it working, the problem is with WalletConnectV2. For this reason I understand that it does not show the modal.

Any suggestions?

Thank you

0

There are 0 best solutions below