Skip to content

Commit

Permalink
refactor switch network logic
Browse files Browse the repository at this point in the history
  • Loading branch information
quetool committed Jun 5, 2024
1 parent d30ebb8 commit e08a70e
Show file tree
Hide file tree
Showing 15 changed files with 77 additions and 89 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 3.2.2

- Network change improvements

## 3.2.1

- Email Wallet improvements:
Expand Down
4 changes: 2 additions & 2 deletions example/android/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
versionName=3.2.1
versionCode=59
versionName=3.2.2
versionCode=61
12 changes: 6 additions & 6 deletions example/ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = W5R8AG9K22;
ENABLE_BITCODE = NO;
Expand All @@ -496,7 +496,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.web3modal.flutterExample.RunnerTests;
Expand All @@ -514,7 +514,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.web3modal.flutterExample.RunnerTests;
Expand All @@ -530,7 +530,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.web3modal.flutterExample.RunnerTests;
Expand Down Expand Up @@ -655,7 +655,7 @@
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = W5R8AG9K22;
ENABLE_BITCODE = NO;
Expand Down Expand Up @@ -686,7 +686,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 59;
CURRENT_PROJECT_VERSION = 61;
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = W5R8AG9K22;
ENABLE_BITCODE = NO;
Expand Down
4 changes: 2 additions & 2 deletions example/ios/Runner/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>3.2.1</string>
<string>3.2.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
Expand All @@ -36,7 +36,7 @@
</dict>
</array>
<key>CFBundleVersion</key>
<string>59</string>
<string>61</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSApplicationQueriesSchemes</key>
Expand Down
14 changes: 7 additions & 7 deletions example/lib/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,13 @@ class _MyHomePageState extends State<MyHomePage> {
ElevatedButton(
onPressed: () async {
_w3mService.launchConnectedWallet();
_w3mService.requestAddChain(polygon).then(
(value) {
final success = value == true;
debugPrint('[ExampleApp] then success $success');
Navigator.of(context).pop();
},
);
try {
await _w3mService.requestSwitchToChain(polygon);
} catch (e) {
debugPrint('[ExampleApp] requestSwitchToChain $e');
}
// ignore: use_build_context_synchronously
Navigator.of(context).pop();
},
child: const Text('Switch'),
),
Expand Down
2 changes: 1 addition & 1 deletion example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1139,7 +1139,7 @@ packages:
path: ".."
relative: true
source: path
version: "3.2.1"
version: "3.2.2"
web_socket_channel:
dependency: transitive
description:
Expand Down
2 changes: 1 addition & 1 deletion example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: A dApp showing how to use WalletConnect v2 with Flutter

publish_to: "none"

version: 3.2.1
version: 3.2.2

environment:
sdk: ">=3.0.1 <4.0.0"
Expand Down
51 changes: 13 additions & 38 deletions lib/pages/connet_network_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,25 @@ class _ConnectNetworkPageState extends State<ConnectNetworkPage>
WidgetsBinding.instance.addPostFrameCallback((_) {
_service = Web3ModalProvider.of(context).service;
_service?.onModalError.subscribe(_errorListener);
_service!.web3App!.onSessionEvent.subscribe(_onSessionEvent);
_service!.web3App!.core.relayClient.onRelayClientMessage.subscribe(
_onRelayClientMessage,
);
setState(() {});
Future.delayed(const Duration(milliseconds: 300), () {
_connect();
});
Future.delayed(const Duration(milliseconds: 300), () => _connect());
});
}

void _connect() {
void _connect() async {
errorEvent = null;
_service!.launchConnectedWallet();
_service!.requestSwitchToChain(widget.chainInfo);
setState(() {});
try {
await _service!.requestSwitchToChain(widget.chainInfo);
final chainId = widget.chainInfo.chainId;
if (W3MChainPresets.chains.containsKey(chainId)) {
Future.delayed(const Duration(milliseconds: 300), () {
widgetStack.instance.pop();
});
}
} catch (e) {
setState(() {});
}
}

@override
Expand All @@ -68,38 +71,10 @@ class _ConnectNetworkPageState extends State<ConnectNetworkPage>
}
}

