diff --git a/.github/actions/dependencies/action.yml b/.github/actions/dependencies/action.yml index 6d4587e8..8b4bf4af 100644 --- a/.github/actions/dependencies/action.yml +++ b/.github/actions/dependencies/action.yml @@ -8,8 +8,7 @@ runs: - name: Install Flutter uses: subosito/flutter-action@v2 with: - channel: "stable" - architecture: x64 + flutter-version: '3.19.5' # Get package dependencies and generate files - name: Get package dependencies and generate files diff --git a/.github/workflows/release_dapp_android.yml b/.github/workflows/release_dapp_android.yml index ce5293c6..3188d495 100644 --- a/.github/workflows/release_dapp_android.yml +++ b/.github/workflows/release_dapp_android.yml @@ -1,4 +1,4 @@ -name: Android Web3Dapp (production) deploy +name: Android Dapp (production) deploy on: workflow_dispatch: diff --git a/.github/workflows/release_dapp_android_internal.yml b/.github/workflows/release_dapp_android_internal.yml index d8570a0b..dd7c9c2e 100644 --- a/.github/workflows/release_dapp_android_internal.yml +++ b/.github/workflows/release_dapp_android_internal.yml @@ -1,4 +1,4 @@ -name: Android Web3Dapp (internal) deploy +name: Android Dapp (internal) deploy on: workflow_dispatch: @@ -60,4 +60,4 @@ jobs: fastlane release_firebase project_id:$PROJECT_ID app_version:$VERSION_NUMBER # Launch locally -# act -j build --container-architecture linux/amd64 -P macos-latest-xlarge=-self-hosted --secret-file .github/workflows/.env.secret -W .github/workflows/release_dapp_android.yml +# act -j build --container-architecture linux/amd64 -P macos-latest-xlarge=-self-hosted --secret-file .github/workflows/.env.secret -W .github/workflows/release_dapp_android_internal.yml diff --git a/.github/workflows/release_dapp_ios.yml b/.github/workflows/release_dapp_ios.yml index a346fe4a..dc0ae861 100644 --- a/.github/workflows/release_dapp_ios.yml +++ b/.github/workflows/release_dapp_ios.yml @@ -1,4 +1,4 @@ -name: iOS Web3Dapp (production) deploy +name: iOS Dapp (production) deploy on: workflow_dispatch: diff --git a/.github/workflows/release_dapp_ios_internal.yml b/.github/workflows/release_dapp_ios_internal.yml index 54911c49..08251e88 100644 --- a/.github/workflows/release_dapp_ios_internal.yml +++ b/.github/workflows/release_dapp_ios_internal.yml @@ -1,4 +1,4 @@ -name: iOS Web3Dapp (internal) deploy +name: iOS Dapp (internal) deploy on: workflow_dispatch: diff --git a/.github/workflows/release_wallet_android.yml b/.github/workflows/release_wallet_android.yml index c660c060..224b336d 100644 --- a/.github/workflows/release_wallet_android.yml +++ b/.github/workflows/release_wallet_android.yml @@ -1,4 +1,4 @@ -name: Android Web3Wallet (production) deploy +name: Android Wallet (production) deploy on: workflow_dispatch: diff --git a/.github/workflows/release_wallet_android_internal.yml b/.github/workflows/release_wallet_android_internal.yml index aca217e8..e5a4b063 100644 --- a/.github/workflows/release_wallet_android_internal.yml +++ b/.github/workflows/release_wallet_android_internal.yml @@ -1,4 +1,4 @@ -name: Android Web3Wallet (internal) deploy +name: Android Wallet (internal) deploy on: workflow_dispatch: @@ -8,7 +8,6 @@ on: jobs: build: - # if: github.event.pull_request.merged == true if: (github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'develop') || github.event_name == 'workflow_dispatch' runs-on: macos-latest-xlarge diff --git a/.github/workflows/release_wallet_ios.yml b/.github/workflows/release_wallet_ios.yml index a3b456e6..e68d75aa 100644 --- a/.github/workflows/release_wallet_ios.yml +++ b/.github/workflows/release_wallet_ios.yml @@ -1,4 +1,4 @@ -name: iOS Web3Wallet (production) deploy +name: iOS Wallet (production) deploy on: workflow_dispatch: diff --git a/.github/workflows/release_wallet_ios_internal.yml b/.github/workflows/release_wallet_ios_internal.yml index 8a3a6cfc..edb04b38 100644 --- a/.github/workflows/release_wallet_ios_internal.yml +++ b/.github/workflows/release_wallet_ios_internal.yml @@ -1,4 +1,4 @@ -name: iOS Web3Wallet (internal) deploy +name: iOS Wallet (internal) deploy on: workflow_dispatch: diff --git a/.gitignore b/.gitignore index c68c1976..de3a30be 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,7 @@ .pub/ pubspec.lock /build/ +coverage/ # Web related lib/generated_plugin_registrant.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c5a15d1..936ea0d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 2.3.1 + +- Added Connectivity check to core and throw exceptions when internet connection is gone +- Fix for https://github.com/WalletConnect/WalletConnectFlutterV2/issues/303 (EIP-55 validation for SIWE) +- Minor improvements + ## 2.3.0 - One-Click Auth support diff --git a/example/dapp/android/app/build.gradle b/example/dapp/android/app/build.gradle index f49bfe40..525e2132 100644 --- a/example/dapp/android/app/build.gradle +++ b/example/dapp/android/app/build.gradle @@ -60,9 +60,17 @@ android { internal { dimension "version" applicationIdSuffix ".internal" + manifestPlaceholders = [ + appIcon: "@mipmap/ic_launcher_internal", + applicationLabel: "FL Dapp (internal)", + ] } production { dimension "version" + manifestPlaceholders = [ + appIcon: "@mipmap/ic_launcher", + applicationLabel: "FL Dapp", + ] } } diff --git a/example/dapp/android/app/src/main/AndroidManifest.xml b/example/dapp/android/app/src/main/AndroidManifest.xml index 4efd0752..1834973a 100644 --- a/example/dapp/android/app/src/main/AndroidManifest.xml +++ b/example/dapp/android/app/src/main/AndroidManifest.xml @@ -1,8 +1,18 @@ + + + + + + + + + + + android:label="${applicationLabel}" + android:name="${applicationName}" + android:icon="${appIcon}"> - + - + - + diff --git a/example/dapp/web/manifest.json b/example/dapp/web/manifest.json index 760f6ae4..4cd3ac9e 100644 --- a/example/dapp/web/manifest.json +++ b/example/dapp/web/manifest.json @@ -1,6 +1,6 @@ { - "name": "Web3Dapp Flutter", - "short_name": "Web3Dapp Flutter", + "name": "Flutter Dapp", + "short_name": "Flutter Dapp", "start_url": ".", "display": "standalone", "background_color": "#0175C2", diff --git a/example/dapp/windows/flutter/generated_plugin_registrant.cc b/example/dapp/windows/flutter/generated_plugin_registrant.cc index 4f788487..5777988d 100644 --- a/example/dapp/windows/flutter/generated_plugin_registrant.cc +++ b/example/dapp/windows/flutter/generated_plugin_registrant.cc @@ -6,9 +6,12 @@ #include "generated_plugin_registrant.h" +#include #include void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/example/dapp/windows/flutter/generated_plugins.cmake b/example/dapp/windows/flutter/generated_plugins.cmake index 88b22e5c..31032063 100644 --- a/example/dapp/windows/flutter/generated_plugins.cmake +++ b/example/dapp/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus url_launcher_windows ) diff --git a/example/wallet/android/app/build.gradle b/example/wallet/android/app/build.gradle index 75e2ca1e..91bef98c 100644 --- a/example/wallet/android/app/build.gradle +++ b/example/wallet/android/app/build.gradle @@ -61,9 +61,17 @@ android { internal { dimension "version" applicationIdSuffix ".internal" + manifestPlaceholders = [ + appIcon: "@mipmap/ic_launcher_internal", + applicationLabel: "FL Wallet (internal)", + ] } production { dimension "version" + manifestPlaceholders = [ + appIcon: "@mipmap/ic_launcher", + applicationLabel: "FL Wallet", + ] } } diff --git a/example/wallet/android/app/src/main/AndroidManifest.xml b/example/wallet/android/app/src/main/AndroidManifest.xml index 6157d923..8171d35a 100644 --- a/example/wallet/android/app/src/main/AndroidManifest.xml +++ b/example/wallet/android/app/src/main/AndroidManifest.xml @@ -1,8 +1,9 @@ + + android:icon="${appIcon}"> + - + + + + + + + diff --git a/example/wallet/android/app/src/main/ic_launcher_internal-playstore.png b/example/wallet/android/app/src/main/ic_launcher_internal-playstore.png new file mode 100644 index 00000000..3ddcfd76 Binary files /dev/null and b/example/wallet/android/app/src/main/ic_launcher_internal-playstore.png differ diff --git a/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal.xml b/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal.xml new file mode 100644 index 00000000..d7da3434 --- /dev/null +++ b/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal_round.xml b/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal_round.xml new file mode 100644 index 00000000..d7da3434 --- /dev/null +++ b/example/wallet/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_internal_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal.webp b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal.webp new file mode 100644 index 00000000..d4b5dc1c Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_foreground.webp b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_foreground.webp new file mode 100644 index 00000000..35ff97f6 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_foreground.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_round.webp b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_round.webp new file mode 100644 index 00000000..641a0450 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-hdpi/ic_launcher_internal_round.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal.webp b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal.webp new file mode 100644 index 00000000..f3f8e656 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_foreground.webp b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_foreground.webp new file mode 100644 index 00000000..3e913aaa Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_foreground.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_round.webp b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_round.webp new file mode 100644 index 00000000..fa530e84 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-mdpi/ic_launcher_internal_round.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal.webp b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal.webp new file mode 100644 index 00000000..7137082c Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_foreground.webp b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_foreground.webp new file mode 100644 index 00000000..af4414ab Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_foreground.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_round.webp b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_round.webp new file mode 100644 index 00000000..124e24e8 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xhdpi/ic_launcher_internal_round.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal.webp b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal.webp new file mode 100644 index 00000000..84421f40 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_foreground.webp b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_foreground.webp new file mode 100644 index 00000000..33a83433 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_foreground.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_round.webp b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_round.webp new file mode 100644 index 00000000..0a9b8ff2 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_internal_round.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal.webp b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal.webp new file mode 100644 index 00000000..76dae9b1 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_foreground.webp b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_foreground.webp new file mode 100644 index 00000000..6fc57ea8 Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_foreground.webp differ diff --git a/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_round.webp b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_round.webp new file mode 100644 index 00000000..43e8f16c Binary files /dev/null and b/example/wallet/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_internal_round.webp differ diff --git a/example/wallet/android/app/src/main/res/values/ic_launcher_internal_background.xml b/example/wallet/android/app/src/main/res/values/ic_launcher_internal_background.xml new file mode 100644 index 00000000..9ab84dff --- /dev/null +++ b/example/wallet/android/app/src/main/res/values/ic_launcher_internal_background.xml @@ -0,0 +1,4 @@ + + + #F5EDFF + \ No newline at end of file diff --git a/example/wallet/android/fastlane/Fastfile b/example/wallet/android/fastlane/Fastfile index 7e81840a..cceb86d4 100644 --- a/example/wallet/android/fastlane/Fastfile +++ b/example/wallet/android/fastlane/Fastfile @@ -55,7 +55,12 @@ platform :android do _latest_release = firebase_app_distribution_get_latest_release( app: "#{firebase_wallet_id}", ) - _new_build_number = _latest_release[:buildVersion].to_i + 1 + if _latest_release && _latest_release[:buildVersion] && !_latest_release[:buildVersion].empty? + _new_build_number = _latest_release[:buildVersion].to_i + 1 + else + _new_build_number = 1 + end + _app_version = "#{options[:app_version]}" _project_id = "#{options[:project_id]}" @@ -73,7 +78,7 @@ platform :android do ) slack( - message: "🔐 Web3Wallet Flutter #{_app_version}-#{_flavor} (#{_new_build_number}) for 🤖 Android successfully released!\n\n", + message: "🔐 Flutter Wallet #{_app_version}-#{_flavor} (#{_new_build_number}) for 🤖 Android successfully released!\n\n", default_payloads: [], attachment_properties: { fields: [ diff --git a/example/wallet/ios/Podfile.lock b/example/wallet/ios/Podfile.lock index 43430323..8cc5efd9 100644 --- a/example/wallet/ios/Podfile.lock +++ b/example/wallet/ios/Podfile.lock @@ -1,4 +1,7 @@ PODS: + - connectivity_plus (0.0.1): + - Flutter + - FlutterMacOS - Flutter (1.0.0) - MTBBarcodeScanner (5.0.11) - package_info_plus (0.4.5): @@ -15,6 +18,7 @@ PODS: - Flutter DEPENDENCIES: + - connectivity_plus (from `.symlinks/plugins/connectivity_plus/darwin`) - Flutter (from `Flutter`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - qr_bar_code_scanner_dialog (from `.symlinks/plugins/qr_bar_code_scanner_dialog/ios`) @@ -27,6 +31,8 @@ SPEC REPOS: - MTBBarcodeScanner EXTERNAL SOURCES: + connectivity_plus: + :path: ".symlinks/plugins/connectivity_plus/darwin" Flutter: :path: Flutter package_info_plus: @@ -41,6 +47,7 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/url_launcher_ios/ios" SPEC CHECKSUMS: + connectivity_plus: ddd7f30999e1faaef5967c23d5b6d503d10434db Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 MTBBarcodeScanner: f453b33c4b7dfe545d8c6484ed744d55671788cb package_info_plus: 58f0028419748fad15bf008b270aaa8e54380b1c diff --git a/example/wallet/ios/Runner/Info-internal.plist b/example/wallet/ios/Runner/Info-internal.plist index 24398bea..8fc880c9 100644 --- a/example/wallet/ios/Runner/Info-internal.plist +++ b/example/wallet/ios/Runner/Info-internal.plist @@ -11,7 +11,7 @@ CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) + com.walletconnect.flutterwallet.internal CFBundleInfoDictionaryVersion 6.0 CFBundleName @@ -28,7 +28,7 @@ CFBundleTypeRole Editor CFBundleURLName - $(PRODUCT_BUNDLE_IDENTIFIER) + com.walletconnect.flutterwallet.internal CFBundleURLSchemes wcflutterwallet-internal diff --git a/example/wallet/ios/Runner/Info.plist b/example/wallet/ios/Runner/Info.plist index 4346cf71..1be80823 100644 --- a/example/wallet/ios/Runner/Info.plist +++ b/example/wallet/ios/Runner/Info.plist @@ -11,7 +11,7 @@ CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) + com.walletconnect.flutterwallet CFBundleInfoDictionaryVersion 6.0 CFBundleName @@ -25,14 +25,14 @@ CFBundleURLTypes - CFBundleTypeRole - Editor - CFBundleURLName - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleURLSchemes - - wcflutterwallet-production - + CFBundleTypeRole + Editor + CFBundleURLName + com.walletconnect.flutterwallet + CFBundleURLSchemes + + wcflutterwallet + CFBundleVersion diff --git a/example/wallet/ios/fastlane/Fastfile b/example/wallet/ios/fastlane/Fastfile index 73819ad6..1c626f22 100644 --- a/example/wallet/ios/fastlane/Fastfile +++ b/example/wallet/ios/fastlane/Fastfile @@ -79,7 +79,12 @@ platform :ios do app_identifier: "#{app_identifier}", username: options[:username], ) - new_build_number = number + 1 + if number && !number.to_s.empty? + new_build_number = number.to_i + 1 + else + # Handle the case where there is no previous build number + new_build_number = 1 + end increment_build_number( build_number: new_build_number, @@ -115,7 +120,7 @@ platform :ios do ) slack( - message: "🔐 Web3Wallet Flutter #{options[:app_version]}-#{_flavor} (#{new_build_number}) for 🍎 iOS successfully released!\n\n", + message: "🔐 Flutter Wallet #{options[:app_version]}-#{_flavor} (#{new_build_number}) for 🍎 iOS successfully released!\n\n", default_payloads: [], attachment_properties: { fields: [ diff --git a/example/wallet/lib/dependencies/bottom_sheet/bottom_sheet_listener.dart b/example/wallet/lib/dependencies/bottom_sheet/bottom_sheet_listener.dart index cac0c2e0..75386db0 100644 --- a/example/wallet/lib/dependencies/bottom_sheet/bottom_sheet_listener.dart +++ b/example/wallet/lib/dependencies/bottom_sheet/bottom_sheet_listener.dart @@ -45,7 +45,12 @@ class BottomSheetListenerState extends State { builder: (context) { if (item.closeAfter > 0) { Future.delayed(Duration(seconds: item.closeAfter), () { - Navigator.pop(context); + try { + if (!mounted) return; + Navigator.pop(context); + } catch (e) { + debugPrint('[$runtimeType] close $e'); + } }); } return Container( diff --git a/example/wallet/lib/dependencies/chains/common.dart b/example/wallet/lib/dependencies/chains/common.dart index 1b5be74c..4e5f4758 100644 --- a/example/wallet/lib/dependencies/chains/common.dart +++ b/example/wallet/lib/dependencies/chains/common.dart @@ -24,19 +24,28 @@ class CommonMethods { ); } } catch (e) { - debugPrint('[WALLET] ${e.toString()}'); + debugPrint('[SampleWallet] ${e.toString()}'); } } - static Future requestApproval(String text, {String? title}) async { + static Future requestApproval( + String text, { + String? title, + String? method, + String? chainId, + String? address, + }) async { final bottomSheetService = GetIt.I(); final WCBottomSheetResult rs = (await bottomSheetService.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionWidget( - title: 'Approve Request', + title: title ?? 'Approve Request', info: [ WCConnectionModel( - title: title, + title: 'Method: $method\n' + 'Chain ID: $chainId\n' + 'Address: $address\n\n' + 'Message:', elements: [ text, ], diff --git a/example/wallet/lib/dependencies/chains/cosmos_service.dart b/example/wallet/lib/dependencies/chains/cosmos_service.dart index a8e68aef..3e443810 100644 --- a/example/wallet/lib/dependencies/chains/cosmos_service.dart +++ b/example/wallet/lib/dependencies/chains/cosmos_service.dart @@ -26,7 +26,7 @@ class CosmosService { } Future cosmosSignDirect(String topic, dynamic parameters) async { - debugPrint('[WALLET] cosmosSignDirect request: $parameters'); + debugPrint('[SampleWallet] cosmosSignDirect request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; final response = JsonRpcResponse( id: pRequest.id, @@ -45,7 +45,7 @@ class CosmosService { } Future cosmosSignAmino(String topic, dynamic parameters) async { - debugPrint('[WALLET] cosmosSignAmino request: $parameters'); + debugPrint('[SampleWallet] cosmosSignAmino request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; final response = JsonRpcResponse( id: pRequest.id, diff --git a/example/wallet/lib/dependencies/chains/evm_service.dart b/example/wallet/lib/dependencies/chains/evm_service.dart index 38ecad84..49887e53 100644 --- a/example/wallet/lib/dependencies/chains/evm_service.dart +++ b/example/wallet/lib/dependencies/chains/evm_service.dart @@ -7,6 +7,7 @@ import 'package:get_it/get_it.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/bottom_sheet/i_bottom_sheet_service.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/chains/common.dart'; +import 'package:walletconnect_flutter_v2_wallet/dependencies/deep_link_handler.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/i_web3wallet_service.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/i_key_service.dart'; import 'package:walletconnect_flutter_v2_wallet/models/chain_metadata.dart'; @@ -96,16 +97,22 @@ class EVMService { // personal_sign is handled using onSessionRequest event for demo purposes Future personalSign(String topic, dynamic parameters) async { - debugPrint('[WALLET] personalSign request: $parameters'); - final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getDataFromParamsList(parameters); + debugPrint('[SampleWallet] personalSign request: $parameters'); + final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last; + final address = EthUtils.getAddressFromSessionRequest(pRequest); + final data = EthUtils.getDataFromSessionRequest(pRequest); final message = EthUtils.getUtf8Message(data.toString()); var response = JsonRpcResponse( id: pRequest.id, jsonrpc: '2.0', ); - if (await CommonMethods.requestApproval(message)) { + if (await CommonMethods.requestApproval( + message, + method: pRequest.method, + chainId: pRequest.chainId, + address: address, + )) { try { // Load the private key final keys = GetIt.I().getKeysForChain( @@ -123,7 +130,7 @@ class EVMService { response = response.copyWith(result: signedTx); } catch (e) { - debugPrint('[WALLET] personalSign error $e'); + debugPrint('[SampleWallet] personalSign error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -134,18 +141,25 @@ class EVMService { ); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future ethSign(String topic, dynamic parameters) async { - debugPrint('[WALLET] ethSign request: $parameters'); + debugPrint('[SampleWallet] ethSign request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getDataFromParamsList(parameters); + final data = EthUtils.getDataFromSessionRequest(pRequest); final message = EthUtils.getUtf8Message(data.toString()); var response = JsonRpcResponse( id: pRequest.id, @@ -170,7 +184,7 @@ class EVMService { response = response.copyWith(result: signedTx); } catch (e) { - debugPrint('[WALLET] ethSign error $e'); + debugPrint('[SampleWallet] ethSign error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -181,18 +195,25 @@ class EVMService { ); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future ethSignTypedData(String topic, dynamic parameters) async { - debugPrint('[WALLET] ethSignTypedData request: $parameters'); + debugPrint('[SampleWallet] ethSignTypedData request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getDataFromParamsList(parameters); + final data = EthUtils.getDataFromSessionRequest(pRequest); var response = JsonRpcResponse( id: pRequest.id, jsonrpc: '2.0', @@ -212,7 +233,7 @@ class EVMService { response = response.copyWith(result: signature); } catch (e) { - debugPrint('[WALLET] ethSignTypedData error $e'); + debugPrint('[SampleWallet] ethSignTypedData error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -223,18 +244,25 @@ class EVMService { ); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future ethSignTypedDataV4(String topic, dynamic parameters) async { - debugPrint('[WALLET] ethSignTypedDataV4 request: $parameters'); + debugPrint('[SampleWallet] ethSignTypedDataV4 request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getDataFromParamsList(parameters); + final data = EthUtils.getDataFromSessionRequest(pRequest); var response = JsonRpcResponse( id: pRequest.id, jsonrpc: '2.0', @@ -254,7 +282,7 @@ class EVMService { response = response.copyWith(result: signature); } catch (e) { - debugPrint('[WALLET] ethSignTypedDataV4 error $e'); + debugPrint('[SampleWallet] ethSignTypedDataV4 error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -265,25 +293,38 @@ class EVMService { ); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future ethSignTransaction(String topic, dynamic parameters) async { - debugPrint('[WALLET] ethSignTransaction request: $parameters'); - final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getTransactionFromParams(parameters); + debugPrint('[SampleWallet] ethSignTransaction request: $parameters'); + final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last; + + final data = EthUtils.getTransactionFromSessionRequest(pRequest); if (data == null) return; + var response = JsonRpcResponse( id: pRequest.id, jsonrpc: '2.0', ); - final transaction = await _approveTransaction(data); + final transaction = await _approveTransaction( + data, + method: pRequest.method, + chainId: pRequest.chainId, + ); if (transaction is Transaction) { try { // Load the private key @@ -305,12 +346,12 @@ class EVMService { response = response.copyWith(result: signedTx); } on RPCError catch (e) { - debugPrint('[WALLET] ethSignTransaction error $e'); + debugPrint('[SampleWallet] ethSignTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: e.errorCode, message: e.message), ); } catch (e) { - debugPrint('[WALLET] ethSignTransaction error $e'); + debugPrint('[SampleWallet] ethSignTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -319,25 +360,38 @@ class EVMService { response = response.copyWith(error: transaction as JsonRpcError); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future ethSendTransaction(String topic, dynamic parameters) async { - debugPrint('[WALLET] ethSendTransaction request: $parameters'); - final pRequest = _web3Wallet.pendingRequests.getAll().last; - final data = EthUtils.getTransactionFromParams(parameters); + debugPrint('[SampleWallet] ethSendTransaction request: $parameters'); + final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last; + + final data = EthUtils.getTransactionFromSessionRequest(pRequest); if (data == null) return; + var response = JsonRpcResponse( id: pRequest.id, jsonrpc: '2.0', ); - final transaction = await _approveTransaction(data); + final transaction = await _approveTransaction( + data, + method: pRequest.method, + chainId: pRequest.chainId, + ); if (transaction is Transaction) { try { // Load the private key @@ -357,12 +411,12 @@ class EVMService { response = response.copyWith(result: signedTx); } on RPCError catch (e) { - debugPrint('[WALLET] ethSendTransaction error $e'); + debugPrint('[SampleWallet] ethSendTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: e.errorCode, message: e.message), ); } catch (e) { - debugPrint('[WALLET] ethSendTransaction error $e'); + debugPrint('[SampleWallet] ethSendTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -371,16 +425,23 @@ class EVMService { response = response.copyWith(error: transaction as JsonRpcError); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, response.result ?? response.error); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, response.result ?? response.error); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } Future switchChain(String topic, dynamic parameters) async { - debugPrint('[WALLET] switchChain request: $topic $parameters'); + debugPrint('[SampleWallet] switchChain request: $topic $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse(id: pRequest.id, jsonrpc: '2.0'); try { @@ -397,27 +458,33 @@ class EVMService { ); response = response.copyWith(result: true); } on WalletConnectError catch (e) { - debugPrint('[WALLET] switchChain error $e'); + debugPrint('[SampleWallet] switchChain error $e'); response = response.copyWith( error: JsonRpcError(code: e.code, message: e.message), ); } catch (e) { - debugPrint('[WALLET] switchChain error $e'); + debugPrint('[SampleWallet] switchChain error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); } - await _web3Wallet.respondSessionRequest( - topic: topic, - response: response, - ); - - CommonMethods.goBackToDapp(topic, true); + try { + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + CommonMethods.goBackToDapp(topic, true); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } // Future addChain(String topic, dynamic parameters) async { - // debugPrint('[WALLET] addChain request: $topic $parameters'); // final pRequest = _web3Wallet.pendingRequests.getAll().last; // await _web3Wallet.respondSessionRequest( // topic: topic, @@ -430,7 +497,12 @@ class EVMService { // CommonMethods.goBackToDapp(topic, true); // } - Future _approveTransaction(Map tJson) async { + Future _approveTransaction( + Map tJson, { + String? title, + String? method, + String? chainId, + }) async { Transaction transaction = tJson.toTransaction(); final gasPrice = await ethClient.getGasPrice(); @@ -480,12 +552,21 @@ class EVMService { final gweiGasPrice = (transaction.gasPrice?.getInWei ?? BigInt.zero) / BigInt.from(1000000000); + const encoder = JsonEncoder.withIndent(' '); + final trx = encoder.convert(tJson); final WCBottomSheetResult rs = (await _bottomSheetService.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionWidget( - title: 'Approve Transaction', + title: title ?? 'Approve Transaction', info: [ - WCConnectionModel(elements: [jsonEncode(tJson)]), + WCConnectionModel( + title: 'Method: $method\n' + 'Chain ID: $chainId\n\n' + 'Transaction:', + elements: [ + trx, + ], + ), WCConnectionModel( title: 'Gas price', elements: ['${gweiGasPrice.toStringAsFixed(2)} GWEI'], @@ -505,7 +586,7 @@ class EVMService { void _onSessionRequest(SessionRequestEvent? args) async { if (args != null && args.chainId == chainSupported.chainId) { - debugPrint('[WALLET] _onSessionRequest ${args.toString()}'); + debugPrint('[SampleWallet] _onSessionRequest ${args.toString()}'); final handler = sessionRequestHandlers[args.method]; if (handler != null) { await handler(args.topic, args.params); @@ -519,24 +600,23 @@ class EVMService { String hexAddress, ) { try { - debugPrint('isValidSignature(): $hexSignature, $message, $hexAddress'); + debugPrint( + '[SampleWallet] isValidSignature: $hexSignature, $message, $hexAddress'); final recoveredAddress = EthSigUtil.recoverPersonalSignature( signature: hexSignature, message: utf8.encode(message), ); - debugPrint('recoveredAddress: $recoveredAddress'); + debugPrint('[SampleWallet] recoveredAddress: $recoveredAddress'); final recoveredAddress2 = EthSigUtil.recoverSignature( signature: hexSignature, message: utf8.encode(message), ); - debugPrint('recoveredAddress2: $recoveredAddress2'); + debugPrint('[SampleWallet] recoveredAddress2: $recoveredAddress2'); final isValid = recoveredAddress == hexAddress; - debugPrint('isValidSignature: $isValid'); return isValid; } catch (e) { - debugPrint('isValidSignature() error, $e'); return false; } } diff --git a/example/wallet/lib/dependencies/chains/kadena_service.dart b/example/wallet/lib/dependencies/chains/kadena_service.dart index f7fd84fb..f0ee3790 100644 --- a/example/wallet/lib/dependencies/chains/kadena_service.dart +++ b/example/wallet/lib/dependencies/chains/kadena_service.dart @@ -47,7 +47,7 @@ class KadenaService { } Future kadenaGetAccountsV1(String topic, dynamic parameters) async { - debugPrint('[WALLET] kadenaGetAccountsV1 request: $parameters'); + debugPrint('[SampleWallet] kadenaGetAccountsV1 request: $parameters'); final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse( id: pRequest.id, @@ -89,7 +89,7 @@ class KadenaService { ).toJson(), ); } catch (e) { - debugPrint('[WALLET] kadenaGetAccountsV1 error: $e'); + debugPrint('[SampleWallet] kadenaGetAccountsV1 error: $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -104,7 +104,8 @@ class KadenaService { } Future kadenaSignV1(String topic, dynamic parameters) async { - debugPrint('[WALLET] kadenaSignV1 request: ${jsonEncode(parameters)}'); + debugPrint( + '[SampleWallet] kadenaSignV1 request: ${jsonEncode(parameters)}'); final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse( id: pRequest.id, @@ -156,7 +157,7 @@ class KadenaService { ); } } catch (e) { - debugPrint('[WALLET] kadenaSignV1 error: $e'); + debugPrint('[SampleWallet] kadenaSignV1 error: $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -171,7 +172,8 @@ class KadenaService { } Future kadenaQuicksignV1(String topic, dynamic parameters) async { - debugPrint('[WALLET] kadenaQuicksignV1 request: ${jsonEncode(parameters)}'); + debugPrint( + '[SampleWallet] kadenaQuicksignV1 request: ${jsonEncode(parameters)}'); final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse( id: pRequest.id, @@ -242,7 +244,7 @@ class KadenaService { ); } } catch (e) { - debugPrint('[WALLET] kadenaSignV1 error: $e'); + debugPrint('[SampleWallet] kadenaSignV1 error: $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -258,7 +260,7 @@ class KadenaService { void _onSessionRequest(SessionRequestEvent? args) async { if (args != null && args.chainId == chainSupported.chainId) { - debugPrint('[WALLET] _onSessionRequest ${args.toString()}'); + debugPrint('[SampleWallet] _onSessionRequest ${args.toString()}'); final handler = kadenaRequestHandlers[args.method]; if (handler != null) { await handler(args.topic, args.params); diff --git a/example/wallet/lib/dependencies/chains/polkadot_service.dart b/example/wallet/lib/dependencies/chains/polkadot_service.dart index 15947daf..a364d49b 100644 --- a/example/wallet/lib/dependencies/chains/polkadot_service.dart +++ b/example/wallet/lib/dependencies/chains/polkadot_service.dart @@ -44,7 +44,7 @@ class PolkadotService { } Future polkadotSignMessage(String topic, dynamic parameters) async { - debugPrint('[WALLET] polkadotSignMessage: $parameters'); + debugPrint('[SampleWallet] polkadotSignMessage: $parameters'); const method = 'polkadot_signMessage'; final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse( @@ -55,7 +55,7 @@ class PolkadotService { try { final params = parameters as Map; final message = params['message'].toString(); - debugPrint('[WALLET] polkadotSignMessage message: $message'); + debugPrint('[SampleWallet] polkadotSignMessage message: $message'); // code final keys = GetIt.I().getKeysForChain( @@ -86,7 +86,7 @@ class PolkadotService { ); } } catch (e) { - debugPrint('[WALLET] polkadotSignMessage error $e'); + debugPrint('[SampleWallet] polkadotSignMessage error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -101,7 +101,8 @@ class PolkadotService { } Future polkadotSignTransaction(String topic, dynamic parameters) async { - debugPrint('[WALLET] polkadotSignTransaction: ${jsonEncode(parameters)}'); + debugPrint( + '[SampleWallet] polkadotSignTransaction: ${jsonEncode(parameters)}'); const method = 'polkadot_signTransaction'; final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse( @@ -144,7 +145,7 @@ class PolkadotService { }, ); } catch (e) { - debugPrint('[WALLET] polkadotSignTransaction error $e'); + debugPrint('[SampleWallet] polkadotSignTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -165,7 +166,7 @@ class PolkadotService { void _onSessionRequest(SessionRequestEvent? args) async { if (args != null && args.chainId == chainSupported.chainId) { - debugPrint('[WALLET] _onSessionRequest ${args.toString()}'); + debugPrint('[SampleWallet] _onSessionRequest ${args.toString()}'); final handler = polkadotRequestHandlers[args.method]; if (handler != null) { await handler(args.topic, args.params); diff --git a/example/wallet/lib/dependencies/chains/solana_service.dart b/example/wallet/lib/dependencies/chains/solana_service.dart index 26fc1954..3c330f5b 100644 --- a/example/wallet/lib/dependencies/chains/solana_service.dart +++ b/example/wallet/lib/dependencies/chains/solana_service.dart @@ -35,7 +35,7 @@ class SolanaService { } Future solanaSignMessage(String topic, dynamic parameters) async { - debugPrint('[WALLET] solanaSignMessage request: $parameters'); + debugPrint('[SampleWallet] solanaSignMessage request: $parameters'); const method = 'solana_signMessage'; final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse(id: pRequest.id, jsonrpc: '2.0'); @@ -71,7 +71,7 @@ class SolanaService { } // } catch (e) { - debugPrint('[WALLET] polkadotSignMessage error $e'); + debugPrint('[SampleWallet] polkadotSignMessage error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); @@ -86,7 +86,8 @@ class SolanaService { } Future solanaSignTransaction(String topic, dynamic parameters) async { - debugPrint('[WALLET] solanaSignTransaction: ${jsonEncode(parameters)}'); + debugPrint( + '[SampleWallet] solanaSignTransaction: ${jsonEncode(parameters)}'); const method = 'solana_signTransaction'; final pRequest = _web3Wallet.pendingRequests.getAll().last; var response = JsonRpcResponse(id: pRequest.id, jsonrpc: '2.0'); @@ -137,7 +138,7 @@ class SolanaService { ); } } catch (e) { - debugPrint('[WALLET] solanaSignTransaction error $e'); + debugPrint('[SampleWallet] solanaSignTransaction error $e'); response = response.copyWith( error: JsonRpcError(code: 0, message: e.toString()), ); diff --git a/example/wallet/lib/dependencies/deep_link_handler.dart b/example/wallet/lib/dependencies/deep_link_handler.dart index beb9d9af..57adba7e 100644 --- a/example/wallet/lib/dependencies/deep_link_handler.dart +++ b/example/wallet/lib/dependencies/deep_link_handler.dart @@ -9,13 +9,15 @@ import 'package:walletconnect_flutter_v2_wallet/dependencies/bottom_sheet/i_bott import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; class DeepLinkHandler { - // - static final waiting = ValueNotifier(false); + static const _methodChannel = MethodChannel( + 'com.walletconnect.flutterwallet/methods', + ); + static const _eventChannel = EventChannel( + 'com.walletconnect.flutterwallet/events', + ); static final _linksController = StreamController.broadcast(); - static const _methodChannel = - MethodChannel('com.walletconnect.flutterwallet/methods'); - static const _eventChannel = - EventChannel('com.walletconnect.flutterwallet/events'); + static Stream get onLink => _linksController.stream; + static final waiting = ValueNotifier(false); static void initListener() { if (kIsWeb) return; @@ -33,12 +35,10 @@ class DeepLinkHandler { onError: _onError, ); } catch (e) { - debugPrint('[WALLET] [DeepLinkHandler] checkInitialLink $e'); + debugPrint('[SampleWallet] [DeepLinkHandler] checkInitialLink $e'); } } - static Stream get onLink => _linksController.stream; - static void goTo( String scheme, { int delay = 100, @@ -47,16 +47,14 @@ class DeepLinkHandler { bool success = true, }) async { waiting.value = false; - if (kIsWeb) return; - if (scheme.isEmpty) return; await Future.delayed(Duration(milliseconds: delay)); - debugPrint('[WALLET] [DeepLinkHandler] redirecting to $scheme'); + debugPrint('[SampleWallet] [DeepLinkHandler] redirecting to $scheme'); try { await launchUrlString(scheme, mode: LaunchMode.externalApplication); } catch (e) { debugPrint( - '[WALLET] [DeepLinkHandler] error re-opening dapp ($scheme). $e'); - _goBackModal( + '[SampleWallet] [DeepLinkHandler] error re-opening dapp ($scheme). $e'); + goBackModal( title: modalTitle, message: modalMessage, success: success, @@ -64,25 +62,7 @@ class DeepLinkHandler { } } - static void _onLink(Object? event) { - final decodedUri = Uri.parse(Uri.decodeFull(event.toString())); - if (decodedUri.toString().startsWith('wc:')) { - return; - } - final pairingUri = decodedUri.query.replaceFirst('uri=', ''); - if (!pairingUri.toString().startsWith('wc:')) { - return; - } - waiting.value = true; - _linksController.sink.add(pairingUri); - } - - static void _onError(Object error) { - waiting.value = false; - debugPrint('[WALLET] [DeepLinkHandler] _onError $error'); - } - - static void _goBackModal({ + static void goBackModal({ String? title, String? message, bool success = true, @@ -115,4 +95,23 @@ class DeepLinkHandler { ), ); } + + static void _onLink(Object? event) { + final decodedUri = Uri.parse(Uri.decodeFull(event.toString())); + if (decodedUri.isScheme('wc')) { + waiting.value = true; + _linksController.sink.add(decodedUri.toString()); + } else { + if (decodedUri.query.startsWith('uri=')) { + final pairingUri = decodedUri.query.replaceFirst('uri=', ''); + waiting.value = true; + _linksController.sink.add(pairingUri); + } + } + } + + static void _onError(Object error) { + waiting.value = false; + debugPrint('[SampleWallet] [DeepLinkHandler] _onError $error'); + } } diff --git a/example/wallet/lib/dependencies/key_service/chain_key.dart b/example/wallet/lib/dependencies/key_service/chain_key.dart index 8db7da01..1c64d9d5 100644 --- a/example/wallet/lib/dependencies/key_service/chain_key.dart +++ b/example/wallet/lib/dependencies/key_service/chain_key.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + class ChainKey { final List chains; final String privateKey; @@ -11,8 +13,29 @@ class ChainKey { required this.address, }); - @override - String toString() { - return 'ChainKey(chains: $chains, privateKey: $privateKey, publicKey: $publicKey, address: $address)'; + String get namespace { + if (chains.isNotEmpty) { + return chains.first.split(':').first; + } + return ''; } + + Map toJson() => { + 'chains': chains, + 'privateKey': privateKey, + 'publicKey': privateKey, + 'address': address, + }; + + factory ChainKey.fromJson(Map json) { + return ChainKey( + chains: (json['chains'] as List).map((e) => '$e').toList(), + privateKey: json['privateKey'], + publicKey: json['publicKey'], + address: json['address'], + ); + } + + @override + String toString() => jsonEncode(toJson()); } diff --git a/example/wallet/lib/dependencies/key_service/i_key_service.dart b/example/wallet/lib/dependencies/key_service/i_key_service.dart index aa3a122b..21d813d2 100644 --- a/example/wallet/lib/dependencies/key_service/i_key_service.dart +++ b/example/wallet/lib/dependencies/key_service/i_key_service.dart @@ -2,7 +2,7 @@ import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/chain_k abstract class IKeyService { /// Returns a list of all the keys. - Future> setKeys(); + Future> loadKeys(); /// Returns a list of all the chain ids. List getChains(); @@ -10,16 +10,14 @@ abstract class IKeyService { /// Returns a list of all the keys for a given chain id. /// If the chain is not found, returns an empty list. /// - [chain]: The chain to get the keys for. - List getKeysForChain(String chain); + List getKeysForChain(String value); /// Returns a list of all the accounts in namespace:chainId:address format. List getAllAccounts(); - Future createNewWallet(); + Future createAddressFromSeed(); Future loadDefaultWallet(); - Future restoreWallet({required String mnemonic}); - - Future deleteWallet(); + Future restoreWalletFromSeed({required String mnemonic}); } diff --git a/example/wallet/lib/dependencies/key_service/key_service.dart b/example/wallet/lib/dependencies/key_service/key_service.dart index 5e0093b9..abfc0be1 100644 --- a/example/wallet/lib/dependencies/key_service/key_service.dart +++ b/example/wallet/lib/dependencies/key_service/key_service.dart @@ -1,3 +1,6 @@ +import 'dart:convert'; +import 'dart:developer'; + import 'package:convert/convert.dart'; import 'package:flutter/foundation.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; @@ -12,48 +15,49 @@ import 'package:walletconnect_flutter_v2_wallet/dependencies/bip32/bip32_base.da import 'package:walletconnect_flutter_v2_wallet/utils/dart_defines.dart'; class KeyService extends IKeyService { - final List keys = []; + List _keys = []; @override - Future> setKeys() async { - // WARNING: SharedPreferences is not the best way to store your keys! + Future> loadKeys() async { + // ⚠️ WARNING: SharedPreferences is not the best way to store your keys! This is just for example purposes! final prefs = await SharedPreferences.getInstance(); - final privateKey = prefs.getString('privateKey') ?? ''; - if (privateKey.isEmpty) { - return []; + try { + final savedKeys = prefs.getStringList('w3w_chain_keys')!; + final chainKeys = savedKeys.map((e) => ChainKey.fromJson(jsonDecode(e))); + _keys = List.from(chainKeys.toList()); + // + final extraKeys = await _extraChainKeys(); + _keys.addAll(extraKeys); + } catch (e, s) { + debugPrint('[$runtimeType] loadKeys() error: $e'); + debugPrint(s.toString()); } - final publicKey = prefs.getString('publicKey') ?? ''; - - final keyPair = CryptoKeyPair(privateKey, publicKey); - final eip155KeyPair = _eip155KeyPair(keyPair); - keys - ..clear() - ..add(eip155KeyPair); - - final extraKeys = await _extraKeyPairs(); - keys.addAll(extraKeys); - return keys; + log('[$runtimeType] _keys $_keys'); + return _keys; } @override List getChains() { final List chainIds = []; - for (final ChainKey key in keys) { + for (final ChainKey key in _keys) { chainIds.addAll(key.chains); } return chainIds; } @override - List getKeysForChain(String chain) { - return keys.where((e) => e.chains.contains(chain)).toList(); + List getKeysForChain(String value) { + if (value.contains(':')) { + return _keys.where((e) => e.chains.contains(value)).toList(); + } + return _keys.where((e) => e.namespace == value).toList(); } @override List getAllAccounts() { final List accounts = []; - for (final ChainKey key in keys) { + for (final ChainKey key in _keys) { for (final String chain in key.chains) { accounts.add('$chain:${key.address}'); } @@ -64,39 +68,54 @@ class KeyService extends IKeyService { // ** bip39/bip32 - EIP155 ** @override - Future createNewWallet() async { - final mnemonic = bip39.generateMnemonic(); - await restoreWallet(mnemonic: mnemonic); + Future loadDefaultWallet() async { + const mnemonic = + 'spoil video deputy round immense setup wasp secret maze slight bag what'; + await restoreWalletFromSeed(mnemonic: mnemonic); } @override - Future restoreWallet({required String mnemonic}) async { - final keyPair = _keyPairFromMnemonic(mnemonic); - - // WARNING: SharedPreferences is not the best way to store your keys! + Future createAddressFromSeed() async { final prefs = await SharedPreferences.getInstance(); - await prefs.setString('privateKey', keyPair.privateKey); - await prefs.setString('publicKey', keyPair.publicKey); - await prefs.setString('mnemonic', mnemonic); + final mnemonic = prefs.getString('w3w_mnemonic')!; + + final chainKeys = getKeysForChain('eip155'); + final index = chainKeys.length; + + final keyPair = _keyPairFromMnemonic(mnemonic, index: index); + final chainKey = _eip155ChainKey(keyPair); - await setKeys(); + _keys.add(chainKey); + + await _saveKeys(); } @override - Future loadDefaultWallet() async { - const mnemonic = - 'spoil video deputy round immense setup wasp secret maze slight bag what'; - await restoreWallet(mnemonic: mnemonic); + Future restoreWalletFromSeed({required String mnemonic}) async { + // ⚠️ WARNING: SharedPreferences is not the best way to store your keys! This is just for example purposes! + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('w3w_chain_keys'); + await prefs.setString('w3w_mnemonic', mnemonic); + + final keyPair = _keyPairFromMnemonic(mnemonic); + final chainKey = _eip155ChainKey(keyPair); + + _keys = List.from([chainKey]); + + await _saveKeys(); } - @override - Future deleteWallet() async { + Future _saveKeys() async { final prefs = await SharedPreferences.getInstance(); - await prefs.clear(); - keys.clear(); + // Store only eip155 keys + final chainKeys = _keys + .where((k) => k.namespace == 'eip155') + .map((e) => jsonEncode(e.toJson())) + .toList(); + await prefs.setStringList('w3w_chain_keys', chainKeys); } - CryptoKeyPair _keyPairFromMnemonic(String mnemonic) { + CryptoKeyPair _keyPairFromMnemonic(String mnemonic, {int index = 0}) { final isValidMnemonic = bip39.validateMnemonic(mnemonic); if (!isValidMnemonic) { throw 'Invalid mnemonic'; @@ -105,13 +124,13 @@ class KeyService extends IKeyService { final seed = bip39.mnemonicToSeed(mnemonic); final root = bip32.BIP32.fromSeed(seed); - final firstChild = root.derivePath("m/44'/60'/0'/0/0"); - final private = hex.encode(firstChild.privateKey as List); - final public = hex.encode(firstChild.publicKey); + final child = root.derivePath("m/44'/60'/0'/0/$index"); + final private = hex.encode(child.privateKey as List); + final public = hex.encode(child.publicKey); return CryptoKeyPair(private, public); } - ChainKey _eip155KeyPair(CryptoKeyPair keyPair) { + ChainKey _eip155ChainKey(CryptoKeyPair keyPair) { final private = EthPrivateKey.fromHex(keyPair.privateKey); final address = private.address.hex; final evmChainKey = ChainKey( @@ -120,20 +139,17 @@ class KeyService extends IKeyService { publicKey: keyPair.publicKey, address: address, ); - debugPrint('[WALLET] evmChainKey ${evmChainKey.toString()}'); + debugPrint('[SampleWallet] evmChainKey ${evmChainKey.toString()}'); return evmChainKey; } // ** extra derivations ** - Future> _extraKeyPairs() async { + Future> _extraChainKeys() async { // HARDCODED VALUES - final kadenaChainKey = _kadenaKeyPair(); - debugPrint('[WALLET] kadenaChainKey ${kadenaChainKey.toString()}'); - final polkadotChainKey = _polkadotKeyPair(); - debugPrint('[WALLET] polkadotChainKey ${polkadotChainKey.toString()}'); - final solanaChainKeys = _solanaKeyPair(); - debugPrint('[WALLET] solanaChainKey $solanaChainKeys'); + final kadenaChainKey = _kadenaChainKey(); + final polkadotChainKey = _polkadotChainKey(); + final solanaChainKeys = _solanaChainKey(); // return [ kadenaChainKey, @@ -142,7 +158,7 @@ class KeyService extends IKeyService { ]; } - ChainKey _kadenaKeyPair() { + ChainKey _kadenaChainKey() { return ChainKey( chains: ChainData.kadenaChains.map((e) => e.chainId).toList(), privateKey: DartDefines.kadenaSecretKey, @@ -151,7 +167,7 @@ class KeyService extends IKeyService { ); } - ChainKey _polkadotKeyPair() { + ChainKey _polkadotChainKey() { return ChainKey( chains: ChainData.polkadotChains.map((e) => e.chainId).toList(), privateKey: DartDefines.polkadotMnemonic, @@ -160,7 +176,7 @@ class KeyService extends IKeyService { ); } - ChainKey _solanaKeyPair() { + ChainKey _solanaChainKey() { return ChainKey( chains: ChainData.solanaChains.map((e) => e.chainId).toList(), privateKey: DartDefines.solanaSecretKey, diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 792dd27c..183a21e7 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -27,12 +27,13 @@ class Web3WalletService extends IWeb3WalletService { @override Future create() async { // Create the web3wallet - const flavor = String.fromEnvironment('FLUTTER_APP_FLAVOR'); + String flavor = '-${const String.fromEnvironment('FLUTTER_APP_FLAVOR')}'; + flavor = flavor.replaceAll('-production', ''); _web3Wallet = Web3Wallet( core: Core( projectId: DartDefines.projectId, ), - metadata: const PairingMetadata( + metadata: PairingMetadata( name: 'Sample Wallet Flutter', description: 'WalletConnect\'s sample wallet with Flutter', url: 'https://walletconnect.com/', @@ -40,8 +41,8 @@ class Web3WalletService extends IWeb3WalletService { 'https://docs.walletconnect.com/assets/images/web3walletLogo-54d3b546146931ceaf47a3500868a73a.png' ], redirect: Redirect( - native: 'wcflutterwallet-$flavor://', - universal: 'https://walletconnect.com', + native: 'wcflutterwallet$flavor://', + // universal: 'https://walletconnect.com', ), ), ); @@ -66,13 +67,11 @@ class Web3WalletService extends IWeb3WalletService { _web3Wallet!.onAuthRequest.subscribe(_onAuthRequest); - await _web3Wallet!.init(); - // Setup our accounts - List chainKeys = await GetIt.I().setKeys(); + List chainKeys = await GetIt.I().loadKeys(); if (chainKeys.isEmpty) { await GetIt.I().loadDefaultWallet(); - chainKeys = await GetIt.I().setKeys(); + chainKeys = await GetIt.I().loadKeys(); } for (final chainKey in chainKeys) { for (final chainId in chainKey.chains) { @@ -99,6 +98,24 @@ class Web3WalletService extends IWeb3WalletService { Future init() async { // Await the initialization of the web3wallet await _web3Wallet!.init(); + + final sessions = _web3Wallet!.sessions.getAll(); + final chainKeys = GetIt.I().getKeysForChain('eip155'); + for (var session in sessions) { + try { + final chainIds = NamespaceUtils.getChainIdsFromNamespaces( + namespaces: session.namespaces, + ); + _web3Wallet!.emitSessionEvent( + topic: session.topic, + chainId: chainIds.first, + event: SessionEventParams( + name: 'accountsChanged', + data: [chainKeys.first.address], + ), + ); + } catch (_) {} + } } void _logListener(LogEvent event) { @@ -131,26 +148,19 @@ class Web3WalletService extends IWeb3WalletService { @override Web3Wallet get web3wallet => _web3Wallet!; + List get _loaderMethods => [ + 'wc_sessionPropose', + 'wc_sessionRequest', + 'wc_sessionAuthenticate', + ]; + void _onRelayClientMessage(MessageEvent? event) async { if (event != null) { final jsonObject = await EthUtils.decodeMessageEvent(event); - debugPrint('[SampleWallet] _onRelayClientMessage $jsonObject'); + log('[SampleWallet] _onRelayClientMessage $jsonObject'); if (jsonObject is JsonRpcRequest) { - if (jsonObject.method == 'wc_sessionPropose' || - jsonObject.method == 'wc_sessionRequest') { - DeepLinkHandler.waiting.value = true; - } - } else { - final session = _web3Wallet!.sessions.get(event.topic); - final scheme = session?.peer.metadata.redirect?.native ?? ''; - final isSuccess = jsonObject.result != null; - final title = isSuccess ? null : 'Error'; - final message = isSuccess ? null : jsonObject.error?.message ?? ''; - DeepLinkHandler.goTo( - scheme, - modalTitle: title, - modalMessage: message, - success: isSuccess, + DeepLinkHandler.waiting.value = _loaderMethods.contains( + jsonObject.method, ); } } @@ -159,28 +169,35 @@ class Web3WalletService extends IWeb3WalletService { void _onSessionProposal(SessionProposalEvent? args) async { if (args != null) { log('[SampleWallet] _onSessionProposal ${jsonEncode(args.params)}'); - final WCBottomSheetResult rs = - (await _bottomSheetHandler.queueBottomSheet( - widget: WCRequestWidget( - child: WCConnectionRequestWidget( - proposalData: args.params, - verifyContext: args.verifyContext, - metadata: args.params.proposer, - ), - ), - )) ?? - WCBottomSheetResult.reject; + final result = (await _bottomSheetHandler.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionRequestWidget( + proposalData: args.params, + verifyContext: args.verifyContext, + metadata: args.params.proposer, + ), + ), + )) ?? + WCBottomSheetResult.reject; - if (rs != WCBottomSheetResult.reject) { + if (result != WCBottomSheetResult.reject) { // generatedNamespaces is constructed based on registered methods handlers // so if you want to handle requests using onSessionRequest event then you would need to manually add that method in the approved namespaces - await _web3Wallet!.approveSession( - id: args.id, - namespaces: NamespaceUtils.regenerateNamespacesWithChains( - args.params.generatedNamespaces!, - ), - sessionProperties: args.params.sessionProperties, - ); + try { + await _web3Wallet!.approveSession( + id: args.id, + namespaces: NamespaceUtils.regenerateNamespacesWithChains( + args.params.generatedNamespaces!, + ), + sessionProperties: args.params.sessionProperties, + ); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } else { final error = Errors.getSdkError(Errors.USER_REJECTED); await _web3Wallet!.rejectSession(id: args.id, reason: error); @@ -188,12 +205,11 @@ class Web3WalletService extends IWeb3WalletService { topic: args.params.pairingTopic, ); - // TODO this should be triggered on _onRelayClientMessage final scheme = args.params.proposer.metadata.redirect?.native ?? ''; DeepLinkHandler.goTo( scheme, modalTitle: 'Error', - modalMessage: 'User rejected', + modalMessage: error.message, success: false, ); } @@ -240,7 +256,7 @@ class Web3WalletService extends IWeb3WalletService { void _onSessionConnect(SessionConnect? args) { if (args != null) { - log('[SampleWallet] _onSessionConnect ${jsonEncode(args.session)}'); + log('[SampleWallet] _onSessionConnect ${jsonEncode(args.session.toJson())}'); final scheme = args.session.peer.metadata.redirect?.native ?? ''; DeepLinkHandler.goTo(scheme); } @@ -296,8 +312,7 @@ class Web3WalletService extends IWeb3WalletService { WCBottomSheetResult.reject; if (rs != WCBottomSheetResult.reject) { - const chain = 'eip155:1'; - final chainKeys = GetIt.I().getKeysForChain(chain); + final chainKeys = GetIt.I().getKeysForChain('eip155:1'); final privateKey = '0x${chainKeys[0].privateKey}'; final credentials = EthPrivateKey.fromHex(privateKey); // @@ -324,12 +339,20 @@ class Web3WalletService extends IWeb3WalletService { ); } // - final _ = await _web3Wallet!.approveSessionAuthenticate( - id: args.id, - auths: cacaos, - ); - final scheme = args.requester.metadata.redirect?.native ?? ''; - DeepLinkHandler.goTo(scheme); + try { + await _web3Wallet!.approveSessionAuthenticate( + id: args.id, + auths: cacaos, + ); + final scheme = args.requester.metadata.redirect?.native ?? ''; + DeepLinkHandler.goTo(scheme); + } on WalletConnectError catch (error) { + DeepLinkHandler.goBackModal( + title: 'Error', + message: error.message, + success: false, + ); + } } else { await _web3Wallet!.rejectSessionAuthenticate( id: args.id, diff --git a/example/wallet/lib/main.dart b/example/wallet/lib/main.dart index 39cff46d..bd4accaa 100644 --- a/example/wallet/lib/main.dart +++ b/example/wallet/lib/main.dart @@ -63,7 +63,7 @@ class _MyHomePageState extends State with GetItStateMixin { GetIt.I.registerSingleton(BottomSheetService()); GetIt.I.registerSingleton(KeyService()); - final IWeb3WalletService web3WalletService = Web3WalletService(); + final web3WalletService = Web3WalletService(); await web3WalletService.create(); GetIt.I.registerSingleton(web3WalletService); @@ -109,6 +109,15 @@ class _MyHomePageState extends State with GetItStateMixin { await web3WalletService.init(); + web3WalletService.web3wallet.core.relayClient.onRelayClientConnect + .subscribe( + _setState, + ); + web3WalletService.web3wallet.core.relayClient.onRelayClientDisconnect + .subscribe( + _setState, + ); + setState(() { _pageDatas = [ PageData( @@ -137,6 +146,8 @@ class _MyHomePageState extends State with GetItStateMixin { }); } + void _setState(dynamic args) => setState(() {}); + @override Widget build(BuildContext context) { if (_initializing) { @@ -159,12 +170,23 @@ class _MyHomePageState extends State with GetItStateMixin { ), ); + final web3Wallet = GetIt.I().web3wallet; return Scaffold( appBar: AppBar( title: Text( _pageDatas[_selectedIndex].title, style: const TextStyle(color: Colors.black), ), + actions: [ + const Text('Relay '), + CircleAvatar( + radius: 6.0, + backgroundColor: web3Wallet.core.relayClient.isConnected + ? Colors.green + : Colors.red, + ), + const SizedBox(width: 16.0), + ], ), body: BottomSheetListener( child: Row( diff --git a/example/wallet/lib/pages/app_detail_page.dart b/example/wallet/lib/pages/app_detail_page.dart index eaf348b7..1605964b 100644 --- a/example/wallet/lib/pages/app_detail_page.dart +++ b/example/wallet/lib/pages/app_detail_page.dart @@ -88,7 +88,7 @@ class AppDetailPageState extends State { ); setState(() {}); } catch (e) { - debugPrint('[WALLET] ${e.toString()}'); + debugPrint('[SampleWallet] ${e.toString()}'); } }, child: const Center( @@ -187,7 +187,7 @@ class AppDetailPageState extends State { } _back(); } catch (e) { - debugPrint('[WALLET] ${e.toString()}'); + debugPrint('[SampleWallet] ${e.toString()}'); } }, child: const Center( diff --git a/example/wallet/lib/pages/apps_page.dart b/example/wallet/lib/pages/apps_page.dart index d46770cf..813f1841 100644 --- a/example/wallet/lib/pages/apps_page.dart +++ b/example/wallet/lib/pages/apps_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:fl_toast/fl_toast.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; @@ -215,31 +217,50 @@ class AppsPageState extends State with GetItStateMixin { DeepLinkHandler.waiting.value = true; final Uri uriData = Uri.parse(uri!); await _web3Wallet.pair(uri: uriData); - } catch (e) { - DeepLinkHandler.waiting.value = false; - showPlatformToast( - child: Container( - padding: const EdgeInsets.all(StyleConstants.linear8), - margin: const EdgeInsets.only( - bottom: StyleConstants.magic40, - ), - decoration: BoxDecoration( - color: StyleConstants.errorColor, - borderRadius: BorderRadius.circular( - StyleConstants.linear16, - ), - ), - child: const Text( - StringConstants.invalidUri, - style: StyleConstants.bodyTextBold, - ), - ), - // ignore: use_build_context_synchronously - context: context, - ); + } on WalletConnectError catch (e) { + _showErrorDialog('${e.code}: ${e.message}'); + } on TimeoutException catch (_) { + _showErrorDialog('Time out error. Check your connection.'); } } + void _showErrorDialog(String message) { + DeepLinkHandler.waiting.value = false; + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text( + 'Error', + style: TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + ), + ), + content: Text( + message, + style: const TextStyle( + color: Colors.black, + ), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: const Text( + 'Close', + style: TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + ), + ), + ) + ], + ); + }); + } + void _onListItemTap(PairingInfo pairing) { Navigator.push( context, diff --git a/example/wallet/lib/pages/settings_page.dart b/example/wallet/lib/pages/settings_page.dart index f6968ede..b3e77ce6 100644 --- a/example/wallet/lib/pages/settings_page.dart +++ b/example/wallet/lib/pages/settings_page.dart @@ -1,3 +1,4 @@ +import 'dart:math'; import 'dart:ui'; import 'package:fl_toast/fl_toast.dart'; @@ -13,8 +14,6 @@ import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/custom_button.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/recover_from_seed.dart'; -// import 'package:package_info_plus/package_info_plus.dart'; - class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -26,147 +25,523 @@ class _SettingsPageState extends State { @override Widget build(BuildContext context) { final keysService = GetIt.I(); - final chainKeys = keysService.getKeysForChain('eip155:1'); - final web3Wallet = GetIt.I().web3wallet; - return Padding( - padding: const EdgeInsets.all(12.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Padding( - padding: EdgeInsets.only(left: 8.0, bottom: 8.0), - child: Text( - 'Account', - style: TextStyle( - color: Colors.black, - fontSize: 16.0, - fontWeight: FontWeight.w500, - ), - ), - ), - _DataContainer( - title: 'CAIP-10', - data: 'eip155:1:${chainKeys.first.address}', - ), - const SizedBox(height: 12.0), - _DataContainer( - title: 'Public key', - data: chainKeys.first.publicKey, - ), - const SizedBox(height: 12.0), - _DataContainer( - title: 'Private key', - data: chainKeys.first.privateKey, - blurred: true, - ), - const SizedBox(height: 12.0), - FutureBuilder( - future: SharedPreferences.getInstance(), - builder: (context, snapshot) { - return _DataContainer( - title: 'Seed phrase', - data: snapshot.data?.getString('mnemonic') ?? '', - blurred: true, + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _EVMAccounts( + onCreateAddress: () async { + await keysService.createAddressFromSeed(); + await keysService.loadKeys(); + // ignore: use_build_context_synchronously + Navigator.of(context).pop(); + setState(() {}); + }, + onAccountChanged: (address) async { + final web3wallet = GetIt.I().web3wallet; + final sessions = web3wallet.sessions.getAll(); + for (var session in sessions) { + await web3wallet.emitSessionEvent( + topic: session.topic, + chainId: 'eip155:1', + event: SessionEventParams( + name: 'accountsChanged', + data: [address], + ), ); - }, - ), - const SizedBox(height: 20.0), - const Divider(height: 1.0), - const Padding( - padding: EdgeInsets.only(left: 8.0, bottom: 8.0, top: 20.0), - child: Text( - 'Device', - style: TextStyle( - color: Colors.black, - fontSize: 16.0, - fontWeight: FontWeight.w500, - ), - ), - ), - FutureBuilder( - future: web3Wallet.core.crypto.getClientId(), - builder: (context, snapshot) { - return _DataContainer( - title: 'Client ID', - data: snapshot.data ?? '', + } + setState(() {}); + }, + ), + // + const SizedBox(height: 20.0), + const Divider(height: 1.0), + _SolanaAccounts(), + const SizedBox(height: 20.0), + const Divider(height: 1.0), + _PolkadotAccounts(), + const SizedBox(height: 20.0), + const Divider(height: 1.0), + _KadenaAccounts(), + const SizedBox(height: 20.0), + const Divider(height: 1.0), + _DeviceData(), + const SizedBox(height: 20.0), + const Divider(height: 1.0), + _Buttons( + onRestoreFromSeed: () async { + final mnemonic = + await GetIt.I().queueBottomSheet( + widget: RecoverFromSeed(), + ); + if (mnemonic is String) { + await keysService.restoreWalletFromSeed( + mnemonic: mnemonic, ); - }, + await keysService.loadKeys(); + await showDialog( + // ignore: use_build_context_synchronously + context: context, + builder: (BuildContext context) { + return const AlertDialog( + content: Text('Wallet from seed restored'), + ); + }, + ); + setState(() {}); + } + }, + onRestoreDefault: () async { + await keysService.loadDefaultWallet(); + await keysService.loadKeys(); + await showDialog( + // ignore: use_build_context_synchronously + context: context, + builder: (BuildContext context) { + return const AlertDialog( + content: Text('Default wallet restored'), + ); + }, + ); + setState(() {}); + }, + ), + // + ], + ), + ), + ), + ], + ); + } +} + +class _EVMAccounts extends StatefulWidget { + final VoidCallback onCreateAddress; + final Function(String) onAccountChanged; + const _EVMAccounts({ + required this.onCreateAddress, + required this.onAccountChanged, + }); + + @override + State<_EVMAccounts> createState() => _EVMAccountsState(); +} + +class _EVMAccountsState extends State<_EVMAccounts> { + int _currentPage = 0; + late final PageController _pageController; + + @override + void initState() { + super.initState(); + _pageController = PageController(); + } + + @override + Widget build(BuildContext context) { + final keysService = GetIt.I(); + final chainKeys = keysService.getKeysForChain('eip155'); + debugPrint('[$runtimeType] chainKeys ${chainKeys.length}'); + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Row( + children: [ + const SizedBox.square(dimension: 8.0), + Expanded( + child: Text( + 'EVM Accounts (${_currentPage + 1}/${chainKeys.length})', + style: const TextStyle( + color: Colors.black, + fontSize: 16.0, + fontWeight: FontWeight.w500, ), - const SizedBox(height: 12.0), - FutureBuilder( - future: PackageInfo.fromPlatform(), - builder: (context, snapshot) { - if (!snapshot.hasData) { - return const SizedBox.shrink(); - } - final v = snapshot.data!.version; - final b = snapshot.data!.buildNumber; - const f = String.fromEnvironment('FLUTTER_APP_FLAVOR'); - return _DataContainer( - title: 'App version', - data: '$v-$f ($b) - SDK v$packageVersion', + ), + ), + IconButton( + onPressed: () async { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text('Create new account'), + content: const Text( + 'This will create a new address out from the same seed phrase', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: widget.onCreateAddress, + child: const Text('Proceed'), + ), + ], ); }, + ); + }, + icon: const Icon(Icons.add_box_rounded), + padding: const EdgeInsets.all(0.0), + visualDensity: VisualDensity.compact, + ), + IconButton( + onPressed: (_currentPage == 0) + ? null + : () { + _pageController.jumpToPage(_currentPage - 1); + }, + icon: const Icon(Icons.arrow_back), + padding: const EdgeInsets.all(0.0), + visualDensity: VisualDensity.compact, + ), + IconButton( + onPressed: (_currentPage == chainKeys.length - 1) + ? null + : () { + _pageController.jumpToPage(_currentPage + 1); + }, + icon: const Icon(Icons.arrow_forward), + padding: const EdgeInsets.all(0.0), + visualDensity: VisualDensity.compact, + ), + ], + ), + ), + SizedBox( + height: 300.0, + child: PageView.builder( + controller: _pageController, + physics: const NeverScrollableScrollPhysics(), + onPageChanged: (value) async { + setState(() => _currentPage = value); + final chainKey = chainKeys[_currentPage]; + widget.onAccountChanged(chainKey.address); + }, + itemBuilder: (BuildContext context, int index) { + final chainKey = chainKeys[index]; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + children: [ + const SizedBox(height: 12.0), + _DataContainer( + title: 'CAIP-10', + data: 'eip155:1:${chainKey.address}', + height: 84.0, + ), + const SizedBox(height: 12.0), + _DataContainer( + title: 'Public key', + data: chainKey.publicKey, + height: 84.0, + ), + const SizedBox(height: 12.0), + _DataContainer( + title: 'Private key', + data: chainKey.privateKey, + blurred: true, + height: 84.0, + ), + const SizedBox(height: 12.0), + ], + ), + ); + }, + itemCount: chainKeys.length, + ), + ), + SizedBox( + height: 16.0, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + // ignore: sdk_version_since + children: chainKeys.indexed + .map( + (e) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 2.0), + child: CircleAvatar( + radius: e.$1 == _currentPage ? 4.0 : 3.0, + backgroundColor: + e.$1 == _currentPage ? Colors.black : Colors.black38, + ), ), - const SizedBox(height: 20.0), - const Divider(height: 1.0), - const SizedBox(height: 20.0), - Row( - children: [ - CustomButton( - onTap: () async { - final mnemonic = await GetIt.I() - .queueBottomSheet( - widget: RecoverFromSeed(), - ); - if (mnemonic is String) { - await keysService.restoreWallet(mnemonic: mnemonic); - setState(() {}); - } - }, - child: const Center( - child: Text( - 'Import account', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ], + ) + .toList(), + ), + ), + const SizedBox(height: 20.0), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: FutureBuilder( + future: SharedPreferences.getInstance(), + builder: (context, snapshot) { + return _DataContainer( + title: 'Seed phrase', + data: snapshot.data?.getString('w3w_mnemonic') ?? '', + blurred: true, + ); + }, + ), + ), + ], + ); + } +} + +class _SolanaAccounts extends StatelessWidget { + @override + Widget build(BuildContext context) { + final keysService = GetIt.I(); + final chainKeys = keysService.getKeysForChain('solana'); + if (chainKeys.isEmpty) return const SizedBox.shrink(); + return Column( + children: [ + const Padding( + padding: EdgeInsets.all(12.0), + child: Row( + children: [ + SizedBox.square(dimension: 8.0), + Expanded( + child: Text( + 'Solana Account', + style: TextStyle( + color: Colors.black, + fontSize: 16.0, + fontWeight: FontWeight.w500, ), - const SizedBox(height: 12.0), - Row( - children: [ - CustomButton( - type: CustomButtonType.invalid, - onTap: () async { - await keysService.loadDefaultWallet(); - setState(() {}); - }, - child: const Center( - child: Text( - 'Restore default', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ], + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + children: [ + _DataContainer( + title: 'Address', + data: chainKeys.first.address, + ), + const SizedBox(height: 12.0), + _DataContainer( + title: 'Secret key', + data: chainKeys.first.privateKey, + blurred: true, + ), + ], + ), + ), + ], + ); + } +} + +class _PolkadotAccounts extends StatelessWidget { + @override + Widget build(BuildContext context) { + final keysService = GetIt.I(); + final chainKeys = keysService.getKeysForChain('polkadot'); + if (chainKeys.isEmpty) return const SizedBox.shrink(); + return Column( + children: [ + const Padding( + padding: EdgeInsets.all(12.0), + child: Row( + children: [ + SizedBox.square(dimension: 8.0), + Expanded( + child: Text( + 'Polkadot Account', + style: TextStyle( + color: Colors.black, + fontSize: 16.0, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + children: [ + _DataContainer( + title: 'Address', + data: chainKeys.first.address, + ), + const SizedBox(height: 12.0), + _DataContainer( + title: 'Mnemonic', + data: chainKeys.first.privateKey, + blurred: true, + ), + ], + ), + ), + ], + ); + } +} + +class _KadenaAccounts extends StatelessWidget { + @override + Widget build(BuildContext context) { + final keysService = GetIt.I(); + final chainKeys = keysService.getKeysForChain('kadena'); + if (chainKeys.isEmpty) return const SizedBox.shrink(); + return Column( + children: [ + const Padding( + padding: EdgeInsets.all(12.0), + child: Row( + children: [ + SizedBox.square(dimension: 8.0), + Expanded( + child: Text( + 'Kadena Account', + style: TextStyle( + color: Colors.black, + fontSize: 16.0, + fontWeight: FontWeight.w500, ), - const SizedBox(height: 12.0), - ], + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + children: [ + _DataContainer( + title: 'Address', + data: chainKeys.first.address, + ), + const SizedBox(height: 12.0), + _DataContainer( + title: 'Secret key', + data: chainKeys.first.privateKey, + blurred: true, + ), + ], + ), + ) + ], + ); + } +} + +class _DeviceData extends StatelessWidget { + @override + Widget build(BuildContext context) { + final web3Wallet = GetIt.I().web3wallet; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.only(left: 8.0, bottom: 8.0, top: 12.0), + child: Text( + 'Device', + style: TextStyle( + color: Colors.black, + fontSize: 16.0, + fontWeight: FontWeight.w500, ), ), ), + FutureBuilder( + future: web3Wallet.core.crypto.getClientId(), + builder: (context, snapshot) { + return _DataContainer( + title: 'Client ID', + data: snapshot.data ?? '', + ); + }, + ), + const SizedBox(height: 12.0), + FutureBuilder( + future: PackageInfo.fromPlatform(), + builder: (context, snapshot) { + if (!snapshot.hasData) { + return const SizedBox.shrink(); + } + final v = snapshot.data!.version; + final b = snapshot.data!.buildNumber; + const f = String.fromEnvironment('FLUTTER_APP_FLAVOR'); + return _DataContainer( + title: 'App version', + data: '$v-$f ($b) - SDK v$packageVersion', + ); + }, + ), + ], + ), + ); + } +} + +class _Buttons extends StatelessWidget { + final VoidCallback onRestoreFromSeed; + final VoidCallback onRestoreDefault; + const _Buttons({ + required this.onRestoreFromSeed, + required this.onRestoreDefault, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(12.0), + child: Column( + children: [ + const SizedBox(height: 8.0), + Row( + children: [ + CustomButton( + type: CustomButtonType.normal, + onTap: onRestoreFromSeed, + child: const Center( + child: Text( + 'Restore wallet from seed', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + const SizedBox(height: 12.0), + Row( + children: [ + CustomButton( + type: CustomButtonType.invalid, + onTap: onRestoreDefault, + child: const Center( + child: Text( + 'Restore default wallet', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), ], ), ); @@ -178,10 +553,12 @@ class _DataContainer extends StatefulWidget { required this.title, required this.data, this.blurred = false, + this.height, }); final String title; final String data; final bool blurred; + final double? height; @override State<_DataContainer> createState() => __DataContainerState(); @@ -213,6 +590,7 @@ class __DataContainerState extends State<_DataContainer> { blurred = widget.blurred; }), child: Container( + height: widget.height, decoration: BoxDecoration( color: StyleConstants.lightGray, borderRadius: BorderRadius.circular( @@ -238,8 +616,11 @@ class __DataContainerState extends State<_DataContainer> { ], ), ImageFiltered( - imageFilter: - ImageFilter.blur(sigmaX: blurValue, sigmaY: blurValue), + imageFilter: ImageFilter.blur( + sigmaX: blurValue, + sigmaY: blurValue, + tileMode: TileMode.decal, + ), child: Text( widget.data, style: const TextStyle( @@ -255,3 +636,142 @@ class __DataContainerState extends State<_DataContainer> { ); } } + +class SizeReportingWidget extends StatefulWidget { + final Widget child; + final ValueChanged onSizeChange; + + const SizeReportingWidget({ + Key? key, + required this.child, + required this.onSizeChange, + }) : super(key: key); + + @override + State createState() => _SizeReportingWidgetState(); +} + +class _SizeReportingWidgetState extends State { + Size? _oldSize; + + @override + Widget build(BuildContext context) { + WidgetsBinding.instance.addPostFrameCallback((_) => _notifySize()); + return widget.child; + } + + void _notifySize() { + if (!mounted) { + return; + } + final size = context.size; + if (_oldSize != size && size != null) { + _oldSize = size; + widget.onSizeChange(size); + } + } +} + +class ExpandablePageView extends StatefulWidget { + final List children; + final PageController? controller; + final Function(int)? onPageChanged; + + const ExpandablePageView({ + Key? key, + required this.children, + this.controller, + this.onPageChanged, + }) : super(key: key); + + @override + State createState() => _ExpandablePageViewState(); +} + +class _ExpandablePageViewState extends State + with TickerProviderStateMixin { + late PageController _pageController; + late List _heights; + int _currentPage = 0; + + double get _currentHeight => _heights[_currentPage]; + + @override + void initState() { + super.initState(); + _heights = widget.children.map((e) => 0.0).toList(); + _pageController = widget.controller ?? PageController() + ..addListener(() { + final newPage = _pageController.page?.round() ?? 0; + if (_currentPage != newPage) { + setState(() => _currentPage = newPage); + } + }); + } + + @override + void didUpdateWidget(covariant ExpandablePageView oldWidget) { + super.didUpdateWidget(oldWidget); + final diff = widget.children.length - oldWidget.children.length; + if (diff > 0) { + for (var i = 0; i < diff; i++) { + final lastHeight = _heights.last; + _heights.add(lastHeight); + } + } + } + + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + debugPrint('${_heights[0]} $_currentHeight'); + return TweenAnimationBuilder( + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 50), + tween: Tween( + begin: max(_heights[0], 200.0), + end: max(_currentHeight, 200.0), + ), + builder: (context, value, child) => SizedBox( + height: value, + child: child, + ), + child: PageView( + physics: const NeverScrollableScrollPhysics(), + controller: _pageController, + onPageChanged: widget.onPageChanged, + children: _sizeReportingChildren + .asMap() // + .map((index, child) => MapEntry(index, child)) + .values + .toList(), + ), + ); + } + + List get _sizeReportingChildren => widget.children + .asMap() // + .map( + (index, child) => MapEntry( + index, + OverflowBox( + //needed, so that parent won't impose its constraints on the children, thus skewing the measurement results. + minHeight: 0, + maxHeight: double.infinity, + alignment: Alignment.topCenter, + child: SizeReportingWidget( + onSizeChange: (size) => + setState(() => _heights[index] = size.height), + child: Align(child: child), + ), + ), + ), + ) + .values + .toList(); +} diff --git a/example/wallet/lib/utils/dart_defines.dart b/example/wallet/lib/utils/dart_defines.dart index 6d157237..6c5964e8 100644 --- a/example/wallet/lib/utils/dart_defines.dart +++ b/example/wallet/lib/utils/dart_defines.dart @@ -2,17 +2,8 @@ class DartDefines { static const String projectId = String.fromEnvironment( 'PROJECT_ID', ); - // - static const eip155PrivateKey = String.fromEnvironment( - 'EIP155_PRIVATE_KEY', - defaultValue: - '5754463bdfbd6e081ca1d6df965927feb1066a0df86d010ac4125eb4bc4c0082', - ); - static const eip155Address = String.fromEnvironment( - 'EIP155_ADDRESS', - defaultValue: '0xf3c95b1a8cabf3d5151912377aeadd84aa41c27c', - ); - // + // HARDCODED TEST KEYS + // KADENA static const kadenaSecretKey = String.fromEnvironment( 'KADENA_SECRET_KEY', defaultValue: @@ -23,7 +14,7 @@ class DartDefines { defaultValue: '3a527a1af7713cde04a4ce8b6c95b3806b7582f2423d740fc16eaa5b7a235d42', ); - // + // SOLANA static const solanaSecretKey = String.fromEnvironment( 'SOLANA_SECRET_KEY', defaultValue: @@ -33,7 +24,7 @@ class DartDefines { 'SOLANA_ADDRESS', defaultValue: 'EbdEmCpKGvEwfwV4ACmVYHFRkwvXdogJhMZeEekDFVVJ', ); - // + // POLKADOT static const polkadotMnemonic = String.fromEnvironment( 'POLKADOT_MNEMONIC', defaultValue: diff --git a/example/wallet/lib/utils/eth_utils.dart b/example/wallet/lib/utils/eth_utils.dart index 1f394a0d..244c4b3a 100644 --- a/example/wallet/lib/utils/eth_utils.dart +++ b/example/wallet/lib/utils/eth_utils.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:convert/convert.dart'; +import 'package:flutter/foundation.dart'; import 'package:get_it/get_it.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/i_web3wallet_service.dart'; @@ -22,36 +23,54 @@ class EthUtils { return maybeHex; } - static dynamic getAddressFromParamsList(dynamic params) { - return (params as List).firstWhere((p) { - try { - if (addressRegEx.hasMatch(p)) { + static String? getAddressFromSessionRequest(SessionRequest request) { + try { + final paramsList = List.from((request.params as List)); + if (request.method == 'personal_sign') { + // for `personal_sign` first value in params has to be always the message + paramsList.removeAt(0); + } + + return paramsList.firstWhere((p) { + try { EthereumAddress.fromHex(p); return true; + } catch (e) { + return false; } - return false; - } catch (e) { - return false; - } - }, orElse: () => null); + }); + } catch (e) { + debugPrint(e.toString()); + return null; + } } - static dynamic getDataFromParamsList(dynamic params) { - final address = getAddressFromParamsList(params); - final param = (params as List).firstWhere( - (p) => p != address, - orElse: () => null, - ); - return param; + static dynamic getDataFromSessionRequest(SessionRequest request) { + try { + final paramsList = List.from((request.params as List)); + if (request.method == 'personal_sign') { + return paramsList.first; + } + return paramsList.firstWhere((p) { + final address = getAddressFromSessionRequest(request); + return p != address; + }); + } catch (e) { + debugPrint(e.toString()); + return null; + } } - static Map? getTransactionFromParams(dynamic params) { - final address = getAddressFromParamsList(params); - final param = params.firstWhere( - (p) => p != address, - orElse: () => null, - ); - return param as Map?; + static Map? getTransactionFromSessionRequest( + SessionRequest request, + ) { + try { + final param = (request.params as List).first; + return param as Map; + } catch (e) { + debugPrint(e.toString()); + return null; + } } static Future decodeMessageEvent(MessageEvent event) async { diff --git a/example/wallet/lib/widgets/custom_button.dart b/example/wallet/lib/widgets/custom_button.dart index f8c79f8f..a49d7111 100644 --- a/example/wallet/lib/widgets/custom_button.dart +++ b/example/wallet/lib/widgets/custom_button.dart @@ -24,7 +24,7 @@ class CustomButton extends StatelessWidget { case CustomButtonType.invalid: return StyleConstants.errorColor; default: - return Colors.blue[200]!; + return Colors.black54; } } diff --git a/example/wallet/lib/widgets/wc_request_widget.dart/wc_request_widget.dart b/example/wallet/lib/widgets/wc_request_widget.dart/wc_request_widget.dart index adbdc543..09b5aee3 100644 --- a/example/wallet/lib/widgets/wc_request_widget.dart/wc_request_widget.dart +++ b/example/wallet/lib/widgets/wc_request_widget.dart/wc_request_widget.dart @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/bottom_sheet/i_bottom_sheet_service.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; @@ -18,44 +19,44 @@ class WCRequestWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - child, - const SizedBox( - height: StyleConstants.linear16, + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: SingleChildScrollView( + child: child, ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - CustomButton( - onTap: onReject ?? - () => Navigator.of(context).pop(WCBottomSheetResult.reject), - type: CustomButtonType.invalid, - child: const Text( - StringConstants.reject, - style: StyleConstants.buttonText, - textAlign: TextAlign.center, - ), + ), + const SizedBox(height: StyleConstants.linear16), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + onTap: onReject ?? + () => Navigator.of(context).pop(WCBottomSheetResult.reject), + type: CustomButtonType.invalid, + child: const Text( + StringConstants.reject, + style: StyleConstants.buttonText, + textAlign: TextAlign.center, ), - const SizedBox( - width: StyleConstants.linear16, + ), + const SizedBox( + width: StyleConstants.linear16, + ), + CustomButton( + onTap: onAccept ?? + () => Navigator.of(context).pop(WCBottomSheetResult.one), + type: CustomButtonType.valid, + child: const Text( + StringConstants.approve, + style: StyleConstants.buttonText, + textAlign: TextAlign.center, ), - CustomButton( - onTap: onAccept ?? - () => Navigator.of(context).pop(WCBottomSheetResult.one), - type: CustomButtonType.valid, - child: const Text( - StringConstants.approve, - style: StyleConstants.buttonText, - textAlign: TextAlign.center, - ), - ), - ], - ), - ], - ), + ), + ], + ), + ], ); } } diff --git a/example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart b/example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart index 6cd4cbf8..c857e03f 100644 --- a/example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart +++ b/example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart @@ -13,49 +13,51 @@ class WCSessionAuthRequestWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - child, - const SizedBox(height: StyleConstants.linear16), - Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - CustomButton( - onTap: () => - Navigator.of(context).pop(WCBottomSheetResult.reject), - type: CustomButtonType.invalid, - child: const Text( - 'Cancel', - style: StyleConstants.buttonText, - textAlign: TextAlign.center, - ), + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: SingleChildScrollView( + child: child, + ), + ), + const SizedBox(height: StyleConstants.linear16), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + CustomButton( + onTap: () => + Navigator.of(context).pop(WCBottomSheetResult.reject), + type: CustomButtonType.invalid, + child: const Text( + 'Cancel', + style: StyleConstants.buttonText, + textAlign: TextAlign.center, ), - const SizedBox(width: StyleConstants.linear8), - CustomButton( - onTap: () => Navigator.of(context).pop(WCBottomSheetResult.one), - type: CustomButtonType.normal, - child: const Text( - 'Sign One', - style: StyleConstants.buttonText, - textAlign: TextAlign.center, - ), + ), + const SizedBox(width: StyleConstants.linear8), + CustomButton( + onTap: () => Navigator.of(context).pop(WCBottomSheetResult.one), + type: CustomButtonType.normal, + child: const Text( + 'Sign One', + style: StyleConstants.buttonText, + textAlign: TextAlign.center, ), - const SizedBox(width: StyleConstants.linear8), - CustomButton( - onTap: () => Navigator.of(context).pop(WCBottomSheetResult.all), - type: CustomButtonType.valid, - child: const Text( - 'Sign All', - style: StyleConstants.buttonText, - textAlign: TextAlign.center, - ), + ), + const SizedBox(width: StyleConstants.linear8), + CustomButton( + onTap: () => Navigator.of(context).pop(WCBottomSheetResult.all), + type: CustomButtonType.valid, + child: const Text( + 'Sign All', + style: StyleConstants.buttonText, + textAlign: TextAlign.center, ), - ], - ), - ], - ), + ), + ], + ), + ], ); } } diff --git a/example/wallet/macos/Flutter/GeneratedPluginRegistrant.swift b/example/wallet/macos/Flutter/GeneratedPluginRegistrant.swift index cc667fc0..a4e08b1e 100644 --- a/example/wallet/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/example/wallet/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,11 +5,13 @@ import FlutterMacOS import Foundation +import connectivity_plus import package_info_plus import shared_preferences_foundation import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) diff --git a/example/wallet/macos/Podfile.lock b/example/wallet/macos/Podfile.lock index 3755bcbc..1f667557 100644 --- a/example/wallet/macos/Podfile.lock +++ b/example/wallet/macos/Podfile.lock @@ -1,7 +1,5 @@ PODS: - FlutterMacOS (1.0.0) - - mobile_scanner (3.5.2): - - FlutterMacOS - package_info_plus (0.0.1): - FlutterMacOS - shared_preferences_foundation (0.0.1): @@ -12,7 +10,6 @@ PODS: DEPENDENCIES: - FlutterMacOS (from `Flutter/ephemeral`) - - mobile_scanner (from `Flutter/ephemeral/.symlinks/plugins/mobile_scanner/macos`) - package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`) - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`) - url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`) @@ -20,8 +17,6 @@ DEPENDENCIES: EXTERNAL SOURCES: FlutterMacOS: :path: Flutter/ephemeral - mobile_scanner: - :path: Flutter/ephemeral/.symlinks/plugins/mobile_scanner/macos package_info_plus: :path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos shared_preferences_foundation: @@ -31,11 +26,10 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 - mobile_scanner: 621cf2c34e1c74ae7ce5c6793638ab600723bdea package_info_plus: fa739dd842b393193c5ca93c26798dff6e3d0e0c - shared_preferences_foundation: 5b919d13b803cadd15ed2dc053125c68730e5126 - url_launcher_macos: d2691c7dd33ed713bf3544850a623080ec693d95 + shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 + url_launcher_macos: 5f437abeda8c85500ceb03f5c1938a8c5a705399 PODFILE CHECKSUM: 353c8bcc5d5b0994e508d035b5431cfe18c1dea7 -COCOAPODS: 1.13.0 +COCOAPODS: 1.15.2 diff --git a/example/wallet/macos/Runner/Configs/AppInfo.xcconfig b/example/wallet/macos/Runner/Configs/AppInfo.xcconfig index da803111..f095b4a5 100644 --- a/example/wallet/macos/Runner/Configs/AppInfo.xcconfig +++ b/example/wallet/macos/Runner/Configs/AppInfo.xcconfig @@ -5,7 +5,7 @@ // 'flutter create' template. // The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = Web3Wallet +PRODUCT_NAME = Flutter Wallet // The application's bundle identifier PRODUCT_BUNDLE_IDENTIFIER = com.example.wallet diff --git a/example/wallet/macos/Runner/DebugProfile.entitlements b/example/wallet/macos/Runner/DebugProfile.entitlements index 0830a9c5..91e6008a 100644 --- a/example/wallet/macos/Runner/DebugProfile.entitlements +++ b/example/wallet/macos/Runner/DebugProfile.entitlements @@ -10,5 +10,7 @@ com.apple.security.network.server + com.apple.security.network.client + diff --git a/example/wallet/macos/Runner/Release.entitlements b/example/wallet/macos/Runner/Release.entitlements index 852fa1a4..ee95ab7e 100644 --- a/example/wallet/macos/Runner/Release.entitlements +++ b/example/wallet/macos/Runner/Release.entitlements @@ -4,5 +4,7 @@ com.apple.security.app-sandbox + com.apple.security.network.client + diff --git a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_code_scanner.dart b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_code_scanner.dart index 0a1deb3a..d92c75d1 100644 --- a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_code_scanner.dart +++ b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_code_scanner.dart @@ -1,3 +1,5 @@ +// ignore_for_file: no_leading_underscores_for_local_identifiers + import 'dart:async'; import 'package:flutter/foundation.dart'; diff --git a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_scanner_overlay_shape.dart b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_scanner_overlay_shape.dart index 83fc5efc..2d251621 100644 --- a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_scanner_overlay_shape.dart +++ b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/qr_scanner_overlay_shape.dart @@ -1,3 +1,5 @@ +// ignore_for_file: no_leading_underscores_for_local_identifiers + import 'dart:math'; import 'package:flutter/material.dart'; diff --git a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/web/flutter_qr_web.dart b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/web/flutter_qr_web.dart index de368ace..ba6f5fe7 100644 --- a/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/web/flutter_qr_web.dart +++ b/example/wallet/packages/qr-bar-code-scanner-dialog/packages/qr_code_scanner/lib/src/web/flutter_qr_web.dart @@ -1,4 +1,4 @@ -// ignore_for_file: avoid_web_libraries_in_flutter +// ignore_for_file: avoid_web_libraries_in_flutter, library_private_types_in_public_api import 'dart:async'; import 'dart:core'; @@ -23,12 +23,12 @@ class WebQrView extends StatefulWidget { final PermissionSetCallback? onPermissionSet; final CameraFacing? cameraFacing; - const WebQrView( - {Key? key, - required this.onPlatformViewCreated, - this.onPermissionSet, - this.cameraFacing = CameraFacing.front}) - : super(key: key); + const WebQrView({ + Key? key, + required this.onPlatformViewCreated, + this.onPermissionSet, + this.cameraFacing = CameraFacing.front, + }) : super(key: key); @override _WebQrViewState createState() => _WebQrViewState(); @@ -64,7 +64,7 @@ class _WebQrViewState extends State { String? code; String? _errorMsg; html.VideoElement video = html.VideoElement(); - String viewID = 'QRVIEW-' + DateTime.now().millisecondsSinceEpoch.toString(); + String viewID = 'QRVIEW-${DateTime.now().millisecondsSinceEpoch}'; final StreamController _scanUpdateController = StreamController(); diff --git a/example/wallet/packages/qr-bar-code-scanner-dialog/test/qr_bar_code_scanner_dialog_method_channel_test.dart b/example/wallet/packages/qr-bar-code-scanner-dialog/test/qr_bar_code_scanner_dialog_method_channel_test.dart index 1f72e4aa..6914ffb1 100644 --- a/example/wallet/packages/qr-bar-code-scanner-dialog/test/qr_bar_code_scanner_dialog_method_channel_test.dart +++ b/example/wallet/packages/qr-bar-code-scanner-dialog/test/qr_bar_code_scanner_dialog_method_channel_test.dart @@ -1,3 +1,5 @@ +// ignore_for_file: deprecated_member_use + import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:qr_bar_code_scanner_dialog/qr_bar_code_scanner_dialog_method_channel.dart'; diff --git a/example/wallet/pubspec.yaml b/example/wallet/pubspec.yaml index b8fa856a..b40d5079 100644 --- a/example/wallet/pubspec.yaml +++ b/example/wallet/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: "none" version: 1.0.0+1 environment: - sdk: ">=2.18.6 <3.0.0" + sdk: ">=2.19.0 <4.0.0" dependencies: flutter: @@ -23,10 +23,13 @@ dependencies: package_info_plus: ^7.0.0 convert: ^3.0.1 url_launcher: ^6.2.2 + + # CHECK WEB SUPPORT kadena_dart_sdk: ^2.3.2 solana: ^0.30.4 polkadart_keyring: ^0.4.3 - polkadart: ^0.4.3 + polkadart: ^0.4.6 + # walletconnect_flutter_v2: path: ../.. diff --git a/example/wallet/windows/flutter/generated_plugin_registrant.cc b/example/wallet/windows/flutter/generated_plugin_registrant.cc index 4f788487..5777988d 100644 --- a/example/wallet/windows/flutter/generated_plugin_registrant.cc +++ b/example/wallet/windows/flutter/generated_plugin_registrant.cc @@ -6,9 +6,12 @@ #include "generated_plugin_registrant.h" +#include #include void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/example/wallet/windows/flutter/generated_plugins.cmake b/example/wallet/windows/flutter/generated_plugins.cmake index 88b22e5c..31032063 100644 --- a/example/wallet/windows/flutter/generated_plugins.cmake +++ b/example/wallet/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus url_launcher_windows ) diff --git a/lib/apis/core/connectivity/connectivity.dart b/lib/apis/core/connectivity/connectivity.dart new file mode 100644 index 00000000..a1639538 --- /dev/null +++ b/lib/apis/core/connectivity/connectivity.dart @@ -0,0 +1,41 @@ +import 'dart:async'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:walletconnect_flutter_v2/apis/core/connectivity/i_connectivity.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class ConnectivityState implements IConnectivity { + final ICore _core; + ConnectivityState({required ICore core}) : _core = core; + + bool _initialized = false; + + bool _isOnline = false; + @override + bool get isOnline => _isOnline; + + @override + Future init() async { + if (_initialized) return; + final result = await Connectivity().checkConnectivity(); + _updateConnectionStatus(result); + Connectivity().onConnectivityChanged.listen( + _updateConnectionStatus, + ); + _initialized = true; + } + + Future _updateConnectionStatus(List result) async { + _core.logger.i('[$runtimeType] Connectivity changed $result'); + final isMobileData = result.contains(ConnectivityResult.mobile); + final isWifi = result.contains(ConnectivityResult.wifi); + + _isOnline = isMobileData || isWifi; + + if (_isOnline && !_core.relayClient.isConnected) { + await _core.relayClient.connect(); + } else if (!_isOnline && _core.relayClient.isConnected) { + await _core.relayClient.disconnect(); + } + } +} diff --git a/lib/apis/core/connectivity/connectivity_models.dart b/lib/apis/core/connectivity/connectivity_models.dart new file mode 100644 index 00000000..a8285097 --- /dev/null +++ b/lib/apis/core/connectivity/connectivity_models.dart @@ -0,0 +1,9 @@ +import 'package:event/event.dart'; + +class ConnectivityEvent extends EventArgs { + final bool connected; + + ConnectivityEvent( + this.connected, + ); +} diff --git a/lib/apis/core/connectivity/i_connectivity.dart b/lib/apis/core/connectivity/i_connectivity.dart new file mode 100644 index 00000000..8320cff6 --- /dev/null +++ b/lib/apis/core/connectivity/i_connectivity.dart @@ -0,0 +1,4 @@ +abstract class IConnectivity { + bool get isOnline; + Future init(); +} diff --git a/lib/apis/core/core.dart b/lib/apis/core/core.dart index 9344cea9..4fede26c 100644 --- a/lib/apis/core/core.dart +++ b/lib/apis/core/core.dart @@ -1,4 +1,6 @@ import 'package:logger/logger.dart'; +import 'package:walletconnect_flutter_v2/apis/core/connectivity/connectivity.dart'; +import 'package:walletconnect_flutter_v2/apis/core/connectivity/i_connectivity.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/i_crypto.dart'; import 'package:walletconnect_flutter_v2/apis/core/echo/echo.dart'; @@ -65,6 +67,9 @@ class Core implements ICore { @override late IVerify verify; + @override + late IConnectivity connectivity; + Logger _logger = Logger( level: Level.off, printer: PrettyPrinter(), @@ -169,6 +174,9 @@ class Core implements ICore { core: this, httpClient: httpClient, ); + connectivity = ConnectivityState( + core: this, + ); } @override @@ -178,6 +186,7 @@ class Core implements ICore { await relayClient.init(); await expirer.init(); await pairing.init(); + await connectivity.init(); heartbeat.init(); } } diff --git a/lib/apis/core/i_core.dart b/lib/apis/core/i_core.dart index 85f067ad..bb88fbb5 100644 --- a/lib/apis/core/i_core.dart +++ b/lib/apis/core/i_core.dart @@ -1,4 +1,5 @@ import 'package:logger/logger.dart'; +import 'package:walletconnect_flutter_v2/apis/core/connectivity/i_connectivity.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/i_crypto.dart'; import 'package:walletconnect_flutter_v2/apis/core/echo/i_echo.dart'; import 'package:walletconnect_flutter_v2/apis/core/heartbit/i_heartbeat.dart'; @@ -21,6 +22,7 @@ abstract class ICore { abstract IRelayClient relayClient; abstract IStore> storage; + abstract IConnectivity connectivity; abstract IExpirer expirer; abstract IPairing pairing; abstract IEcho echo; diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index 4ea2e633..ce34b7c0 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -194,19 +194,25 @@ class Pairing implements IPairing { rethrow; } - await pairings.set(topic, pairing); - await core.crypto.setSymKey(symKey, overrideTopic: topic); - await core.relayClient.subscribe(topic: topic); - await core.expirer.set(topic, expiry); - - onPairingCreate.broadcast( - PairingEvent( - topic: topic, - ), - ); + try { + await pairings.set(topic, pairing); + await core.crypto.setSymKey(symKey, overrideTopic: topic); + await core.relayClient.subscribe(topic: topic).timeout( + const Duration(seconds: 15), + ); + await core.expirer.set(topic, expiry); + + onPairingCreate.broadcast( + PairingEvent( + topic: topic, + ), + ); - if (activatePairing) { - await activate(topic: topic); + if (activatePairing) { + await activate(topic: topic); + } + } catch (e) { + rethrow; } return pairing; diff --git a/lib/apis/core/pairing/utils/pairing_models.freezed.dart b/lib/apis/core/pairing/utils/pairing_models.freezed.dart index 0275658d..e3d14d76 100644 --- a/lib/apis/core/pairing/utils/pairing_models.freezed.dart +++ b/lib/apis/core/pairing/utils/pairing_models.freezed.dart @@ -12,7 +12,7 @@ part of 'pairing_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); PairingInfo _$PairingInfoFromJson(Map json) { return _PairingInfo.fromJson(json); @@ -221,7 +221,7 @@ class _$PairingInfoImpl implements _PairingInfo { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$PairingInfoImpl && @@ -488,7 +488,7 @@ class _$PairingMetadataImpl implements _PairingMetadata { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$PairingMetadataImpl && @@ -663,7 +663,7 @@ class _$RedirectImpl implements _Redirect { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RedirectImpl && @@ -904,7 +904,7 @@ class _$JsonRpcRecordImpl implements _JsonRpcRecord { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$JsonRpcRecordImpl && @@ -1101,7 +1101,7 @@ class _$ReceiverPublicKeyImpl implements _ReceiverPublicKey { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ReceiverPublicKeyImpl && diff --git a/lib/apis/core/pairing/utils/pairing_models.g.dart b/lib/apis/core/pairing/utils/pairing_models.g.dart index 78975b35..4e1e81f9 100644 --- a/lib/apis/core/pairing/utils/pairing_models.g.dart +++ b/lib/apis/core/pairing/utils/pairing_models.g.dart @@ -9,7 +9,7 @@ part of 'pairing_models.dart'; _$PairingInfoImpl _$$PairingInfoImplFromJson(Map json) => _$PairingInfoImpl( topic: json['topic'] as String, - expiry: json['expiry'] as int, + expiry: (json['expiry'] as num).toInt(), relay: Relay.fromJson(json['relay'] as Map), active: json['active'] as bool, methods: @@ -77,12 +77,12 @@ Map _$$RedirectImplToJson(_$RedirectImpl instance) => _$JsonRpcRecordImpl _$$JsonRpcRecordImplFromJson(Map json) => _$JsonRpcRecordImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), topic: json['topic'] as String, method: json['method'] as String, params: json['params'], chainId: json['chainId'] as String?, - expiry: json['expiry'] as int?, + expiry: (json['expiry'] as num?)?.toInt(), response: json['response'], ); @@ -111,7 +111,7 @@ _$ReceiverPublicKeyImpl _$$ReceiverPublicKeyImplFromJson( _$ReceiverPublicKeyImpl( topic: json['topic'] as String, publicKey: json['publicKey'] as String, - expiry: json['expiry'] as int, + expiry: (json['expiry'] as num).toInt(), ); Map _$$ReceiverPublicKeyImplToJson( diff --git a/lib/apis/core/relay_auth/relay_auth_models.g.dart b/lib/apis/core/relay_auth/relay_auth_models.g.dart index a116a6ac..3f2975f0 100644 --- a/lib/apis/core/relay_auth/relay_auth_models.g.dart +++ b/lib/apis/core/relay_auth/relay_auth_models.g.dart @@ -20,8 +20,8 @@ JWTPayload _$JWTPayloadFromJson(Map json) => JWTPayload( json['iss'] as String, json['sub'] as String, json['aud'] as String, - json['iat'] as int, - json['exp'] as int, + (json['iat'] as num).toInt(), + (json['exp'] as num).toInt(), ); Map _$JWTPayloadToJson(JWTPayload instance) => diff --git a/lib/apis/core/verify/models/verify_context.freezed.dart b/lib/apis/core/verify/models/verify_context.freezed.dart index a10cb641..8880e088 100644 --- a/lib/apis/core/verify/models/verify_context.freezed.dart +++ b/lib/apis/core/verify/models/verify_context.freezed.dart @@ -12,7 +12,7 @@ part of 'verify_context.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); VerifyContext _$VerifyContextFromJson(Map json) { return _VerifyContext.fromJson(json); @@ -157,7 +157,7 @@ class _$VerifyContextImpl implements _VerifyContext { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$VerifyContextImpl && @@ -337,7 +337,7 @@ class _$AttestationResponseImpl implements _AttestationResponse { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$AttestationResponseImpl && diff --git a/lib/apis/models/basic_models.freezed.dart b/lib/apis/models/basic_models.freezed.dart index 30bead8d..d766af7f 100644 --- a/lib/apis/models/basic_models.freezed.dart +++ b/lib/apis/models/basic_models.freezed.dart @@ -12,7 +12,7 @@ part of 'basic_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); WalletConnectError _$WalletConnectErrorFromJson(Map json) { return _WalletConnectError.fromJson(json); @@ -138,7 +138,7 @@ class _$WalletConnectErrorImpl implements _WalletConnectError { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WalletConnectErrorImpl && @@ -303,7 +303,7 @@ class _$RpcOptionsImpl implements _RpcOptions { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RpcOptionsImpl && @@ -464,7 +464,7 @@ class _$ConnectionMetadataImpl implements _ConnectionMetadata { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ConnectionMetadataImpl && diff --git a/lib/apis/models/basic_models.g.dart b/lib/apis/models/basic_models.g.dart index 24ae3314..978fa4b5 100644 --- a/lib/apis/models/basic_models.g.dart +++ b/lib/apis/models/basic_models.g.dart @@ -9,7 +9,7 @@ part of 'basic_models.dart'; _$WalletConnectErrorImpl _$$WalletConnectErrorImplFromJson( Map json) => _$WalletConnectErrorImpl( - code: json['code'] as int, + code: (json['code'] as num).toInt(), message: json['message'] as String, data: json['data'] as String?, ); diff --git a/lib/apis/models/json_rpc_error.freezed.dart b/lib/apis/models/json_rpc_error.freezed.dart index 13304bda..3e5da530 100644 --- a/lib/apis/models/json_rpc_error.freezed.dart +++ b/lib/apis/models/json_rpc_error.freezed.dart @@ -12,7 +12,7 @@ part of 'json_rpc_error.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); JsonRpcError _$JsonRpcErrorFromJson(Map json) { return _JsonRpcError.fromJson(json); @@ -125,7 +125,7 @@ class _$JsonRpcErrorImpl implements _JsonRpcError { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$JsonRpcErrorImpl && diff --git a/lib/apis/models/json_rpc_error.g.dart b/lib/apis/models/json_rpc_error.g.dart index ce1b1cd9..cf700f9f 100644 --- a/lib/apis/models/json_rpc_error.g.dart +++ b/lib/apis/models/json_rpc_error.g.dart @@ -8,7 +8,7 @@ part of 'json_rpc_error.dart'; _$JsonRpcErrorImpl _$$JsonRpcErrorImplFromJson(Map json) => _$JsonRpcErrorImpl( - code: json['code'] as int?, + code: (json['code'] as num?)?.toInt(), message: json['message'] as String?, ); diff --git a/lib/apis/models/json_rpc_request.freezed.dart b/lib/apis/models/json_rpc_request.freezed.dart index ea961a82..aeb19c7c 100644 --- a/lib/apis/models/json_rpc_request.freezed.dart +++ b/lib/apis/models/json_rpc_request.freezed.dart @@ -12,7 +12,7 @@ part of 'json_rpc_request.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); JsonRpcRequest _$JsonRpcRequestFromJson(Map json) { return _JsonRpcRequest.fromJson(json); @@ -156,7 +156,7 @@ class _$JsonRpcRequestImpl implements _JsonRpcRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$JsonRpcRequestImpl && diff --git a/lib/apis/models/json_rpc_request.g.dart b/lib/apis/models/json_rpc_request.g.dart index 392f4011..d50e1fd0 100644 --- a/lib/apis/models/json_rpc_request.g.dart +++ b/lib/apis/models/json_rpc_request.g.dart @@ -8,7 +8,7 @@ part of 'json_rpc_request.dart'; _$JsonRpcRequestImpl _$$JsonRpcRequestImplFromJson(Map json) => _$JsonRpcRequestImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), jsonrpc: json['jsonrpc'] as String? ?? '2.0', method: json['method'] as String, params: json['params'], diff --git a/lib/apis/models/json_rpc_response.freezed.dart b/lib/apis/models/json_rpc_response.freezed.dart index 58e87c5b..f913b10a 100644 --- a/lib/apis/models/json_rpc_response.freezed.dart +++ b/lib/apis/models/json_rpc_response.freezed.dart @@ -12,7 +12,7 @@ part of 'json_rpc_response.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); JsonRpcResponse _$JsonRpcResponseFromJson( Map json, T Function(Object?) fromJsonT) { @@ -172,7 +172,7 @@ class _$JsonRpcResponseImpl implements _JsonRpcResponse { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$JsonRpcResponseImpl && diff --git a/lib/apis/models/json_rpc_response.g.dart b/lib/apis/models/json_rpc_response.g.dart index 3e1795f4..fa84c4f7 100644 --- a/lib/apis/models/json_rpc_response.g.dart +++ b/lib/apis/models/json_rpc_response.g.dart @@ -11,7 +11,7 @@ _$JsonRpcResponseImpl _$$JsonRpcResponseImplFromJson( T Function(Object? json) fromJsonT, ) => _$JsonRpcResponseImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), jsonrpc: json['jsonrpc'] as String? ?? '2.0', error: json['error'] == null ? null diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index b0dc519a..3aa30669 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -104,7 +104,6 @@ abstract class ISignClient { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index 05b1ffe8..ccfa481c 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -33,7 +33,6 @@ abstract class ISignEngineApp extends ISignEngineCommon { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, diff --git a/lib/apis/sign_api/models/auth/auth_client_models.freezed.dart b/lib/apis/sign_api/models/auth/auth_client_models.freezed.dart index 05fbc985..f06f8ba4 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.freezed.dart @@ -12,7 +12,7 @@ part of 'auth_client_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); AuthPayloadParams _$AuthPayloadParamsFromJson(Map json) { return _AuthPayloadParams.fromJson(json); @@ -301,7 +301,7 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$AuthPayloadParamsImpl && @@ -575,7 +575,7 @@ class _$PendingAuthRequestImpl implements _PendingAuthRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$PendingAuthRequestImpl && diff --git a/lib/apis/sign_api/models/auth/auth_client_models.g.dart b/lib/apis/sign_api/models/auth/auth_client_models.g.dart index d75b386a..826e5c4e 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.g.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.g.dart @@ -54,7 +54,7 @@ Map _$$AuthPayloadParamsImplToJson( _$PendingAuthRequestImpl _$$PendingAuthRequestImplFromJson( Map json) => _$PendingAuthRequestImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), pairingTopic: json['pairingTopic'] as String, metadata: ConnectionMetadata.fromJson(json['metadata'] as Map), diff --git a/lib/apis/sign_api/models/auth/common_auth_models.freezed.dart b/lib/apis/sign_api/models/auth/common_auth_models.freezed.dart index 55109512..d362c912 100644 --- a/lib/apis/sign_api/models/auth/common_auth_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/common_auth_models.freezed.dart @@ -12,7 +12,7 @@ part of 'common_auth_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); AuthPublicKey _$AuthPublicKeyFromJson(Map json) { return _AuthPublicKey.fromJson(json); @@ -112,7 +112,7 @@ class _$AuthPublicKeyImpl implements _AuthPublicKey { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$AuthPublicKeyImpl && @@ -406,7 +406,7 @@ class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CacaoRequestPayloadImpl && @@ -766,7 +766,7 @@ class _$CacaoPayloadImpl implements _CacaoPayload { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CacaoPayloadImpl && @@ -960,7 +960,7 @@ class _$CacaoHeaderImpl implements _CacaoHeader { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CacaoHeaderImpl && @@ -1123,7 +1123,7 @@ class _$CacaoSignatureImpl implements _CacaoSignature { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CacaoSignatureImpl && @@ -1328,7 +1328,7 @@ class _$CacaoImpl implements _Cacao { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CacaoImpl && @@ -1575,7 +1575,7 @@ class _$StoredCacaoImpl implements _StoredCacao { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$StoredCacaoImpl && diff --git a/lib/apis/sign_api/models/auth/common_auth_models.g.dart b/lib/apis/sign_api/models/auth/common_auth_models.g.dart index 23fd94e6..02d49a50 100644 --- a/lib/apis/sign_api/models/auth/common_auth_models.g.dart +++ b/lib/apis/sign_api/models/auth/common_auth_models.g.dart @@ -147,7 +147,7 @@ Map _$$CacaoImplToJson(_$CacaoImpl instance) => _$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => _$StoredCacaoImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), pairingTopic: json['pairingTopic'] as String, h: CacaoHeader.fromJson(json['h'] as Map), p: CacaoPayload.fromJson(json['p'] as Map), diff --git a/lib/apis/sign_api/models/auth/session_auth_models.freezed.dart b/lib/apis/sign_api/models/auth/session_auth_models.freezed.dart index c8ab6514..c15f889a 100644 --- a/lib/apis/sign_api/models/auth/session_auth_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/session_auth_models.freezed.dart @@ -12,7 +12,7 @@ part of 'session_auth_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); SessionAuthRequestParams _$SessionAuthRequestParamsFromJson( Map json) { @@ -339,7 +339,7 @@ class _$SessionAuthRequestParamsImpl implements _SessionAuthRequestParams { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionAuthRequestParamsImpl && @@ -734,7 +734,7 @@ class _$SessionAuthPayloadImpl implements _SessionAuthPayload { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionAuthPayloadImpl && @@ -1056,7 +1056,7 @@ class _$PendingSessionAuthRequestImpl implements _PendingSessionAuthRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$PendingSessionAuthRequestImpl && diff --git a/lib/apis/sign_api/models/auth/session_auth_models.g.dart b/lib/apis/sign_api/models/auth/session_auth_models.g.dart index b0193a8b..d1ea250e 100644 --- a/lib/apis/sign_api/models/auth/session_auth_models.g.dart +++ b/lib/apis/sign_api/models/auth/session_auth_models.g.dart @@ -24,7 +24,7 @@ _$SessionAuthRequestParamsImpl _$$SessionAuthRequestParamsImplFromJson( resources: (json['resources'] as List?) ?.map((e) => e as String) .toList(), - expiry: json['expiry'] as int?, + expiry: (json['expiry'] as num?)?.toInt(), methods: (json['methods'] as List?) ?.map((e) => e as String) .toList() ?? @@ -106,11 +106,11 @@ Map _$$SessionAuthPayloadImplToJson( _$PendingSessionAuthRequestImpl _$$PendingSessionAuthRequestImplFromJson( Map json) => _$PendingSessionAuthRequestImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), pairingTopic: json['pairingTopic'] as String, requester: ConnectionMetadata.fromJson( json['requester'] as Map), - expiryTimestamp: json['expiryTimestamp'] as int, + expiryTimestamp: (json['expiryTimestamp'] as num).toInt(), authPayload: CacaoRequestPayload.fromJson( json['authPayload'] as Map), verifyContext: diff --git a/lib/apis/sign_api/models/json_rpc_models.freezed.dart b/lib/apis/sign_api/models/json_rpc_models.freezed.dart index f72335a4..984d2422 100644 --- a/lib/apis/sign_api/models/json_rpc_models.freezed.dart +++ b/lib/apis/sign_api/models/json_rpc_models.freezed.dart @@ -12,7 +12,7 @@ part of 'json_rpc_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); WcPairingDeleteRequest _$WcPairingDeleteRequestFromJson( Map json) { @@ -131,7 +131,7 @@ class _$WcPairingDeleteRequestImpl implements _WcPairingDeleteRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcPairingDeleteRequestImpl && @@ -281,7 +281,7 @@ class _$WcPairingPingRequestImpl implements _WcPairingPingRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcPairingPingRequestImpl && @@ -545,7 +545,7 @@ class _$WcSessionProposeRequestImpl implements _WcSessionProposeRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionProposeRequestImpl && @@ -730,7 +730,7 @@ class _$WcSessionProposeResponseImpl implements _WcSessionProposeResponse { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionProposeResponseImpl && @@ -1032,7 +1032,7 @@ class _$WcSessionSettleRequestImpl implements _WcSessionSettleRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionSettleRequestImpl && @@ -1221,7 +1221,7 @@ class _$WcSessionUpdateRequestImpl implements _WcSessionUpdateRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionUpdateRequestImpl && @@ -1376,7 +1376,7 @@ class _$WcSessionExtendRequestImpl implements _WcSessionExtendRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionExtendRequestImpl && @@ -1548,7 +1548,7 @@ class _$WcSessionDeleteRequestImpl implements _WcSessionDeleteRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionDeleteRequestImpl && @@ -1704,7 +1704,7 @@ class _$WcSessionPingRequestImpl implements _WcSessionPingRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionPingRequestImpl && @@ -1877,7 +1877,7 @@ class _$WcSessionRequestRequestImpl implements _WcSessionRequestRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionRequestRequestImpl && @@ -2036,7 +2036,7 @@ class _$SessionRequestParamsImpl implements _SessionRequestParams { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionRequestParamsImpl && @@ -2212,7 +2212,7 @@ class _$WcSessionEventRequestImpl implements _WcSessionEventRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionEventRequestImpl && @@ -2368,7 +2368,7 @@ class _$SessionEventParamsImpl implements _SessionEventParams { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionEventParamsImpl && @@ -2551,7 +2551,7 @@ class _$WcAuthRequestRequestImpl implements _WcAuthRequestRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcAuthRequestRequestImpl && @@ -2711,7 +2711,7 @@ class _$WcAuthRequestResultImpl implements _WcAuthRequestResult { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcAuthRequestResultImpl && @@ -2916,7 +2916,7 @@ class _$WcSessionAuthRequestParamsImpl implements _WcSessionAuthRequestParams { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionAuthRequestParamsImpl && @@ -3109,7 +3109,7 @@ class _$WcSessionAuthRequestResultImpl implements _WcSessionAuthRequestResult { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$WcSessionAuthRequestResultImpl && diff --git a/lib/apis/sign_api/models/json_rpc_models.g.dart b/lib/apis/sign_api/models/json_rpc_models.g.dart index 8008131a..fe4ad4f6 100644 --- a/lib/apis/sign_api/models/json_rpc_models.g.dart +++ b/lib/apis/sign_api/models/json_rpc_models.g.dart @@ -9,7 +9,7 @@ part of 'json_rpc_models.dart'; _$WcPairingDeleteRequestImpl _$$WcPairingDeleteRequestImplFromJson( Map json) => _$WcPairingDeleteRequestImpl( - code: json['code'] as int, + code: (json['code'] as num).toInt(), message: json['message'] as String, ); @@ -112,7 +112,7 @@ _$WcSessionSettleRequestImpl _$$WcSessionSettleRequestImplFromJson( (json['sessionProperties'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - expiry: json['expiry'] as int, + expiry: (json['expiry'] as num).toInt(), controller: ConnectionMetadata.fromJson( json['controller'] as Map), ); @@ -177,7 +177,7 @@ Map _$$WcSessionExtendRequestImplToJson( _$WcSessionDeleteRequestImpl _$$WcSessionDeleteRequestImplFromJson( Map json) => _$WcSessionDeleteRequestImpl( - code: json['code'] as int, + code: (json['code'] as num).toInt(), message: json['message'] as String, data: json['data'] as String?, ); @@ -311,7 +311,7 @@ _$WcSessionAuthRequestParamsImpl _$$WcSessionAuthRequestParamsImplFromJson( json['authPayload'] as Map), requester: ConnectionMetadata.fromJson( json['requester'] as Map), - expiryTimestamp: json['expiryTimestamp'] as int, + expiryTimestamp: (json['expiryTimestamp'] as num).toInt(), ); Map _$$WcSessionAuthRequestParamsImplToJson( diff --git a/lib/apis/sign_api/models/proposal_models.freezed.dart b/lib/apis/sign_api/models/proposal_models.freezed.dart index a516bba7..02ba5bdd 100644 --- a/lib/apis/sign_api/models/proposal_models.freezed.dart +++ b/lib/apis/sign_api/models/proposal_models.freezed.dart @@ -12,7 +12,7 @@ part of 'proposal_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); RequiredNamespace _$RequiredNamespaceFromJson(Map json) { return _RequiredNamespace.fromJson(json); @@ -163,7 +163,7 @@ class _$RequiredNamespaceImpl implements _RequiredNamespace { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RequiredNamespaceImpl && @@ -340,7 +340,7 @@ class _$SessionProposalImpl implements _SessionProposal { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionProposalImpl && @@ -673,7 +673,7 @@ class _$ProposalDataImpl implements _ProposalData { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ProposalDataImpl && diff --git a/lib/apis/sign_api/models/proposal_models.g.dart b/lib/apis/sign_api/models/proposal_models.g.dart index e63f97a3..4cdacce3 100644 --- a/lib/apis/sign_api/models/proposal_models.g.dart +++ b/lib/apis/sign_api/models/proposal_models.g.dart @@ -36,7 +36,7 @@ Map _$$RequiredNamespaceImplToJson( _$SessionProposalImpl _$$SessionProposalImplFromJson( Map json) => _$SessionProposalImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), params: ProposalData.fromJson(json['params'] as Map), ); @@ -49,8 +49,8 @@ Map _$$SessionProposalImplToJson( _$ProposalDataImpl _$$ProposalDataImplFromJson(Map json) => _$ProposalDataImpl( - id: json['id'] as int, - expiry: json['expiry'] as int, + id: (json['id'] as num).toInt(), + expiry: (json['expiry'] as num).toInt(), relays: (json['relays'] as List) .map((e) => Relay.fromJson(e as Map)) .toList(), diff --git a/lib/apis/sign_api/models/session_models.freezed.dart b/lib/apis/sign_api/models/session_models.freezed.dart index e0f91698..7da892aa 100644 --- a/lib/apis/sign_api/models/session_models.freezed.dart +++ b/lib/apis/sign_api/models/session_models.freezed.dart @@ -12,7 +12,7 @@ part of 'session_models.dart'; T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); Namespace _$NamespaceFromJson(Map json) { return _Namespace.fromJson(json); @@ -191,7 +191,7 @@ class _$NamespaceImpl implements _Namespace { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NamespaceImpl && @@ -589,7 +589,7 @@ class _$SessionDataImpl implements _SessionData { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionDataImpl && @@ -887,7 +887,7 @@ class _$SessionRequestImpl implements _SessionRequest { } @override - bool operator ==(dynamic other) { + bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$SessionRequestImpl && diff --git a/lib/apis/sign_api/models/session_models.g.dart b/lib/apis/sign_api/models/session_models.g.dart index 40c5558a..fb0c2596 100644 --- a/lib/apis/sign_api/models/session_models.g.dart +++ b/lib/apis/sign_api/models/session_models.g.dart @@ -39,7 +39,7 @@ _$SessionDataImpl _$$SessionDataImplFromJson(Map json) => topic: json['topic'] as String, pairingTopic: json['pairingTopic'] as String, relay: Relay.fromJson(json['relay'] as Map), - expiry: json['expiry'] as int, + expiry: (json['expiry'] as num).toInt(), acknowledged: json['acknowledged'] as bool, controller: json['controller'] as String, namespaces: (json['namespaces'] as Map).map( @@ -92,7 +92,7 @@ Map _$$SessionDataImplToJson(_$SessionDataImpl instance) { _$SessionRequestImpl _$$SessionRequestImplFromJson(Map json) => _$SessionRequestImpl( - id: json['id'] as int, + id: (json['id'] as num).toInt(), topic: json['topic'] as String, method: json['method'] as String, chainId: json['chainId'] as String, diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index fba5a520..4ddab595 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -293,7 +293,7 @@ class SignClient implements ISignClient { required String functionName, required String rpcUrl, EthereumAddress? sender, - List parameters = const [], + List parameters = const [], }) async { try { return await engine.requestReadContract( @@ -312,18 +312,16 @@ class SignClient implements ISignClient { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, - String? method, List parameters = const [], + String? method, }) async { try { return await engine.requestWriteContract( topic: topic, chainId: chainId, - rpcUrl: rpcUrl, deployedContract: deployedContract, functionName: functionName, transaction: transaction, diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index ac6e2910..05a61f6a 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -6,7 +6,6 @@ import 'package:http/http.dart' as http; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/utils/custom_credentials.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/sign_api_validator_utils.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/recaps_utils.dart'; @@ -543,27 +542,20 @@ class SignEngine implements ISignEngine { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, - String? method, List parameters = const [], + String? method, }) async { if (transaction.from == null) { throw Exception('Transaction must include `from` value'); } - final credentials = CustomCredentials( - signEngine: this, - topic: topic, - chainId: chainId, - address: transaction.from!, - method: method, - ); + final trx = Transaction.callContract( contract: deployedContract, function: deployedContract.function(functionName), - from: credentials.address, + from: transaction.from!, value: transaction.value, maxGas: transaction.maxGas, gasPrice: transaction.gasPrice, @@ -573,13 +565,13 @@ class SignEngine implements ISignEngine { parameters: parameters, ); - if (chainId.contains(':')) { - chainId = chainId.split(':').last; - } - return await Web3Client(rpcUrl, http.Client()).sendTransaction( - credentials, - trx, - chainId: int.parse(chainId), + return await request( + topic: topic, + chainId: chainId, + request: SessionRequestParams( + method: method ?? MethodsConstants.ethSendTransaction, + params: [trx.toJson()], + ), ); } @@ -836,6 +828,9 @@ class SignEngine implements ISignEngine { if (!_initialized) { throw Errors.getInternalError(Errors.NOT_INITIALIZED); } + if (!core.connectivity.isOnline) { + throw WalletConnectError(code: -1, message: 'No internet connection'); + } } String _getRegisterKey(String chainId, String value) { @@ -1869,7 +1864,7 @@ class SignEngine implements ISignEngine { final chainId = AddressUtils.getDidChainId(payload.iss); final isValid = await AuthSignature.verifySignature( - walletAddress, + walletAddress.toEIP55(), reconstructed, signature, chainId, @@ -1924,7 +1919,7 @@ class SignEngine implements ISignEngine { final message = [ header, - walletAddress, + walletAddress.toEIP55(), '', statement, '', @@ -1962,11 +1957,11 @@ class SignEngine implements ISignEngine { // FORMER AUTH ENGINE PROPERTY @override Map getPendingAuthRequests() { - Map pendingRequests = {}; + Map pendingAuthRequests = {}; authRequests.getAll().forEach((key) { - pendingRequests[key.id] = key; + pendingAuthRequests[key.id] = key; }); - return pendingRequests; + return pendingAuthRequests; } // FORMER AUTH ENGINE PROPERTY @@ -2128,11 +2123,11 @@ class SignEngine implements ISignEngine { // NEW ONE-CLICK AUTH METHOD FOR DAPPS @override Map getPendingSessionAuthRequests() { - Map pendingRequests = {}; + Map pendingSessionAuthRequests = {}; sessionAuthRequests.getAll().forEach((key) { - pendingRequests[key.id] = key; + pendingSessionAuthRequests[key.id] = key; }); - return pendingRequests; + return pendingSessionAuthRequests; } @override @@ -2385,7 +2380,7 @@ class SignEngine implements ISignEngine { final parsedAddress = AddressUtils.getDidAddress(payload.iss); for (var chain in approvedChains.toSet()) { - approvedAccounts.add('$chain:$parsedAddress'); + approvedAccounts.add('$chain:${parsedAddress.toEIP55()}'); } } } on WalletConnectError catch (e) { @@ -2584,7 +2579,7 @@ class SignEngine implements ISignEngine { final parsedAddress = AddressUtils.getDidAddress(payload.iss); for (var chain in approvedChains.toSet()) { - approvedAccounts.add('$chain:$parsedAddress'); + approvedAccounts.add('$chain:${parsedAddress.toEIP55()}'); } } diff --git a/lib/apis/sign_api/utils/auth/address_utils.dart b/lib/apis/sign_api/utils/auth/address_utils.dart index 77acd45e..ad6509e4 100644 --- a/lib/apis/sign_api/utils/auth/address_utils.dart +++ b/lib/apis/sign_api/utils/auth/address_utils.dart @@ -1,3 +1,5 @@ +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + class AddressUtils { static String getDidAddress(String iss) { return iss.split(':').last; @@ -11,3 +13,9 @@ class AddressUtils { return iss.substring(iss.indexOf(RegExp(r':')) + 1); } } + +extension AddressUtilsExtension on String { + String toEIP55() { + return EthereumAddress.fromHex(this).hexEip55; + } +} diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index bdd7ea50..826a105e 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -8,6 +8,7 @@ import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils. import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/address_utils.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/recaps_utils.dart'; import 'package:web3dart/crypto.dart' as crypto; @@ -199,6 +200,8 @@ class AuthSignature { if (!iss.contains('did:pkh:')) { iss = 'did:pkh:$iss'; } + final address = AddressUtils.getDidAddress(iss); + iss = iss.replaceAll(address, address.toEIP55()); return Cacao( h: const CacaoHeader(t: CacaoHeader.CAIP122), p: CacaoPayload.fromRequestPayload( diff --git a/lib/apis/sign_api/utils/custom_credentials.dart b/lib/apis/sign_api/utils/custom_credentials.dart deleted file mode 100644 index 1db2c80e..00000000 --- a/lib/apis/sign_api/utils/custom_credentials.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'dart:convert'; -import 'dart:typed_data'; - -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -import 'package:web3dart/crypto.dart' as crypto; - -class CustomCredentials extends CustomTransactionSender { - CustomCredentials({ - required ISignEngine signEngine, - required String topic, - required String chainId, - required EthereumAddress address, - String? method, - }) : _signEngine = signEngine, - _topic = topic, - _chainId = chainId, - _address = address, - _method = method; - - final ISignEngine _signEngine; - final String _topic; - final String _chainId; - final EthereumAddress _address; - final String? _method; - - @override - EthereumAddress get address => _address; - - @override - Future sendTransaction(Transaction transaction) async { - final result = await _sendTransaction(transaction); - if (result is Map) { - return jsonEncode(result); - } - return result.toString(); - } - - Future _sendTransaction(Transaction transaction) async { - final sessionRequestParams = SessionRequestParams( - method: _method ?? MethodsConstants.ethSendTransaction, - params: [ - transaction.toJson(), - ], - ); - - final result = await _signEngine.request( - topic: _topic, - chainId: _chainId, - request: sessionRequestParams, - ); - return result; - } - - @override - Future extractAddress() => Future.value(_address); - - @override - Future signToSignature( - Uint8List payload, { - int? chainId, - bool isEIP1559 = false, - }) { - final signature = signToEcSignature( - payload, - chainId: chainId, - isEIP1559: isEIP1559, - ); - return Future.value(signature); - } - - @override - crypto.MsgSignature signToEcSignature( - Uint8List payload, { - int? chainId, - bool isEIP1559 = false, - }) { - // TODO: implement signToEcSignature - throw UnimplementedError(); - } -} diff --git a/lib/apis/utils/extensions.dart b/lib/apis/utils/extensions.dart index 596e3539..0d4c466c 100644 --- a/lib/apis/utils/extensions.dart +++ b/lib/apis/utils/extensions.dart @@ -7,8 +7,8 @@ import 'package:web3dart/crypto.dart' as crypto; extension TransactionExtension on Transaction { Map toJson() { return { - if (from != null) 'from': from!.hex, - if (to != null) 'to': to!.hex, + if (from != null) 'from': from!.hexEip55, + if (to != null) 'to': to!.hexEip55, if (maxGas != null) 'gas': '0x${maxGas!.toRadixString(16)}', if (gasPrice != null) 'gasPrice': '0x${gasPrice!.getInWei.toRadixString(16)}', @@ -57,7 +57,7 @@ extension EtheraAmountExtension on String? { final hexValue = this!.replaceFirst('0x', ''); return EtherAmount.fromBigInt( EtherUnit.wei, - BigInt.from(int.parse(hexValue, radix: 16)), + BigInt.parse(hexValue, radix: 16), ); } return null; diff --git a/lib/apis/utils/walletconnect_utils.dart b/lib/apis/utils/walletconnect_utils.dart index 901b26f2..875b2e8a 100644 --- a/lib/apis/utils/walletconnect_utils.dart +++ b/lib/apis/utils/walletconnect_utils.dart @@ -3,9 +3,7 @@ import 'dart:io'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:flutter/foundation.dart' show kIsWeb; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/uri_parse_result.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; class WalletConnectUtils { static bool isExpired(int expiry) { @@ -91,14 +89,31 @@ class WalletConnectUtils { }) { final Uri uri = Uri.parse(relayUrl); final Map queryParams = Uri.splitQueryString(uri.query); - String ua = formatUA(protocol, version, sdkVersion); + final userAgent = formatUA(protocol, version, sdkVersion); + // Add basic query params final Map relayParams = { 'auth': auth, - if ((projectId ?? '').isNotEmpty) 'projectId': projectId!, - 'ua': ua, - if ((packageName ?? '').isNotEmpty) 'origin': packageName!, + 'ua': userAgent, }; + + // Add projectId query param + if ((projectId ?? '').isNotEmpty) { + relayParams['projectId'] = projectId!; + } + + // Add bundleId, packageName or origin query param based on platform + if ((packageName ?? '').isNotEmpty) { + final platform = getId(); + if (platform == 'ios') { + relayParams['bundleId'] = packageName!; + } else if (platform == 'android') { + relayParams['packageName'] = packageName!; + } else { + relayParams['origin'] = packageName!; + } + } + queryParams.addAll(relayParams); return uri.replace(queryParameters: queryParams).toString(); } diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index a0523310..a9bdd506 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -228,7 +228,7 @@ class Web3App implements IWeb3App { required String functionName, required String rpcUrl, EthereumAddress? sender, - List parameters = const [], + List parameters = const [], }) async { try { return await signEngine.requestReadContract( @@ -247,7 +247,6 @@ class Web3App implements IWeb3App { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, @@ -258,7 +257,6 @@ class Web3App implements IWeb3App { return await signEngine.requestWriteContract( topic: topic, chainId: chainId, - rpcUrl: rpcUrl, deployedContract: deployedContract, functionName: functionName, transaction: transaction, diff --git a/lib/src/version.dart b/lib/src/version.dart index 36925912..ea3a9755 100644 --- a/lib/src/version.dart +++ b/lib/src/version.dart @@ -1,2 +1,2 @@ // Generated code. Do not modify. -const packageVersion = '2.3.0'; +const packageVersion = '2.3.1'; diff --git a/pubspec.yaml b/pubspec.yaml index d35f5742..71ac1658 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: walletconnect_flutter_v2 description: WalletConnect's official Dart library v2 for WalletKit and AppKit. The communications protocol for web3. -version: 2.3.0 +version: 2.3.1 repository: https://github.com/WalletConnect/WalletConnectFlutterV2 environment: @@ -8,6 +8,7 @@ environment: dependencies: bs58: ^1.0.2 + connectivity_plus: ^6.0.4 convert: ^3.0.1 cryptography: ^2.0.5 ed25519_edwards: ^0.3.1 @@ -19,7 +20,7 @@ dependencies: json_annotation: ^4.8.1 logger: ^2.2.0 package_info_plus: ^7.0.0 - pointycastle: ^3.7.4 + pointycastle: ^3.9.1 shared_preferences: ^2.2.2 stack_trace: ^1.10.0 stream_channel: ^2.1.0 diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index 9a795561..e233f328 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -1,9 +1,10 @@ import 'dart:async'; -import 'dart:typed_data'; -import 'package:eth_sig_util/eth_sig_util.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; + +import 'package:eth_sig_util/eth_sig_util.dart'; + import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_app.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_wallet.dart'; @@ -18,13 +19,8 @@ import 'utils/signature_constants.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); final List Function(PairingMetadata)> authAppCreators = [ diff --git a/test/core_api/core_test.dart b/test/core_api/core_test.dart index 77f352ac..4587adbe 100644 --- a/test/core_api/core_test.dart +++ b/test/core_api/core_test.dart @@ -1,6 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; @@ -9,13 +8,8 @@ import '../shared/shared_test_utils.mocks.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(['none']); group('Core throws errors', () { test('on start if there is no internet connection', () async { diff --git a/test/core_api/pairing_store_test.dart b/test/core_api/pairing_store_test.dart index 62f6d670..c5315d43 100644 --- a/test/core_api/pairing_store_test.dart +++ b/test/core_api/pairing_store_test.dart @@ -1,5 +1,4 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/i_json_rpc_history.dart'; @@ -18,13 +17,8 @@ import '../shared/shared_test_values.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); group('Pairing store', () { late ICore coreA; diff --git a/test/core_api/pairing_test.dart b/test/core_api/pairing_test.dart index a38c0c80..1f0d5dad 100644 --- a/test/core_api/pairing_test.dart +++ b/test/core_api/pairing_test.dart @@ -1,7 +1,8 @@ +@Timeout(Duration(seconds: 45)) + import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; @@ -18,13 +19,8 @@ import '../shared/shared_test_values.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); test('Format and parses URI correctly', () { Uri response = WalletConnectUtils.formatUri( @@ -271,18 +267,18 @@ void main() { }); test('clients can ping each other', () async { - final CreateResponse response = await coreA.pairing.create(); - // await coreB.pairing.pair(uri: response.uri); + // TODO more logs to check any fails in the future. + final pairingInfo = await coreA.pairing.create(); - Completer completer = Completer(); + final completer = Completer(); coreB.pairing.onPairingPing.subscribe((args) { expect(args != null, true); completer.complete(); }); + await coreB.pairing.pair(uri: pairingInfo.uri, activatePairing: true); - await coreB.pairing.pair(uri: response.uri, activatePairing: true); - await coreA.pairing.activate(topic: response.topic); - await coreA.pairing.ping(topic: response.topic); + await coreA.pairing.activate(topic: pairingInfo.topic); + await coreA.pairing.ping(topic: pairingInfo.topic); await completer.future; }); diff --git a/test/core_api/relay_auth_test.dart b/test/core_api/relay_auth_test.dart index ed0fe89b..683f529e 100644 --- a/test/core_api/relay_auth_test.dart +++ b/test/core_api/relay_auth_test.dart @@ -1,21 +1,18 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_auth/relay_auth.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_auth/relay_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import '../shared/shared_test_utils.dart'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); group('Relay Auth/API', () { // Client will sign a unique identifier as the subject diff --git a/test/core_api/relay_client_test.dart b/test/core_api/relay_client_test.dart index bbefcaf3..1cdaaf6c 100644 --- a/test/core_api/relay_client_test.dart +++ b/test/core_api/relay_client_test.dart @@ -3,7 +3,6 @@ import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart'; import 'package:mockito/mockito.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; @@ -13,13 +12,8 @@ import '../shared/shared_test_utils.mocks.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); const TEST_TOPIC = 'abc123'; const TEST_MESSAGE = 'swagmasterss'; diff --git a/test/shared/shared_test_utils.dart b/test/shared/shared_test_utils.dart index c9b56aa9..30c29b8e 100644 --- a/test/shared/shared_test_utils.dart +++ b/test/shared/shared_test_utils.dart @@ -1,8 +1,11 @@ // ignore_for_file: no_leading_underscores_for_local_identifiers +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_utils.dart'; @@ -82,3 +85,39 @@ MockHttpWrapper getHttpWrapper() { return httpWrapper; } + +mockPackageInfo() { + PackageInfo.setMockInitialValues( + appName: _mockInitialValues['appName'], + packageName: _mockInitialValues['packageName'], + version: _mockInitialValues['version'], + buildNumber: _mockInitialValues['buildNumber'], + buildSignature: _mockInitialValues['buildSignature'], + ); +} + +mockConnectivity([List values = const ['wifi']]) { + const channel = MethodChannel('dev.fluttercommunity.plus/connectivity'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMessageHandler( + channel.name, + (data) async { + final call = channel.codec.decodeMethodCall(data); + if (call.method == 'getAll') { + return channel.codec.encodeSuccessEnvelope(_mockInitialValues); + } + if (call.method == 'check') { + return channel.codec.encodeSuccessEnvelope(values); + } + return null; + }, + ); +} + +Map get _mockInitialValues => { + 'appName': 'walletconnect_flutter_v2', + 'packageName': 'com.walletconnect.flutterdapp', + 'version': '1.0', + 'buildNumber': '2', + 'buildSignature': 'buildSignature', + }; diff --git a/test/shared/shared_test_utils.mocks.dart b/test/shared/shared_test_utils.mocks.dart index f0475a40..6ea9a3b6 100644 --- a/test/shared/shared_test_utils.mocks.dart +++ b/test/shared/shared_test_utils.mocks.dart @@ -1,22 +1,24 @@ -// Mocks generated by Mockito 5.4.3 from annotations +// Mocks generated by Mockito 5.4.4 from annotations // in walletconnect_flutter_v2/test/shared/shared_test_utils.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i21; -import 'dart:typed_data' as _i19; +import 'dart:async' as _i22; +import 'dart:typed_data' as _i20; import 'package:event/event.dart' as _i8; import 'package:http/http.dart' as _i9; -import 'package:logger/logger.dart' as _i17; +import 'package:logger/logger.dart' as _i18; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i20; -import 'package:walletconnect_flutter_v2/apis/core/core.dart' as _i26; -import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto.dart' as _i22; +import 'package:mockito/src/dummies.dart' as _i21; +import 'package:walletconnect_flutter_v2/apis/core/connectivity/i_connectivity.dart' + as _i17; +import 'package:walletconnect_flutter_v2/apis/core/core.dart' as _i27; +import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto.dart' as _i23; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart' as _i2; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_utils.dart' - as _i18; + as _i19; import 'package:walletconnect_flutter_v2/apis/core/crypto/i_crypto.dart' as _i10; import 'package:walletconnect_flutter_v2/apis/core/crypto/i_crypto_utils.dart' @@ -34,16 +36,16 @@ import 'package:walletconnect_flutter_v2/apis/core/relay_auth/i_relay_auth.dart' import 'package:walletconnect_flutter_v2/apis/core/relay_client/i_relay_client.dart' as _i11; import 'package:walletconnect_flutter_v2/apis/core/relay_client/message_tracker.dart' - as _i23; + as _i24; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart' - as _i25; + as _i26; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/websocket_handler.dart' - as _i27; + as _i28; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart' as _i4; import 'package:walletconnect_flutter_v2/apis/core/store/i_store.dart' as _i7; import 'package:walletconnect_flutter_v2/apis/core/store/store_models.dart' - as _i24; + as _i25; import 'package:walletconnect_flutter_v2/apis/core/verify/i_verify.dart' as _i16; @@ -234,8 +236,19 @@ class _FakeIVerify_16 extends _i1.SmartFake implements _i16.IVerify { ); } -class _FakeLogger_17 extends _i1.SmartFake implements _i17.Logger { - _FakeLogger_17( +class _FakeIConnectivity_17 extends _i1.SmartFake + implements _i17.IConnectivity { + _FakeIConnectivity_17( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeLogger_18 extends _i1.SmartFake implements _i18.Logger { + _FakeLogger_18( Object parent, Invocation parentInvocation, ) : super( @@ -247,7 +260,7 @@ class _FakeLogger_17 extends _i1.SmartFake implements _i17.Logger { /// A class which mocks [CryptoUtils]. /// /// See the documentation for Mockito's code generation for more information. -class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { +class MockCryptoUtils extends _i1.Mock implements _i19.CryptoUtils { MockCryptoUtils() { _i1.throwOnMissingStub(this); } @@ -268,13 +281,13 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ) as _i2.CryptoKeyPair); @override - _i19.Uint8List randomBytes(int? length) => (super.noSuchMethod( + _i20.Uint8List randomBytes(int? length) => (super.noSuchMethod( Invocation.method( #randomBytes, [length], ), - returnValue: _i19.Uint8List(0), - ) as _i19.Uint8List); + returnValue: _i20.Uint8List(0), + ) as _i20.Uint8List); @override String generateRandomBytes32() => (super.noSuchMethod( @@ -282,7 +295,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { #generateRandomBytes32, [], ), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.method( #generateRandomBytes32, @@ -292,7 +305,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ) as String); @override - _i21.Future deriveSymKey( + _i22.Future deriveSymKey( String? privKeyA, String? pubKeyB, ) => @@ -304,7 +317,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { pubKeyB, ], ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #deriveSymKey, @@ -314,7 +327,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ], ), )), - ) as _i21.Future); + ) as _i22.Future); @override String hashKey(String? key) => (super.noSuchMethod( @@ -322,7 +335,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { #hashKey, [key], ), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.method( #hashKey, @@ -337,7 +350,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { #hashMessage, [message], ), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.method( #hashMessage, @@ -347,7 +360,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ) as String); @override - _i21.Future encrypt( + _i22.Future encrypt( String? message, String? symKey, { int? type, @@ -367,7 +380,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { #senderPublicKey: senderPublicKey, }, ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #encrypt, @@ -382,10 +395,10 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { }, ), )), - ) as _i21.Future); + ) as _i22.Future); @override - _i21.Future decrypt( + _i22.Future decrypt( String? symKey, String? encoded, ) => @@ -397,7 +410,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { encoded, ], ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #decrypt, @@ -407,14 +420,14 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ], ), )), - ) as _i21.Future); + ) as _i22.Future); @override String serialize( int? type, - _i19.Uint8List? sealed, - _i19.Uint8List? iv, { - _i19.Uint8List? senderPublicKey, + _i20.Uint8List? sealed, + _i20.Uint8List? iv, { + _i20.Uint8List? senderPublicKey, }) => (super.noSuchMethod( Invocation.method( @@ -426,7 +439,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { ], {#senderPublicKey: senderPublicKey}, ), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.method( #serialize, @@ -519,7 +532,7 @@ class MockCryptoUtils extends _i1.Mock implements _i18.CryptoUtils { /// A class which mocks [Crypto]. /// /// See the documentation for Mockito's code generation for more information. -class MockCrypto extends _i1.Mock implements _i22.Crypto { +class MockCrypto extends _i1.Mock implements _i23.Crypto { MockCrypto() { _i1.throwOnMissingStub(this); } @@ -590,21 +603,21 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { @override String get name => (super.noSuchMethod( Invocation.getter(#name), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#name), ), ) as String); @override - _i21.Future init() => (super.noSuchMethod( + _i22.Future init() => (super.noSuchMethod( Invocation.method( #init, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override bool hasKeys(String? tag) => (super.noSuchMethod( @@ -616,37 +629,37 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { ) as bool); @override - _i21.Future getClientId() => (super.noSuchMethod( + _i22.Future getClientId() => (super.noSuchMethod( Invocation.method( #getClientId, [], ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #getClientId, [], ), )), - ) as _i21.Future); + ) as _i22.Future); @override - _i21.Future generateKeyPair() => (super.noSuchMethod( + _i22.Future generateKeyPair() => (super.noSuchMethod( Invocation.method( #generateKeyPair, [], ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #generateKeyPair, [], ), )), - ) as _i21.Future); + ) as _i22.Future); @override - _i21.Future generateSharedKey( + _i22.Future generateSharedKey( String? selfPublicKey, String? peerPublicKey, { String? overrideTopic, @@ -660,7 +673,7 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { ], {#overrideTopic: overrideTopic}, ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #generateSharedKey, @@ -671,10 +684,10 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { {#overrideTopic: overrideTopic}, ), )), - ) as _i21.Future); + ) as _i22.Future); @override - _i21.Future setSymKey( + _i22.Future setSymKey( String? symKey, { String? overrideTopic, }) => @@ -684,7 +697,7 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { [symKey], {#overrideTopic: overrideTopic}, ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #setSymKey, @@ -692,30 +705,30 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { {#overrideTopic: overrideTopic}, ), )), - ) as _i21.Future); + ) as _i22.Future); @override - _i21.Future deleteKeyPair(String? publicKey) => (super.noSuchMethod( + _i22.Future deleteKeyPair(String? publicKey) => (super.noSuchMethod( Invocation.method( #deleteKeyPair, [publicKey], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future deleteSymKey(String? topic) => (super.noSuchMethod( + _i22.Future deleteSymKey(String? topic) => (super.noSuchMethod( Invocation.method( #deleteSymKey, [topic], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future encode( + _i22.Future encode( String? topic, Map? payload, { _i2.EncodeOptions? options, @@ -729,11 +742,11 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { ], {#options: options}, ), - returnValue: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future decode( + _i22.Future decode( String? topic, String? encoded, { _i2.DecodeOptions? options, @@ -747,23 +760,23 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { ], {#options: options}, ), - returnValue: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future signJWT(String? aud) => (super.noSuchMethod( + _i22.Future signJWT(String? aud) => (super.noSuchMethod( Invocation.method( #signJWT, [aud], ), - returnValue: _i21.Future.value(_i20.dummyValue( + returnValue: _i22.Future.value(_i21.dummyValue( this, Invocation.method( #signJWT, [aud], ), )), - ) as _i21.Future); + ) as _i22.Future); @override int getPayloadType(String? encoded) => (super.noSuchMethod( @@ -793,7 +806,7 @@ class MockCrypto extends _i1.Mock implements _i22.Crypto { /// A class which mocks [MessageTracker]. /// /// See the documentation for Mockito's code generation for more information. -class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { +class MockMessageTracker extends _i1.Mock implements _i24.MessageTracker { MockMessageTracker() { _i1.throwOnMissingStub(this); } @@ -801,7 +814,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { @override String get context => (super.noSuchMethod( Invocation.getter(#context), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#context), ), @@ -810,7 +823,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { @override String get version => (super.noSuchMethod( Invocation.getter(#version), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#version), ), @@ -826,43 +839,43 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { ) as _i7.IStore); @override - _i8.Event<_i24.StoreCreateEvent>> get onCreate => + _i8.Event<_i25.StoreCreateEvent>> get onCreate => (super.noSuchMethod( Invocation.getter(#onCreate), - returnValue: _FakeEvent_8<_i24.StoreCreateEvent>>( + returnValue: _FakeEvent_8<_i25.StoreCreateEvent>>( this, Invocation.getter(#onCreate), ), - ) as _i8.Event<_i24.StoreCreateEvent>>); + ) as _i8.Event<_i25.StoreCreateEvent>>); @override - _i8.Event<_i24.StoreUpdateEvent>> get onUpdate => + _i8.Event<_i25.StoreUpdateEvent>> get onUpdate => (super.noSuchMethod( Invocation.getter(#onUpdate), - returnValue: _FakeEvent_8<_i24.StoreUpdateEvent>>( + returnValue: _FakeEvent_8<_i25.StoreUpdateEvent>>( this, Invocation.getter(#onUpdate), ), - ) as _i8.Event<_i24.StoreUpdateEvent>>); + ) as _i8.Event<_i25.StoreUpdateEvent>>); @override - _i8.Event<_i24.StoreDeleteEvent>> get onDelete => + _i8.Event<_i25.StoreDeleteEvent>> get onDelete => (super.noSuchMethod( Invocation.getter(#onDelete), - returnValue: _FakeEvent_8<_i24.StoreDeleteEvent>>( + returnValue: _FakeEvent_8<_i25.StoreDeleteEvent>>( this, Invocation.getter(#onDelete), ), - ) as _i8.Event<_i24.StoreDeleteEvent>>); + ) as _i8.Event<_i25.StoreDeleteEvent>>); @override - _i8.Event<_i24.StoreSyncEvent> get onSync => (super.noSuchMethod( + _i8.Event<_i25.StoreSyncEvent> get onSync => (super.noSuchMethod( Invocation.getter(#onSync), - returnValue: _FakeEvent_8<_i24.StoreSyncEvent>( + returnValue: _FakeEvent_8<_i25.StoreSyncEvent>( this, Invocation.getter(#onSync), ), - ) as _i8.Event<_i24.StoreSyncEvent>); + ) as _i8.Event<_i25.StoreSyncEvent>); @override Map> get data => (super.noSuchMethod( @@ -888,7 +901,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { @override String get storageKey => (super.noSuchMethod( Invocation.getter(#storageKey), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#storageKey), ), @@ -900,7 +913,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { #hashMessage, [message], ), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.method( #hashMessage, @@ -910,7 +923,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { ) as String); @override - _i21.Future recordMessageEvent( + _i22.Future recordMessageEvent( String? topic, String? message, ) => @@ -922,9 +935,9 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { message, ], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override bool messageIsRecorded( @@ -943,14 +956,14 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { ) as bool); @override - _i21.Future init() => (super.noSuchMethod( + _i22.Future init() => (super.noSuchMethod( Invocation.method( #init, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override bool has(String? key) => (super.noSuchMethod( @@ -978,7 +991,7 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { ) as List>); @override - _i21.Future set( + _i22.Future set( String? key, Map? value, ) => @@ -990,39 +1003,39 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { value, ], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future delete(String? key) => (super.noSuchMethod( + _i22.Future delete(String? key) => (super.noSuchMethod( Invocation.method( #delete, [key], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future persist() => (super.noSuchMethod( + _i22.Future persist() => (super.noSuchMethod( Invocation.method( #persist, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future restore() => (super.noSuchMethod( + _i22.Future restore() => (super.noSuchMethod( Invocation.method( #restore, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override void checkInitialized() => super.noSuchMethod( @@ -1037,13 +1050,13 @@ class MockMessageTracker extends _i1.Mock implements _i23.MessageTracker { /// A class which mocks [HttpWrapper]. /// /// See the documentation for Mockito's code generation for more information. -class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { +class MockHttpWrapper extends _i1.Mock implements _i26.HttpWrapper { MockHttpWrapper() { _i1.throwOnMissingStub(this); } @override - _i21.Future<_i9.Response> get( + _i22.Future<_i9.Response> get( Uri? url, { Map? headers, }) => @@ -1053,7 +1066,7 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { [url], {#headers: headers}, ), - returnValue: _i21.Future<_i9.Response>.value(_FakeResponse_9( + returnValue: _i22.Future<_i9.Response>.value(_FakeResponse_9( this, Invocation.method( #get, @@ -1061,10 +1074,10 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { {#headers: headers}, ), )), - ) as _i21.Future<_i9.Response>); + ) as _i22.Future<_i9.Response>); @override - _i21.Future<_i9.Response> delete( + _i22.Future<_i9.Response> delete( Uri? url, { Map? headers, }) => @@ -1074,7 +1087,7 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { [url], {#headers: headers}, ), - returnValue: _i21.Future<_i9.Response>.value(_FakeResponse_9( + returnValue: _i22.Future<_i9.Response>.value(_FakeResponse_9( this, Invocation.method( #delete, @@ -1082,10 +1095,10 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { {#headers: headers}, ), )), - ) as _i21.Future<_i9.Response>); + ) as _i22.Future<_i9.Response>); @override - _i21.Future<_i9.Response> post( + _i22.Future<_i9.Response> post( Uri? url, { Map? headers, Object? body, @@ -1099,7 +1112,7 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { #body: body, }, ), - returnValue: _i21.Future<_i9.Response>.value(_FakeResponse_9( + returnValue: _i22.Future<_i9.Response>.value(_FakeResponse_9( this, Invocation.method( #post, @@ -1110,13 +1123,13 @@ class MockHttpWrapper extends _i1.Mock implements _i25.HttpWrapper { }, ), )), - ) as _i21.Future<_i9.Response>); + ) as _i22.Future<_i9.Response>); } /// A class which mocks [Core]. /// /// See the documentation for Mockito's code generation for more information. -class MockCore extends _i1.Mock implements _i26.Core { +class MockCore extends _i1.Mock implements _i27.Core { MockCore() { _i1.throwOnMissingStub(this); } @@ -1124,7 +1137,7 @@ class MockCore extends _i1.Mock implements _i26.Core { @override String get projectId => (super.noSuchMethod( Invocation.getter(#projectId), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#projectId), ), @@ -1133,7 +1146,7 @@ class MockCore extends _i1.Mock implements _i26.Core { @override String get relayUrl => (super.noSuchMethod( Invocation.getter(#relayUrl), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#relayUrl), ), @@ -1151,7 +1164,7 @@ class MockCore extends _i1.Mock implements _i26.Core { @override String get pushUrl => (super.noSuchMethod( Invocation.getter(#pushUrl), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#pushUrl), ), @@ -1292,6 +1305,24 @@ class MockCore extends _i1.Mock implements _i26.Core { returnValueForMissingStub: null, ); + @override + _i17.IConnectivity get connectivity => (super.noSuchMethod( + Invocation.getter(#connectivity), + returnValue: _FakeIConnectivity_17( + this, + Invocation.getter(#connectivity), + ), + ) as _i17.IConnectivity); + + @override + set connectivity(_i17.IConnectivity? _connectivity) => super.noSuchMethod( + Invocation.setter( + #connectivity, + _connectivity, + ), + returnValueForMissingStub: null, + ); + @override _i7.IStore> get storage => (super.noSuchMethod( Invocation.getter(#storage), @@ -1313,7 +1344,7 @@ class MockCore extends _i1.Mock implements _i26.Core { @override String get protocol => (super.noSuchMethod( Invocation.getter(#protocol), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#protocol), ), @@ -1322,23 +1353,23 @@ class MockCore extends _i1.Mock implements _i26.Core { @override String get version => (super.noSuchMethod( Invocation.getter(#version), - returnValue: _i20.dummyValue( + returnValue: _i21.dummyValue( this, Invocation.getter(#version), ), ) as String); @override - _i17.Logger get logger => (super.noSuchMethod( + _i18.Logger get logger => (super.noSuchMethod( Invocation.getter(#logger), - returnValue: _FakeLogger_17( + returnValue: _FakeLogger_18( this, Invocation.getter(#logger), ), - ) as _i17.Logger); + ) as _i18.Logger); @override - void addLogListener(_i17.LogCallback? callback) => super.noSuchMethod( + void addLogListener(_i18.LogCallback? callback) => super.noSuchMethod( Invocation.method( #addLogListener, [callback], @@ -1347,7 +1378,7 @@ class MockCore extends _i1.Mock implements _i26.Core { ); @override - bool removeLogListener(_i17.LogCallback? callback) => (super.noSuchMethod( + bool removeLogListener(_i18.LogCallback? callback) => (super.noSuchMethod( Invocation.method( #removeLogListener, [callback], @@ -1356,58 +1387,58 @@ class MockCore extends _i1.Mock implements _i26.Core { ) as bool); @override - _i21.Future start() => (super.noSuchMethod( + _i22.Future start() => (super.noSuchMethod( Invocation.method( #start, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); } /// A class which mocks [WebSocketHandler]. /// /// See the documentation for Mockito's code generation for more information. -class MockWebSocketHandler extends _i1.Mock implements _i27.WebSocketHandler { +class MockWebSocketHandler extends _i1.Mock implements _i28.WebSocketHandler { MockWebSocketHandler() { _i1.throwOnMissingStub(this); } @override - _i21.Future get ready => (super.noSuchMethod( + _i22.Future get ready => (super.noSuchMethod( Invocation.getter(#ready), - returnValue: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future setup({required String? url}) => (super.noSuchMethod( + _i22.Future setup({required String? url}) => (super.noSuchMethod( Invocation.method( #setup, [], {#url: url}, ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future connect() => (super.noSuchMethod( + _i22.Future connect() => (super.noSuchMethod( Invocation.method( #connect, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); @override - _i21.Future close() => (super.noSuchMethod( + _i22.Future close() => (super.noSuchMethod( Invocation.method( #close, [], ), - returnValue: _i21.Future.value(), - returnValueForMissingStub: _i21.Future.value(), - ) as _i21.Future); + returnValue: _i22.Future.value(), + returnValueForMissingStub: _i22.Future.value(), + ) as _i22.Future); } diff --git a/test/sign_api/sign_client_test.dart b/test/sign_api/sign_client_test.dart index ced4babc..aebe1fb5 100644 --- a/test/sign_api/sign_client_test.dart +++ b/test/sign_api/sign_client_test.dart @@ -1,7 +1,4 @@ -@Timeout(Duration(seconds: 45)) - import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_utils.dart'; @@ -11,13 +8,8 @@ import 'utils/sign_client_test_wrapper.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); signEngineTests( context: 'SignClient', diff --git a/test/sign_api/sign_engine_test.dart b/test/sign_api/sign_engine_test.dart index d6b4b433..b30f6d5e 100644 --- a/test/sign_api/sign_engine_test.dart +++ b/test/sign_api/sign_engine_test.dart @@ -1,5 +1,4 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; @@ -10,13 +9,8 @@ import 'tests/sign_common.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); signEngineTests( context: 'SignEngine', diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index cc8074ef..a83d5812 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -224,7 +224,7 @@ class SignClientTestWrapper implements ISignEngine { required String functionName, required String rpcUrl, EthereumAddress? sender, - List parameters = const [], + List parameters = const [], }) async { try { return await client.requestReadContract( @@ -243,18 +243,16 @@ class SignClientTestWrapper implements ISignEngine { Future requestWriteContract({ required String topic, required String chainId, - required String rpcUrl, required DeployedContract deployedContract, required String functionName, required Transaction transaction, String? method, - List parameters = const [], + List parameters = const [], }) async { try { return await client.requestWriteContract( topic: topic, chainId: chainId, - rpcUrl: rpcUrl, deployedContract: deployedContract, functionName: functionName, transaction: transaction, diff --git a/test/sign_api/web3wallet_sign_test.dart b/test/sign_api/web3wallet_sign_test.dart index 04f689b3..770bc7df 100644 --- a/test/sign_api/web3wallet_sign_test.dart +++ b/test/sign_api/web3wallet_sign_test.dart @@ -1,5 +1,4 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_utils.dart'; @@ -8,13 +7,8 @@ import 'tests/sign_common.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); signEngineTests( context: 'Web3App/Wallet', diff --git a/test/web3wallet/web3wallet_test.dart b/test/web3wallet/web3wallet_test.dart index 7893abfc..8c3e849d 100644 --- a/test/web3wallet/web3wallet_test.dart +++ b/test/web3wallet/web3wallet_test.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_utils.dart'; @@ -10,13 +9,9 @@ import 'web3wallet_helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - PackageInfo.setMockInitialValues( - appName: 'walletconnect_flutter_v2', - packageName: 'com.walletconnect.flutterdapp', - version: '1.0', - buildNumber: '2', - buildSignature: 'buildSignature', - ); + mockPackageInfo(); + mockConnectivity(); + final List Function(PairingMetadata)> appCreators = [ (PairingMetadata metadata) async => await Web3App.createInstance( projectId: TEST_PROJECT_ID,