diff --git a/android/build.gradle b/android/build.gradle index 7e18622..ab87e1d 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -51,6 +51,6 @@ android { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' - implementation 'com.github.Web3Auth:web3auth-android-sdk:9.1.3' + implementation 'com.github.Web3Auth:web3auth-android-sdk:10.0.0' implementation 'com.google.code.gson:gson:2.10.1' } diff --git a/android/src/main/kotlin/com/web3auth/flutter/web3auth_flutter/Web3AuthFlutterPlugin.kt b/android/src/main/kotlin/com/web3auth/flutter/web3auth_flutter/Web3AuthFlutterPlugin.kt index 4efb1a0..e0a18b4 100644 --- a/android/src/main/kotlin/com/web3auth/flutter/web3auth_flutter/Web3AuthFlutterPlugin.kt +++ b/android/src/main/kotlin/com/web3auth/flutter/web3auth_flutter/Web3AuthFlutterPlugin.kt @@ -3,7 +3,6 @@ package com.web3auth.flutter.web3auth_flutter import android.app.Activity import android.content.Context import android.content.Intent -import android.net.Uri import android.util.Log import androidx.annotation.Keep import androidx.annotation.NonNull @@ -12,7 +11,6 @@ import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.web3auth.core.Web3Auth -import com.web3auth.core.types.ChainConfig import com.web3auth.core.types.ErrorCode import com.web3auth.core.types.LoginParams import com.web3auth.core.types.Web3AuthError @@ -99,7 +97,8 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, val initParams = gson.fromJson(initArgs, Web3AuthOptions::class.java) // handle custom parameters which are gson excluded val obj = JSONObject(initArgs) - if (obj.has("redirectUrl")) initParams.redirectUrl = Uri.parse(obj.get("redirectUrl") as String?) + if (obj.has("redirectUrl")) initParams.redirectUrl = + obj.get("redirectUrl").toString() // Log.d(initParams.toString(), "#initParams") web3auth = Web3Auth( initParams, activity!! @@ -111,14 +110,13 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, return null } - "login" -> { + "connectTo" -> { try { val loginArgs = call.arguments() ?: return null val loginParams = gson.fromJson(loginArgs, LoginParams::class.java) val obj = JSONObject(loginArgs) - if (obj.has("redirectUrl")) loginParams.redirectUrl = Uri.parse(obj.get("redirectUrl") as String?) - val loginCF = web3auth.login(loginParams) - // Log.d(loginParams.toString(), "#loginParams") + //Log.d("#loginParams", loginParams.toString()) + val loginCF = web3auth.connectTo(loginParams) Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#login") val loginResult: Web3AuthResponse = loginCF.get() return gson.toJson(loginResult) @@ -151,15 +149,15 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, } } - "getPrivKey" -> { - val privKey = web3auth.getPrivkey() - Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#getPrivKey") + "getPrivateKey" -> { + val privKey = web3auth.getPrivateKey() + Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#getPrivateKey") return privKey } - "getEd25519PrivKey" -> { - val ed25519Key = web3auth.getEd25519PrivKey() - Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#getEd25519PrivKey") + "getEd25519PrivateKey" -> { + val ed25519Key = web3auth.getEd25519PrivateKey() + Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#getEd25519PrivateKey") return ed25519Key } @@ -189,14 +187,13 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, } } - "launchWalletServices" -> { + "showWalletUI" -> { try { - Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#launchWalletServices") + Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#showWalletUI") val wsArgs = call.arguments() ?: return null val wsParams = gson.fromJson(wsArgs, WalletServicesJson::class.java) Log.d(wsParams.toString(), "#wsParams") - val launchWalletCF = web3auth.launchWalletServices( - wsParams.chainConfig, + val launchWalletCF = web3auth.showWalletUI( wsParams.path ) launchWalletCF.get() @@ -213,8 +210,6 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, val loginArgs = call.arguments() ?: return null val loginParams = gson.fromJson(loginArgs, LoginParams::class.java) val obj = JSONObject(loginArgs) - if (obj.has("redirectUrl")) loginParams.redirectUrl = - Uri.parse(obj.get("redirectUrl") as String?) val setupMfaCF = web3auth.enableMFA(loginParams) Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#enableMFA") return setupMfaCF.get() @@ -241,12 +236,11 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, "request" -> { try { - Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#signMessage") + Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#request") val requestArgs = call.arguments() ?: return null val reqParams = gson.fromJson(requestArgs, RequestJson::class.java) Log.d(reqParams.toString(), "#reqParams") val requestCF = web3auth.request( - reqParams.chainConfig, reqParams.method, convertListToJsonArray(reqParams.requestParams) , reqParams.path, @@ -265,8 +259,6 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, val loginArgs = call.arguments() ?: return null val loginParams = gson.fromJson(loginArgs, LoginParams::class.java) val obj = JSONObject(loginArgs) - if (obj.has("redirectUrl")) loginParams.redirectUrl = - Uri.parse(obj.get("redirectUrl") as String?) val setupMfaCF = web3auth.manageMFA(loginParams) Log.d("${Web3AuthFlutterPlugin::class.qualifiedName}", "#enableMFA") return setupMfaCF.get() @@ -301,13 +293,11 @@ class Web3AuthFlutterPlugin : FlutterPlugin, ActivityAware, MethodCallHandler, } @Keep data class WalletServicesJson( - @Keep val chainConfig: ChainConfig, @Keep val path: String? = "wallet" ) @Keep data class RequestJson( - @Keep val chainConfig: ChainConfig, @Keep val method: String, @Keep val requestParams: List, @Keep val path: String? = "wallet/request", diff --git a/example/lib/main.dart b/example/lib/main.dart index deeebed..55f2db0 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -8,6 +8,7 @@ import 'package:web3auth_flutter/enums.dart'; import 'package:web3auth_flutter/input.dart'; import 'package:web3auth_flutter/output.dart'; import 'package:web3auth_flutter/web3auth_flutter.dart'; +import 'package:web3auth_flutter_example/utils.dart'; import 'package:web3dart/web3dart.dart'; void main() { @@ -53,39 +54,35 @@ class _MyAppState extends State with WidgetsBindingObserver { HashMap themeMap = HashMap(); themeMap['primary'] = "#229954"; - Uri redirectUrl; + String redirectUrl; if (Platform.isAndroid) { - redirectUrl = Uri.parse('torusapp://org.torusresearch.flutter.web3authexample'); + redirectUrl = 'torusapp://org.torusresearch.flutter.web3authexample'; } else if (Platform.isIOS) { - redirectUrl = - Uri.parse('com.web3auth.flutter.web3authflutterexample://auth'); + redirectUrl = 'com.web3auth.flutter.web3authflutterexample://auth'; } else { throw UnKnownException('Unknown platform'); } - final loginConfig = HashMap(); - loginConfig['jwt'] = LoginConfigItem( - verifier: "w3a-auth0-demo", // get it from web3auth dashboard - typeOfLogin: TypeOfLogin.jwt, - clientId: "hUVVf4SEsZT7syOiL0gLU9hFEtm2gQ6O" // auth0 client id - ); + final List authConnectionConfig = [ + AuthConnectionConfig( + authConnectionId: "web3auth-auth0-email-passwordless-sapphire-devnet", + authConnection: AuthConnection.custom, + clientId: "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C", + ) + ]; await Web3AuthFlutter.init( Web3AuthOptions( clientId: - 'BHgArYmWwSeq21czpcarYh0EVq2WWOzflX-NTK-tY1-1pauPzHKRRLgpABkmYiIV_og9jAvoIxQ8L3Smrwe04Lw', + 'BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ', //sdkUrl: 'https://auth.mocaverse.xyz', //walletSdkUrl: 'https://lrc-mocaverse.web3auth.io', - network: Network.sapphire_devnet, - buildEnv: BuildEnv.production, + web3AuthNetwork: Web3AuthNetwork.sapphire_mainnet, + authBuildEnv: BuildEnv.testing, redirectUrl: redirectUrl, - whiteLabel: WhiteLabelData( - mode: ThemeModes.dark, - defaultLanguage: Language.en, - appName: "Web3Auth Flutter App", - theme: themeMap, - ), - loginConfig: loginConfig, + authConnectionConfig: authConnectionConfig, + defaultChainId: "0x1", + isFlutterAnalytics: true, ), ); @@ -95,7 +92,7 @@ class _MyAppState extends State with WidgetsBindingObserver { print('Error during Web3Auth initialization: $e'); } - final String res = await Web3AuthFlutter.getPrivKey(); + final String res = await Web3AuthFlutter.getPrivateKey(); log(res); if (res.isNotEmpty) { setState(() { @@ -186,6 +183,10 @@ class _MyAppState extends State with WidgetsBindingObserver { onPressed: _login(_withDiscord), child: const Text('Discord'), ), + ElevatedButton( + onPressed: _login(sfaSignIn), + child: const Text('SFA SignIn'), + ), ], ), ), @@ -213,8 +214,8 @@ class _MyAppState extends State with WidgetsBindingObserver { child: const Text('Launch Wallet Services'), ), ElevatedButton( - onPressed: _setupMFA(), - child: const Text('Setup MFA'), + onPressed: _enableMFA(), + child: const Text('Enable MFA'), ), ElevatedButton( onPressed: _manageMFA(), @@ -267,7 +268,7 @@ class _MyAppState extends State with WidgetsBindingObserver { logoutVisible = false; }); } on UserCancelledException { - log("User cancelled."); + log("User cancelled"); } on UnKnownException { log("Unknown exception occurred"); } @@ -277,7 +278,7 @@ class _MyAppState extends State with WidgetsBindingObserver { VoidCallback _privKey(Future Function() method) { return () async { try { - final String response = await Web3AuthFlutter.getPrivKey(); + final String response = await Web3AuthFlutter.getPrivateKey(); setState(() { _result = response; logoutVisible = true; @@ -290,10 +291,10 @@ class _MyAppState extends State with WidgetsBindingObserver { }; } - VoidCallback _userInfo(Future Function() method) { + VoidCallback _userInfo(Future Function() method) { return () async { try { - final TorusUserInfo response = await Web3AuthFlutter.getUserInfo(); + final UserInfo response = await Web3AuthFlutter.getUserInfo(); setState(() { _result = response.toString(); logoutVisible = true; @@ -307,19 +308,24 @@ class _MyAppState extends State with WidgetsBindingObserver { } Future _withGoogle() { - return Web3AuthFlutter.login( - LoginParams(loginProvider: Provider.google, mfaLevel: MFALevel.NONE), + return Web3AuthFlutter.connectTo( + LoginParams( + authConnection: AuthConnection.google, + authConnectionId: "w3ads", + groupedAuthConnectionId: "aggregate-mobile", + mfaLevel: MFALevel.NONE), ); } Future _withFacebook() { - return Web3AuthFlutter.login(LoginParams(loginProvider: Provider.facebook)); + return Web3AuthFlutter.connectTo( + LoginParams(authConnection: AuthConnection.facebook)); } Future _withEmailPasswordless() { - return Web3AuthFlutter.login( + return Web3AuthFlutter.connectTo( LoginParams( - loginProvider: Provider.email_passwordless, + authConnection: AuthConnection.email_passwordless, extraLoginOptions: ExtraLoginOptions( login_hint: textEditingController.text, ), @@ -328,27 +334,30 @@ class _MyAppState extends State with WidgetsBindingObserver { } Future _withDiscord() { - return Web3AuthFlutter.login(LoginParams(loginProvider: Provider.discord)); + return Web3AuthFlutter.connectTo( + LoginParams(authConnection: AuthConnection.discord)); + } + + Future sfaSignIn() { + return Web3AuthFlutter.connectTo( + LoginParams(authConnection: AuthConnection.google, + authConnectionId: "torus-test-health", + idToken: Utils().es256Token("devnettestuser@tor.us"), + groupedAuthConnectionId: "torus-aggregate-sapphire-mainnet")); } Future _getPrivKey() { - return Web3AuthFlutter.getPrivKey(); + return Web3AuthFlutter.getPrivateKey(); } - Future _getUserInfo() { + Future _getUserInfo() { return Web3AuthFlutter.getUserInfo(); } VoidCallback _launchWalletServices() { return () async { try { - await Web3AuthFlutter.launchWalletServices( - ChainConfig( - chainId: "0x89", - rpcTarget: - "https://mainnet.infura.io/v3/daeee53504be4cd3a997d4f2718d33e0", - ), - ); + await Web3AuthFlutter.showWalletUI(); } on UserCancelledException { log("User cancelled."); } on UnKnownException { @@ -357,7 +366,7 @@ class _MyAppState extends State with WidgetsBindingObserver { }; } - VoidCallback _setupMFA() { + VoidCallback _enableMFA() { return () async { try { await Web3AuthFlutter.enableMFA(); @@ -397,7 +406,6 @@ class _MyAppState extends State with WidgetsBindingObserver { params.add(address.hexEip55); params.add("Web3Auth"); final signResponse = await Web3AuthFlutter.request( - ChainConfig(chainId: "0x89", rpcTarget: "https://polygon-rpc.com/"), "personal_sign", params, appState: "web3auth", diff --git a/example/lib/utils.dart b/example/lib/utils.dart new file mode 100644 index 0000000..f97e321 --- /dev/null +++ b/example/lib/utils.dart @@ -0,0 +1,32 @@ +import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; + +class Utils { + String es256Token(String email) { + String token; + + /* Sign */ { + // Create a json web token + final jwt = JWT({ + "sub": "email|hello", + "aud": "torus-key-test", + "exp": DateTime.now().millisecond, + "iat": DateTime.now().millisecond, + "iss": "torus-key-test", + "email": email, + "nickname": email.split("@")[0], + "name": email, + "picture": "", + "email_verified": true + }); + + // Sign it + final key = ECPrivateKey("-----BEGIN PRIVATE KEY-----\n" + "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCD7oLrcKae+jVZPGx52Cb/lKhdKxpXjl9eGNa1MlY57A==" + "\n-----END PRIVATE KEY-----"); + token = jwt.sign(key, algorithm: JWTAlgorithm.ES256); + + print('Signed token: \n $token\n'); + return token; + } + } +} diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 2ac596b..7e36217 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -30,6 +30,7 @@ dependencies: # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 web3dart: ^2.7.3 + dart_jsonwebtoken: ^2.7.1 dev_dependencies: flutter_test: diff --git a/ios/Classes/SwiftWeb3AuthFlutterPlugin.swift b/ios/Classes/SwiftWeb3AuthFlutterPlugin.swift index 74da053..9c10bcd 100644 --- a/ios/Classes/SwiftWeb3AuthFlutterPlugin.swift +++ b/ios/Classes/SwiftWeb3AuthFlutterPlugin.swift @@ -1,6 +1,7 @@ import Flutter import UIKit import Web3Auth +import FetchNodeDetails public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { @@ -9,9 +10,28 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { registrar.addMethodCallDelegate(instance, channel: channel) } + private func getNetwork(_ network: String) -> Web3AuthNetwork { + switch network { + case "mainnet": + return .MAINNET + case "testnet": + return .TESTNET + case "aqua": + return .AQUA + case "cyan": + return .CYAN + case "sapphire_devnet": + return .SAPPHIRE_DEVNET + case "sapphire_mainnet": + return .SAPPHIRE_MAINNET + default: + return .SAPPHIRE_MAINNET + } + } + var web3auth: Web3Auth? - public var state: Web3AuthState? { - return web3auth?.state + public var web3AuthResponse: Web3AuthResponse? { + return web3auth?.web3AuthResponse } var decoder = JSONDecoder() var encoder = JSONEncoder() @@ -36,10 +56,37 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { // print("call data", data) switch call.method { case "init": - let initParams: W3AInitParams + var options: Web3AuthOptions + //print("RAW INIT DATA:", String(data: data, encoding: .utf8) ?? "Invalid UTF8") do { - initParams = try decoder.decode(W3AInitParams.self, from: data) - // print(initParams, "params") + let params = try decoder.decode(InitParams.self, from: data) + let network = getNetwork(params.network) + let buildEnv: BuildEnv = BuildEnv(rawValue: params.authBuildEnv ?? "production") ?? .production + options = Web3AuthOptions( + clientId: params.clientId, + redirectUrl: params.redirectUrl, + originData: params.originData, + authBuildEnv: buildEnv, + sdkUrl: params.sdkUrl, + storageServerUrl: params.storageServerUrl, + sessionSocketUrl: params.sessionSocketUrl, + authConnectionConfig: params.authConnectionConfig, + whiteLabel: params.whiteLabel, + dashboardUrl: params.dashboardUrl, + accountAbstractionConfig: params.accountAbstractionConfig, + walletSdkUrl: params.walletSdkUrl, + includeUserDataInToken: params.includeUserDataInToken ?? true, + chains: params.chains, + defaultChainId: params.defaultChainId ?? "0x1", + enableLogging: params.enableLogging ?? false, + sessionTime: params.sessionTime ?? 30 * 86400, + web3AuthNetwork: network, + useSFAKey: params.useSFAKey ?? false, + walletServicesConfig: params.walletServicesConfig, + mfaSettings: params.mfaSettings + ) + + options.setFlutterAnalytics(params.isFlutterAnalytics ?? true, sdkVersion: params.sdkVersion) } catch { // print(error) result(FlutterError( @@ -49,7 +96,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { return } do { - let web3auth = try await Web3Auth(initParams) + let web3auth = try await Web3Auth(options: options) self.web3auth = web3auth result(nil) return @@ -60,7 +107,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { details: error.localizedDescription)) return } - case "login": + case "connectTo": guard let web3auth = web3auth else { result(FlutterError( @@ -69,12 +116,12 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { details: nil)) return } - let loginParams: W3ALoginParams + let loginParams: LoginParams do { - loginParams = try decoder.decode(W3ALoginParams.self, from: data) - //print("loginParams: \(loginParams)") + loginParams = try decoder.decode(LoginParams.self, from: data) + print("loginParams: \(loginParams)") } catch { - //print(error) + print(error) result(FlutterError( code: "INVALID_ARGUMENTS", message: "Invalid Login Params", @@ -83,7 +130,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { } var resultMap: String = "" do { - let result = try await web3auth.login(loginParams) + let result = try await web3auth.connectTo(loginParams: loginParams) let resultData = try encoder.encode(result) resultMap = String(decoding: resultData, as: UTF8.self) } catch { @@ -113,19 +160,18 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { // There is no initialize function in swift result(nil) return - case "getPrivKey": - let privKey = web3auth?.getPrivkey() + case "getPrivateKey": + let privKey = web3auth?.getPrivateKey() result(privKey) return - case "getEd25519PrivKey": - let getEd25519PrivKey = web3auth?.getEd25519PrivKey() + case "getEd25519PrivateKey": + let getEd25519PrivKey = try? web3auth?.getEd25519PrivateKey() result(getEd25519PrivKey) return - case "launchWalletServices": + case "showWalletUI": let wsParams: WalletServicesParams do { wsParams = try decoder.decode(WalletServicesParams.self, from: data) - print("chainConfig: \(wsParams.chainConfig)") } catch { result(FlutterError( code: "INVALID_ARGUMENTS", @@ -135,7 +181,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { } do { - try await web3auth?.launchWalletServices(chainConfig: wsParams.chainConfig, path: wsParams.path) + try await web3auth?.showWalletUI(path: wsParams.path) result(nil) return } catch { @@ -147,7 +193,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { } case "enableMFA": do { - let loginParams = try? decoder.decode(W3ALoginParams.self, from: data) + let loginParams = try? decoder.decode(LoginParams.self, from: data) if let params = loginParams { let enableMFAResult = try await web3auth?.enableMFA(params) @@ -166,7 +212,7 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { } case "manageMFA": do { - let loginParams = try? decoder.decode(W3ALoginParams.self, from: data) + let loginParams = try? decoder.decode(LoginParams.self, from: data) if let params = loginParams { let manageMFAResult = try await web3auth?.manageMFA(params) @@ -197,7 +243,6 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { do { let signResponse = try await web3auth?.request( - chainConfig: reqParams.chainConfig, method: reqParams.method, requestParams: reqParams.requestParams, path: reqParams.path, @@ -256,14 +301,39 @@ public class SwiftWeb3AuthFlutterPlugin: NSObject, FlutterPlugin { } struct WalletServicesParams: Codable { - let chainConfig: ChainConfig let path: String? } struct RequestJson: Codable { - let chainConfig: ChainConfig let method: String let requestParams: [String] let path: String? let appState: String? } + +struct InitParams: Codable { + let clientId: String + let redirectUrl: String + let originData: [String: String]? + let authBuildEnv: String? + let sdkUrl: String? + let storageServerUrl: String? + let sessionSocketUrl: String? + let authConnectionConfig: [AuthConnectionConfig]? + let whiteLabel: WhiteLabelData? + let dashboardUrl: String? + let accountAbstractionConfig: String? + let walletSdkUrl: String? + let sessionNamespace: String? + let includeUserDataInToken: Bool? + let chains: [Chains]? + let defaultChainId: String? + let enableLogging: Bool? + let sessionTime: Int? + let network: String + let useSFAKey: Bool? + let walletServicesConfig: WalletServicesConfig? + let mfaSettings: MfaSettings? + let isFlutterAnalytics: Bool? + let sdkVersion: String? +} diff --git a/ios/web3auth_flutter.podspec b/ios/web3auth_flutter.podspec index e83606b..b1f59c8 100644 --- a/ios/web3auth_flutter.podspec +++ b/ios/web3auth_flutter.podspec @@ -15,7 +15,7 @@ Flutter SDK for Torus Web3Auth (OpenLogin) s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'Web3Auth', '~> 11.1.0' + s.dependency 'Web3Auth', '~> 12.0.0' s.platform = :ios, '14.0' # Flutter.framework does not contain a i386 slice. diff --git a/lib/enums.dart b/lib/enums.dart index aa7086c..dc244be 100644 --- a/lib/enums.dart +++ b/lib/enums.dart @@ -1,4 +1,4 @@ -enum Network { mainnet, testnet, cyan, aqua, sapphire_devnet, sapphire_mainnet } +enum Web3AuthNetwork { mainnet, testnet, cyan, aqua, sapphire_devnet, sapphire_mainnet } enum BuildEnv { production, staging, testing } @@ -8,25 +8,7 @@ enum Language { en, de, ja, ko, zh, es, fr, pt, nl , tr} enum ThemeModes { light, dark, auto } -enum Provider { - google, - facebook, - reddit, - discord, - twitch, - github, - apple, - linkedin, - twitter, - line, - kakao, - email_passwordless, - jwt, - sms_passwordless, - farcaster, -} - -enum TypeOfLogin { +enum AuthConnection { google, facebook, reddit, @@ -42,11 +24,16 @@ enum TypeOfLogin { line, email_passwordless, email_password, - jwt, + custom, sms_passwordless, farcaster, } +enum EmailFlowType { + link, + code, +} + enum Display { /// Displays the UI with a full page view. page, @@ -104,3 +91,10 @@ enum Prompt { } enum Curve { secp256k1, ed25519 } + +enum ConfirmationStrategy { + popup, + modal, + autoApprove, + defaultStrategy +} diff --git a/lib/input.dart b/lib/input.dart index 80016c5..6f2572d 100644 --- a/lib/input.dart +++ b/lib/input.dart @@ -1,12 +1,29 @@ import 'dart:collection'; +import 'package:json_annotation/json_annotation.dart'; import 'package:web3auth_flutter/enums.dart'; import 'package:web3auth_flutter/web3auth_flutter.dart'; class LoginParams { - /// [loginProvider] sets the oAuth login method to be used. You can use any of the - /// valid [Provider] from the supported list. - final Provider loginProvider; + /// [authConnection] sets the oAuth login method to be used. You can use any of the + /// valid [AuthConnection] from the supported list. + final AuthConnection authConnection; + + /// The auth connection id to be used for login. + final String? authConnectionId; + + /// The grouped auth connection id to be used for login. + final String? groupedAuthConnectionId; + + final String? appState; + + /// Customize the MFA screen shown to the user during OAuth authentication. + final MFALevel? mfaLevel; + + /// [extraLoginOptions] can be used to set the OAuth login options for corresponding [AuthConnection]. + /// + /// For instance, you'll need to pass user's email address as `login_hint` for [Provider.email_passwordless]. + final ExtraLoginOptions? extraLoginOptions; /// Custom verifier logins can get a dapp share returned to them post successful login. /// This is useful if the dapps want to use this share to allow users to login seamlessly. @@ -22,48 +39,49 @@ class LoginParams { /// The default value is [Curve.secp256k1]. final Curve? curve; - /// [extraLoginOptions] can be used to set the OAuth login options for corresponding [loginProvider]. - /// - /// For instance, you'll need to pass user's email address as `login_hint` for [Provider.email_passwordless]. - final ExtraLoginOptions? extraLoginOptions; - - /// Deeplinking for the application where user will be redirected after login. - final Uri? redirectUrl; - - final String? appState; - - /// Customize the MFA screen shown to the user during OAuth authentication. - final MFALevel? mfaLevel; final String? dappUrl; - LoginParams( - {required this.loginProvider, - this.dappShare, - this.curve = Curve.secp256k1, - this.extraLoginOptions, - this.redirectUrl, - this.appState, - this.mfaLevel, - this.dappUrl}); + String? loginHint; + final String? idToken; + + LoginParams({ + required this.authConnection, + this.authConnectionId, + this.groupedAuthConnectionId, + this.appState, + this.mfaLevel, + this.extraLoginOptions, + this.dappShare, + this.curve = Curve.secp256k1, + this.dappUrl, + this.loginHint, + this.idToken, + }); - Map toJson() => { - "loginProvider": loginProvider.name, - "dappShare": dappShare, - "curve": curve?.name, - "extraLoginOptions": extraLoginOptions?.toJson(), - "redirectUrl": redirectUrl?.toString(), - "appState": appState, - "mfaLevel": mfaLevel?.type, - "dappUrl": dappUrl - }; + Map toJson() { + return { + 'authConnection': authConnection.name, + 'authConnectionId': authConnectionId, + 'groupedAuthConnectionId': groupedAuthConnectionId, + 'appState': appState, + 'mfaLevel': mfaLevel?.type, + 'extraLoginOptions': extraLoginOptions?.toJson(), + 'dappShare': dappShare, + 'curve': curve?.name, + 'dappUrl': dappUrl, + 'loginHint': loginHint, + 'idToken': idToken, + }; + } } -class LoginConfigItem { - /// Custom verifier name given in the developer dashboard. - final String verifier; +class AuthConnectionConfig { /// The type of login for custom verifier. - final TypeOfLogin typeOfLogin; + final AuthConnection authConnection; + + /// Custom verifier name given in the developer dashboard. + final String authConnectionId; /// Client id provided by your login provider used for custom verifier. final String clientId; @@ -74,9 +92,9 @@ class LoginConfigItem { /// Description for the button. If provided, it renders as a full length button. else, icon button. final String? description; - /// The field in JWT token which maps to verifier id. Please make sure you selected - /// correct JWT verifier id in the developer dashboard. - final String? verifierSubIdentifier; + /// The grouped auth connection id. + /// If provided, authConnectionId will become a sub identifier for the groupedAuthConnectionId. + final String? groupedAuthConnectionId; /// Logo to be shown on mouse hover. final String? logoHover; @@ -99,13 +117,15 @@ class LoginConfigItem { /// Whether to show the login button on Mobile. final bool? showOnMobile; - LoginConfigItem({ - required this.verifier, - required this.typeOfLogin, + final ExtraLoginOptions? jwtParameters; + + AuthConnectionConfig({ + required this.authConnection, + required this.authConnectionId, required this.clientId, this.name, this.description, - this.verifierSubIdentifier, + this.groupedAuthConnectionId, this.logoHover, this.logoLight, this.logoDark, @@ -113,23 +133,25 @@ class LoginConfigItem { this.showOnModal, this.showOnDesktop, this.showOnMobile, + this.jwtParameters, }); Map toJson() { return { - 'verifier': verifier, - 'typeOfLogin': typeOfLogin.name, + 'authConnection': authConnection.name, + 'authConnectionId': authConnectionId, 'clientId': clientId, 'name': name, 'description': description, - 'verifierSubIdentifier': verifierSubIdentifier, + 'groupedAuthConnectionId': groupedAuthConnectionId, 'logoHover': logoHover, 'logoLight': logoLight, 'logoDark': logoDark, 'mainOption': mainOption, 'showOnModal': showOnModal, 'showOnDesktop': showOnDesktop, - 'showOnMobile': showOnMobile + 'showOnMobile': showOnMobile, + 'jwtParameters': jwtParameters?.toJson() }; } } @@ -150,10 +172,12 @@ class ExtraLoginOptions { /// The field in JWT token which maps to verifier id. Please make sure you selected /// correct JWT verifier id in the developer dashboard. - final String? verifierIdField; + final String? userIdField; /// Whether the verifier id field is case sensitive or not. - final bool? isVerifierIdCaseSensitive; + final bool? isUserIdCaseSensitive; + + final String? access_token; /// Allows developers the configure the display of UI. Checkout [Display] for more /// details. @@ -176,6 +200,8 @@ class ExtraLoginOptions { final String? id_token; + final EmailFlowType? flow_type; + /// [login_hint] is used to send the user's email address during [Provider.email_passwordless]. final String? login_hint; @@ -209,8 +235,10 @@ class ExtraLoginOptions { this.domain, this.client_id, this.leeway, - this.verifierIdField, - this.isVerifierIdCaseSensitive, + this.userIdField, + this.isUserIdCaseSensitive, + this.access_token, + this.flow_type = EmailFlowType.code, this.display, this.prompt, this.max_age, @@ -233,8 +261,10 @@ class ExtraLoginOptions { "domain": domain, "client_id": client_id, "leeway": leeway, - "verifierIdField": verifierIdField, - "isVerifierIdCaseSensitive": isVerifierIdCaseSensitive, + "userIdField": userIdField, + "isUserIdCaseSensitive": isUserIdCaseSensitive, + "access_token": access_token, + "flow_type": flow_type?.name, "display": display?.name, "prompt": prompt?.name, "max_age": max_age, @@ -364,7 +394,7 @@ class MfaSettings { } } -class ChainConfig { +class Chains { final ChainNamespace chainNamespace; final int? decimals; final String? blockExplorerUrl; @@ -375,7 +405,7 @@ class ChainConfig { final String? ticker; final String? tickerName; - ChainConfig({ + Chains({ this.chainNamespace = ChainNamespace.eip155, this.decimals = 18, this.blockExplorerUrl, @@ -408,100 +438,149 @@ class Web3AuthOptions { /// You can obtain your client id from the web3auth [developer dashboard](https://dashboard.web3auth.io/). final String clientId; - /// Web3Auth Network to use for the session & the issued idToken. + /// Deeplinking for the application where user will be redirected after login. + /// Ideally, it should be bundleId and package name for iOS and Android respectively. /// - /// User [Network.sapphire_mainnet] for production build. - final Network network; + /// While using redirectUrl, please make sure you have whitelisted it + /// developer dashboard. Checkout [SDK reference](https://web3auth.io/docs/sdk/pnp/flutter/install#configuration-1) more details. + final String redirectUrl; + final Map? originData; - /// [buildEnv] is used for internal testing purposes. This buildEnv + /// [authBuildEnv] is used for internal testing purposes. This buildEnv /// signifies the enviroment for Web3Auth, and doesn't signifies /// the enviorment of the application. - final BuildEnv? buildEnv; + @JsonKey(name: 'buildEnv') + final BuildEnv? authBuildEnv; /// Define the desired Web3Auth service url. final String? sdkUrl; - final String? walletSdkUrl; - /// Deeplinking for the application where user will be redirected after login. - /// Ideally, it should be bundleId and package name for iOS and Android respectively. - /// - /// While using redirectUrl, please make sure you have whitelisted it - /// developer dashboard. Checkout [SDK reference](https://web3auth.io/docs/sdk/pnp/flutter/install#configuration-1) more details. - final Uri? redirectUrl; + String? storageServerUrl; + String? sessionSocketUrl; + + /// Login config for the custom verifiers. + List? authConnectionConfig; /// WhiteLabel options for web3auth. It helps you define - /// custom UI, branding, and translations for your brand app. - /// - /// Checkout [WhiteLabelData] for more details. + /// custom UI, branding, and translations for your brand app final WhiteLabelData? whiteLabel; - /// Login config for the custom verifiers. - final HashMap? loginConfig; + final String? dashboardUrl; + String? accountAbstractionConfig; + final String? walletSdkUrl; + String? sessionNamespace; - /// Use [useCoreKitKey] to get the core kit key. - final bool? useCoreKitKey; + /// [includeUserDataInToken] allows developers to include user data in the token. + bool? includeUserDataInToken; - final ChainNamespace? chainNamespace; - - /// Allows developers to configure the [MfaSettings] for authentication. - /// - /// Checkout [MFA SDK Reference](https://web3auth.io/docs/sdk/pnp/flutter/mfa) for more details. - final MfaSettings? mfaSettings; + Chains? chains; + String? defaultChainId = '0x1'; + bool enableLogging; /// [sessionTime] allows developers to configure the session management time. /// /// Session Time is in seconds, default is 86400 seconds which is 1 day. [sessionTime] can be max 30 days. - final int? sessionTime; + final int sessionTime; - final ChainConfig? chainConfig; + /// Web3Auth Network to use for the session & the issued idToken. + /// + /// User [Web3AuthNetwork.sapphire_mainnet] for production build. + @JsonKey(name: 'network') + final Web3AuthNetwork web3AuthNetwork; - final Map? originData; + final bool? useSFAKey; - final String? dashboardUrl; + /// WhiteLabel options for web3auth. It helps you define + /// custom UI, branding, and translations for your brand app. + /// + /// Checkout [WalletServicesConfig] for more details. + final WalletServicesConfig? walletServicesConfig; + + /// Allows developers to configure the [MfaSettings] for authentication. + /// + /// Checkout [MFA SDK Reference](https://web3auth.io/docs/sdk/pnp/flutter/mfa) for more details. + final MfaSettings? mfaSettings; + + /// Indicates if this is a Flutter SDK session + bool isFlutterAnalytics; + + /// SDK version (used mainly for Flutter SDK) + String? sdkVersion; Web3AuthOptions({ required this.clientId, - required this.network, - this.buildEnv = BuildEnv.production, + required this.redirectUrl, + this.originData, + this.authBuildEnv = BuildEnv.production, String? sdkUrl, - String? walletSdkUrl, - this.redirectUrl, + this.storageServerUrl, + this.sessionSocketUrl, + this.authConnectionConfig = const [], this.whiteLabel, - this.loginConfig, - this.useCoreKitKey, - this.chainNamespace = ChainNamespace.eip155, + String? dashboardUrl, + this.accountAbstractionConfig, + String? walletSdkUrl, + this.sessionNamespace, + this.includeUserDataInToken = true, + this.chains, + this.defaultChainId, + this.enableLogging = false, this.sessionTime = 30 * 86400, + required this.web3AuthNetwork, + this.useSFAKey = false, + this.walletServicesConfig, this.mfaSettings, - this.originData, - String? dashboardUrl, - }) : chainConfig = null, - sdkUrl = sdkUrl ?? getSdkUrl(buildEnv ?? BuildEnv.production), - walletSdkUrl = - walletSdkUrl ?? getWalletSdkUrl(buildEnv ?? BuildEnv.production), - dashboardUrl = - dashboardUrl ?? getDashboardUrl(buildEnv ?? BuildEnv.production); + this.isFlutterAnalytics = true, + this.sdkVersion, + }) : sdkUrl = sdkUrl ?? getSdkUrl(authBuildEnv), + dashboardUrl = dashboardUrl ?? getDashboardUrl(authBuildEnv), + walletSdkUrl = walletSdkUrl ?? getWalletSdkUrl(authBuildEnv); Map toJson() { return { 'clientId': clientId, - 'network': network.name, + 'redirectUrl': redirectUrl, + 'originData': originData, + 'buildEnv': authBuildEnv?.name.toLowerCase(), 'sdkUrl': sdkUrl, - 'walletSdkUrl': walletSdkUrl, - 'buildEnv': buildEnv?.name, - 'redirectUrl': redirectUrl.toString(), + 'storageServerUrl': storageServerUrl, + 'sessionSocketUrl': sessionSocketUrl, + 'authConnectionConfig': authConnectionConfig?.map((config) => config.toJson()).toList(), 'whiteLabel': whiteLabel?.toJson(), - 'loginConfig': loginConfig, - 'useCoreKitKey': useCoreKitKey, - 'chainNamespace': chainNamespace?.name, - 'mfaSettings': mfaSettings, - "sessionTime": sessionTime, - "chainConfig": chainConfig?.toJson(), - "originData": originData, - "dashboardUrl": dashboardUrl, + 'dashboardUrl': dashboardUrl, + 'accountAbstractionConfig': accountAbstractionConfig, + 'walletSdkUrl': walletSdkUrl, + 'sessionNamespace': sessionNamespace, + 'includeUserDataInToken': includeUserDataInToken, + 'chains': chains?.toJson(), + 'defaultChainId': defaultChainId, + 'enableLogging': enableLogging, + 'sessionTime': sessionTime, + 'network': web3AuthNetwork.name.toLowerCase(), + 'useSFAKey': useSFAKey, + 'walletServicesConfig': walletServicesConfig?.toJson(), + 'mfaSettings': mfaSettings?.toJson(), + 'isFlutterAnalytics': isFlutterAnalytics, + 'sdkVersion': sdkVersion, }; } } +class WalletServicesConfig { + final ConfirmationStrategy? confirmationStrategy; + final WhiteLabelData? whiteLabel; + + WalletServicesConfig({ + this.confirmationStrategy = ConfirmationStrategy.defaultStrategy, + this.whiteLabel, + }); + + Map toJson() => { + 'confirmationStrategy': confirmationStrategy?.name, + 'whiteLabel': whiteLabel?.toJson(), + }; +} + class UserCancelledException implements Exception {} class UnKnownException implements Exception { @@ -511,7 +590,7 @@ class UnKnownException implements Exception { } String getSdkUrl(BuildEnv? buildEnv) { - const String version = "v9"; + const String version = "v10"; switch (buildEnv) { case BuildEnv.staging: return "https://staging-auth.web3auth.io/$version"; @@ -524,7 +603,7 @@ String getSdkUrl(BuildEnv? buildEnv) { } String getWalletSdkUrl(BuildEnv? buildEnv) { - const String walletServicesVersion = "v4"; + const String walletServicesVersion = "v5"; switch (buildEnv) { case BuildEnv.staging: return "https://staging-wallet.web3auth.io/$walletServicesVersion"; @@ -538,13 +617,14 @@ String getWalletSdkUrl(BuildEnv? buildEnv) { String getDashboardUrl(BuildEnv? buildEnv) { const String walletAccountConstant = "wallet/account"; + const String authDashboardVersion = "v10"; switch (buildEnv) { case BuildEnv.staging: - return "https://staging-account.web3auth.io/$walletAccountConstant"; + return "https://staging-account.web3auth.io/$authDashboardVersion/$walletAccountConstant"; case BuildEnv.testing: return "https://develop-account.web3auth.io/$walletAccountConstant"; case BuildEnv.production: default: - return "https://account.web3auth.io/$walletAccountConstant"; + return "https://account.web3auth.io/$authDashboardVersion/$walletAccountConstant"; } } diff --git a/lib/output.dart b/lib/output.dart index c7b02a9..1d06d34 100644 --- a/lib/output.dart +++ b/lib/output.dart @@ -1,20 +1,24 @@ import 'dart:core'; +import 'package:json_annotation/json_annotation.dart'; + class Web3AuthResponse { /// secp256k1 private key compaitible with Ethereum ecosystem. - final String? privKey; + @JsonKey(name: 'privKey') + final String? privateKey; /// ed25519 private key compaitible with Solana ecosystem. - final String? ed25519PrivKey; - - /// Current We3Auth sessionId. - final String? sessionId; + @JsonKey(name: 'ed25519PrivKey') + final String? ed25519PrivateKey; /// User's information based on the current session. - final TorusUserInfo? userInfo; + final UserInfo? userInfo; final String? error; + /// Current We3Auth sessionId. + final String? sessionId; + /// secp256k1 core kit key. final String? coreKitKey; @@ -25,39 +29,40 @@ class Web3AuthResponse { final int? tssShareIndex; final String? tssPubKey; final String? tssShare; + final String? tssTag; final int? tssNonce; final List? nodeIndexes; final String? keyMode; - Web3AuthResponse({ - this.privKey, - this.userInfo, - this.error, - this.ed25519PrivKey, - this.sessionId, - this.coreKitKey, - this.coreKitEd25519PrivKey, - this.factorKey, - this.signatures, - this.tssShareIndex, - this.tssPubKey, - this.tssShare, - this.tssNonce, - this.nodeIndexes, - this.keyMode - }); + Web3AuthResponse( + {this.privateKey, + this.userInfo, + this.error, + this.ed25519PrivateKey, + this.sessionId, + this.coreKitKey, + this.coreKitEd25519PrivKey, + this.factorKey, + this.signatures, + this.tssShareIndex, + this.tssPubKey, + this.tssShare, + this.tssTag, + this.tssNonce, + this.nodeIndexes, + this.keyMode}); @override String toString() { - return "{privKey=$privKey, userInfo = ${userInfo.toString()}, ed25519PrivKey=$ed25519PrivKey, coreKitKey=$coreKitKey, coreKitEd25519PrivKey=$coreKitEd25519PrivKey, sessionId=$sessionId, error=$error," - "factorKey=$factorKey, signatures=$signatures, tssShareIndex=$tssShareIndex, tssPubKey=$tssPubKey, tssShare=$tssShare, tssNonce=$tssNonce, nodeIndexes=$nodeIndexes, keyMode=$keyMode}"; + return "{privateKey=$privateKey, userInfo = ${userInfo.toString()}, ed25519PrivateKey=$ed25519PrivateKey, coreKitKey=$coreKitKey, coreKitEd25519PrivKey=$coreKitEd25519PrivKey, sessionId=$sessionId, error=$error," + "factorKey=$factorKey, signatures=$signatures, tssShareIndex=$tssShareIndex, tssPubKey=$tssPubKey, tssShare=$tssShare, tssTag:$tssTag, tssNonce=$tssNonce, nodeIndexes=$nodeIndexes, keyMode=$keyMode}"; } Map toJson() { return { - 'privKey': privKey, + 'privKey': privateKey, 'userInfo': userInfo?.toJson(), - 'ed25519PrivKey': ed25519PrivKey, + 'ed25519PrivKey': ed25519PrivateKey, 'sessionId': sessionId, 'error': error, 'coreKitKey': coreKitKey, @@ -67,6 +72,7 @@ class Web3AuthResponse { 'tssShareIndex': tssShareIndex, 'tssPubKey': tssPubKey, 'tssShare': tssShare, + 'tssTag': tssTag, 'tssNonce': tssNonce, 'nodeIndexes': nodeIndexes, 'keyMode': keyMode @@ -74,11 +80,11 @@ class Web3AuthResponse { } Web3AuthResponse.fromJson(Map json) - : privKey = json['privKey'], + : privateKey = json['privKey'], userInfo = json['userInfo'] != null - ? TorusUserInfo.fromJson(json['userInfo']) + ? UserInfo.fromJson(json['userInfo']) : null, - ed25519PrivKey = json['ed25519PrivKey'], + ed25519PrivateKey = json['ed25519PrivKey'], sessionId = json['sessionId'], coreKitKey = json['coreKitKey'], coreKitEd25519PrivKey = json['coreKitEd25519PrivKey'], @@ -90,6 +96,7 @@ class Web3AuthResponse { tssShareIndex = json['tssShareIndex'], tssPubKey = json['tssPubKey'], tssShare = json['tssShare'], + tssTag = json['tssTag'], tssNonce = json['tssNonce'], nodeIndexes = json['nodeIndexes'] != null ? List.from(json['nodeIndexes']) @@ -97,7 +104,7 @@ class Web3AuthResponse { keyMode = json['keyMode']; } -class TorusUserInfo { +class UserInfo { /// Email of the connected user. final String? email; @@ -108,16 +115,16 @@ class TorusUserInfo { final String? profileImage; /// Details of the verifier type. - final String? verifier; + final String? authConnectionId; /// Verified id for the custom verifiers. - final String? verifierId; + final String? userId; /// Type of login choosen by user, like google, facebook, etc. - final String? typeOfLogin; + final String? authConnection; /// Details of the aggregate verifier, if present. - final String? aggregateVerifier; + final String? groupedAuthConnectionId; /// If you are using a Custom Verifier, you can get a dapp share after successful login. /// This share can act as a replacement to your user's device share. @@ -137,14 +144,14 @@ class TorusUserInfo { /// Defines whether MFA is enabled or not. final bool? isMfaEnabled; - const TorusUserInfo({ + const UserInfo({ this.email, this.name, this.profileImage, - this.verifier, - this.verifierId, - this.typeOfLogin, - this.aggregateVerifier, + this.authConnectionId, + this.userId, + this.authConnection, + this.groupedAuthConnectionId, this.dappShare, this.idToken, this.oAuthIdToken, @@ -154,8 +161,8 @@ class TorusUserInfo { @override String toString() { - return "{email=$email, name=$name, profileImage=$profileImage, verifier=$verifier," - "verifierId=$verifierId, typeOfLogin=$typeOfLogin, dappShare=$dappShare, idToken=$idToken, oAuthIdToken=$oAuthIdToken, oAuthAccessToken=$oAuthAccessToken, isMfaEnabled=$isMfaEnabled}"; + return "{email=$email, name=$name, profileImage=$profileImage, authConnectionId=$authConnectionId," + "userId=$userId, authConnection=$authConnection, dappShare=$dappShare, idToken=$idToken, oAuthIdToken=$oAuthIdToken, oAuthAccessToken=$oAuthAccessToken, isMfaEnabled=$isMfaEnabled}"; } Map toJson() { @@ -163,10 +170,10 @@ class TorusUserInfo { 'email': email, 'name': name, 'profileImage': profileImage, - 'verifier': verifier, - 'verifierId': verifierId, - 'typeOfLogin': typeOfLogin, - 'aggregateVerifier': aggregateVerifier, + 'authConnectionId': authConnectionId, + 'userId': userId, + 'authConnection': authConnection, + 'groupedAuthConnectionId': groupedAuthConnectionId, 'dappShare': dappShare, 'idToken': idToken, 'oAuthIdToken': oAuthIdToken, @@ -175,14 +182,14 @@ class TorusUserInfo { }; } - TorusUserInfo.fromJson(Map json) + UserInfo.fromJson(Map json) : email = json['email'], name = json['name'], profileImage = json['profileImage'], - verifier = json['verifier'], - verifierId = json['verifierId'], - typeOfLogin = json['typeOfLogin'], - aggregateVerifier = json['aggregateVerifier'], + authConnectionId = json['authConnectionId'], + userId = json['userId'], + authConnection = json['authConnection'], + groupedAuthConnectionId = json['groupedAuthConnectionId'], dappShare = json['dappShare'], idToken = json['idToken'], oAuthIdToken = json['oAuthIdToken'], diff --git a/lib/web3auth_flutter.dart b/lib/web3auth_flutter.dart index a87dcc2..f68ccb8 100644 --- a/lib/web3auth_flutter.dart +++ b/lib/web3auth_flutter.dart @@ -19,22 +19,23 @@ class Web3AuthFlutter { await _channel.invokeMethod('init', jsonEncode(initParamsJson)); } - /// [login] method will initiate login flow, opening the browser allowing + /// [connectTo] method will initiate login flow, opening the browser allowing /// users to authenticate themselves with preferred login provider. /// /// Use [loginParams] to change the login provider, curve, and other parameters. /// For more details, look into [LoginParams]. - static Future login(LoginParams loginParams) async { + static Future connectTo(LoginParams loginParams) async { try { Map loginParamsJson = loginParams.toJson(); loginParamsJson.removeWhere((key, value) => value == null); + //print(jsonEncode(loginParamsJson)); final String loginResponse = await _channel.invokeMethod( - 'login', + 'connectTo', jsonEncode(loginParamsJson), ); - return Web3AuthResponse.fromJson(jsonDecode(loginResponse)); } on PlatformException catch (e) { + throw _handlePlatformException(e); } } @@ -67,10 +68,10 @@ class Web3AuthFlutter { /// authenticated. /// /// If user is not authenticated, it'll return empty string. - static Future getPrivKey() async { + static Future getPrivateKey() async { try { final String privKey = - await _channel.invokeMethod('getPrivKey', jsonEncode({})); + await _channel.invokeMethod('getPrivateKey', jsonEncode({})); return privKey; } on PlatformException catch (e) { throw _handlePlatformException(e); @@ -81,10 +82,10 @@ class Web3AuthFlutter { /// authenticated. /// /// If user is not authenticated, it'll return empty string. - static Future getEd25519PrivKey() async { + static Future getEd25519PrivateKey() async { try { final String getEd25519PrivKey = - await _channel.invokeMethod('getEd25519PrivKey', jsonEncode({})); + await _channel.invokeMethod('getEd25519PrivateKey', jsonEncode({})); return getEd25519PrivKey; } on PlatformException catch (e) { throw _handlePlatformException(e); @@ -94,16 +95,16 @@ class Web3AuthFlutter { /// Returns the user information such as email address, name, session id, and etc. /// /// If user is not authenticated, it'll throw an error. - static Future getUserInfo() async { + static Future getUserInfo() async { try { final String torusUserInfo = await _channel.invokeMethod('getUserInfo', jsonEncode({})); - return TorusUserInfo.fromJson(jsonDecode(torusUserInfo)); + return UserInfo.fromJson(jsonDecode(torusUserInfo)); } on PlatformException catch (e) { throw _handlePlatformException(e); } } - + /// [setCustomTabsClosed] helps to trigger the [UserCancelledException] exception /// on Android. /// @@ -136,20 +137,16 @@ class Web3AuthFlutter { } } - static Future launchWalletServices( - ChainConfig chainConfig, { + static Future showWalletUI({ String path = "wallet", }) async { try { - Map chainConfigJson = chainConfig.toJson(); - chainConfigJson.removeWhere((key, value) => value == null); - - Map walletServicesJson = {}; - walletServicesJson["chainConfig"] = chainConfigJson; - walletServicesJson["path"] = path; + Map walletServicesJson = { + "path": path, + }; await _channel.invokeMethod( - 'launchWalletServices', + 'showWalletUI', jsonEncode(walletServicesJson), ); @@ -202,24 +199,23 @@ class Web3AuthFlutter { } static Future request( - ChainConfig chainConfig, String method, List requestParams, { String path = "wallet/request", String? appState, }) async { try { - Map chainConfigJson = chainConfig.toJson(); - chainConfigJson.removeWhere((key, value) => value == null); - + // Encode each request param as a string List modifiedRequestParams = - requestParams.map((param) => jsonEncode(param)).toList(); + requestParams.map((param) => jsonEncode(param)).toList(); + + // Build the request JSON + Map requestJson = { + "method": method, + "requestParams": modifiedRequestParams, + "path": path, + }; - Map requestJson = {}; - requestJson["chainConfig"] = chainConfigJson; - requestJson["method"] = method; - requestJson["requestParams"] = modifiedRequestParams; - requestJson["path"] = path; if (appState != null) { requestJson["appState"] = appState; } diff --git a/pubspec.yaml b/pubspec.yaml index fbfde45..3e132b0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,11 +11,14 @@ environment: dependencies: flutter: sdk: flutter + json_annotation: ^4.8.1 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^4.0.0 + build_runner: ^2.4.6 + json_serializable: ^6.7.1 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec