requestSwitchToChain method

  1. @override
Future<void> requestSwitchToChain(
  1. ReownAppKitModalNetworkInfo newChain
)
override

Implementation

@override
Future<void> requestSwitchToChain(
    ReownAppKitModalNetworkInfo newChain) async {
  if (_currentSession?.sessionService.isMagic == true) {
    await selectChain(newChain);
    return;
  }
  final currentChain = '${CoreConstants.namespace}:$_currentSelectedChainId';
  final newChainId = '${CoreConstants.namespace}:${newChain.chainId}';
  _logger.i('[$runtimeType] requesting switch to chain $newChainId');
  try {
    await request(
      topic: _currentSession?.topic ?? '',
      chainId: currentChain,
      switchToChainId: newChainId,
      request: SessionRequestParams(
        method: MethodsConstants.walletSwitchEthChain,
        params: [
          {'chainId': newChain.chainHexId}
        ],
      ),
    );
    _currentSelectedChainId = newChain.chainId;
    await _setSesionAndChainData(_currentSession!);
    return;
  } catch (e) {
    _logger.i('[$runtimeType] requestSwitchToChain error $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);
      } catch (e) {
        rethrow;
      }
    }
  }
}