requestSwitchToChain method
Implementation
@override
Future<void> requestSwitchToChain(
ReownAppKitModalNetworkInfo newChain,
) async {
final namespace = ReownAppKitModalNetworks.getNamespaceForChainId(
newChain.chainId,
);
if (namespace != NetworkUtils.eip155) {
// If chain is not EVM then there's no need to request a switch since it doesn't exist such method for non-EVM chains
// Therefor at this point the selected non-EVM chain is either already approved, invalidating the need of a switch call, or not approved, failing with the following error.
throw ReownAppKitModalException('Chain namespace is not supported');
}
if (_currentSession?.sessionService.isMagic == true) {
await selectChain(newChain);
return;
}
final currentCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
_currentSelectedChainId!,
);
final newCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
newChain.chainId,
);
_appKit.core.logger.i(
'[$runtimeType] requesting switch to chain $newCaip2Chain',
);
try {
await request(
topic: _currentSession?.topic ?? '',
chainId: currentCaip2Chain,
switchToChainId: newCaip2Chain,
request: SessionRequestParams(
method: MethodsConstants.walletSwitchEthChain,
params: [
{'chainId': newChain.chainHexId}
],
),
);
_currentSelectedChainId = newChain.chainId;
await _setSesionAndChainData(_currentSession!);
return;
} catch (e) {
// if request errors due to user rejection then set the previous chain
if (_isUserRejectedError(e)) {
// fallback to current chain if rejected by user
await _setLocalEthChain(_currentSelectedChainId!);
throw JsonRpcError(code: 5002, message: 'User rejected methods.');
} else {
try {
// Otherwise it meas chain has to be added.
return await requestAddChain(newChain);
} on JsonRpcError catch (e) {
_appKit.core.logger.e(
'[$runtimeType] Switch to chain error: ${e.toJson()}',
);
rethrow;
} on ReownAppKitModalException catch (e) {
_appKit.core.logger.e(
'[$runtimeType] Switch to chain error: ${e.message}',
stackTrace: e.stackTrace,
);
rethrow;
} catch (e, s) {
_appKit.core.logger.e(
'[$runtimeType] Switch to chain error: ${e.toString()}',
stackTrace: s,
);
rethrow;
}
}
}
}