Connect to specific blockchain on CoinbaseWalletSdk provider init

Viewed 26

I am trying to connect to the polygon chain when creating a new Web3Modal and the coinbaseWalletSdk.

According to what I found, the following code initializes the provider and should connect to chain id 137 (polygon). It does create the provider and connect to it, but the wallet app displays a message asking to switch to the Ethereum chain.

const providerOptions = {
    'custom-coinbase': {
        display: {
          name: 'Coinbase',
          description: 'Scan with Coinbase to connect',
          logo: "assets/coinbase_logo.jpg"
        },
        options: {
          appName: 'My app', // Your app name
          networkUrl: `https://mainnet.infura.io/v3/${INFURA_KEY}`,
          chainId: 137,
        },
        package: CoinbaseWalletSDK,
        connector: async (_, options) => {
            const { appName, networkUrl, chainId } = options
            const coinbaseLink = new CoinbaseWalletSDK({
                appName
            });
            const provider = coinbaseLink.makeWeb3Provider(networkUrl, chainId);
            await provider.enable();
            return provider;
        }
    }
}
this.web3Modal = new Web3Modal.default({
    cacheProvider: false,
    providerOptions
});
let provider = await this.web3Modal.connectTo("custom-coinbase");
this.web3 = new Web3(provider);

Okay, all goes well and after scanning the QR code presented it makes connection to my wallet. But after allowing the connection in the wallet I get a popup that the website wants to switch to the ethereum network.

Ethereum popup

Only after switching chain ID manually, the wallet gets connected to the polygon chain.

const chainId = 137;
await this.web3.currentProvider.request({
    method: 'wallet_switchEthereumChain',
    params: [{ chainId: Web3.utils.toHex(chainId) }],
});

Switch polygon chain

Is there a way to do it in one go? I would really like the user to be connected to the polygon chain immediately.

If this question is better asked on the ethereum.stackexchange then please feel free to move it there.

1 Answers

There's one potential issue that I can see. You are using the wrong RPC for polygon:

        options: {
          appName: 'My app', // Your app name
          networkUrl: `https://mainnet.infura.io/v3/${INFURA_KEY}`,
          chainId: 137,
        },

Secondly, from the docs, it appears that your initialization should be:

const providerOptions = {
  coinbasewallet: {
    package: CoinbaseWalletSDK,
    options: {
      appName: "My Awesome App",
      infuraId: "INFURA_ID",
      chainId: 137,
    }
  }
};

Without a custom connector.

Related