Breaking change in SDK version 0.4.0: switchActiveNetwork no longer automatically calls addNetwork when the network is not added to the wallet. You must now handle NetworkNotAddedError and explicitly call addNetwork if needed.
The active network id is the id that the Dynamic SDK uses to identify the active network of a wallet account.
For EVM wallets, it will be the same as the chain id (e.g: 1, 137, 56, etc).
For other chains, it will an internal id used in Dynamic.
To switch the active network, you can use the switchActiveNetwork function.
Usage
import { switchActiveNetwork } from '@dynamic-labs-sdk/client';
const switchNetwork = async () => {
// Replace with the network id you want to switch to
await switchActiveNetwork({ walletAccount, networkId: '1' });
}
Error Handling
The switchActiveNetwork function can throw the following errors:
NetworkSwitchingUnavailableError
If the wallet provider does not support network switching, the function will throw a NetworkSwitchingUnavailableError error.
You can check if the wallet provider supports network switching by calling the isProgrammaticNetworkSwitchAvailable function.
NetworkNotAddedError
If the network is not added to the wallet, the function will throw a NetworkNotAddedError error. This error includes the network data in the networkData property, which can be passed directly to the addNetwork function.
import { switchActiveNetwork, addNetwork, NetworkNotAddedError } from '@dynamic-labs-sdk/client';
const switchNetwork = async () => {
try {
await switchActiveNetwork({ walletAccount, networkId: '137' });
} catch (error) {
if (error instanceof NetworkNotAddedError) {
// The network is not added to the wallet
// You can add it using the addNetwork function
try {
await addNetwork({
walletAccount,
networkData: error.networkData
});
// Retry switching after adding the network
await switchActiveNetwork({ walletAccount, networkId: '137' });
} catch (addError) {
if (addError instanceof NetworkAddingUnavailableError) {
console.error('This wallet does not support adding networks');
// Prompt user to manually add the network in their wallet
}
}
}
}
}