How to switchChain() using Wagmi connectors?

SDK Version:
@web3auth/ethereum-provider”: “^7.2.0”,
@web3auth/modal”: “^7.2.0”,
@web3auth/openlogin-adapter”: “^7.2.0”,
@web3auth/wallet-connect-v2-adapter”: “^7.2.0”,
@web3auth/web3auth-wagmi-connector”: “^5.0.1”,
@web3modal/ethereum”: “2.6.2”,
@web3modal/react”: “^2.6.2”,

I read docs
(Using PnP Web Modal SDK | Documentation | Web3Auth)

but Nothing is happening to me
What is my problem?

this my code

import { mainnet } from 'wagmi/chains';
import { CHAIN_NAMESPACES } from '@web3auth/base';
import { Chain, useAccount } from 'wagmi';

const { connector } = useAccount();

const web3AuthChainConfig = (chains: Chain) => {
  return {
    chainNamespace: CHAIN_NAMESPACES.EIP155,
    chainId: '0x' + chains.id.toString(16),
    rpcTarget: chains.rpcUrls.default.http[0],
    displayName: chains.name,
    tickerName: chains.nativeCurrency?.name,
    ticker: chains.nativeCurrency?.symbol,
    blockExplorer: chains.blockExplorers?.default.url as string,
    decimals: chains.nativeCurrency.decimals,
  };
};

const handleChain = async () => {
    const web3Auth = connector?.options.web3AuthInstance;
    const eth = web3AuthChainConfig(mainnet);
    console.log(eth);
    await web3Auth.addChain(eth);
    await web3Auth.switchChain({ chainId: eth.chainId });
    console.log(`switchChain`);
  };

return (
   {chain?.name} **{/* < =Chain name not changed */}**
   <button onclick={handleChain}>chain</button>
)

console.log(eth) {
  blockExplorer: "https://etherscan.io"
  chainId: "0x1"
  chainNamespace: "eip155"
  decimals: 18
  displayName: "Ethereum"
  rpcTarget: "https://cloudflare-eth.com"
  ticker: "ETH"
  tickerName: "Ether"
}

@jh.koo Thanks for reaching out.

I will link an example here to understand the usage of switchchain()

I’ve already seen it.
(https://github.com/Web3Auth/web3auth-pnp-examples/blob/main/web-modal-sdk/blockchain-connection-examples/evm-modal-example/src/App.tsx#L283)

Which should I choose, import { useNetwork, useSwitchNetwork } from ‘wagmi’ or
await web3Auth.switchChain({ chainId: eth.chainId });?

Neither works.

Are you adding the chain first using addChain() that you need to switch to using switchChain() ? It is working for me. Please see the functions below:

If you want to use Wagmi to switch chains, you can utilize NetworkSwitcher function below:

1 Like

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