walletSwitchChain method

Future<void> walletSwitchChain(
  1. int chainId, [
  2. void unrecognizedChainHandler()?
])

Creates a confirmation asking the user to switch to the chain with the specified chainId.

If the specified chain ID has not been added, unrecognizedChainHandler will be called if not null. Else will throw EthereumUnrecognizedChainException.

As with any method that causes a confirmation to appear, wallet_switchEthereumChain should only be called as a result of direct user action, such as the click of a button.

MetaMask will automatically reject the request under the following circumstances:

  • If the chain ID is malformed
  • If the chain with the specified chain ID has not been added to MetaMask

// Switch to chain 97 and add the chain when unrecognized

await ethereum!.walletSwitchChain(97, () async {
  await ethereum!.walletAddChain(
    chainId: 97,
    chainName: 'Binance Testnet',
    nativeCurrency:
        CurrencyParams(name: 'BNB', symbol: 'BNB', decimals: 18),
    rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
  );
});

// Or catch `EthereumUnrecognizedChainException`
try {
  await ethereum!.walletSwitchChain(97);
} on EthereumUnrecognizedChainException {
  await ethereum!.walletAddChain(
    chainId: 97,
    chainName: 'Binance Testnet',
    nativeCurrency:
        CurrencyParams(name: 'BNB', symbol: 'BNB', decimals: 18),
    rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
  );
}

Implementation

Future<void> walletSwitchChain(int chainId,
    [void Function()? unrecognizedChainHandler]) async {
  try {
    await request('wallet_switchEthereumChain', [
      _AddEthereumChainParameterImpl(
          chainId: '0x' + chainId.toRadixString(16)),
    ]);
  } catch (error) {
    switch (convertToDart(error)['code']) {
      case 4902:
        unrecognizedChainHandler != null
            ? unrecognizedChainHandler.call()
            : throw EthereumUnrecognizedChainException(chainId);
        break;
      default:
        rethrow;
    }
  }
}