void _onSessionEvent(SessionEvent? event) async {
if (!mounted) return;
if (event?.name == EventsConstants.chainChanged) {
debugPrint('[$runtimeType] _onSessionEvent $event');
final chainId = event?.data.toString() ?? '';
if (W3MChainPresets.chains.containsKey(chainId)) {
_service?.web3App?.onSessionEvent.unsubscribe(_onSessionEvent);
widgetStack.instance.pop();
}
}
}

void _onRelayClientMessage(MessageEvent? event) async {
if (!mounted) return;
if (event != null) {
final payloadString = await _service!.web3App!.core.crypto.decode(
event.topic,
event.message,
);
if (payloadString == null) return;
debugPrint('[$runtimeType] payloadString $payloadString');
}
}

void _errorListener(ModalError? event) => setState(() => errorEvent = event);

@override
void dispose() {
_service?.web3App?.core.relayClient.onRelayClientMessage.unsubscribe(
_onRelayClientMessage,
);
_service?.web3App?.onSessionEvent.unsubscribe(_onSessionEvent);
_service?.onModalError.unsubscribe(_errorListener);
WidgetsBinding.instance.removeObserver(this);
super.dispose();
Expand Down
10 changes: 4 additions & 6 deletions lib/pages/select_network_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,15 @@ class SelectNetworkPage extends StatelessWidget {

final Function(W3MChainInfo)? onTapNetwork;

void _onSelectNetwork(BuildContext context, W3MChainInfo chainInfo) {
void _onSelectNetwork(BuildContext context, W3MChainInfo chainInfo) async {
final service = Web3ModalProvider.of(context).service;
if (service.isConnected) {
final approvedChains = service.session!.getApprovedChains() ?? [];
final hasChainAlready = approvedChains.contains(
chainInfo.namespace,
);
final isChainApproved = approvedChains.contains(chainInfo.namespace);
if (chainInfo.chainId == service.selectedChain?.chainId) {
widgetStack.instance.pop();
} else if (hasChainAlready || service.session!.sessionService.isMagic) {
service.selectChain(chainInfo, switchChain: true);
} else if (isChainApproved || service.session!.sessionService.isMagic) {
await service.selectChain(chainInfo, switchChain: true);
widgetStack.instance.pop();
} else {
widgetStack.instance.push(ConnectNetworkPage(chainInfo: chainInfo));
Expand Down
4 changes: 2 additions & 2 deletions lib/services/w3m_service/i_w3m_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ abstract class IW3MService with ChangeNotifier {
required SessionRequestParams request,
});

Future<dynamic> requestSwitchToChain(W3MChainInfo newChain);
Future<dynamic> requestAddChain(W3MChainInfo newChain);
Future<void> requestSwitchToChain(W3MChainInfo newChain);
Future<void> requestAddChain(W3MChainInfo newChain);

/// Closes the modal.
void closeModal();
Expand Down
34 changes: 19 additions & 15 deletions lib/services/w3m_service/w3m_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1108,15 +1108,16 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
}

@override
Future<dynamic> requestSwitchToChain(W3MChainInfo newChain) async {
Future<void> requestSwitchToChain(W3MChainInfo newChain) async {
if (_currentSession?.sessionService.isMagic == true) {
return selectChain(newChain);
await selectChain(newChain);
return;
}
final currentChainId = _currentSelectedChain!.namespace;
final newChainId = newChain.namespace;
_logger.i('[$runtimeType] requesting switch to chain $newChainId');
try {
final response = await request(
await request(
topic: _currentSession?.topic ?? '',
chainId: currentChainId,
switchToChainId: newChainId,
Expand All @@ -1129,29 +1130,32 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
);
_currentSelectedChain = newChain;
await _setSesionAndChainData(_currentSession!);
return response ?? true;
return;
} catch (e) {
_logger.i('[$runtimeType] requesting switchChain error $e');
_logger.i('[$runtimeType] requestSwitchToChain error $e');
// if request errors due to user rejection then set the previous chain
if (_isUserRejectedError(e)) {
loggerService.instance.i('[$runtimeType] User declined connection');
await _setLocalEthChain(_currentSelectedChain!);
return null;
throw JsonRpcError(code: 5002, message: 'User rejected methods.');
} else {
// Otherwise it meas chain has to be added.
return await requestAddChain(newChain);
try {
// Otherwise it meas chain has to be added.
return await requestAddChain(newChain);
} catch (e) {
rethrow;
}
}
}
}

@override
Future<dynamic> requestAddChain(W3MChainInfo newChain) async {
Future<void> requestAddChain(W3MChainInfo newChain) async {
final topic = _currentSession?.topic ?? '';
final currentChainId = _currentSelectedChain!.namespace;
final newChainId = newChain.namespace;
_logger.i('[$runtimeType] requesting switch to chain $newChainId');
_logger.i('[$runtimeType] requesting switch to add chain $newChainId');
try {
final response = await request(
await request(
topic: topic,
chainId: currentChainId,
switchToChainId: newChainId,
Expand All @@ -1162,11 +1166,11 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
);
_currentSelectedChain = newChain;
await _setSesionAndChainData(_currentSession!);
return response ?? true;
return;
} catch (e) {
_logger.i('[$runtimeType] requesting addChain error $e');
_logger.i('[$runtimeType] requestAddChain error $e');
await _setLocalEthChain(_currentSelectedChain!);
return null;
throw JsonRpcError(code: 5002, message: 'User rejected methods.');
}
}

Expand Down
7 changes: 6 additions & 1 deletion lib/utils/w3m_chains_presets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ class W3MChainPresets {
chainId: '137',
chainIcon: chainImagesId['137'],
tokenName: 'MATIC',
rpcUrl: 'https://rpc-mainnet.maticvigil.com',
rpcUrl: 'https://polygon-bor-rpc.publicnode.com',
extraRpcUrls: [
'https://polygon.drpc.org',
'https://1rpc.io/matic',
'https://endpoints.omniatech.io/v1/matic/mainnet/public',
],
blockExplorer: W3MBlockExplorer(
name: 'Explorer',
url: 'https://polygonscan.com',
Expand Down
2 changes: 1 addition & 1 deletion lib/version.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: web3modal_flutter
description: "WalletConnect Web3Modal: Simple, intuitive wallet login. With this drop-in UI SDK, enable any wallet's users to seamlessly log in to your app and enjoy a unified experience"
version: 3.2.1
version: 3.2.2
repository: https://github.com/WalletConnect/Web3ModalFlutter

environment:
Expand Down
14 changes: 8 additions & 6 deletions test/mock_classes.mocks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -870,23 +870,25 @@ class MockW3MService extends _i1.Mock implements _i3.W3MService {
returnValueForMissingStub: _i14.Future<void>.value(),
) as _i14.Future<void>);
@override
_i14.Future<dynamic> requestSwitchToChain(_i3.W3MChainInfo? newChain) =>
_i14.Future<void> requestSwitchToChain(_i3.W3MChainInfo? newChain) =>
(super.noSuchMethod(
Invocation.method(
#requestSwitchToChain,
[newChain],
),
returnValue: _i14.Future<dynamic>.value(),
) as _i14.Future<dynamic>);
returnValue: _i14.Future<void>.value(),
returnValueForMissingStub: _i14.Future<void>.value(),
) as _i14.Future<void>);
@override
_i14.Future<dynamic> requestAddChain(_i3.W3MChainInfo? newChain) =>
_i14.Future<void> requestAddChain(_i3.W3MChainInfo? newChain) =>
(super.noSuchMethod(
Invocation.method(
#requestAddChain,
[newChain],
),
returnValue: _i14.Future<dynamic>.value(),
) as _i14.Future<dynamic>);
returnValue: _i14.Future<void>.value(),
returnValueForMissingStub: _i14.Future<void>.value(),
) as _i14.Future<void>);
@override
void addListener(_i17.VoidCallback? listener) => super.noSuchMethod(
Invocation.method(
Expand Down

0 comments on commit e08a70e

Please sign in to comment.