From 025a0d0825b209e1777fe3babd7844f2a5ee0d6e Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 20 May 2024 12:10:23 +0200 Subject: [PATCH 01/29] remove signclient and auth client and minor preparations --- example/dapp/lib/pages/connect_page.dart | 9 +- lib/apis/auth_api/auth_client.dart | 394 +++---- lib/apis/auth_api/auth_engine.dart | 6 +- lib/apis/auth_api/i_auth_client.dart | 112 +- .../auth_api/models/auth_client_models.dart | 14 + lib/apis/auth_api/utils/auth_signature.dart | 2 + lib/apis/sign_api/i_sign_client.dart | 252 ++--- lib/apis/sign_api/sign_client.dart | 944 ++++++++--------- lib/apis/utils/method_constants.dart | 13 + lib/apis/web3wallet/web3wallet.dart | 1 + test/auth_api/auth_client_test.dart | 988 +++++++++--------- .../utils/auth_client_test_wrapper.dart | 286 ++--- test/sign_api/sign_client_test.dart | 78 +- .../utils/sign_client_test_wrapper.dart | 864 +++++++-------- 14 files changed, 2000 insertions(+), 1963 deletions(-) diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 91e45881..7f5684a9 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -294,6 +294,10 @@ class ConnectPageState extends State { Navigator.pop(context); } + _requestAuth(event); + } + + void _requestAuth(SessionConnect? event) async { final shouldAuth = await showDialog( context: context, barrierDismissible: false, @@ -321,10 +325,11 @@ class ConnectPageState extends State { if (!shouldAuth) return; try { - final scheme = event.session.peer.metadata.redirect?.native ?? ''; + final scheme = + event?.session.peer.metadata.redirect?.native ?? 'wcflutterwallet://'; launchUrlString(scheme, mode: LaunchMode.externalApplication); - final pairingTopic = event.session.pairingTopic; + final pairingTopic = event?.session.pairingTopic; // Send off an auth request now that the pairing/session is established debugPrint('Requesting authentication'); final authRes = await widget.web3App.requestAuth( diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index 1d773cef..c0a03002 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,197 +1,197 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; - -class AuthClient implements IAuthClient { - bool _initialized = false; - - @override - String get protocol => 'wc'; - - @override - int get version => 2; - - @override - Event get onAuthRequest => engine.onAuthRequest; - @override - Event get onAuthResponse => engine.onAuthResponse; - - @override - ICore get core => engine.core; - @override - PairingMetadata get metadata => engine.metadata; - @override - IGenericStore get authKeys => engine.authKeys; - @override - IGenericStore get pairingTopics => engine.pairingTopics; - @override - IGenericStore get authRequests => engine.authRequests; - @override - IGenericStore get completeRequests => engine.completeRequests; - - @override - late IAuthEngine engine; - - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - IHttpClient httpClient = const HttpWrapper(), - LogLevel logLevel = LogLevel.nothing, - }) async { - final client = AuthClient( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - httpClient: httpClient, - logLevel: logLevel, - ), - metadata: metadata, - ); - await client.init(); - - return client; - } - - AuthClient({ - required ICore core, - required PairingMetadata metadata, - }) { - engine = AuthEngine( - core: core, - metadata: metadata, - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value as String; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - } - - @override - Future init() async { - if (_initialized) { - return; - } - - await core.start(); - await engine.init(); - - _initialized = true; - } - - @override - Future request({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods = AuthEngine.defaultMethods, - }) async { - try { - return engine.requestAuth( - params: params, - pairingTopic: pairingTopic, - methods: methods, - ); - } catch (e) { - rethrow; - } - } - - @override - Future respond({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }) async { - try { - return engine.respondAuthRequest( - id: id, - iss: iss, - signature: signature, - error: error, - ); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingRequests() { - try { - return engine.getPendingAuthRequests(); - } catch (e) { - rethrow; - } - } - - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return engine.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - - @override - String formatMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }) { - try { - return engine.formatAuthMessage( - iss: iss, - cacaoPayload: cacaoPayload, - ); - } catch (e) { - rethrow; - } - } -} +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; + +// class AuthClient implements IAuthClient { +// bool _initialized = false; + +// @override +// String get protocol => 'wc'; + +// @override +// int get version => 2; + +// @override +// Event get onAuthRequest => engine.onAuthRequest; +// @override +// Event get onAuthResponse => engine.onAuthResponse; + +// @override +// ICore get core => engine.core; +// @override +// PairingMetadata get metadata => engine.metadata; +// @override +// IGenericStore get authKeys => engine.authKeys; +// @override +// IGenericStore get pairingTopics => engine.pairingTopics; +// @override +// IGenericStore get authRequests => engine.authRequests; +// @override +// IGenericStore get completeRequests => engine.completeRequests; + +// @override +// late IAuthEngine engine; + +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// IHttpClient httpClient = const HttpWrapper(), +// LogLevel logLevel = LogLevel.nothing, +// }) async { +// final client = AuthClient( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// httpClient: httpClient, +// logLevel: logLevel, +// ), +// metadata: metadata, +// ); +// await client.init(); + +// return client; +// } + +// AuthClient({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// engine = AuthEngine( +// core: core, +// metadata: metadata, +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value as String; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// } + +// @override +// Future init() async { +// if (_initialized) { +// return; +// } + +// await core.start(); +// await engine.init(); + +// _initialized = true; +// } + +// @override +// Future request({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods = AuthEngine.DEFAULT_METHODS, +// }) async { +// try { +// return engine.requestAuth( +// params: params, +// pairingTopic: pairingTopic, +// methods: methods, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future respond({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) async { +// try { +// return engine.respondAuthRequest( +// id: id, +// iss: iss, +// signature: signature, +// error: error, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingRequests() { +// try { +// return engine.getPendingAuthRequests(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return engine.getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// String formatMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }) { +// try { +// return engine.formatAuthMessage( +// iss: iss, +// cacaoPayload: cacaoPayload, +// ); +// } catch (e) { +// rethrow; +// } +// } +// } diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index c9eba970..670e3a8c 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -22,7 +22,7 @@ import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; class AuthEngine implements IAuthEngine { - static const List> defaultMethods = [ + static const List> DEFAULT_METHODS = [ [ MethodConstants.WC_AUTH_REQUEST, ] @@ -80,7 +80,7 @@ class AuthEngine implements IAuthEngine { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = defaultMethods, + List>? methods = DEFAULT_METHODS, }) async { _checkInitialized(); @@ -343,6 +343,8 @@ class AuthEngine implements IAuthEngine { return completedRequests; } + // kind of a core method to move to sign + // Formats the message that is coming from requestAuth() @override String formatAuthMessage({ required String iss, diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 100fcd26..848d0974 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,56 +1,56 @@ -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -abstract class IAuthClient { - final String protocol = 'wc'; - final int version = 2; - - abstract final IAuthEngine engine; - - // Common - abstract final ICore core; - abstract final PairingMetadata metadata; - - abstract final IGenericStore authKeys; - abstract final IGenericStore pairingTopics; - abstract final IGenericStore completeRequests; - - // initializes the client with persisted storage and a network connection - Future init(); - - /// format payload to message string - String formatMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }); - - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }); - - // App - abstract final Event onAuthResponse; - - // request wallet authentication - Future request({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods, - }); - - // Wallet - abstract final Event onAuthRequest; - - abstract final IGenericStore authRequests; - - /// respond wallet authentication - Future respond({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }); - - // query all pending requests - Map getPendingRequests(); -} +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +// abstract class IAuthClient { +// final String protocol = 'wc'; +// final int version = 2; + +// abstract final IAuthEngine engine; + +// // Common +// abstract final ICore core; +// abstract final PairingMetadata metadata; + +// abstract final IGenericStore authKeys; +// abstract final IGenericStore pairingTopics; +// abstract final IGenericStore completeRequests; + +// // initializes the client with persisted storage and a network connection +// Future init(); + +// /// format payload to message string +// String formatMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }); + +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }); + +// // App +// abstract final Event onAuthResponse; + +// // request wallet authentication +// Future request({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods, +// }); + +// // Wallet +// abstract final Event onAuthRequest; + +// abstract final IGenericStore authRequests; + +// /// respond wallet authentication +// Future respond({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }); + +// // query all pending requests +// Map getPendingRequests(); +// } diff --git a/lib/apis/auth_api/models/auth_client_models.dart b/lib/apis/auth_api/models/auth_client_models.dart index 20fc75e1..d42eb135 100644 --- a/lib/apis/auth_api/models/auth_client_models.dart +++ b/lib/apis/auth_api/models/auth_client_models.dart @@ -68,6 +68,20 @@ class AuthRequestParams { this.resources, this.expiry, }) : nonce = nonce ?? AuthUtils.generateNonce(); + + Map toJson() => { + 'chainId': chainId, + 'aud': aud, + 'domain': domain, + 'nonce': nonce, + if (type != null) 'type': type, + if (nbf != null) 'nbf': nbf, + if (exp != null) 'exp': exp, + if (statement != null) 'statement': statement, + if (requestId != null) 'requestId': requestId, + if (resources != null) 'resources': resources, + if (expiry != null) 'expiry': expiry, + }; } @freezed diff --git a/lib/apis/auth_api/utils/auth_signature.dart b/lib/apis/auth_api/utils/auth_signature.dart index fa706de2..a860fe8a 100644 --- a/lib/apis/auth_api/utils/auth_signature.dart +++ b/lib/apis/auth_api/utils/auth_signature.dart @@ -158,6 +158,8 @@ class AuthSignature { } } + // verifies CACAO signature + // Used by the wallet after formatting the message static Future verifySignature( String address, String reconstructedMessage, diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 10f7b318..3d19034a 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -1,136 +1,136 @@ -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/walletconnect_flutter_v2.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/walletconnect_flutter_v2.dart'; -abstract class ISignClient { - final String protocol = 'wc'; - final int version = 2; +// abstract class ISignClient { +// final String protocol = 'wc'; +// final int version = 2; - abstract final ISignEngine engine; +// abstract final ISignEngine engine; - // Common - abstract final Event onSessionConnect; - abstract final Event onSessionDelete; - abstract final Event onSessionExpire; - abstract final Event onSessionPing; - abstract final Event onProposalExpire; +// // Common +// abstract final Event onSessionConnect; +// abstract final Event onSessionDelete; +// abstract final Event onSessionExpire; +// abstract final Event onSessionPing; +// abstract final Event onProposalExpire; - abstract final ICore core; - abstract final PairingMetadata metadata; - abstract final IGenericStore proposals; - abstract final ISessions sessions; - abstract final IGenericStore pendingRequests; +// abstract final ICore core; +// abstract final PairingMetadata metadata; +// abstract final IGenericStore proposals; +// abstract final ISessions sessions; +// abstract final IGenericStore pendingRequests; - // Wallet - abstract final Event onSessionProposal; - abstract final Event onSessionProposalError; - abstract final Event onSessionRequest; +// // Wallet +// abstract final Event onSessionProposal; +// abstract final Event onSessionProposalError; +// abstract final Event onSessionRequest; - // App - abstract final Event onSessionUpdate; - abstract final Event onSessionExtend; - abstract final Event onSessionEvent; +// // App +// abstract final Event onSessionUpdate; +// abstract final Event onSessionExtend; +// abstract final Event onSessionEvent; - Future init(); - Future connect({ - Map? requiredNamespaces, - Map? optionalNamespaces, - Map? sessionProperties, - String? pairingTopic, - List? relays, - List>? methods, - }); - Future pair({ - required Uri uri, - }); - Future approve({ - required int id, - required Map namespaces, - Map? sessionProperties, - String? relayProtocol, - }); - Future reject({ - required int id, - required WalletConnectError reason, - }); - Future update({ - required String topic, - required Map namespaces, - }); - Future extend({ - required String topic, - }); - void registerRequestHandler({ - required String chainId, - required String method, - dynamic Function(String, dynamic)? handler, - }); - Future respond({ - required String topic, - required JsonRpcResponse response, - }); - Future emit({ - required String topic, - required String chainId, - required SessionEventParams event, - }); - Future request({ - required String topic, - required String chainId, - required SessionRequestParams request, - }); - Future> requestReadContract({ - required DeployedContract deployedContract, - required String functionName, - required String rpcUrl, - List parameters = const [], - }); - 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 [], - }); +// Future init(); +// Future connect({ +// Map? requiredNamespaces, +// Map? optionalNamespaces, +// Map? sessionProperties, +// String? pairingTopic, +// List? relays, +// List>? methods, +// }); +// Future pair({ +// required Uri uri, +// }); +// Future approve({ +// required int id, +// required Map namespaces, +// Map? sessionProperties, +// String? relayProtocol, +// }); +// Future reject({ +// required int id, +// required WalletConnectError reason, +// }); +// Future update({ +// required String topic, +// required Map namespaces, +// }); +// Future extend({ +// required String topic, +// }); +// void registerRequestHandler({ +// required String chainId, +// required String method, +// dynamic Function(String, dynamic)? handler, +// }); +// Future respond({ +// required String topic, +// required JsonRpcResponse response, +// }); +// Future emit({ +// required String topic, +// required String chainId, +// required SessionEventParams event, +// }); +// Future request({ +// required String topic, +// required String chainId, +// required SessionRequestParams request, +// }); +// Future> requestReadContract({ +// required DeployedContract deployedContract, +// required String functionName, +// required String rpcUrl, +// List parameters = const [], +// }); +// 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 [], +// }); - void registerEventHandler({ - required String chainId, - required String event, - required dynamic Function(String, dynamic)? handler, - }); - Future ping({ - required String topic, - }); - Future disconnect({ - required String topic, - required WalletConnectError reason, - }); - SessionData? find({ - required Map requiredNamespaces, - }); - Map getActiveSessions(); - Map getSessionsForPairing({ - required String pairingTopic, - }); - Map getPendingSessionProposals(); - Map getPendingSessionRequests(); - abstract final IPairingStore pairings; +// void registerEventHandler({ +// required String chainId, +// required String event, +// required dynamic Function(String, dynamic)? handler, +// }); +// Future ping({ +// required String topic, +// }); +// Future disconnect({ +// required String topic, +// required WalletConnectError reason, +// }); +// SessionData? find({ +// required Map requiredNamespaces, +// }); +// Map getActiveSessions(); +// Map getSessionsForPairing({ +// required String pairingTopic, +// }); +// Map getPendingSessionProposals(); +// Map getPendingSessionRequests(); +// abstract final IPairingStore pairings; - /// Register event emitters for a given namespace or chainId - /// Used to construct the Namespaces map for the session proposal - void registerEventEmitter({ - required String chainId, - required String event, - }); +// /// Register event emitters for a given namespace or chainId +// /// Used to construct the Namespaces map for the session proposal +// void registerEventEmitter({ +// required String chainId, +// required String event, +// }); - /// Register accounts for a given namespace or chainId. - /// Used to construct the Namespaces map for the session proposal. - /// Each account must follow the namespace:chainId:address format or this will throw an error. - void registerAccount({ - required String chainId, - required String accountAddress, - }); -} +// /// Register accounts for a given namespace or chainId. +// /// Used to construct the Namespaces map for the session proposal. +// /// Each account must follow the namespace:chainId:address format or this will throw an error. +// void registerAccount({ +// required String chainId, +// required String accountAddress, +// }); +// } diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index a81fe3ab..9aebf091 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -1,472 +1,472 @@ -import 'package:event/event.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_pairing_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_client.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/sessions.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -import 'package:web3dart/web3dart.dart'; - -class SignClient implements ISignClient { - bool _initialized = false; - - @override - final String protocol = 'wc'; - @override - final int version = 2; - - @override - Event get onSessionDelete => engine.onSessionDelete; - @override - Event get onSessionConnect => engine.onSessionConnect; - @override - Event get onSessionEvent => engine.onSessionEvent; - @override - Event get onSessionExpire => engine.onSessionExpire; - @override - Event get onSessionExtend => engine.onSessionExtend; - @override - Event get onSessionPing => engine.onSessionPing; - @override - Event get onSessionProposal => engine.onSessionProposal; - @override - Event get onSessionProposalError => - engine.onSessionProposalError; - @override - Event get onProposalExpire => engine.onProposalExpire; - @override - Event get onSessionRequest => engine.onSessionRequest; - @override - Event get onSessionUpdate => engine.onSessionUpdate; - - @override - ICore get core => engine.core; - @override - PairingMetadata get metadata => engine.metadata; - @override - IGenericStore get proposals => engine.proposals; - @override - ISessions get sessions => engine.sessions; - @override - IGenericStore get pendingRequests => engine.pendingRequests; - - @override - late ISignEngine engine; - - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - LogLevel logLevel = LogLevel.nothing, - }) async { - final client = SignClient( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - logLevel: logLevel, - ), - metadata: metadata, - ); - await client.init(); - - return client; - } - - SignClient({ - required ICore core, - required PairingMetadata metadata, - }) { - engine = SignEngine( - core: core, - metadata: metadata, - proposals: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PROPOSALS, - version: StoreVersions.VERSION_PROPOSALS, - fromJson: (dynamic value) { - return ProposalData.fromJson(value); - }, - ), - sessions: Sessions( - storage: core.storage, - context: StoreVersions.CONTEXT_SESSIONS, - version: StoreVersions.VERSION_SESSIONS, - fromJson: (dynamic value) { - return SessionData.fromJson(value); - }, - ), - pendingRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PENDING_REQUESTS, - version: StoreVersions.VERSION_PENDING_REQUESTS, - fromJson: (dynamic value) { - return SessionRequest.fromJson(value); - }, - ), - ); - } - - @override - Future init() async { - if (_initialized) { - return; - } - - await core.start(); - await engine.init(); - - _initialized = true; - } - - @override - Future connect({ - Map? requiredNamespaces, - Map? optionalNamespaces, - Map? sessionProperties, - String? pairingTopic, - List? relays, - List>? methods = SignEngine.DEFAULT_METHODS, - }) async { - try { - return await engine.connect( - requiredNamespaces: requiredNamespaces, - optionalNamespaces: optionalNamespaces, - sessionProperties: sessionProperties, - pairingTopic: pairingTopic, - relays: relays, - methods: methods, - ); - } catch (e) { - // print(e); - rethrow; - } - } - - @override - Future pair({ - required Uri uri, - }) async { - try { - return await engine.pair(uri: uri); - } catch (e) { - rethrow; - } - } - - @override - Future approve({ - required int id, - required Map namespaces, - Map? sessionProperties, - String? relayProtocol, - }) async { - try { - return await engine.approveSession( - id: id, - namespaces: namespaces, - sessionProperties: sessionProperties, - relayProtocol: relayProtocol, - ); - } catch (e) { - rethrow; - } - } - - @override - Future reject({ - required int id, - required WalletConnectError reason, - }) async { - try { - return await engine.rejectSession( - id: id, - reason: reason, - ); - } catch (e) { - rethrow; - } - } - - @override - Future update({ - required String topic, - required Map namespaces, - }) async { - try { - return await engine.updateSession( - topic: topic, - namespaces: namespaces, - ); - } catch (e) { - // final error = e as WCError; - rethrow; - } - } - - @override - Future extend({ - required String topic, - }) async { - try { - return await engine.extendSession(topic: topic); - } catch (e) { - rethrow; - } - } - - @override - void registerRequestHandler({ - required String chainId, - required String method, - void Function(String, dynamic)? handler, - }) { - try { - return engine.registerRequestHandler( - chainId: chainId, - method: method, - handler: handler, - ); - } catch (e) { - rethrow; - } - } - - @override - Future request({ - required String topic, - required String chainId, - required SessionRequestParams request, - }) async { - try { - return await engine.request( - topic: topic, - chainId: chainId, - request: request, - ); - } catch (e) { - rethrow; - } - } - - @override - Future> requestReadContract({ - required DeployedContract deployedContract, - required String functionName, - required String rpcUrl, - List parameters = const [], - }) async { - try { - return await engine.requestReadContract( - deployedContract: deployedContract, - functionName: functionName, - rpcUrl: rpcUrl, - parameters: parameters, - ); - } catch (e) { - rethrow; - } - } - - @override - 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 [], - }) async { - try { - return await engine.requestWriteContract( - topic: topic, - chainId: chainId, - rpcUrl: rpcUrl, - deployedContract: deployedContract, - functionName: functionName, - transaction: transaction, - method: method, - parameters: parameters, - ); - } catch (e) { - rethrow; - } - } - - @override - Future respond({ - required String topic, - required JsonRpcResponse response, - }) { - try { - return engine.respondSessionRequest( - topic: topic, - response: response, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerEventHandler({ - required String chainId, - required String event, - dynamic Function(String, dynamic)? handler, - }) { - try { - return engine.registerEventHandler( - chainId: chainId, - event: event, - handler: handler, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerEventEmitter({ - required String chainId, - required String event, - }) { - try { - return engine.registerEventEmitter( - chainId: chainId, - event: event, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerAccount({ - required String chainId, - required String accountAddress, - }) { - try { - return engine.registerAccount( - chainId: chainId, - accountAddress: accountAddress, - ); - } catch (e) { - rethrow; - } - } - - @override - Future emit({ - required String topic, - required String chainId, - required SessionEventParams event, - }) async { - try { - return await engine.emitSessionEvent( - topic: topic, - chainId: chainId, - event: event, - ); - } catch (e) { - rethrow; - } - } - - @override - Future ping({ - required String topic, - }) async { - try { - return await engine.ping(topic: topic); - } catch (e) { - rethrow; - } - } - - @override - Future disconnect({ - required String topic, - required WalletConnectError reason, - }) async { - try { - return await engine.disconnectSession( - topic: topic, - reason: reason, - ); - } catch (e) { - rethrow; - } - } - - @override - SessionData? find({ - required Map requiredNamespaces, - }) { - try { - return engine.find(requiredNamespaces: requiredNamespaces); - } catch (e) { - rethrow; - } - } - - @override - Map getActiveSessions() { - try { - return engine.getActiveSessions(); - } catch (e) { - rethrow; - } - } - - @override - Map getSessionsForPairing({ - required String pairingTopic, - }) { - try { - return engine.getSessionsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingSessionProposals() { - try { - return engine.getPendingSessionProposals(); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingSessionRequests() { - try { - return engine.getPendingSessionRequests(); - } catch (e) { - rethrow; - } - } - - @override - IPairingStore get pairings => core.pairing.getStore(); -} +// import 'package:event/event.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_pairing_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/sessions.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +// import 'package:web3dart/web3dart.dart'; + +// class SignClient implements ISignClient { +// bool _initialized = false; + +// @override +// final String protocol = 'wc'; +// @override +// final int version = 2; + +// @override +// Event get onSessionDelete => engine.onSessionDelete; +// @override +// Event get onSessionConnect => engine.onSessionConnect; +// @override +// Event get onSessionEvent => engine.onSessionEvent; +// @override +// Event get onSessionExpire => engine.onSessionExpire; +// @override +// Event get onSessionExtend => engine.onSessionExtend; +// @override +// Event get onSessionPing => engine.onSessionPing; +// @override +// Event get onSessionProposal => engine.onSessionProposal; +// @override +// Event get onSessionProposalError => +// engine.onSessionProposalError; +// @override +// Event get onProposalExpire => engine.onProposalExpire; +// @override +// Event get onSessionRequest => engine.onSessionRequest; +// @override +// Event get onSessionUpdate => engine.onSessionUpdate; + +// @override +// ICore get core => engine.core; +// @override +// PairingMetadata get metadata => engine.metadata; +// @override +// IGenericStore get proposals => engine.proposals; +// @override +// ISessions get sessions => engine.sessions; +// @override +// IGenericStore get pendingRequests => engine.pendingRequests; + +// @override +// late ISignEngine engine; + +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// LogLevel logLevel = LogLevel.nothing, +// }) async { +// final client = SignClient( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// logLevel: logLevel, +// ), +// metadata: metadata, +// ); +// await client.init(); + +// return client; +// } + +// SignClient({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// engine = SignEngine( +// core: core, +// metadata: metadata, +// proposals: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PROPOSALS, +// version: StoreVersions.VERSION_PROPOSALS, +// fromJson: (dynamic value) { +// return ProposalData.fromJson(value); +// }, +// ), +// sessions: Sessions( +// storage: core.storage, +// context: StoreVersions.CONTEXT_SESSIONS, +// version: StoreVersions.VERSION_SESSIONS, +// fromJson: (dynamic value) { +// return SessionData.fromJson(value); +// }, +// ), +// pendingRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PENDING_REQUESTS, +// version: StoreVersions.VERSION_PENDING_REQUESTS, +// fromJson: (dynamic value) { +// return SessionRequest.fromJson(value); +// }, +// ), +// ); +// } + +// @override +// Future init() async { +// if (_initialized) { +// return; +// } + +// await core.start(); +// await engine.init(); + +// _initialized = true; +// } + +// @override +// Future connect({ +// Map? requiredNamespaces, +// Map? optionalNamespaces, +// Map? sessionProperties, +// String? pairingTopic, +// List? relays, +// List>? methods = SignEngine.DEFAULT_METHODS, +// }) async { +// try { +// return await engine.connect( +// requiredNamespaces: requiredNamespaces, +// optionalNamespaces: optionalNamespaces, +// sessionProperties: sessionProperties, +// pairingTopic: pairingTopic, +// relays: relays, +// methods: methods, +// ); +// } catch (e) { +// // print(e); +// rethrow; +// } +// } + +// @override +// Future pair({ +// required Uri uri, +// }) async { +// try { +// return await engine.pair(uri: uri); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future approve({ +// required int id, +// required Map namespaces, +// Map? sessionProperties, +// String? relayProtocol, +// }) async { +// try { +// return await engine.approveSession( +// id: id, +// namespaces: namespaces, +// sessionProperties: sessionProperties, +// relayProtocol: relayProtocol, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future reject({ +// required int id, +// required WalletConnectError reason, +// }) async { +// try { +// return await engine.rejectSession( +// id: id, +// reason: reason, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future update({ +// required String topic, +// required Map namespaces, +// }) async { +// try { +// return await engine.updateSession( +// topic: topic, +// namespaces: namespaces, +// ); +// } catch (e) { +// // final error = e as WCError; +// rethrow; +// } +// } + +// @override +// Future extend({ +// required String topic, +// }) async { +// try { +// return await engine.extendSession(topic: topic); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerRequestHandler({ +// required String chainId, +// required String method, +// void Function(String, dynamic)? handler, +// }) { +// try { +// return engine.registerRequestHandler( +// chainId: chainId, +// method: method, +// handler: handler, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future request({ +// required String topic, +// required String chainId, +// required SessionRequestParams request, +// }) async { +// try { +// return await engine.request( +// topic: topic, +// chainId: chainId, +// request: request, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future> requestReadContract({ +// required DeployedContract deployedContract, +// required String functionName, +// required String rpcUrl, +// List parameters = const [], +// }) async { +// try { +// return await engine.requestReadContract( +// deployedContract: deployedContract, +// functionName: functionName, +// rpcUrl: rpcUrl, +// parameters: parameters, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// 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 [], +// }) async { +// try { +// return await engine.requestWriteContract( +// topic: topic, +// chainId: chainId, +// rpcUrl: rpcUrl, +// deployedContract: deployedContract, +// functionName: functionName, +// transaction: transaction, +// method: method, +// parameters: parameters, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future respond({ +// required String topic, +// required JsonRpcResponse response, +// }) { +// try { +// return engine.respondSessionRequest( +// topic: topic, +// response: response, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerEventHandler({ +// required String chainId, +// required String event, +// dynamic Function(String, dynamic)? handler, +// }) { +// try { +// return engine.registerEventHandler( +// chainId: chainId, +// event: event, +// handler: handler, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerEventEmitter({ +// required String chainId, +// required String event, +// }) { +// try { +// return engine.registerEventEmitter( +// chainId: chainId, +// event: event, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerAccount({ +// required String chainId, +// required String accountAddress, +// }) { +// try { +// return engine.registerAccount( +// chainId: chainId, +// accountAddress: accountAddress, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future emit({ +// required String topic, +// required String chainId, +// required SessionEventParams event, +// }) async { +// try { +// return await engine.emitSessionEvent( +// topic: topic, +// chainId: chainId, +// event: event, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future ping({ +// required String topic, +// }) async { +// try { +// return await engine.ping(topic: topic); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future disconnect({ +// required String topic, +// required WalletConnectError reason, +// }) async { +// try { +// return await engine.disconnectSession( +// topic: topic, +// reason: reason, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// SessionData? find({ +// required Map requiredNamespaces, +// }) { +// try { +// return engine.find(requiredNamespaces: requiredNamespaces); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getActiveSessions() { +// try { +// return engine.getActiveSessions(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getSessionsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return engine.getSessionsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingSessionProposals() { +// try { +// return engine.getPendingSessionProposals(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingSessionRequests() { +// try { +// return engine.getPendingSessionRequests(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// IPairingStore get pairings => core.pairing.getStore(); +// } diff --git a/lib/apis/utils/method_constants.dart b/lib/apis/utils/method_constants.dart index d80b141e..01b3e80c 100644 --- a/lib/apis/utils/method_constants.dart +++ b/lib/apis/utils/method_constants.dart @@ -14,6 +14,7 @@ class MethodConstants { static const WC_SESSION_EVENT = 'wc_sessionEvent'; static const WC_SESSION_DELETE = 'wc_sessionDelete'; static const WC_SESSION_PING = 'wc_sessionPing'; + // static const WC_SESSION_AUTHENTICATE = 'wc_sessionAuthenticate'; TODO static const WC_AUTH_REQUEST = 'wc_authRequest'; @@ -150,6 +151,18 @@ class MethodConstants { tag: 1115, ), }, + // WC_SESSION_AUTHENTICATE: { TODO + // 'req': RpcOptions( + // ttl: WalletConnectConstants.ONE_HOUR, + // prompt: false, + // tag: 1116, + // ), + // 'res': RpcOptions( + // ttl: WalletConnectConstants.ONE_HOUR, + // prompt: false, + // tag: 1117, + // ), + // }, WC_AUTH_REQUEST: { 'req': RpcOptions( ttl: WalletConnectConstants.ONE_DAY, diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index fe11ac3c..d5d5a395 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -443,6 +443,7 @@ class Web3Wallet implements IWeb3Wallet { } } + /// format payload to message string before signing @override String formatAuthMessage({ required String iss, diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index 2333782d..de143617 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -1,494 +1,494 @@ -import 'dart:async'; -import 'dart:typed_data'; - -import 'package:eth_sig_util/eth_sig_util.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.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'; -import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -import '../shared/shared_test_utils.dart'; -import '../shared/shared_test_values.dart'; -import 'utils/auth_client_test_wrapper.dart'; -import 'utils/engine_constants.dart'; -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', - ); - - final List Function(PairingMetadata)> authAppCreators = - [ - (PairingMetadata metadata) async => - await AuthClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - (PairingMetadata? self) async { - final core = Core( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ); - IAuthEngine e = AuthEngine( - core: core, - metadata: self ?? PairingMetadata.empty(), - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - await core.start(); - await e.init(); - - return e; - }, - (PairingMetadata metadata) async => - await AuthClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - ]; - - final List Function(PairingMetadata)> - authWalletCreators = [ - (PairingMetadata metadata) async => await Web3Wallet.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - (PairingMetadata metadata) async { - final core = Core( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ); - IAuthEngine e = AuthEngine( - core: core, - metadata: metadata, - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - await core.start(); - await e.init(); - - return e; - }, - (PairingMetadata metadata) async => await Web3Wallet.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - ]; - - final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; - - for (int i = 0; i < authAppCreators.length; i++) { - runTests( - context: contexts[i], - engineAppCreator: authAppCreators[i], - engineWalletCreator: authWalletCreators[i], - ); - } -} - -void runTests({ - required String context, - required Future Function(PairingMetadata) engineAppCreator, - required Future Function(PairingMetadata) - engineWalletCreator, -}) { - group(context, () { - late IAuthEngineApp clientA; - late IAuthEngineWallet clientB; - - setUp(() async { - clientA = await engineAppCreator( - TEST_METADATA_REQUESTER, - ); - clientB = await engineWalletCreator( - TEST_METADATA_RESPONDER, - ); - }); - - tearDown(() async { - await clientA.core.relayClient.disconnect(); - await clientB.core.relayClient.disconnect(); - }); - - group('happy path', () { - test('Initializes', () async { - expect(clientA.core.pairing.getPairings().length, 0); - expect(clientB.core.pairing.getPairings().length, 0); - }); - - test( - 'connects and receives request, reconnects and receives another request, and emits proper events', - () async { - AuthRequestResponse response = await clientA.requestAuth( - params: defaultRequestParams, - ); - final String pairingTopic = response.pairingTopic; - - Completer completerAPairing = Completer(); - Completer completerBPairing = Completer(); - Completer completerA = Completer(); - Completer completerB = Completer(); - int counterAPairing = 0; - int counterBPairing = 0; - int counterA = 0; - int counterB = 0; - clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { - expect(pairing != null, true); - expect(pairing!.topic, pairingTopic); - counterAPairing++; - completerAPairing.complete(); - }); - clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { - expect(pairing != null, true); - expect(pairing!.topic, pairingTopic); - counterBPairing++; - completerBPairing.complete(); - }); - clientA.onAuthResponse.subscribe((AuthResponse? args) { - counterA++; - completerA.complete(); - - expect(args!.result, isNotNull); - }); - clientB.onAuthRequest.subscribe((AuthRequest? args) async { - counterB++; - - int currReqCount = clientB.getPendingAuthRequests().length; - - expect(args != null, true); - - // Create the message to be signed - String message = clientB.formatAuthMessage( - iss: TEST_ISSUER_EIP191, - cacaoPayload: CacaoRequestPayload.fromPayloadParams( - args!.payloadParams, - ), - ); - - String sig = EthSigUtil.signPersonalMessage( - message: Uint8List.fromList(message.codeUnits), - privateKey: TEST_PRIVATE_KEY_EIP191, - ); - - await clientB.respondAuthRequest( - id: args.id, - iss: TEST_ISSUER_EIP191, - signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), - ); - - expect(clientB.getPendingAuthRequests().length, currReqCount - 1); - - completerB.complete(); - }); - - expect(response.uri != null, true); - - await clientB.core.pairing.pair(uri: response.uri!); - expect(clientA.core.pairing.getPairings().length, 1); - expect(clientB.core.pairing.getPairings().length, 1); - // AuthResponse authResponse = await response.completer.future; - - await clientA.core.pairing.ping(topic: pairingTopic); - await clientB.core.pairing.ping(topic: pairingTopic); - - if (!completerAPairing.isCompleted) { - clientA.core.logger.i('Waiting for completerAPairing'); - await completerAPairing.future; - } - if (!completerBPairing.isCompleted) { - clientA.core.logger.i('Waiting for completerBPairing'); - await completerBPairing.future; - } - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - if (!completerB.isCompleted) { - clientA.core.logger.i('Waiting for completerB'); - await completerB.future; - } - - AuthResponse authResponse = await response.completer.future; - expect(authResponse.result != null, true); - - expect(counterAPairing, 1); - expect(counterBPairing, 1); - - expect(counterA, 1); - expect(counterB, 1); - - expect( - clientA - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 1, - ); - expect( - clientB - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 1, - ); - - completerA = Completer(); - completerB = Completer(); - - response = await clientA.requestAuth( - params: defaultRequestParams, - pairingTopic: pairingTopic, - ); - - expect(response.uri == null, true); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - if (!completerB.isCompleted) { - clientA.core.logger.i('Waiting for completerB'); - await completerB.future; - } - - authResponse = await response.completer.future; - expect(authResponse.result != null, true); - - // Got the second request and response - expect(counterA, 2); - expect(counterB, 2); - - expect( - clientA - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 2, - ); - expect( - clientB - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 2, - ); - - clientA.onAuthResponse.unsubscribeAll(); - clientB.onAuthRequest.unsubscribeAll(); - clientA.core.pairing.onPairingPing.unsubscribeAll(); - clientB.core.pairing.onPairingPing.unsubscribeAll(); - }); - - test('counts pendingAuthRequests properly', () async { - AuthRequestResponse response = await clientA.requestAuth( - params: defaultRequestParams, - ); - final String pairingTopic = response.pairingTopic; - - await clientB.core.pairing.pair(uri: response.uri!); - - Completer completerA = Completer(); - clientB.onAuthRequest.subscribe((AuthRequest? args) async { - // print('got here'); - // print(clientB.getPendingAuthRequests().length); - completerA.complete(); - }); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - - expect(clientB.getPendingAuthRequests().length, 1); - - completerA = Completer(); - - response = await clientA.requestAuth( - params: defaultRequestParams, - pairingTopic: pairingTopic, - ); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - - expect(clientB.getPendingAuthRequests().length, 2); - }); - }); - - group('requestAuth', () { - test('creates correct URI', () async { - AuthRequestResponse response = await clientA.requestAuth( - params: testAuthRequestParamsValid, - ); - - expect(response.uri != null, true); - URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); - expect(parsed.protocol, 'wc'); - expect(parsed.version, URIVersion.v2); - expect(parsed.topic, response.pairingTopic); - expect(parsed.v2Data!.relay.protocol, 'irn'); - if (clientA is IWeb3App) { - expect(parsed.v2Data!.methods.length, 3); - expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); - expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); - expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); - } else { - expect(parsed.v2Data!.methods.length, 1); - expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); - } - - response = await clientA.requestAuth( - params: testAuthRequestParamsValid, - methods: [], - ); - - expect(response.uri != null, true); - parsed = WalletConnectUtils.parseUri(response.uri!); - expect(parsed.protocol, 'wc'); - expect(parsed.version, URIVersion.v2); - expect(parsed.v2Data!.relay.protocol, 'irn'); - expect(parsed.v2Data!.methods.length, 0); - }); - - test('invalid request params', () async { - expect( - () => clientA.requestAuth( - params: testAuthRequestParamsInvalidAud, - ), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', - ), - ), - ); - }); - }); - - group('respondAuth', () { - test('invalid response params', () async { - expect( - () => clientB.respondAuthRequest( - id: -1, - iss: TEST_ISSUER_EIP191, - ), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', - ), - ), - ); - }); - }); - - group('formatAuthMessage', () { - test('works', () { - final String message = clientA.formatAuthMessage( - iss: TEST_ISSUER_EIP191, - cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), - ); - expect(message, TEST_FORMATTED_MESSAGE); - }); - }); - }); -} +// import 'dart:async'; +// import 'dart:typed_data'; + +// import 'package:eth_sig_util/eth_sig_util.dart'; +// import 'package:flutter_test/flutter_test.dart'; +// import 'package:package_info_plus/package_info_plus.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'; +// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +// import '../shared/shared_test_utils.dart'; +// import '../shared/shared_test_values.dart'; +// import 'utils/auth_client_test_wrapper.dart'; +// import 'utils/engine_constants.dart'; +// 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', +// ); + +// final List Function(PairingMetadata)> authAppCreators = +// [ +// (PairingMetadata metadata) async => +// await AuthClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// (PairingMetadata? self) async { +// final core = Core( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ); +// IAuthEngine e = AuthEngine( +// core: core, +// metadata: self ?? PairingMetadata.empty(), +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// await core.start(); +// await e.init(); + +// return e; +// }, +// (PairingMetadata metadata) async => +// await AuthClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// ]; + +// final List Function(PairingMetadata)> +// authWalletCreators = [ +// (PairingMetadata metadata) async => await Web3Wallet.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// (PairingMetadata metadata) async { +// final core = Core( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ); +// IAuthEngine e = AuthEngine( +// core: core, +// metadata: metadata, +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// await core.start(); +// await e.init(); + +// return e; +// }, +// (PairingMetadata metadata) async => await Web3Wallet.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// ]; + +// final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; + +// for (int i = 0; i < authAppCreators.length; i++) { +// runTests( +// context: contexts[i], +// engineAppCreator: authAppCreators[i], +// engineWalletCreator: authWalletCreators[i], +// ); +// } +// } + +// void runTests({ +// required String context, +// required Future Function(PairingMetadata) engineAppCreator, +// required Future Function(PairingMetadata) +// engineWalletCreator, +// }) { +// group(context, () { +// late IAuthEngineApp clientA; +// late IAuthEngineWallet clientB; + +// setUp(() async { +// clientA = await engineAppCreator( +// TEST_METADATA_REQUESTER, +// ); +// clientB = await engineWalletCreator( +// TEST_METADATA_RESPONDER, +// ); +// }); + +// tearDown(() async { +// await clientA.core.relayClient.disconnect(); +// await clientB.core.relayClient.disconnect(); +// }); + +// group('happy path', () { +// test('Initializes', () async { +// expect(clientA.core.pairing.getPairings().length, 0); +// expect(clientB.core.pairing.getPairings().length, 0); +// }); + +// test( +// 'connects and receives request, reconnects and receives another request, and emits proper events', +// () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: defaultRequestParams, +// ); +// final String pairingTopic = response.pairingTopic; + +// Completer completerAPairing = Completer(); +// Completer completerBPairing = Completer(); +// Completer completerA = Completer(); +// Completer completerB = Completer(); +// int counterAPairing = 0; +// int counterBPairing = 0; +// int counterA = 0; +// int counterB = 0; +// clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { +// expect(pairing != null, true); +// expect(pairing!.topic, pairingTopic); +// counterAPairing++; +// completerAPairing.complete(); +// }); +// clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { +// expect(pairing != null, true); +// expect(pairing!.topic, pairingTopic); +// counterBPairing++; +// completerBPairing.complete(); +// }); +// clientA.onAuthResponse.subscribe((AuthResponse? args) { +// counterA++; +// completerA.complete(); + +// expect(args!.result, isNotNull); +// }); +// clientB.onAuthRequest.subscribe((AuthRequest? args) async { +// counterB++; + +// int currReqCount = clientB.getPendingAuthRequests().length; + +// expect(args != null, true); + +// // Create the message to be signed +// String message = clientB.formatAuthMessage( +// iss: TEST_ISSUER_EIP191, +// cacaoPayload: CacaoRequestPayload.fromPayloadParams( +// args!.payloadParams, +// ), +// ); + +// String sig = EthSigUtil.signPersonalMessage( +// message: Uint8List.fromList(message.codeUnits), +// privateKey: TEST_PRIVATE_KEY_EIP191, +// ); + +// await clientB.respondAuthRequest( +// id: args.id, +// iss: TEST_ISSUER_EIP191, +// signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), +// ); + +// expect(clientB.getPendingAuthRequests().length, currReqCount - 1); + +// completerB.complete(); +// }); + +// expect(response.uri != null, true); + +// await clientB.core.pairing.pair(uri: response.uri!); +// expect(clientA.core.pairing.getPairings().length, 1); +// expect(clientB.core.pairing.getPairings().length, 1); +// // AuthResponse authResponse = await response.completer.future; + +// await clientA.core.pairing.ping(topic: pairingTopic); +// await clientB.core.pairing.ping(topic: pairingTopic); + +// if (!completerAPairing.isCompleted) { +// clientA.core.logger.i('Waiting for completerAPairing'); +// await completerAPairing.future; +// } +// if (!completerBPairing.isCompleted) { +// clientA.core.logger.i('Waiting for completerBPairing'); +// await completerBPairing.future; +// } +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } +// if (!completerB.isCompleted) { +// clientA.core.logger.i('Waiting for completerB'); +// await completerB.future; +// } + +// AuthResponse authResponse = await response.completer.future; +// expect(authResponse.result != null, true); + +// expect(counterAPairing, 1); +// expect(counterBPairing, 1); + +// expect(counterA, 1); +// expect(counterB, 1); + +// expect( +// clientA +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 1, +// ); +// expect( +// clientB +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 1, +// ); + +// completerA = Completer(); +// completerB = Completer(); + +// response = await clientA.requestAuth( +// params: defaultRequestParams, +// pairingTopic: pairingTopic, +// ); + +// expect(response.uri == null, true); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } +// if (!completerB.isCompleted) { +// clientA.core.logger.i('Waiting for completerB'); +// await completerB.future; +// } + +// authResponse = await response.completer.future; +// expect(authResponse.result != null, true); + +// // Got the second request and response +// expect(counterA, 2); +// expect(counterB, 2); + +// expect( +// clientA +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 2, +// ); +// expect( +// clientB +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 2, +// ); + +// clientA.onAuthResponse.unsubscribeAll(); +// clientB.onAuthRequest.unsubscribeAll(); +// clientA.core.pairing.onPairingPing.unsubscribeAll(); +// clientB.core.pairing.onPairingPing.unsubscribeAll(); +// }); + +// test('counts pendingAuthRequests properly', () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: defaultRequestParams, +// ); +// final String pairingTopic = response.pairingTopic; + +// await clientB.core.pairing.pair(uri: response.uri!); + +// Completer completerA = Completer(); +// clientB.onAuthRequest.subscribe((AuthRequest? args) async { +// // print('got here'); +// // print(clientB.getPendingAuthRequests().length); +// completerA.complete(); +// }); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } + +// expect(clientB.getPendingAuthRequests().length, 1); + +// completerA = Completer(); + +// response = await clientA.requestAuth( +// params: defaultRequestParams, +// pairingTopic: pairingTopic, +// ); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } + +// expect(clientB.getPendingAuthRequests().length, 2); +// }); +// }); + +// group('requestAuth', () { +// test('creates correct URI', () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: testAuthRequestParamsValid, +// ); + +// expect(response.uri != null, true); +// URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); +// expect(parsed.protocol, 'wc'); +// expect(parsed.version, URIVersion.v2); +// expect(parsed.topic, response.pairingTopic); +// expect(parsed.v2Data!.relay.protocol, 'irn'); +// if (clientA is IWeb3App) { +// expect(parsed.v2Data!.methods.length, 3); +// expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); +// expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); +// expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); +// } else { +// expect(parsed.v2Data!.methods.length, 1); +// expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); +// } + +// response = await clientA.requestAuth( +// params: testAuthRequestParamsValid, +// methods: [], +// ); + +// expect(response.uri != null, true); +// parsed = WalletConnectUtils.parseUri(response.uri!); +// expect(parsed.protocol, 'wc'); +// expect(parsed.version, URIVersion.v2); +// expect(parsed.v2Data!.relay.protocol, 'irn'); +// expect(parsed.v2Data!.methods.length, 0); +// }); + +// test('invalid request params', () async { +// expect( +// () => clientA.requestAuth( +// params: testAuthRequestParamsInvalidAud, +// ), +// throwsA( +// isA().having( +// (e) => e.message, +// 'message', +// 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', +// ), +// ), +// ); +// }); +// }); + +// group('respondAuth', () { +// test('invalid response params', () async { +// expect( +// () => clientB.respondAuthRequest( +// id: -1, +// iss: TEST_ISSUER_EIP191, +// ), +// throwsA( +// isA().having( +// (e) => e.message, +// 'message', +// 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', +// ), +// ), +// ); +// }); +// }); + +// group('formatAuthMessage', () { +// test('works', () { +// final String message = clientA.formatAuthMessage( +// iss: TEST_ISSUER_EIP191, +// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), +// ); +// expect(message, TEST_FORMATTED_MESSAGE); +// }); +// }); +// }); +// } diff --git a/test/auth_api/utils/auth_client_test_wrapper.dart b/test/auth_api/utils/auth_client_test_wrapper.dart index b3d68eb6..730a7059 100644 --- a/test/auth_api/utils/auth_client_test_wrapper.dart +++ b/test/auth_api/utils/auth_client_test_wrapper.dart @@ -1,158 +1,158 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -class AuthClientTestWrapper implements IAuthEngine { - bool _initialized = false; +// class AuthClientTestWrapper implements IAuthEngine { +// bool _initialized = false; - @override - Event get onAuthRequest => client.onAuthRequest; - @override - Event get onAuthResponse => client.onAuthResponse; +// @override +// Event get onAuthRequest => client.onAuthRequest; +// @override +// Event get onAuthResponse => client.onAuthResponse; - @override - ICore get core => client.core; - @override - PairingMetadata get metadata => client.metadata; - @override - IGenericStore get authKeys => client.authKeys; - @override - IGenericStore get pairingTopics => client.pairingTopics; - @override - IGenericStore get authRequests => client.authRequests; - @override - IGenericStore get completeRequests => client.completeRequests; +// @override +// ICore get core => client.core; +// @override +// PairingMetadata get metadata => client.metadata; +// @override +// IGenericStore get authKeys => client.authKeys; +// @override +// IGenericStore get pairingTopics => client.pairingTopics; +// @override +// IGenericStore get authRequests => client.authRequests; +// @override +// IGenericStore get completeRequests => client.completeRequests; - late IAuthClient client; +// late IAuthClient client; - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - LogLevel logLevel = LogLevel.nothing, - IHttpClient httpClient = const HttpWrapper(), - }) async { - final client = AuthClientTestWrapper( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - logLevel: logLevel, - httpClient: httpClient, - ), - metadata: metadata, - ); - await client.init(); +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// LogLevel logLevel = LogLevel.nothing, +// IHttpClient httpClient = const HttpWrapper(), +// }) async { +// final client = AuthClientTestWrapper( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// logLevel: logLevel, +// httpClient: httpClient, +// ), +// metadata: metadata, +// ); +// await client.init(); - return client; - } +// return client; +// } - AuthClientTestWrapper({ - required ICore core, - required PairingMetadata metadata, - }) { - client = AuthClient( - core: core, - metadata: metadata, - ); - } +// AuthClientTestWrapper({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// client = AuthClient( +// core: core, +// metadata: metadata, +// ); +// } - @override - Future init() async { - if (_initialized) { - return; - } +// @override +// Future init() async { +// if (_initialized) { +// return; +// } - await core.start(); - await client.init(); +// await core.start(); +// await client.init(); - _initialized = true; - } +// _initialized = true; +// } - @override - Future requestAuth({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods = AuthEngine.defaultMethods, - }) async { - try { - return client.request( - params: params, - pairingTopic: pairingTopic, - methods: methods, - ); - } catch (e) { - rethrow; - } - } +// @override +// Future requestAuth({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods = AuthEngine.DEFAULT_METHODS, +// }) async { +// try { +// return client.request( +// params: params, +// pairingTopic: pairingTopic, +// methods: methods, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - Future respondAuthRequest({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }) async { - try { - return client.respond( - id: id, - iss: iss, - signature: signature, - error: error, - ); - } catch (e) { - rethrow; - } - } +// @override +// Future respondAuthRequest({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) async { +// try { +// return client.respond( +// id: id, +// iss: iss, +// signature: signature, +// error: error, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - Map getPendingAuthRequests() { - try { - return client.getPendingRequests(); - } catch (e) { - rethrow; - } - } +// @override +// Map getPendingAuthRequests() { +// try { +// return client.getPendingRequests(); +// } catch (e) { +// rethrow; +// } +// } - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return client.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } +// @override +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return client.getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - String formatAuthMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }) { - try { - return client.formatMessage( - iss: iss, - cacaoPayload: cacaoPayload, - ); - } catch (e) { - rethrow; - } - } -} +// @override +// String formatAuthMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }) { +// try { +// return client.formatMessage( +// iss: iss, +// cacaoPayload: cacaoPayload, +// ); +// } catch (e) { +// rethrow; +// } +// } +// } diff --git a/test/sign_api/sign_client_test.dart b/test/sign_api/sign_client_test.dart index ced4babc..4a97e16d 100644 --- a/test/sign_api/sign_client_test.dart +++ b/test/sign_api/sign_client_test.dart @@ -1,43 +1,43 @@ -@Timeout(Duration(seconds: 45)) +// @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 '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'; -import '../shared/shared_test_values.dart'; -import 'tests/sign_common.dart'; -import 'utils/sign_client_test_wrapper.dart'; +// import '../shared/shared_test_utils.dart'; +// import '../shared/shared_test_values.dart'; +// import 'tests/sign_common.dart'; +// 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', - ); +// void main() { +// TestWidgetsFlutterBinding.ensureInitialized(); +// PackageInfo.setMockInitialValues( +// appName: 'walletconnect_flutter_v2', +// packageName: 'com.walletconnect.flutterdapp', +// version: '1.0', +// buildNumber: '2', +// buildSignature: 'buildSignature', +// ); - signEngineTests( - context: 'SignClient', - clientACreator: (PairingMetadata metadata) async => - await SignClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: Level.info, - httpClient: getHttpWrapper(), - ), - clientBCreator: (PairingMetadata metadata) async => - await SignClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: Level.info, - httpClient: getHttpWrapper(), - ), - ); -} +// signEngineTests( +// context: 'SignClient', +// clientACreator: (PairingMetadata metadata) async => +// await SignClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: Level.info, +// httpClient: getHttpWrapper(), +// ), +// clientBCreator: (PairingMetadata metadata) async => +// await SignClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: Level.info, +// httpClient: getHttpWrapper(), +// ), +// ); +// } diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index 6b260a19..2b69514b 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -1,432 +1,432 @@ -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.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/sign_engine.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -class SignClientTestWrapper implements ISignEngine { - bool _initialized = false; - - @override - Event get onSessionDelete => client.onSessionDelete; - @override - Event get onSessionConnect => client.onSessionConnect; - @override - Event get onSessionEvent => client.onSessionEvent; - @override - Event get onSessionExpire => client.onSessionExpire; - @override - Event get onSessionExtend => client.onSessionExtend; - @override - Event get onSessionPing => client.onSessionPing; - @override - Event get onSessionProposal => client.onSessionProposal; - @override - Event get onSessionProposalError => - client.onSessionProposalError; - @override - Event get onProposalExpire => client.onProposalExpire; - @override - Event get onSessionRequest => client.onSessionRequest; - @override - Event get onSessionUpdate => client.onSessionUpdate; - - @override - ICore get core => client.core; - @override - PairingMetadata get metadata => client.metadata; - @override - IGenericStore get proposals => client.proposals; - @override - ISessions get sessions => client.sessions; - @override - IGenericStore get pendingRequests => client.pendingRequests; - - late ISignClient client; - - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - Level logLevel = Level.off, - IHttpClient httpClient = const HttpWrapper(), - }) async { - final client = SignClientTestWrapper( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - httpClient: httpClient, - ), - metadata: metadata, - ); - await client.init(); - - return client; - } - - SignClientTestWrapper({ - required ICore core, - required PairingMetadata metadata, - }) { - client = SignClient( - core: core, - metadata: metadata, - ); - } - - @override - Future init() async { - if (_initialized) { - return; - } - - await core.start(); - await client.init(); - - _initialized = true; - } - - @override - Future connect({ - Map? requiredNamespaces, - Map? optionalNamespaces, - Map? sessionProperties, - String? pairingTopic, - List? relays, - List>? methods = SignEngine.DEFAULT_METHODS, - }) async { - try { - return await client.connect( - requiredNamespaces: requiredNamespaces, - optionalNamespaces: optionalNamespaces, - sessionProperties: sessionProperties, - pairingTopic: pairingTopic, - relays: relays, - methods: methods, - ); - } catch (e) { - // print(e); - rethrow; - } - } - - @override - Future pair({ - required Uri uri, - }) async { - try { - return await client.pair(uri: uri); - } catch (e) { - rethrow; - } - } - - @override - Future approveSession({ - required int id, - required Map namespaces, - Map? sessionProperties, - String? relayProtocol, - }) async { - try { - return await client.approve( - id: id, - namespaces: namespaces, - relayProtocol: relayProtocol, - ); - } catch (e) { - rethrow; - } - } - - @override - Future rejectSession({ - required int id, - required WalletConnectError reason, - }) async { - try { - return await client.reject( - id: id, - reason: reason, - ); - } catch (e) { - rethrow; - } - } - - @override - Future updateSession({ - required String topic, - required Map namespaces, - }) async { - try { - return await client.update( - topic: topic, - namespaces: namespaces, - ); - } catch (e) { - // final error = e as WCError; - rethrow; - } - } - - @override - Future extendSession({ - required String topic, - }) async { - try { - return await client.extend(topic: topic); - } catch (e) { - rethrow; - } - } - - @override - void registerRequestHandler({ - required String chainId, - required String method, - void Function(String, dynamic)? handler, - }) { - try { - return client.registerRequestHandler( - chainId: chainId, - method: method, - handler: handler, - ); - } catch (e) { - rethrow; - } - } - - @override - Future request({ - required String topic, - required String chainId, - required SessionRequestParams request, - }) async { - try { - return await client.request( - topic: topic, - chainId: chainId, - request: request, - ); - } catch (e) { - rethrow; - } - } - - @override - Future> requestReadContract({ - required DeployedContract deployedContract, - required String functionName, - required String rpcUrl, - List parameters = const [], - }) async { - try { - return await client.requestReadContract( - deployedContract: deployedContract, - functionName: functionName, - rpcUrl: rpcUrl, - parameters: parameters, - ); - } catch (e) { - rethrow; - } - } - - @override - 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 [], - }) async { - try { - return await client.requestWriteContract( - topic: topic, - chainId: chainId, - rpcUrl: rpcUrl, - deployedContract: deployedContract, - functionName: functionName, - transaction: transaction, - method: method, - parameters: parameters, - ); - } catch (e) { - rethrow; - } - } - - @override - Future respondSessionRequest({ - required String topic, - required JsonRpcResponse response, - }) { - try { - return client.respond( - topic: topic, - response: response, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerEventHandler({ - required String chainId, - required String event, - dynamic Function(String, dynamic)? handler, - }) { - try { - return client.registerEventHandler( - chainId: chainId, - event: event, - handler: handler, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerEventEmitter({ - required String chainId, - required String event, - }) { - try { - return client.registerEventEmitter( - chainId: chainId, - event: event, - ); - } catch (e) { - rethrow; - } - } - - @override - void registerAccount({ - required String chainId, - required String accountAddress, - }) { - try { - return client.registerAccount( - chainId: chainId, - accountAddress: accountAddress, - ); - } catch (e) { - rethrow; - } - } - - @override - Future emitSessionEvent({ - required String topic, - required String chainId, - required SessionEventParams event, - }) async { - try { - return await client.emit( - topic: topic, - chainId: chainId, - event: event, - ); - } catch (e) { - rethrow; - } - } - - @override - Future ping({ - required String topic, - }) async { - try { - return await client.ping(topic: topic); - } catch (e) { - rethrow; - } - } - - @override - Future disconnectSession({ - required String topic, - required WalletConnectError reason, - }) async { - try { - return await client.disconnect( - topic: topic, - reason: reason, - ); - } catch (e) { - rethrow; - } - } - - @override - SessionData? find({ - required Map requiredNamespaces, - }) { - try { - return client.find(requiredNamespaces: requiredNamespaces); - } catch (e) { - rethrow; - } - } - - @override - Map getActiveSessions() { - try { - return client.getActiveSessions(); - } catch (e) { - rethrow; - } - } - - @override - Map getSessionsForPairing({ - required String pairingTopic, - }) { - try { - return client.getSessionsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingSessionProposals() { - try { - return client.getPendingSessionProposals(); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingSessionRequests() { - try { - return client.getPendingSessionRequests(); - } catch (e) { - rethrow; - } - } - - @override - IPairingStore get pairings => core.pairing.getStore(); - - @override - Future checkAndExpire() async { - for (var session in sessions.getAll()) { - await core.expirer.checkAndExpire(session.topic); - } - } -} +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.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/sign_engine.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +// class SignClientTestWrapper implements ISignEngine { +// bool _initialized = false; + +// @override +// Event get onSessionDelete => client.onSessionDelete; +// @override +// Event get onSessionConnect => client.onSessionConnect; +// @override +// Event get onSessionEvent => client.onSessionEvent; +// @override +// Event get onSessionExpire => client.onSessionExpire; +// @override +// Event get onSessionExtend => client.onSessionExtend; +// @override +// Event get onSessionPing => client.onSessionPing; +// @override +// Event get onSessionProposal => client.onSessionProposal; +// @override +// Event get onSessionProposalError => +// client.onSessionProposalError; +// @override +// Event get onProposalExpire => client.onProposalExpire; +// @override +// Event get onSessionRequest => client.onSessionRequest; +// @override +// Event get onSessionUpdate => client.onSessionUpdate; + +// @override +// ICore get core => client.core; +// @override +// PairingMetadata get metadata => client.metadata; +// @override +// IGenericStore get proposals => client.proposals; +// @override +// ISessions get sessions => client.sessions; +// @override +// IGenericStore get pendingRequests => client.pendingRequests; + +// late ISignClient client; + +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// Level logLevel = Level.off, +// IHttpClient httpClient = const HttpWrapper(), +// }) async { +// final client = SignClientTestWrapper( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// httpClient: httpClient, +// ), +// metadata: metadata, +// ); +// await client.init(); + +// return client; +// } + +// SignClientTestWrapper({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// client = SignClient( +// core: core, +// metadata: metadata, +// ); +// } + +// @override +// Future init() async { +// if (_initialized) { +// return; +// } + +// await core.start(); +// await client.init(); + +// _initialized = true; +// } + +// @override +// Future connect({ +// Map? requiredNamespaces, +// Map? optionalNamespaces, +// Map? sessionProperties, +// String? pairingTopic, +// List? relays, +// List>? methods = SignEngine.DEFAULT_METHODS, +// }) async { +// try { +// return await client.connect( +// requiredNamespaces: requiredNamespaces, +// optionalNamespaces: optionalNamespaces, +// sessionProperties: sessionProperties, +// pairingTopic: pairingTopic, +// relays: relays, +// methods: methods, +// ); +// } catch (e) { +// // print(e); +// rethrow; +// } +// } + +// @override +// Future pair({ +// required Uri uri, +// }) async { +// try { +// return await client.pair(uri: uri); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future approveSession({ +// required int id, +// required Map namespaces, +// Map? sessionProperties, +// String? relayProtocol, +// }) async { +// try { +// return await client.approve( +// id: id, +// namespaces: namespaces, +// relayProtocol: relayProtocol, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future rejectSession({ +// required int id, +// required WalletConnectError reason, +// }) async { +// try { +// return await client.reject( +// id: id, +// reason: reason, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future updateSession({ +// required String topic, +// required Map namespaces, +// }) async { +// try { +// return await client.update( +// topic: topic, +// namespaces: namespaces, +// ); +// } catch (e) { +// // final error = e as WCError; +// rethrow; +// } +// } + +// @override +// Future extendSession({ +// required String topic, +// }) async { +// try { +// return await client.extend(topic: topic); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerRequestHandler({ +// required String chainId, +// required String method, +// void Function(String, dynamic)? handler, +// }) { +// try { +// return client.registerRequestHandler( +// chainId: chainId, +// method: method, +// handler: handler, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future request({ +// required String topic, +// required String chainId, +// required SessionRequestParams request, +// }) async { +// try { +// return await client.request( +// topic: topic, +// chainId: chainId, +// request: request, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future> requestReadContract({ +// required DeployedContract deployedContract, +// required String functionName, +// required String rpcUrl, +// List parameters = const [], +// }) async { +// try { +// return await client.requestReadContract( +// deployedContract: deployedContract, +// functionName: functionName, +// rpcUrl: rpcUrl, +// parameters: parameters, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// 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 [], +// }) async { +// try { +// return await client.requestWriteContract( +// topic: topic, +// chainId: chainId, +// rpcUrl: rpcUrl, +// deployedContract: deployedContract, +// functionName: functionName, +// transaction: transaction, +// method: method, +// parameters: parameters, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future respondSessionRequest({ +// required String topic, +// required JsonRpcResponse response, +// }) { +// try { +// return client.respond( +// topic: topic, +// response: response, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerEventHandler({ +// required String chainId, +// required String event, +// dynamic Function(String, dynamic)? handler, +// }) { +// try { +// return client.registerEventHandler( +// chainId: chainId, +// event: event, +// handler: handler, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerEventEmitter({ +// required String chainId, +// required String event, +// }) { +// try { +// return client.registerEventEmitter( +// chainId: chainId, +// event: event, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// void registerAccount({ +// required String chainId, +// required String accountAddress, +// }) { +// try { +// return client.registerAccount( +// chainId: chainId, +// accountAddress: accountAddress, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future emitSessionEvent({ +// required String topic, +// required String chainId, +// required SessionEventParams event, +// }) async { +// try { +// return await client.emit( +// topic: topic, +// chainId: chainId, +// event: event, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future ping({ +// required String topic, +// }) async { +// try { +// return await client.ping(topic: topic); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future disconnectSession({ +// required String topic, +// required WalletConnectError reason, +// }) async { +// try { +// return await client.disconnect( +// topic: topic, +// reason: reason, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// SessionData? find({ +// required Map requiredNamespaces, +// }) { +// try { +// return client.find(requiredNamespaces: requiredNamespaces); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getActiveSessions() { +// try { +// return client.getActiveSessions(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getSessionsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return client.getSessionsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingSessionProposals() { +// try { +// return client.getPendingSessionProposals(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingSessionRequests() { +// try { +// return client.getPendingSessionRequests(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// IPairingStore get pairings => core.pairing.getStore(); + +// @override +// Future checkAndExpire() async { +// for (var session in sessions.getAll()) { +// await core.expirer.checkAndExpire(session.topic); +// } +// } +// } From 7f95148875a735abdd3491ce2bb76786c2987ef9 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 20 May 2024 13:13:40 +0200 Subject: [PATCH 02/29] preparation for future mixpanel events --- .../lib/dependencies/web3wallet_service.dart | 9 +++++++++ lib/apis/core/core.dart | 12 +++++++++++- lib/apis/core/i_core.dart | 3 +++ lib/apis/core/pairing/pairing.dart | 2 +- lib/apis/core/relay_client/relay_client.dart | 14 +++++++------- lib/apis/core/verify/verify.dart | 5 ++--- lib/apis/sign_api/sign_engine.dart | 2 -- test/shared/shared_test_utils.mocks.dart | 18 ++++++++++++++++++ 8 files changed, 51 insertions(+), 14 deletions(-) diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index d90eb4ef..3a9fb801 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -58,6 +58,7 @@ class Web3WalletService extends IWeb3WalletService { ), ), ); + _web3Wallet!.core.addLogListener(_logListener); // Setup our accounts List chainKeys = await GetIt.I().setKeys(); @@ -104,9 +105,17 @@ class Web3WalletService extends IWeb3WalletService { await _web3Wallet!.init(); } + void _logListener(LogEvent event) { + debugPrint('${event.time} LogEvent ${event.level.name}: ${event.message}'); + if (event.level == Level.error) { + // TODO send to mixpanel + } + } + @override FutureOr onDispose() { debugPrint('[$runtimeType] [WALLET] dispose'); + _web3Wallet!.core.removeLogListener(_logListener); _web3Wallet!.core.pairing.onPairingInvalid.unsubscribe(_onPairingInvalid); _web3Wallet!.core.pairing.onPairingCreate.unsubscribe(_onPairingCreate); _web3Wallet!.onSessionProposal.unsubscribe(_onSessionProposal); diff --git a/lib/apis/core/core.dart b/lib/apis/core/core.dart index 13766119..97296705 100644 --- a/lib/apis/core/core.dart +++ b/lib/apis/core/core.dart @@ -72,6 +72,16 @@ class Core implements ICore { @override Logger get logger => _logger; + @override + void addLogListener(LogCallback callback) { + Logger.addLogListener(callback); + } + + @override + bool removeLogListener(LogCallback callback) { + return Logger.removeLogListener(callback); + } + @override late IStore> storage; @@ -86,7 +96,7 @@ class Core implements ICore { }) { _logger = Logger( level: logLevel.toLevel(), - printer: PrettyPrinter(), + printer: PrettyPrinter(methodCount: null), ); heartbeat = HeartBeat(); storage = SharedPrefsStores( diff --git a/lib/apis/core/i_core.dart b/lib/apis/core/i_core.dart index b713ad22..85f067ad 100644 --- a/lib/apis/core/i_core.dart +++ b/lib/apis/core/i_core.dart @@ -27,5 +27,8 @@ abstract class ICore { abstract final Logger logger; abstract IVerify verify; + void addLogListener(LogCallback callback); + bool removeLogListener(LogCallback callback); + Future start(); } diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index b97a3d22..debab9c4 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -649,7 +649,7 @@ class Pairing implements IPairing { // print(payloadString); Map data = jsonDecode(payloadString); - core.logger.i('Pairing _onMessageEvent, Received data: $data'); + core.logger.t('Pairing _onMessageEvent, Received data: $data'); // If it's an rpc request, handle it // print('Pairing: Received data: $data'); diff --git a/lib/apis/core/relay_client/relay_client.dart b/lib/apis/core/relay_client/relay_client.dart index 8e482da8..699e54a4 100644 --- a/lib/apis/core/relay_client/relay_client.dart +++ b/lib/apis/core/relay_client/relay_client.dart @@ -170,7 +170,7 @@ class RelayClient implements IRelayClient { Future connect({String? relayUrl}) async { _checkInitialized(); - core.logger.i('RelayClient: Connecting to relay'); + core.logger.t('RelayClient: Connecting to relay'); await _connect(relayUrl: relayUrl); } @@ -179,7 +179,7 @@ class RelayClient implements IRelayClient { Future disconnect() async { _checkInitialized(); - core.logger.i('RelayClient: Disconnecting from relay'); + core.logger.t('RelayClient: Disconnecting from relay'); await _disconnect(); } @@ -302,12 +302,12 @@ class RelayClient implements IRelayClient { Future _handleRelayClose(int? code, String? reason) async { if (_handledClose) { - core.logger.i('Relay close already handled'); + core.logger.t('Relay close already handled'); return; } _handledClose = true; - core.logger.i('Handling relay close, code: $code, reason: $reason'); + core.logger.t('Handling relay close, code: $code, reason: $reason'); // If the relay isn't active (Disconnected manually), don't do anything if (!_active) { return; @@ -364,7 +364,7 @@ class RelayClient implements IRelayClient { core.logger.t('Handling Publish Message: $topic, $message'); // If we want to ignore the message, stop if (await _shouldIgnoreMessageEvent(topic, message)) { - core.logger.w('Ignoring Message: $topic, $message'); + core.logger.e('Ignoring Message: $topic, $message'); return false; } @@ -392,7 +392,7 @@ class RelayClient implements IRelayClient { } void _handleUnsubscribe(Parameters params) { - core.logger.i('[$runtimeType] _handleUnsubscribe $params'); + core.logger.t('[$runtimeType] _handleUnsubscribe $params'); } /// MESSAGE HANDLING @@ -441,7 +441,7 @@ class RelayClient implements IRelayClient { JsonRpcUtils.payloadId(entropy: 6), ); } catch (e) { - core.logger.w('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); + core.logger.e('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); onRelayClientError.broadcast(ErrorEvent(e)); } diff --git a/lib/apis/core/verify/verify.dart b/lib/apis/core/verify/verify.dart index 0538c4de..4e63c5c6 100644 --- a/lib/apis/core/verify/verify.dart +++ b/lib/apis/core/verify/verify.dart @@ -30,8 +30,7 @@ class Verify implements IVerify { AttestationResponse? response; try { response = await _fetchAttestation(attestationId, _verifyUrl); - } on AttestationNotFound catch (e) { - _core.logger.i(e.message); + } on AttestationNotFound catch (_) { response = await _fetchAttestation( attestationId, WalletConnectConstants.VERIFY_FALLBACK_SERVER, @@ -75,7 +74,7 @@ class Verify implements IVerify { String url = verifyUrl ?? WalletConnectConstants.VERIFY_SERVER; if (!WalletConnectConstants.TRUSTED_VERIFY_URLS.contains(url)) { - _core.logger.i( + _core.logger.t( '[$runtimeType] verifyUrl $url not included in trusted list, ' 'assigning default: ${WalletConnectConstants.VERIFY_SERVER}', ); diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 9815fb55..70e5e008 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -478,14 +478,12 @@ class SignEngine implements ISignEngine { List parameters = const [], }) async { try { - core.logger.i('readContractCall: with function $functionName'); final results = await Web3Client(rpcUrl, http.Client()).call( contract: deployedContract, function: deployedContract.function(functionName), params: parameters, ); - core.logger.i('readContractCall: $functionName - results: $results'); return results; } catch (e) { rethrow; diff --git a/test/shared/shared_test_utils.mocks.dart b/test/shared/shared_test_utils.mocks.dart index f2f7f851..f0475a40 100644 --- a/test/shared/shared_test_utils.mocks.dart +++ b/test/shared/shared_test_utils.mocks.dart @@ -1337,6 +1337,24 @@ class MockCore extends _i1.Mock implements _i26.Core { ), ) as _i17.Logger); + @override + void addLogListener(_i17.LogCallback? callback) => super.noSuchMethod( + Invocation.method( + #addLogListener, + [callback], + ), + returnValueForMissingStub: null, + ); + + @override + bool removeLogListener(_i17.LogCallback? callback) => (super.noSuchMethod( + Invocation.method( + #removeLogListener, + [callback], + ), + returnValue: false, + ) as bool); + @override _i21.Future start() => (super.noSuchMethod( Invocation.method( From db1f9d16862d7330ff11eb06824983bde76f67f6 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Thu, 23 May 2024 14:39:39 +0200 Subject: [PATCH 03/29] moved auth api method inside sign api --- example/dapp/lib/widgets/auth_item.dart | 3 +- .../lib/dependencies/chains/evm_service.dart | 53 +- .../lib/dependencies/web3wallet_service.dart | 6 +- .../wc_auth_request_model.dart | 2 +- lib/apis/auth_api/auth_engine.dart | 14 +- lib/apis/auth_api/i_auth_engine_app.dart | 4 +- lib/apis/auth_api/i_auth_engine_common.dart | 2 +- lib/apis/auth_api/i_auth_engine_wallet.dart | 4 +- .../auth_api/models/auth_client_events.dart | 76 +- .../auth_api/models/auth_client_models.dart | 652 +++++++++--------- lib/apis/auth_api/models/json_rpc_models.dart | 48 +- lib/apis/auth_api/utils/address_utils.dart | 22 +- .../auth_api/utils/auth_api_validators.dart | 136 ++-- lib/apis/auth_api/utils/auth_constants.dart | 14 +- lib/apis/auth_api/utils/auth_signature.dart | 380 +++++----- lib/apis/auth_api/utils/auth_utils.dart | 10 +- .../utils/secp256k1/auth_secp256k1.dart | 230 +++--- lib/apis/sign_api/i_sign_client.dart | 136 ---- lib/apis/sign_api/i_sign_engine_app.dart | 10 + lib/apis/sign_api/i_sign_engine_common.dart | 17 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 20 + .../models/auth/auth_client_events.dart | 44 ++ .../models/auth/auth_client_models.dart | 326 +++++++++ .../auth}/auth_client_models.freezed.dart | 0 .../models/auth}/auth_client_models.g.dart | 0 .../sign_api/models/auth/json_rpc_models.dart | 29 + .../models/auth}/json_rpc_models.freezed.dart | 0 .../models/auth}/json_rpc_models.g.dart | 0 lib/apis/sign_api/sign_client.dart | 472 ------------- lib/apis/sign_api/sign_engine.dart | 388 ++++++++++- .../sign_api/utils/auth/address_utils.dart | 13 + .../utils/auth/auth_api_validators.dart | 78 +++ .../sign_api/utils/auth/auth_constants.dart | 10 + .../sign_api/utils/auth/auth_signature.dart | 190 +++++ lib/apis/sign_api/utils/auth/auth_utils.dart | 5 + .../sign_api/utils/auth/secp256k1/LICENSE | 7 + .../utils/auth/secp256k1/auth_secp256k1.dart | 115 +++ lib/apis/web3app/i_web3app.dart | 4 +- lib/apis/web3app/web3app.dart | 24 +- lib/apis/web3wallet/i_web3wallet.dart | 4 +- lib/apis/web3wallet/web3wallet.dart | 28 +- lib/walletconnect_flutter_v2.dart | 23 +- test/auth_api/address_utils_test.dart | 2 +- test/auth_api/signature_test.dart | 3 +- test/auth_api/utils/signature_constants.dart | 2 +- test/auth_api/validation_test.dart | 2 +- test/sign_api/sign_engine_test.dart | 64 ++ 47 files changed, 2188 insertions(+), 1484 deletions(-) delete mode 100644 lib/apis/sign_api/i_sign_client.dart create mode 100644 lib/apis/sign_api/models/auth/auth_client_events.dart create mode 100644 lib/apis/sign_api/models/auth/auth_client_models.dart rename lib/apis/{auth_api/models => sign_api/models/auth}/auth_client_models.freezed.dart (100%) rename lib/apis/{auth_api/models => sign_api/models/auth}/auth_client_models.g.dart (100%) create mode 100644 lib/apis/sign_api/models/auth/json_rpc_models.dart rename lib/apis/{auth_api/models => sign_api/models/auth}/json_rpc_models.freezed.dart (100%) rename lib/apis/{auth_api/models => sign_api/models/auth}/json_rpc_models.g.dart (100%) delete mode 100644 lib/apis/sign_api/sign_client.dart create mode 100644 lib/apis/sign_api/utils/auth/address_utils.dart create mode 100644 lib/apis/sign_api/utils/auth/auth_api_validators.dart create mode 100644 lib/apis/sign_api/utils/auth/auth_constants.dart create mode 100644 lib/apis/sign_api/utils/auth/auth_signature.dart create mode 100644 lib/apis/sign_api/utils/auth/auth_utils.dart create mode 100644 lib/apis/sign_api/utils/auth/secp256k1/LICENSE create mode 100644 lib/apis/sign_api/utils/auth/secp256k1/auth_secp256k1.dart diff --git a/example/dapp/lib/widgets/auth_item.dart b/example/dapp/lib/widgets/auth_item.dart index 26c1151d..611e255f 100644 --- a/example/dapp/lib/widgets/auth_item.dart +++ b/example/dapp/lib/widgets/auth_item.dart @@ -1,7 +1,8 @@ import 'package:flutter/material.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_dapp/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; + class AuthItem extends StatelessWidget { const AuthItem({ required Key key, diff --git a/example/wallet/lib/dependencies/chains/evm_service.dart b/example/wallet/lib/dependencies/chains/evm_service.dart index 8b84f960..44d4d110 100644 --- a/example/wallet/lib/dependencies/chains/evm_service.dart +++ b/example/wallet/lib/dependencies/chains/evm_service.dart @@ -29,7 +29,7 @@ class EVMService { 'eth_signTransaction': ethSignTransaction, 'eth_signTypedData': ethSignTypedData, 'eth_signTypedData_v4': ethSignTypedDataV4, - // 'wallet_switchEthereumChain': switchChain, + 'wallet_switchEthereumChain': switchChain, // 'wallet_addEthereumChain': addChain, }; @@ -339,21 +339,42 @@ class EVMService { CommonMethods.goBackToDapp(topic, response.result ?? response.error); } - // Future switchChain(String topic, dynamic parameters) async { - // debugPrint('[WALLET] switchChain request: $topic $parameters'); - // final params = (parameters as List).first as Map; - // final hexChainId = params['chainId'].toString().replaceFirst('0x', ''); - // final chainId = int.parse(hexChainId, radix: 16); - // await _web3Wallet.emitSessionEvent( - // topic: topic, - // chainId: 'eip155:$chainId', - // event: SessionEventParams( - // name: 'chainChanged', - // data: chainId, - // ), - // ); - // CommonMethods.goBackToDapp(topic, true); - // } + Future switchChain(String topic, dynamic parameters) async { + debugPrint('[WALLET] switchChain request: $topic $parameters'); + final pRequest = _web3Wallet.pendingRequests.getAll().last; + var response = JsonRpcResponse(id: pRequest.id, jsonrpc: '2.0'); + try { + final params = (parameters as List).first as Map; + final hexChainId = params['chainId'].toString().replaceFirst('0x', ''); + final chainId = int.parse(hexChainId, radix: 16); + await _web3Wallet.emitSessionEvent( + topic: topic, + chainId: 'eip155:$chainId', + event: SessionEventParams( + name: 'chainChanged', + data: chainId, + ), + ); + response = response.copyWith(result: true); + } on WalletConnectError catch (e) { + debugPrint('[WALLET] switchChain error $e'); + response = response.copyWith( + error: JsonRpcError(code: e.code, message: e.message), + ); + } catch (e) { + debugPrint('[WALLET] switchChain error $e'); + response = response.copyWith( + error: JsonRpcError(code: 0, message: e.toString()), + ); + } + + await _web3Wallet.respondSessionRequest( + topic: topic, + response: response, + ); + + CommonMethods.goBackToDapp(topic, true); + } // Future addChain(String topic, dynamic parameters) async { // debugPrint('[WALLET] addChain request: $topic $parameters'); diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 531ed0b1..6d9ff280 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -1,4 +1,6 @@ import 'dart:async'; +import 'dart:convert'; +import 'dart:developer'; import 'dart:typed_data'; import 'package:eth_sig_util/eth_sig_util.dart'; @@ -148,8 +150,8 @@ class Web3WalletService extends IWeb3WalletService { } void _onSessionProposal(SessionProposalEvent? args) async { - debugPrint('[$runtimeType] [WALLET] _onSessionProposal $args'); if (args != null) { + log('[$runtimeType] [WALLET] _onSessionProposal ${jsonEncode(args.params)}'); final approved = await _bottomSheetHandler.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionRequestWidget( @@ -228,8 +230,8 @@ class Web3WalletService extends IWeb3WalletService { } void _onSessionConnect(SessionConnect? args) { - debugPrint('[$runtimeType] [WALLET] _onSessionConnect $args'); if (args != null) { + log('[$runtimeType] [WALLET] _onSessionConnect ${jsonEncode(args.session)}'); final scheme = args.session.peer.metadata.redirect?.native ?? ''; DeepLinkHandler.goTo(scheme); } diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart b/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart index cf5efd26..61df3e1d 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; class WCAuthRequestModel { final String iss; diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index 670e3a8c..9c52e1bf 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -2,14 +2,14 @@ import 'dart:async'; import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/json_rpc_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/json_rpc_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/address_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_api_validators.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_signature.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_api_validators.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; diff --git a/lib/apis/auth_api/i_auth_engine_app.dart b/lib/apis/auth_api/i_auth_engine_app.dart index 925a49b6..4fa6ea19 100644 --- a/lib/apis/auth_api/i_auth_engine_app.dart +++ b/lib/apis/auth_api/i_auth_engine_app.dart @@ -1,7 +1,7 @@ import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; abstract class IAuthEngineApp extends IAuthEngineCommon { abstract final Event onAuthResponse; diff --git a/lib/apis/auth_api/i_auth_engine_common.dart b/lib/apis/auth_api/i_auth_engine_common.dart index d51c4690..36c9e9b2 100644 --- a/lib/apis/auth_api/i_auth_engine_common.dart +++ b/lib/apis/auth_api/i_auth_engine_common.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; diff --git a/lib/apis/auth_api/i_auth_engine_wallet.dart b/lib/apis/auth_api/i_auth_engine_wallet.dart index 323aa30c..c35781cf 100644 --- a/lib/apis/auth_api/i_auth_engine_wallet.dart +++ b/lib/apis/auth_api/i_auth_engine_wallet.dart @@ -1,7 +1,7 @@ import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; diff --git a/lib/apis/auth_api/models/auth_client_events.dart b/lib/apis/auth_api/models/auth_client_events.dart index aa6f0b67..29ae6bce 100644 --- a/lib/apis/auth_api/models/auth_client_events.dart +++ b/lib/apis/auth_api/models/auth_client_events.dart @@ -1,44 +1,44 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; -class AuthRequest extends EventArgs { - final int id; - final String topic; - final AuthPayloadParams payloadParams; - final ConnectionMetadata requester; +// class AuthRequest extends EventArgs { +// final int id; +// final String topic; +// final AuthPayloadParams payloadParams; +// final ConnectionMetadata requester; - AuthRequest({ - required this.id, - required this.topic, - required this.payloadParams, - required this.requester, - }); +// AuthRequest({ +// required this.id, +// required this.topic, +// required this.payloadParams, +// required this.requester, +// }); - @override - String toString() { - return 'AuthRequest(id: $id, topic: $topic, payloadParams: $payloadParams, requester: $requester)'; - } -} +// @override +// String toString() { +// return 'AuthRequest(id: $id, topic: $topic, payloadParams: $payloadParams, requester: $requester)'; +// } +// } -class AuthResponse extends EventArgs { - final int id; - final String topic; - final Cacao? result; - final WalletConnectError? error; - final JsonRpcError? jsonRpcError; +// class AuthResponse extends EventArgs { +// final int id; +// final String topic; +// final Cacao? result; +// final WalletConnectError? error; +// final JsonRpcError? jsonRpcError; - AuthResponse({ - required this.id, - required this.topic, - this.result, - this.error, - this.jsonRpcError, - }); +// AuthResponse({ +// required this.id, +// required this.topic, +// this.result, +// this.error, +// this.jsonRpcError, +// }); - @override - String toString() { - return 'AuthResponse(id: $id, topic: $topic, result: $result, error: $error, jsonRpcError: $jsonRpcError)'; - } -} +// @override +// String toString() { +// return 'AuthResponse(id: $id, topic: $topic, result: $result, error: $error, jsonRpcError: $jsonRpcError)'; +// } +// } diff --git a/lib/apis/auth_api/models/auth_client_models.dart b/lib/apis/auth_api/models/auth_client_models.dart index d42eb135..94e751cf 100644 --- a/lib/apis/auth_api/models/auth_client_models.dart +++ b/lib/apis/auth_api/models/auth_client_models.dart @@ -1,326 +1,326 @@ -import 'dart:async'; - -import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; - -part 'auth_client_models.g.dart'; -part 'auth_client_models.freezed.dart'; - -class AuthRequestResponse { - final int id; - final String pairingTopic; - final Completer completer; - final Uri? uri; - - AuthRequestResponse({ - required this.id, - required this.pairingTopic, - required this.completer, - this.uri, - }); -} - -@freezed -class AuthPublicKey with _$AuthPublicKey { - @JsonSerializable(includeIfNull: false) - const factory AuthPublicKey({ - required String publicKey, - }) = _AuthPublicKey; - - factory AuthPublicKey.fromJson(Map json) => - _$AuthPublicKeyFromJson(json); -} - -class AuthRequestParams { - /// The Chain ID. - /// Examples: eip155:1 (Eth Mainnet), eip155:43114 (Avalanche) - final String chainId; - - /// The complete URL you are logging into. - /// Example: https://example.com/login - final String aud; - - /// The domain you are logging in to. - /// Example: example.com - /// Domain must exist within the aud, or validation will fail - final String domain; - final String nonce; - final String? type; - final String? nbf; - final String? exp; - final String? statement; - final String? requestId; - final List? resources; - final int? expiry; - - AuthRequestParams({ - required this.chainId, - required this.domain, - required this.aud, - String? nonce, - this.type = CacaoHeader.EIP4361, - this.nbf, - this.exp, - this.statement, - this.requestId, - this.resources, - this.expiry, - }) : nonce = nonce ?? AuthUtils.generateNonce(); - - Map toJson() => { - 'chainId': chainId, - 'aud': aud, - 'domain': domain, - 'nonce': nonce, - if (type != null) 'type': type, - if (nbf != null) 'nbf': nbf, - if (exp != null) 'exp': exp, - if (statement != null) 'statement': statement, - if (requestId != null) 'requestId': requestId, - if (resources != null) 'resources': resources, - if (expiry != null) 'expiry': expiry, - }; -} - -@freezed -class AuthPayloadParams with _$AuthPayloadParams { - @JsonSerializable(includeIfNull: false) - const factory AuthPayloadParams({ - required String type, - required String chainId, - required String domain, - required String aud, - required String version, - required String nonce, - required String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources, - }) = _AuthPayloadParams; - - factory AuthPayloadParams.fromRequestParams(AuthRequestParams params) { - return AuthPayloadParams( - type: params.type ?? CacaoHeader.EIP4361, - chainId: params.chainId, - domain: params.domain, - aud: params.aud, - version: '1', - nonce: params.nonce, - iat: DateTime.now().toIso8601String(), - nbf: params.nbf, - exp: params.exp, - statement: params.statement, - requestId: params.requestId, - resources: params.resources, - ); - } - - factory AuthPayloadParams.fromJson(Map json) => - _$AuthPayloadParamsFromJson(json); -} - -@freezed -class CacaoRequestPayload with _$CacaoRequestPayload { - @JsonSerializable(includeIfNull: false) - const factory CacaoRequestPayload({ - required String domain, - required String aud, - required String version, - required String nonce, - required String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources, - }) = _CacaoRequestPayload; - - factory CacaoRequestPayload.fromPayloadParams(AuthPayloadParams params) { - return CacaoRequestPayload( - domain: params.domain, - aud: params.aud, - version: params.version, - nonce: params.nonce, - iat: params.iat, - nbf: params.nbf, - exp: params.exp, - statement: params.statement, - requestId: params.requestId, - resources: params.resources, - ); - } - - factory CacaoRequestPayload.fromCacaoPayload(CacaoPayload payload) { - return CacaoRequestPayload( - domain: payload.domain, - aud: payload.aud, - version: payload.version, - nonce: payload.nonce, - iat: payload.iat, - nbf: payload.nbf, - exp: payload.exp, - statement: payload.statement, - requestId: payload.requestId, - resources: payload.resources, - ); - } - - factory CacaoRequestPayload.fromJson(Map json) => - _$CacaoRequestPayloadFromJson(json); -} - -@freezed -class CacaoPayload with _$CacaoPayload { - @JsonSerializable(includeIfNull: false) - const factory CacaoPayload({ - required String iss, - required String domain, - required String aud, - required String version, - required String nonce, - required String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources, - }) = _CacaoPayload; - - factory CacaoPayload.fromRequestPayload({ - required String issuer, - required CacaoRequestPayload payload, - }) { - return CacaoPayload( - iss: issuer, - domain: payload.domain, - aud: payload.aud, - version: payload.version, - nonce: payload.nonce, - iat: payload.iat, - nbf: payload.nbf, - exp: payload.exp, - statement: payload.statement, - requestId: payload.requestId, - resources: payload.resources, - ); - } - - factory CacaoPayload.fromJson(Map json) => - _$CacaoPayloadFromJson(json); -} - -@freezed -class CacaoHeader with _$CacaoHeader { - static const EIP4361 = 'eip4361'; - - @JsonSerializable(includeIfNull: false) - const factory CacaoHeader({ - @Default('eip4361') String t, - }) = _CacaoHeader; - - factory CacaoHeader.fromJson(Map json) => - _$CacaoHeaderFromJson(json); -} - -@freezed -class CacaoSignature with _$CacaoSignature { - static const EIP191 = 'eip191'; - static const EIP1271 = 'eip1271'; - - @JsonSerializable(includeIfNull: false) - const factory CacaoSignature({ - required String t, - required String s, - String? m, - }) = _CacaoSignature; - - factory CacaoSignature.fromJson(Map json) => - _$CacaoSignatureFromJson(json); -} - -@freezed -class Cacao with _$Cacao { - @JsonSerializable(includeIfNull: false) - const factory Cacao({ - required CacaoHeader h, - required CacaoPayload p, - required CacaoSignature s, - }) = _Cacao; - - factory Cacao.fromJson(Map json) => _$CacaoFromJson(json); -} - -@freezed -class StoredCacao with _$StoredCacao { - @JsonSerializable(includeIfNull: false) - const factory StoredCacao({ - required int id, - required String pairingTopic, - required CacaoHeader h, - required CacaoPayload p, - required CacaoSignature s, - }) = _StoredCacao; - - factory StoredCacao.fromCacao({ - required int id, - required String pairingTopic, - required Cacao cacao, - }) { - return StoredCacao( - id: id, - pairingTopic: pairingTopic, - h: cacao.h, - p: cacao.p, - s: cacao.s, - ); - } - - factory StoredCacao.fromJson(Map json) => - _$StoredCacaoFromJson(json); -} - -@freezed -class PendingAuthRequest with _$PendingAuthRequest { - @JsonSerializable(includeIfNull: false) - const factory PendingAuthRequest({ - required int id, - required String pairingTopic, - required ConnectionMetadata metadata, - required CacaoRequestPayload cacaoPayload, - }) = _PendingAuthRequest; - - factory PendingAuthRequest.fromJson(Map json) => - _$PendingAuthRequestFromJson(json); -} - -class AuthRequestCompleter { - final int id; - final String pairingTopic; - final String responseTopic; - final PendingAuthRequest request; - final Completer completer; - - AuthRequestCompleter({ - required this.id, - required this.pairingTopic, - required this.responseTopic, - required this.request, - required this.completer, - }); -} - -class RespondParams { - final int id; - final CacaoSignature? signature; - final WalletConnectError? error; - - RespondParams({ - required this.id, - this.signature, - this.error, - }); -} +// import 'dart:async'; + +// import 'package:freezed_annotation/freezed_annotation.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_utils.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; + +// part 'auth_client_models.g.dart'; +// part 'auth_client_models.freezed.dart'; + +// class AuthRequestResponse { +// final int id; +// final String pairingTopic; +// final Completer completer; +// final Uri? uri; + +// AuthRequestResponse({ +// required this.id, +// required this.pairingTopic, +// required this.completer, +// this.uri, +// }); +// } + +// @freezed +// class AuthPublicKey with _$AuthPublicKey { +// @JsonSerializable(includeIfNull: false) +// const factory AuthPublicKey({ +// required String publicKey, +// }) = _AuthPublicKey; + +// factory AuthPublicKey.fromJson(Map json) => +// _$AuthPublicKeyFromJson(json); +// } + +// class AuthRequestParams { +// /// The Chain ID. +// /// Examples: eip155:1 (Eth Mainnet), eip155:43114 (Avalanche) +// final String chainId; + +// /// The complete URL you are logging into. +// /// Example: https://example.com/login +// final String aud; + +// /// The domain you are logging in to. +// /// Example: example.com +// /// Domain must exist within the aud, or validation will fail +// final String domain; +// final String nonce; +// final String? type; +// final String? nbf; +// final String? exp; +// final String? statement; +// final String? requestId; +// final List? resources; +// final int? expiry; + +// AuthRequestParams({ +// required this.chainId, +// required this.domain, +// required this.aud, +// String? nonce, +// this.type = CacaoHeader.EIP4361, +// this.nbf, +// this.exp, +// this.statement, +// this.requestId, +// this.resources, +// this.expiry, +// }) : nonce = nonce ?? AuthUtils.generateNonce(); + +// Map toJson() => { +// 'chainId': chainId, +// 'aud': aud, +// 'domain': domain, +// 'nonce': nonce, +// if (type != null) 'type': type, +// if (nbf != null) 'nbf': nbf, +// if (exp != null) 'exp': exp, +// if (statement != null) 'statement': statement, +// if (requestId != null) 'requestId': requestId, +// if (resources != null) 'resources': resources, +// if (expiry != null) 'expiry': expiry, +// }; +// } + +// @freezed +// class AuthPayloadParams with _$AuthPayloadParams { +// @JsonSerializable(includeIfNull: false) +// const factory AuthPayloadParams({ +// required String type, +// required String chainId, +// required String domain, +// required String aud, +// required String version, +// required String nonce, +// required String iat, +// String? nbf, +// String? exp, +// String? statement, +// String? requestId, +// List? resources, +// }) = _AuthPayloadParams; + +// factory AuthPayloadParams.fromRequestParams(AuthRequestParams params) { +// return AuthPayloadParams( +// type: params.type ?? CacaoHeader.EIP4361, +// chainId: params.chainId, +// domain: params.domain, +// aud: params.aud, +// version: '1', +// nonce: params.nonce, +// iat: DateTime.now().toIso8601String(), +// nbf: params.nbf, +// exp: params.exp, +// statement: params.statement, +// requestId: params.requestId, +// resources: params.resources, +// ); +// } + +// factory AuthPayloadParams.fromJson(Map json) => +// _$AuthPayloadParamsFromJson(json); +// } + +// @freezed +// class CacaoRequestPayload with _$CacaoRequestPayload { +// @JsonSerializable(includeIfNull: false) +// const factory CacaoRequestPayload({ +// required String domain, +// required String aud, +// required String version, +// required String nonce, +// required String iat, +// String? nbf, +// String? exp, +// String? statement, +// String? requestId, +// List? resources, +// }) = _CacaoRequestPayload; + +// factory CacaoRequestPayload.fromPayloadParams(AuthPayloadParams params) { +// return CacaoRequestPayload( +// domain: params.domain, +// aud: params.aud, +// version: params.version, +// nonce: params.nonce, +// iat: params.iat, +// nbf: params.nbf, +// exp: params.exp, +// statement: params.statement, +// requestId: params.requestId, +// resources: params.resources, +// ); +// } + +// factory CacaoRequestPayload.fromCacaoPayload(CacaoPayload payload) { +// return CacaoRequestPayload( +// domain: payload.domain, +// aud: payload.aud, +// version: payload.version, +// nonce: payload.nonce, +// iat: payload.iat, +// nbf: payload.nbf, +// exp: payload.exp, +// statement: payload.statement, +// requestId: payload.requestId, +// resources: payload.resources, +// ); +// } + +// factory CacaoRequestPayload.fromJson(Map json) => +// _$CacaoRequestPayloadFromJson(json); +// } + +// @freezed +// class CacaoPayload with _$CacaoPayload { +// @JsonSerializable(includeIfNull: false) +// const factory CacaoPayload({ +// required String iss, +// required String domain, +// required String aud, +// required String version, +// required String nonce, +// required String iat, +// String? nbf, +// String? exp, +// String? statement, +// String? requestId, +// List? resources, +// }) = _CacaoPayload; + +// factory CacaoPayload.fromRequestPayload({ +// required String issuer, +// required CacaoRequestPayload payload, +// }) { +// return CacaoPayload( +// iss: issuer, +// domain: payload.domain, +// aud: payload.aud, +// version: payload.version, +// nonce: payload.nonce, +// iat: payload.iat, +// nbf: payload.nbf, +// exp: payload.exp, +// statement: payload.statement, +// requestId: payload.requestId, +// resources: payload.resources, +// ); +// } + +// factory CacaoPayload.fromJson(Map json) => +// _$CacaoPayloadFromJson(json); +// } + +// @freezed +// class CacaoHeader with _$CacaoHeader { +// static const EIP4361 = 'eip4361'; + +// @JsonSerializable(includeIfNull: false) +// const factory CacaoHeader({ +// @Default('eip4361') String t, +// }) = _CacaoHeader; + +// factory CacaoHeader.fromJson(Map json) => +// _$CacaoHeaderFromJson(json); +// } + +// @freezed +// class CacaoSignature with _$CacaoSignature { +// static const EIP191 = 'eip191'; +// static const EIP1271 = 'eip1271'; + +// @JsonSerializable(includeIfNull: false) +// const factory CacaoSignature({ +// required String t, +// required String s, +// String? m, +// }) = _CacaoSignature; + +// factory CacaoSignature.fromJson(Map json) => +// _$CacaoSignatureFromJson(json); +// } + +// @freezed +// class Cacao with _$Cacao { +// @JsonSerializable(includeIfNull: false) +// const factory Cacao({ +// required CacaoHeader h, +// required CacaoPayload p, +// required CacaoSignature s, +// }) = _Cacao; + +// factory Cacao.fromJson(Map json) => _$CacaoFromJson(json); +// } + +// @freezed +// class StoredCacao with _$StoredCacao { +// @JsonSerializable(includeIfNull: false) +// const factory StoredCacao({ +// required int id, +// required String pairingTopic, +// required CacaoHeader h, +// required CacaoPayload p, +// required CacaoSignature s, +// }) = _StoredCacao; + +// factory StoredCacao.fromCacao({ +// required int id, +// required String pairingTopic, +// required Cacao cacao, +// }) { +// return StoredCacao( +// id: id, +// pairingTopic: pairingTopic, +// h: cacao.h, +// p: cacao.p, +// s: cacao.s, +// ); +// } + +// factory StoredCacao.fromJson(Map json) => +// _$StoredCacaoFromJson(json); +// } + +// @freezed +// class PendingAuthRequest with _$PendingAuthRequest { +// @JsonSerializable(includeIfNull: false) +// const factory PendingAuthRequest({ +// required int id, +// required String pairingTopic, +// required ConnectionMetadata metadata, +// required CacaoRequestPayload cacaoPayload, +// }) = _PendingAuthRequest; + +// factory PendingAuthRequest.fromJson(Map json) => +// _$PendingAuthRequestFromJson(json); +// } + +// class AuthRequestCompleter { +// final int id; +// final String pairingTopic; +// final String responseTopic; +// final PendingAuthRequest request; +// final Completer completer; + +// AuthRequestCompleter({ +// required this.id, +// required this.pairingTopic, +// required this.responseTopic, +// required this.request, +// required this.completer, +// }); +// } + +// class RespondParams { +// final int id; +// final CacaoSignature? signature; +// final WalletConnectError? error; + +// RespondParams({ +// required this.id, +// this.signature, +// this.error, +// }); +// } diff --git a/lib/apis/auth_api/models/json_rpc_models.dart b/lib/apis/auth_api/models/json_rpc_models.dart index 4ca5e008..2b86511f 100644 --- a/lib/apis/auth_api/models/json_rpc_models.dart +++ b/lib/apis/auth_api/models/json_rpc_models.dart @@ -1,29 +1,29 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:freezed_annotation/freezed_annotation.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -part 'json_rpc_models.g.dart'; -part 'json_rpc_models.freezed.dart'; +// part 'json_rpc_models.g.dart'; +// part 'json_rpc_models.freezed.dart'; -@freezed -class WcAuthRequestRequest with _$WcAuthRequestRequest { - @JsonSerializable() - const factory WcAuthRequestRequest({ - required AuthPayloadParams payloadParams, - required ConnectionMetadata requester, - }) = _WcAuthRequestRequest; +// @freezed +// class WcAuthRequestRequest with _$WcAuthRequestRequest { +// @JsonSerializable() +// const factory WcAuthRequestRequest({ +// required AuthPayloadParams payloadParams, +// required ConnectionMetadata requester, +// }) = _WcAuthRequestRequest; - factory WcAuthRequestRequest.fromJson(Map json) => - _$WcAuthRequestRequestFromJson(json); -} +// factory WcAuthRequestRequest.fromJson(Map json) => +// _$WcAuthRequestRequestFromJson(json); +// } -@freezed -class WcAuthRequestResult with _$WcAuthRequestResult { - @JsonSerializable() - const factory WcAuthRequestResult({ - required Cacao cacao, - }) = _WcAuthRequestResult; +// @freezed +// class WcAuthRequestResult with _$WcAuthRequestResult { +// @JsonSerializable() +// const factory WcAuthRequestResult({ +// required Cacao cacao, +// }) = _WcAuthRequestResult; - factory WcAuthRequestResult.fromJson(Map json) => - _$WcAuthRequestResultFromJson(json); -} +// factory WcAuthRequestResult.fromJson(Map json) => +// _$WcAuthRequestResultFromJson(json); +// } diff --git a/lib/apis/auth_api/utils/address_utils.dart b/lib/apis/auth_api/utils/address_utils.dart index 77acd45e..2126c1f0 100644 --- a/lib/apis/auth_api/utils/address_utils.dart +++ b/lib/apis/auth_api/utils/address_utils.dart @@ -1,13 +1,13 @@ -class AddressUtils { - static String getDidAddress(String iss) { - return iss.split(':').last; - } +// class AddressUtils { +// static String getDidAddress(String iss) { +// return iss.split(':').last; +// } - static String getDidChainId(String iss) { - return iss.split(':')[3]; - } +// static String getDidChainId(String iss) { +// return iss.split(':')[3]; +// } - static String getNamespaceDidChainId(String iss) { - return iss.substring(iss.indexOf(RegExp(r':')) + 1); - } -} +// static String getNamespaceDidChainId(String iss) { +// return iss.substring(iss.indexOf(RegExp(r':')) + 1); +// } +// } diff --git a/lib/apis/auth_api/utils/auth_api_validators.dart b/lib/apis/auth_api/utils/auth_api_validators.dart index 8d43c28c..3be9009b 100644 --- a/lib/apis/auth_api/utils/auth_api_validators.dart +++ b/lib/apis/auth_api/utils/auth_api_validators.dart @@ -1,78 +1,78 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -class AuthApiValidators { - static bool isValidRequestExpiry(int expiry) { - return AuthConstants.AUTH_REQUEST_EXPIRY_MIN <= expiry && - expiry <= AuthConstants.AUTH_REQUEST_EXPIRY_MAX; - } +// class AuthApiValidators { +// static bool isValidRequestExpiry(int expiry) { +// return AuthConstants.AUTH_REQUEST_EXPIRY_MIN <= expiry && +// expiry <= AuthConstants.AUTH_REQUEST_EXPIRY_MAX; +// } - static bool isValidRequest(AuthRequestParams params) { - if (!NamespaceUtils.isValidUrl(params.aud)) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: - 'requestAuth() invalid aud: ${params.aud}. Must be a valid url.', - ); - } - // final validChainId = true; //NamespaceUtils.isValidChainId(params.chainId); +// static bool isValidRequest(AuthRequestParams params) { +// if (!NamespaceUtils.isValidUrl(params.aud)) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: +// 'requestAuth() invalid aud: ${params.aud}. Must be a valid url.', +// ); +// } +// // final validChainId = true; //NamespaceUtils.isValidChainId(params.chainId); - if (!params.aud.contains(params.domain)) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: - 'requestAuth() invalid domain: ${params.domain}. aud must contain domain.', - ); - } +// if (!params.aud.contains(params.domain)) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: +// 'requestAuth() invalid domain: ${params.domain}. aud must contain domain.', +// ); +// } - if (params.nonce.isEmpty) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: 'requestAuth() nonce must be nonempty.', - ); - } +// if (params.nonce.isEmpty) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: 'requestAuth() nonce must be nonempty.', +// ); +// } - // params.type == null || params.type == CacaoHeader.EIP4361 - if (params.type != null && params.type != CacaoHeader.EIP4361) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: 'requestAuth() type must null or ${CacaoHeader.EIP4361}.', - ); - } +// // params.type == null || params.type == CacaoHeader.EIP4361 +// if (params.type != null && params.type != CacaoHeader.EIP4361) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: 'requestAuth() type must null or ${CacaoHeader.EIP4361}.', +// ); +// } - final expiry = params.expiry; - if (expiry != null && !isValidRequestExpiry(expiry)) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: - 'requestAuth() expiry: $expiry. Expiry must be a number (in seconds) between ${AuthConstants.AUTH_REQUEST_EXPIRY_MIN} and ${AuthConstants.AUTH_REQUEST_EXPIRY_MAX}', - ); - } +// final expiry = params.expiry; +// if (expiry != null && !isValidRequestExpiry(expiry)) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: +// 'requestAuth() expiry: $expiry. Expiry must be a number (in seconds) between ${AuthConstants.AUTH_REQUEST_EXPIRY_MIN} and ${AuthConstants.AUTH_REQUEST_EXPIRY_MAX}', +// ); +// } - return true; - } +// return true; +// } - static bool isValidRespond({ - required int id, - required Map pendingRequests, - CacaoSignature? signature, - WalletConnectError? error, - }) { - if (!pendingRequests.containsKey(id)) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: 'respondAuth() invalid id: $id. No pending request found.', - ); - } +// static bool isValidRespond({ +// required int id, +// required Map pendingRequests, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) { +// if (!pendingRequests.containsKey(id)) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: 'respondAuth() invalid id: $id. No pending request found.', +// ); +// } - if (signature == null && error == null) { - throw Errors.getInternalError( - Errors.MISSING_OR_INVALID, - context: - 'respondAuth() invalid response. Must contain either signature or error.', - ); - } +// if (signature == null && error == null) { +// throw Errors.getInternalError( +// Errors.MISSING_OR_INVALID, +// context: +// 'respondAuth() invalid response. Must contain either signature or error.', +// ); +// } - return true; - } -} +// return true; +// } +// } diff --git a/lib/apis/auth_api/utils/auth_constants.dart b/lib/apis/auth_api/utils/auth_constants.dart index 9450479c..a558c25c 100644 --- a/lib/apis/auth_api/utils/auth_constants.dart +++ b/lib/apis/auth_api/utils/auth_constants.dart @@ -1,10 +1,10 @@ -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -class AuthConstants { - static const AUTH_REQUEST_EXPIRY_MIN = WalletConnectConstants.FIVE_MINUTES; - static const AUTH_REQUEST_EXPIRY_MAX = WalletConnectConstants.SEVEN_DAYS; +// class AuthConstants { +// static const AUTH_REQUEST_EXPIRY_MIN = WalletConnectConstants.FIVE_MINUTES; +// static const AUTH_REQUEST_EXPIRY_MAX = WalletConnectConstants.SEVEN_DAYS; - static const AUTH_DEFAULT_URL = 'https://rpc.walletconnect.com/v1'; +// static const AUTH_DEFAULT_URL = 'https://rpc.walletconnect.com/v1'; - static const AUTH_CLIENT_PUBLIC_KEY_NAME = 'PUB_KEY'; -} +// static const AUTH_CLIENT_PUBLIC_KEY_NAME = 'PUB_KEY'; +// } diff --git a/lib/apis/auth_api/utils/auth_signature.dart b/lib/apis/auth_api/utils/auth_signature.dart index a860fe8a..93a8adfe 100644 --- a/lib/apis/auth_api/utils/auth_signature.dart +++ b/lib/apis/auth_api/utils/auth_signature.dart @@ -1,190 +1,190 @@ -import 'dart:convert'; -import 'dart:typed_data'; -import 'package:convert/convert.dart'; -import 'package:http/http.dart' as http; - -import 'package:pointycastle/digests/keccak.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -import 'package:web3dart/crypto.dart' as crypto; - -class AuthSignature { - static final KeccakDigest keccakDigest = KeccakDigest(256); - static Uint8List keccak256(Uint8List input) { - keccakDigest.reset(); - return keccakDigest.process(input); - } - - static Uint8List hashMessage(String message) { - return keccak256( - Uint8List.fromList( - utf8.encode( - [ - '\x19Ethereum Signed Message:\n', - message.length.toString(), - message, - ].join(), - ), - ), - ); - } - - static int getNormalizedV(int v) { - if (v == 0 || v == 27) { - return 27; - } - if (v == 1 || v == 28) { - return 28; - } - return v & 1 == 1 ? 27 : 28; - } - - static bool isValidEip191Signature( - String address, - String message, - String sig, - ) { - // Get the sig bytes - // print(sig); - final sigBytes = Uint8List.fromList( - hex.decode(sig.substring(2)), - ); - - // If the sig bytes aren't 65 bytes long, throw an error - if (sigBytes.length != 65) { - throw Exception('Invalid signature length'); - } - - // Get the r and s values from the sig bytes - final r = BigInt.parse( - hex.encode(sigBytes.sublist(0, 32)), - radix: 16, - ); - final s = BigInt.parse( - hex.encode(sigBytes.sublist(32, 64)), - radix: 16, - ); - // print(sigBytes[64]); - final v = getNormalizedV(sigBytes[64]); - // print(r); - // print(s); - // print(v); - - // // Recover the public key from the signature - // Uint8List? publicKeyBytes = AuthSecp256k1.recoverPublicKeyFromSignature( - // v - 27, - // r, - // s, - // hashMessage(message), - // ); - - // // If the public key is null, return false - // if (publicKeyBytes == null) { - // print('Could not derive publicKey'); - // return false; - // } - - // Convert the public key to an address - final publicKeyBytes = crypto.ecRecover( - hashMessage(message), - crypto.MsgSignature(r, s, v), - ); - // print(hex.encode(publicKeyBytes)); - final hashedPubKeyBytes = keccak256(publicKeyBytes); - final addressBytes = hashedPubKeyBytes.sublist(12, 32); - final recoveredAddress = '0x${hex.encode(addressBytes)}'; - - // final String recoveredAddress = EthSigUtil.recoverSignature( - // signature: sig, - // message: hashMessage(message), - // // Uint8List.fromList( - // // ascii.encode(message), - // // ), - // ); - - // print(recoveredAddress.toLowerCase()); - // print(address.toLowerCase()); - - return recoveredAddress.toLowerCase() == address.toLowerCase(); - } - - static Future isValidEip1271Signature( - String address, - String reconstructedMessage, - String cacaoSignature, - String chainId, - String projectId, - ) async { - try { - const String eip1271MagicValue = '0x1626ba7e'; - const String dynamicTypeOffset = - '0000000000000000000000000000000000000000000000000000000000000040'; - const String dynamicTypeLength = - '0000000000000000000000000000000000000000000000000000000000000041'; - final String nonPrefixedSignature = cacaoSignature.substring(2); - final String nonPrefixedHashedMessage = - hex.encode(hashMessage(reconstructedMessage)).substring(2); - - final String data = eip1271MagicValue + - nonPrefixedHashedMessage + - dynamicTypeOffset + - dynamicTypeLength + - nonPrefixedSignature; - - final Uri url = Uri.parse( - '${AuthConstants.AUTH_DEFAULT_URL}/?chainId=$chainId&projectId=$projectId', - ); - final Map body = JsonRpcUtils.formatJsonRpcRequest( - 'eth_call', - { - 'to': address, - 'data': data, - }, - ); - - final http.Response response = await http.post( - url, - body: body, - ); - - // print(response.body); - // final jsonBody = jsonDecode(response.body); - final String recoveredValue = - response.body.substring(0, eip1271MagicValue.length); - return recoveredValue.toLowerCase() == eip1271MagicValue.toLowerCase(); - } catch (e) { - return false; - } - } - - // verifies CACAO signature - // Used by the wallet after formatting the message - static Future verifySignature( - String address, - String reconstructedMessage, - CacaoSignature cacaoSignature, - String chainId, - String projectId, - ) async { - if (cacaoSignature.t == 'eip191') { - return isValidEip191Signature( - address, - reconstructedMessage, - cacaoSignature.s, - ); - } else if (cacaoSignature.t == 'eip1271') { - return await isValidEip1271Signature( - address, - reconstructedMessage, - cacaoSignature.s, - chainId, - projectId, - ); - } else { - throw Exception( - 'verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${cacaoSignature.t}', - ); - } - } -} +// import 'dart:convert'; +// import 'dart:typed_data'; +// import 'package:convert/convert.dart'; +// import 'package:http/http.dart' as http; + +// import 'package:pointycastle/digests/keccak.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; +// import 'package:web3dart/crypto.dart' as crypto; + +// class AuthSignature { +// static final KeccakDigest keccakDigest = KeccakDigest(256); +// static Uint8List keccak256(Uint8List input) { +// keccakDigest.reset(); +// return keccakDigest.process(input); +// } + +// static Uint8List hashMessage(String message) { +// return keccak256( +// Uint8List.fromList( +// utf8.encode( +// [ +// '\x19Ethereum Signed Message:\n', +// message.length.toString(), +// message, +// ].join(), +// ), +// ), +// ); +// } + +// static int getNormalizedV(int v) { +// if (v == 0 || v == 27) { +// return 27; +// } +// if (v == 1 || v == 28) { +// return 28; +// } +// return v & 1 == 1 ? 27 : 28; +// } + +// static bool isValidEip191Signature( +// String address, +// String message, +// String sig, +// ) { +// // Get the sig bytes +// // print(sig); +// final sigBytes = Uint8List.fromList( +// hex.decode(sig.substring(2)), +// ); + +// // If the sig bytes aren't 65 bytes long, throw an error +// if (sigBytes.length != 65) { +// throw Exception('Invalid signature length'); +// } + +// // Get the r and s values from the sig bytes +// final r = BigInt.parse( +// hex.encode(sigBytes.sublist(0, 32)), +// radix: 16, +// ); +// final s = BigInt.parse( +// hex.encode(sigBytes.sublist(32, 64)), +// radix: 16, +// ); +// // print(sigBytes[64]); +// final v = getNormalizedV(sigBytes[64]); +// // print(r); +// // print(s); +// // print(v); + +// // // Recover the public key from the signature +// // Uint8List? publicKeyBytes = AuthSecp256k1.recoverPublicKeyFromSignature( +// // v - 27, +// // r, +// // s, +// // hashMessage(message), +// // ); + +// // // If the public key is null, return false +// // if (publicKeyBytes == null) { +// // print('Could not derive publicKey'); +// // return false; +// // } + +// // Convert the public key to an address +// final publicKeyBytes = crypto.ecRecover( +// hashMessage(message), +// crypto.MsgSignature(r, s, v), +// ); +// // print(hex.encode(publicKeyBytes)); +// final hashedPubKeyBytes = keccak256(publicKeyBytes); +// final addressBytes = hashedPubKeyBytes.sublist(12, 32); +// final recoveredAddress = '0x${hex.encode(addressBytes)}'; + +// // final String recoveredAddress = EthSigUtil.recoverSignature( +// // signature: sig, +// // message: hashMessage(message), +// // // Uint8List.fromList( +// // // ascii.encode(message), +// // // ), +// // ); + +// // print(recoveredAddress.toLowerCase()); +// // print(address.toLowerCase()); + +// return recoveredAddress.toLowerCase() == address.toLowerCase(); +// } + +// static Future isValidEip1271Signature( +// String address, +// String reconstructedMessage, +// String cacaoSignature, +// String chainId, +// String projectId, +// ) async { +// try { +// const String eip1271MagicValue = '0x1626ba7e'; +// const String dynamicTypeOffset = +// '0000000000000000000000000000000000000000000000000000000000000040'; +// const String dynamicTypeLength = +// '0000000000000000000000000000000000000000000000000000000000000041'; +// final String nonPrefixedSignature = cacaoSignature.substring(2); +// final String nonPrefixedHashedMessage = +// hex.encode(hashMessage(reconstructedMessage)).substring(2); + +// final String data = eip1271MagicValue + +// nonPrefixedHashedMessage + +// dynamicTypeOffset + +// dynamicTypeLength + +// nonPrefixedSignature; + +// final Uri url = Uri.parse( +// '${AuthConstants.AUTH_DEFAULT_URL}/?chainId=$chainId&projectId=$projectId', +// ); +// final Map body = JsonRpcUtils.formatJsonRpcRequest( +// 'eth_call', +// { +// 'to': address, +// 'data': data, +// }, +// ); + +// final http.Response response = await http.post( +// url, +// body: body, +// ); + +// // print(response.body); +// // final jsonBody = jsonDecode(response.body); +// final String recoveredValue = +// response.body.substring(0, eip1271MagicValue.length); +// return recoveredValue.toLowerCase() == eip1271MagicValue.toLowerCase(); +// } catch (e) { +// return false; +// } +// } + +// // verifies CACAO signature +// // Used by the wallet after formatting the message +// static Future verifySignature( +// String address, +// String reconstructedMessage, +// CacaoSignature cacaoSignature, +// String chainId, +// String projectId, +// ) async { +// if (cacaoSignature.t == 'eip191') { +// return isValidEip191Signature( +// address, +// reconstructedMessage, +// cacaoSignature.s, +// ); +// } else if (cacaoSignature.t == 'eip1271') { +// return await isValidEip1271Signature( +// address, +// reconstructedMessage, +// cacaoSignature.s, +// chainId, +// projectId, +// ); +// } else { +// throw Exception( +// 'verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${cacaoSignature.t}', +// ); +// } +// } +// } diff --git a/lib/apis/auth_api/utils/auth_utils.dart b/lib/apis/auth_api/utils/auth_utils.dart index 7f4e8016..6f641c6f 100644 --- a/lib/apis/auth_api/utils/auth_utils.dart +++ b/lib/apis/auth_api/utils/auth_utils.dart @@ -1,5 +1,5 @@ -class AuthUtils { - static String generateNonce() { - return DateTime.now().millisecondsSinceEpoch.toString(); - } -} +// class AuthUtils { +// static String generateNonce() { +// return DateTime.now().millisecondsSinceEpoch.toString(); +// } +// } diff --git a/lib/apis/auth_api/utils/secp256k1/auth_secp256k1.dart b/lib/apis/auth_api/utils/secp256k1/auth_secp256k1.dart index 20475249..607f21eb 100644 --- a/lib/apis/auth_api/utils/secp256k1/auth_secp256k1.dart +++ b/lib/apis/auth_api/utils/secp256k1/auth_secp256k1.dart @@ -1,115 +1,115 @@ -import 'dart:math'; -import 'dart:typed_data'; - -import 'package:convert/convert.dart'; -import 'package:pointycastle/ecc/api.dart'; -import 'package:pointycastle/ecc/curves/secp256k1.dart'; - -enum Endian { - be, -} - -class AuthSecp256k1 { - static final ECDomainParameters _params = ECCurve_secp256k1(); - static final BigInt _byteMask = BigInt.from(0xff); - - static BigInt decodeBigInt(List bytes) { - BigInt result = BigInt.from(0); - for (int i = 0; i < bytes.length; i++) { - result += BigInt.from(bytes[bytes.length - i - 1]) << (8 * i); - } - return result; - } - - static Uint8List encodeBigInt( - BigInt input, { - Endian endian = Endian.be, - int length = 0, - }) { - int byteLength = (input.bitLength + 7) >> 3; - int reqLength = length > 0 ? length : max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - var res = Uint8List(reqLength); - res.fillRange(0, reqLength - byteLength, 0); - - var q = input; - if (endian == Endian.be) { - for (int i = 0; i < byteLength; i++) { - res[reqLength - i - 1] = (q & _byteMask).toInt(); - q = q >> 8; - } - return res; - } - - return Uint8List(0); - } - - static ECPoint _decompressKey(BigInt xBN, bool yBit, ECCurve c) { - List x9IntegerToBytes(BigInt s, int qLength) { - //https://github.com/bcgit/bc-java/blob/master/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java#L45 - String hexString = s.toRadixString(16); - if (hexString.length % 2 == 1) { - hexString = '0$hexString'; - } - final bytes = hex.decode(hexString); - - if (qLength < bytes.length) { - return bytes.sublist(0, bytes.length - qLength); - } else if (qLength > bytes.length) { - final tmp = List.filled(qLength, 0); - - final offset = qLength - bytes.length; - for (var i = 0; i < bytes.length; i++) { - tmp[i + offset] = bytes[i]; - } - - return tmp; - } - - return bytes; - } - - final compEnc = x9IntegerToBytes(xBN, 1 + ((c.fieldSize + 7) ~/ 8)); - compEnc[0] = yBit ? 0x03 : 0x02; - return c.decodePoint(compEnc)!; - } - - static Uint8List? recoverPublicKeyFromSignature( - int recId, - BigInt r, - BigInt s, - Uint8List message, - ) { - final n = _params.n; - final i = BigInt.from(recId ~/ 2); - final x = r + (i * n); - - //Parameter q of curve - final prime = BigInt.parse( - 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', - radix: 16); - if (x.compareTo(prime) >= 0) return null; - - final R = _decompressKey(x, (recId & 1) == 1, _params.curve); - final ECPoint? ecPoint = R * n; - if (ecPoint == null || !ecPoint.isInfinity) return null; - - // print(bytesToHex(message)); - // final e = BigInt.parse(bytesToHex(message).substring(1)); - final e = decodeBigInt(message.toList()); - - final eInv = (BigInt.zero - e) % n; - final rInv = r.modInverse(n); - final srInv = (rInv * s) % n; - final eInvrInv = (rInv * eInv) % n; - - final preQ = (_params.G * eInvrInv); - if (preQ == null) return null; - final q = preQ + (R * srInv); - - final bytes = q?.getEncoded(false); - return bytes?.sublist(1); - } -} +// import 'dart:math'; +// import 'dart:typed_data'; + +// import 'package:convert/convert.dart'; +// import 'package:pointycastle/ecc/api.dart'; +// import 'package:pointycastle/ecc/curves/secp256k1.dart'; + +// enum Endian { +// be, +// } + +// class AuthSecp256k1 { +// static final ECDomainParameters _params = ECCurve_secp256k1(); +// static final BigInt _byteMask = BigInt.from(0xff); + +// static BigInt decodeBigInt(List bytes) { +// BigInt result = BigInt.from(0); +// for (int i = 0; i < bytes.length; i++) { +// result += BigInt.from(bytes[bytes.length - i - 1]) << (8 * i); +// } +// return result; +// } + +// static Uint8List encodeBigInt( +// BigInt input, { +// Endian endian = Endian.be, +// int length = 0, +// }) { +// int byteLength = (input.bitLength + 7) >> 3; +// int reqLength = length > 0 ? length : max(1, byteLength); +// assert(byteLength <= reqLength, 'byte array longer than desired length'); +// assert(reqLength > 0, 'Requested array length <= 0'); + +// var res = Uint8List(reqLength); +// res.fillRange(0, reqLength - byteLength, 0); + +// var q = input; +// if (endian == Endian.be) { +// for (int i = 0; i < byteLength; i++) { +// res[reqLength - i - 1] = (q & _byteMask).toInt(); +// q = q >> 8; +// } +// return res; +// } + +// return Uint8List(0); +// } + +// static ECPoint _decompressKey(BigInt xBN, bool yBit, ECCurve c) { +// List x9IntegerToBytes(BigInt s, int qLength) { +// //https://github.com/bcgit/bc-java/blob/master/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java#L45 +// String hexString = s.toRadixString(16); +// if (hexString.length % 2 == 1) { +// hexString = '0$hexString'; +// } +// final bytes = hex.decode(hexString); + +// if (qLength < bytes.length) { +// return bytes.sublist(0, bytes.length - qLength); +// } else if (qLength > bytes.length) { +// final tmp = List.filled(qLength, 0); + +// final offset = qLength - bytes.length; +// for (var i = 0; i < bytes.length; i++) { +// tmp[i + offset] = bytes[i]; +// } + +// return tmp; +// } + +// return bytes; +// } + +// final compEnc = x9IntegerToBytes(xBN, 1 + ((c.fieldSize + 7) ~/ 8)); +// compEnc[0] = yBit ? 0x03 : 0x02; +// return c.decodePoint(compEnc)!; +// } + +// static Uint8List? recoverPublicKeyFromSignature( +// int recId, +// BigInt r, +// BigInt s, +// Uint8List message, +// ) { +// final n = _params.n; +// final i = BigInt.from(recId ~/ 2); +// final x = r + (i * n); + +// //Parameter q of curve +// final prime = BigInt.parse( +// 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', +// radix: 16); +// if (x.compareTo(prime) >= 0) return null; + +// final R = _decompressKey(x, (recId & 1) == 1, _params.curve); +// final ECPoint? ecPoint = R * n; +// if (ecPoint == null || !ecPoint.isInfinity) return null; + +// // print(bytesToHex(message)); +// // final e = BigInt.parse(bytesToHex(message).substring(1)); +// final e = decodeBigInt(message.toList()); + +// final eInv = (BigInt.zero - e) % n; +// final rInv = r.modInverse(n); +// final srInv = (rInv * s) % n; +// final eInvrInv = (rInv * eInv) % n; + +// final preQ = (_params.G * eInvrInv); +// if (preQ == null) return null; +// final q = preQ + (R * srInv); + +// final bytes = q?.getEncoded(false); +// return bytes?.sublist(1); +// } +// } diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart deleted file mode 100644 index 3d19034a..00000000 --- a/lib/apis/sign_api/i_sign_client.dart +++ /dev/null @@ -1,136 +0,0 @@ -// 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/walletconnect_flutter_v2.dart'; - -// abstract class ISignClient { -// final String protocol = 'wc'; -// final int version = 2; - -// abstract final ISignEngine engine; - -// // Common -// abstract final Event onSessionConnect; -// abstract final Event onSessionDelete; -// abstract final Event onSessionExpire; -// abstract final Event onSessionPing; -// abstract final Event onProposalExpire; - -// abstract final ICore core; -// abstract final PairingMetadata metadata; -// abstract final IGenericStore proposals; -// abstract final ISessions sessions; -// abstract final IGenericStore pendingRequests; - -// // Wallet -// abstract final Event onSessionProposal; -// abstract final Event onSessionProposalError; -// abstract final Event onSessionRequest; - -// // App -// abstract final Event onSessionUpdate; -// abstract final Event onSessionExtend; -// abstract final Event onSessionEvent; - -// Future init(); -// Future connect({ -// Map? requiredNamespaces, -// Map? optionalNamespaces, -// Map? sessionProperties, -// String? pairingTopic, -// List? relays, -// List>? methods, -// }); -// Future pair({ -// required Uri uri, -// }); -// Future approve({ -// required int id, -// required Map namespaces, -// Map? sessionProperties, -// String? relayProtocol, -// }); -// Future reject({ -// required int id, -// required WalletConnectError reason, -// }); -// Future update({ -// required String topic, -// required Map namespaces, -// }); -// Future extend({ -// required String topic, -// }); -// void registerRequestHandler({ -// required String chainId, -// required String method, -// dynamic Function(String, dynamic)? handler, -// }); -// Future respond({ -// required String topic, -// required JsonRpcResponse response, -// }); -// Future emit({ -// required String topic, -// required String chainId, -// required SessionEventParams event, -// }); -// Future request({ -// required String topic, -// required String chainId, -// required SessionRequestParams request, -// }); -// Future> requestReadContract({ -// required DeployedContract deployedContract, -// required String functionName, -// required String rpcUrl, -// List parameters = const [], -// }); -// 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 [], -// }); - -// void registerEventHandler({ -// required String chainId, -// required String event, -// required dynamic Function(String, dynamic)? handler, -// }); -// Future ping({ -// required String topic, -// }); -// Future disconnect({ -// required String topic, -// required WalletConnectError reason, -// }); -// SessionData? find({ -// required Map requiredNamespaces, -// }); -// Map getActiveSessions(); -// Map getSessionsForPairing({ -// required String pairingTopic, -// }); -// Map getPendingSessionProposals(); -// Map getPendingSessionRequests(); -// abstract final IPairingStore pairings; - -// /// Register event emitters for a given namespace or chainId -// /// Used to construct the Namespaces map for the session proposal -// void registerEventEmitter({ -// required String chainId, -// required String event, -// }); - -// /// Register accounts for a given namespace or chainId. -// /// Used to construct the Namespaces map for the session proposal. -// /// Each account must follow the namespace:chainId:address format or this will throw an error. -// void registerAccount({ -// required String chainId, -// required String accountAddress, -// }); -// } diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index df93ba67..206c9262 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -5,6 +5,8 @@ abstract class ISignEngineApp extends ISignEngineCommon { abstract final Event onSessionUpdate; abstract final Event onSessionExtend; abstract final Event onSessionEvent; + // FORMER AUTH ENGINE PROPERTY + abstract final Event onAuthResponse; Future connect({ Map? requiredNamespaces, @@ -44,4 +46,12 @@ abstract class ISignEngineApp extends ISignEngineCommon { Future ping({ required String topic, }); + + // FORMER AUTH ENGINE PROPERTY + // to be transformed into authenticate({}); + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index b4d4ae91..37472c4e 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -8,6 +8,7 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; abstract class ISignEngineCommon { abstract final Event onSessionConnect; @@ -22,6 +23,12 @@ abstract class ISignEngineCommon { abstract final ISessions sessions; abstract final IGenericStore pendingRequests; + // FORMER AUTH ENGINE PROPERTY + abstract final IPairingStore pairings; + abstract final IGenericStore authKeys; + abstract final IGenericStore pairingTopics; + abstract final IGenericStore completeRequests; + Future init(); Future disconnectSession({ required String topic, @@ -33,5 +40,13 @@ abstract class ISignEngineCommon { }); Map getPendingSessionProposals(); - abstract final IPairingStore pairings; + // FORMER AUTH ENGINE PROPERTY + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }); + // FORMER AUTH ENGINE PROPERTY + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index 86244be5..6d93e11d 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -8,12 +8,19 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.da import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; abstract class ISignEngineWallet extends ISignEngineCommon { abstract final Event onSessionProposal; abstract final Event onSessionProposalError; abstract final Event onSessionRequest; + // FORMER AUTH ENGINE PROPERTY + abstract final Event onAuthRequest; + abstract final IGenericStore authRequests; + Future pair({ required Uri uri, }); @@ -76,4 +83,17 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // required Map requiredNamespaces, // Map? optionalNamespaces, // }); + + // FORMER AUTH ENGINE PROPERTY + // to be transformed into approveSessionAuthenticate({}) + // to be transformed into rejectSessionAuthenticate({}) + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }); + // FORMER AUTH ENGINE PROPERTY + // query all pending requests + Map getPendingAuthRequests(); } diff --git a/lib/apis/sign_api/models/auth/auth_client_events.dart b/lib/apis/sign_api/models/auth/auth_client_events.dart new file mode 100644 index 00000000..e4bc7f3a --- /dev/null +++ b/lib/apis/sign_api/models/auth/auth_client_events.dart @@ -0,0 +1,44 @@ +import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; + +class AuthRequest extends EventArgs { + final int id; + final String topic; + final AuthPayloadParams payloadParams; + final ConnectionMetadata requester; + + AuthRequest({ + required this.id, + required this.topic, + required this.payloadParams, + required this.requester, + }); + + @override + String toString() { + return 'AuthRequest(id: $id, topic: $topic, payloadParams: $payloadParams, requester: $requester)'; + } +} + +class AuthResponse extends EventArgs { + final int id; + final String topic; + final Cacao? result; + final WalletConnectError? error; + final JsonRpcError? jsonRpcError; + + AuthResponse({ + required this.id, + required this.topic, + this.result, + this.error, + this.jsonRpcError, + }); + + @override + String toString() { + return 'AuthResponse(id: $id, topic: $topic, result: $result, error: $error, jsonRpcError: $jsonRpcError)'; + } +} diff --git a/lib/apis/sign_api/models/auth/auth_client_models.dart b/lib/apis/sign_api/models/auth/auth_client_models.dart new file mode 100644 index 00000000..d5df707d --- /dev/null +++ b/lib/apis/sign_api/models/auth/auth_client_models.dart @@ -0,0 +1,326 @@ +import 'dart:async'; + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_utils.dart'; + +part 'auth_client_models.g.dart'; +part 'auth_client_models.freezed.dart'; + +class AuthRequestResponse { + final int id; + final String pairingTopic; + final Completer completer; + final Uri? uri; + + AuthRequestResponse({ + required this.id, + required this.pairingTopic, + required this.completer, + this.uri, + }); +} + +@freezed +class AuthPublicKey with _$AuthPublicKey { + @JsonSerializable(includeIfNull: false) + const factory AuthPublicKey({ + required String publicKey, + }) = _AuthPublicKey; + + factory AuthPublicKey.fromJson(Map json) => + _$AuthPublicKeyFromJson(json); +} + +class AuthRequestParams { + /// The Chain ID. + /// Examples: eip155:1 (Eth Mainnet), eip155:43114 (Avalanche) + final String chainId; + + /// The complete URL you are logging into. + /// Example: https://example.com/login + final String aud; + + /// The domain you are logging in to. + /// Example: example.com + /// Domain must exist within the aud, or validation will fail + final String domain; + final String nonce; + final String? type; + final String? nbf; + final String? exp; + final String? statement; + final String? requestId; + final List? resources; + final int? expiry; + + AuthRequestParams({ + required this.chainId, + required this.domain, + required this.aud, + String? nonce, + this.type = CacaoHeader.EIP4361, + this.nbf, + this.exp, + this.statement, + this.requestId, + this.resources, + this.expiry, + }) : nonce = nonce ?? AuthUtils.generateNonce(); + + Map toJson() => { + 'chainId': chainId, + 'aud': aud, + 'domain': domain, + 'nonce': nonce, + if (type != null) 'type': type, + if (nbf != null) 'nbf': nbf, + if (exp != null) 'exp': exp, + if (statement != null) 'statement': statement, + if (requestId != null) 'requestId': requestId, + if (resources != null) 'resources': resources, + if (expiry != null) 'expiry': expiry, + }; +} + +@freezed +class AuthPayloadParams with _$AuthPayloadParams { + @JsonSerializable(includeIfNull: false) + const factory AuthPayloadParams({ + required String type, + required String chainId, + required String domain, + required String aud, + required String version, + required String nonce, + required String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _AuthPayloadParams; + + factory AuthPayloadParams.fromRequestParams(AuthRequestParams params) { + return AuthPayloadParams( + type: params.type ?? CacaoHeader.EIP4361, + chainId: params.chainId, + domain: params.domain, + aud: params.aud, + version: '1', + nonce: params.nonce, + iat: DateTime.now().toIso8601String(), + nbf: params.nbf, + exp: params.exp, + statement: params.statement, + requestId: params.requestId, + resources: params.resources, + ); + } + + factory AuthPayloadParams.fromJson(Map json) => + _$AuthPayloadParamsFromJson(json); +} + +@freezed +class CacaoRequestPayload with _$CacaoRequestPayload { + @JsonSerializable(includeIfNull: false) + const factory CacaoRequestPayload({ + required String domain, + required String aud, + required String version, + required String nonce, + required String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _CacaoRequestPayload; + + factory CacaoRequestPayload.fromPayloadParams(AuthPayloadParams params) { + return CacaoRequestPayload( + domain: params.domain, + aud: params.aud, + version: params.version, + nonce: params.nonce, + iat: params.iat, + nbf: params.nbf, + exp: params.exp, + statement: params.statement, + requestId: params.requestId, + resources: params.resources, + ); + } + + factory CacaoRequestPayload.fromCacaoPayload(CacaoPayload payload) { + return CacaoRequestPayload( + domain: payload.domain, + aud: payload.aud, + version: payload.version, + nonce: payload.nonce, + iat: payload.iat, + nbf: payload.nbf, + exp: payload.exp, + statement: payload.statement, + requestId: payload.requestId, + resources: payload.resources, + ); + } + + factory CacaoRequestPayload.fromJson(Map json) => + _$CacaoRequestPayloadFromJson(json); +} + +@freezed +class CacaoPayload with _$CacaoPayload { + @JsonSerializable(includeIfNull: false) + const factory CacaoPayload({ + required String iss, + required String domain, + required String aud, + required String version, + required String nonce, + required String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _CacaoPayload; + + factory CacaoPayload.fromRequestPayload({ + required String issuer, + required CacaoRequestPayload payload, + }) { + return CacaoPayload( + iss: issuer, + domain: payload.domain, + aud: payload.aud, + version: payload.version, + nonce: payload.nonce, + iat: payload.iat, + nbf: payload.nbf, + exp: payload.exp, + statement: payload.statement, + requestId: payload.requestId, + resources: payload.resources, + ); + } + + factory CacaoPayload.fromJson(Map json) => + _$CacaoPayloadFromJson(json); +} + +@freezed +class CacaoHeader with _$CacaoHeader { + static const EIP4361 = 'eip4361'; + + @JsonSerializable(includeIfNull: false) + const factory CacaoHeader({ + @Default('eip4361') String t, + }) = _CacaoHeader; + + factory CacaoHeader.fromJson(Map json) => + _$CacaoHeaderFromJson(json); +} + +@freezed +class CacaoSignature with _$CacaoSignature { + static const EIP191 = 'eip191'; + static const EIP1271 = 'eip1271'; + + @JsonSerializable(includeIfNull: false) + const factory CacaoSignature({ + required String t, + required String s, + String? m, + }) = _CacaoSignature; + + factory CacaoSignature.fromJson(Map json) => + _$CacaoSignatureFromJson(json); +} + +@freezed +class Cacao with _$Cacao { + @JsonSerializable(includeIfNull: false) + const factory Cacao({ + required CacaoHeader h, + required CacaoPayload p, + required CacaoSignature s, + }) = _Cacao; + + factory Cacao.fromJson(Map json) => _$CacaoFromJson(json); +} + +@freezed +class StoredCacao with _$StoredCacao { + @JsonSerializable(includeIfNull: false) + const factory StoredCacao({ + required int id, + required String pairingTopic, + required CacaoHeader h, + required CacaoPayload p, + required CacaoSignature s, + }) = _StoredCacao; + + factory StoredCacao.fromCacao({ + required int id, + required String pairingTopic, + required Cacao cacao, + }) { + return StoredCacao( + id: id, + pairingTopic: pairingTopic, + h: cacao.h, + p: cacao.p, + s: cacao.s, + ); + } + + factory StoredCacao.fromJson(Map json) => + _$StoredCacaoFromJson(json); +} + +@freezed +class PendingAuthRequest with _$PendingAuthRequest { + @JsonSerializable(includeIfNull: false) + const factory PendingAuthRequest({ + required int id, + required String pairingTopic, + required ConnectionMetadata metadata, + required CacaoRequestPayload cacaoPayload, + }) = _PendingAuthRequest; + + factory PendingAuthRequest.fromJson(Map json) => + _$PendingAuthRequestFromJson(json); +} + +class AuthRequestCompleter { + final int id; + final String pairingTopic; + final String responseTopic; + final PendingAuthRequest request; + final Completer completer; + + AuthRequestCompleter({ + required this.id, + required this.pairingTopic, + required this.responseTopic, + required this.request, + required this.completer, + }); +} + +class RespondParams { + final int id; + final CacaoSignature? signature; + final WalletConnectError? error; + + RespondParams({ + required this.id, + this.signature, + this.error, + }); +} diff --git a/lib/apis/auth_api/models/auth_client_models.freezed.dart b/lib/apis/sign_api/models/auth/auth_client_models.freezed.dart similarity index 100% rename from lib/apis/auth_api/models/auth_client_models.freezed.dart rename to lib/apis/sign_api/models/auth/auth_client_models.freezed.dart diff --git a/lib/apis/auth_api/models/auth_client_models.g.dart b/lib/apis/sign_api/models/auth/auth_client_models.g.dart similarity index 100% rename from lib/apis/auth_api/models/auth_client_models.g.dart rename to lib/apis/sign_api/models/auth/auth_client_models.g.dart diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.dart b/lib/apis/sign_api/models/auth/json_rpc_models.dart new file mode 100644 index 00000000..232ac842 --- /dev/null +++ b/lib/apis/sign_api/models/auth/json_rpc_models.dart @@ -0,0 +1,29 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; + +part 'json_rpc_models.g.dart'; +part 'json_rpc_models.freezed.dart'; + +@freezed +class WcAuthRequestRequest with _$WcAuthRequestRequest { + @JsonSerializable() + const factory WcAuthRequestRequest({ + required AuthPayloadParams payloadParams, + required ConnectionMetadata requester, + }) = _WcAuthRequestRequest; + + factory WcAuthRequestRequest.fromJson(Map json) => + _$WcAuthRequestRequestFromJson(json); +} + +@freezed +class WcAuthRequestResult with _$WcAuthRequestResult { + @JsonSerializable() + const factory WcAuthRequestResult({ + required Cacao cacao, + }) = _WcAuthRequestResult; + + factory WcAuthRequestResult.fromJson(Map json) => + _$WcAuthRequestResultFromJson(json); +} diff --git a/lib/apis/auth_api/models/json_rpc_models.freezed.dart b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart similarity index 100% rename from lib/apis/auth_api/models/json_rpc_models.freezed.dart rename to lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart diff --git a/lib/apis/auth_api/models/json_rpc_models.g.dart b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart similarity index 100% rename from lib/apis/auth_api/models/json_rpc_models.g.dart rename to lib/apis/sign_api/models/auth/json_rpc_models.g.dart diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart deleted file mode 100644 index 9aebf091..00000000 --- a/lib/apis/sign_api/sign_client.dart +++ /dev/null @@ -1,472 +0,0 @@ -// import 'package:event/event.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_pairing_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/sessions.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -// import 'package:web3dart/web3dart.dart'; - -// class SignClient implements ISignClient { -// bool _initialized = false; - -// @override -// final String protocol = 'wc'; -// @override -// final int version = 2; - -// @override -// Event get onSessionDelete => engine.onSessionDelete; -// @override -// Event get onSessionConnect => engine.onSessionConnect; -// @override -// Event get onSessionEvent => engine.onSessionEvent; -// @override -// Event get onSessionExpire => engine.onSessionExpire; -// @override -// Event get onSessionExtend => engine.onSessionExtend; -// @override -// Event get onSessionPing => engine.onSessionPing; -// @override -// Event get onSessionProposal => engine.onSessionProposal; -// @override -// Event get onSessionProposalError => -// engine.onSessionProposalError; -// @override -// Event get onProposalExpire => engine.onProposalExpire; -// @override -// Event get onSessionRequest => engine.onSessionRequest; -// @override -// Event get onSessionUpdate => engine.onSessionUpdate; - -// @override -// ICore get core => engine.core; -// @override -// PairingMetadata get metadata => engine.metadata; -// @override -// IGenericStore get proposals => engine.proposals; -// @override -// ISessions get sessions => engine.sessions; -// @override -// IGenericStore get pendingRequests => engine.pendingRequests; - -// @override -// late ISignEngine engine; - -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// LogLevel logLevel = LogLevel.nothing, -// }) async { -// final client = SignClient( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// logLevel: logLevel, -// ), -// metadata: metadata, -// ); -// await client.init(); - -// return client; -// } - -// SignClient({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// engine = SignEngine( -// core: core, -// metadata: metadata, -// proposals: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PROPOSALS, -// version: StoreVersions.VERSION_PROPOSALS, -// fromJson: (dynamic value) { -// return ProposalData.fromJson(value); -// }, -// ), -// sessions: Sessions( -// storage: core.storage, -// context: StoreVersions.CONTEXT_SESSIONS, -// version: StoreVersions.VERSION_SESSIONS, -// fromJson: (dynamic value) { -// return SessionData.fromJson(value); -// }, -// ), -// pendingRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PENDING_REQUESTS, -// version: StoreVersions.VERSION_PENDING_REQUESTS, -// fromJson: (dynamic value) { -// return SessionRequest.fromJson(value); -// }, -// ), -// ); -// } - -// @override -// Future init() async { -// if (_initialized) { -// return; -// } - -// await core.start(); -// await engine.init(); - -// _initialized = true; -// } - -// @override -// Future connect({ -// Map? requiredNamespaces, -// Map? optionalNamespaces, -// Map? sessionProperties, -// String? pairingTopic, -// List? relays, -// List>? methods = SignEngine.DEFAULT_METHODS, -// }) async { -// try { -// return await engine.connect( -// requiredNamespaces: requiredNamespaces, -// optionalNamespaces: optionalNamespaces, -// sessionProperties: sessionProperties, -// pairingTopic: pairingTopic, -// relays: relays, -// methods: methods, -// ); -// } catch (e) { -// // print(e); -// rethrow; -// } -// } - -// @override -// Future pair({ -// required Uri uri, -// }) async { -// try { -// return await engine.pair(uri: uri); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future approve({ -// required int id, -// required Map namespaces, -// Map? sessionProperties, -// String? relayProtocol, -// }) async { -// try { -// return await engine.approveSession( -// id: id, -// namespaces: namespaces, -// sessionProperties: sessionProperties, -// relayProtocol: relayProtocol, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future reject({ -// required int id, -// required WalletConnectError reason, -// }) async { -// try { -// return await engine.rejectSession( -// id: id, -// reason: reason, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future update({ -// required String topic, -// required Map namespaces, -// }) async { -// try { -// return await engine.updateSession( -// topic: topic, -// namespaces: namespaces, -// ); -// } catch (e) { -// // final error = e as WCError; -// rethrow; -// } -// } - -// @override -// Future extend({ -// required String topic, -// }) async { -// try { -// return await engine.extendSession(topic: topic); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerRequestHandler({ -// required String chainId, -// required String method, -// void Function(String, dynamic)? handler, -// }) { -// try { -// return engine.registerRequestHandler( -// chainId: chainId, -// method: method, -// handler: handler, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future request({ -// required String topic, -// required String chainId, -// required SessionRequestParams request, -// }) async { -// try { -// return await engine.request( -// topic: topic, -// chainId: chainId, -// request: request, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future> requestReadContract({ -// required DeployedContract deployedContract, -// required String functionName, -// required String rpcUrl, -// List parameters = const [], -// }) async { -// try { -// return await engine.requestReadContract( -// deployedContract: deployedContract, -// functionName: functionName, -// rpcUrl: rpcUrl, -// parameters: parameters, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// 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 [], -// }) async { -// try { -// return await engine.requestWriteContract( -// topic: topic, -// chainId: chainId, -// rpcUrl: rpcUrl, -// deployedContract: deployedContract, -// functionName: functionName, -// transaction: transaction, -// method: method, -// parameters: parameters, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future respond({ -// required String topic, -// required JsonRpcResponse response, -// }) { -// try { -// return engine.respondSessionRequest( -// topic: topic, -// response: response, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerEventHandler({ -// required String chainId, -// required String event, -// dynamic Function(String, dynamic)? handler, -// }) { -// try { -// return engine.registerEventHandler( -// chainId: chainId, -// event: event, -// handler: handler, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerEventEmitter({ -// required String chainId, -// required String event, -// }) { -// try { -// return engine.registerEventEmitter( -// chainId: chainId, -// event: event, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerAccount({ -// required String chainId, -// required String accountAddress, -// }) { -// try { -// return engine.registerAccount( -// chainId: chainId, -// accountAddress: accountAddress, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future emit({ -// required String topic, -// required String chainId, -// required SessionEventParams event, -// }) async { -// try { -// return await engine.emitSessionEvent( -// topic: topic, -// chainId: chainId, -// event: event, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future ping({ -// required String topic, -// }) async { -// try { -// return await engine.ping(topic: topic); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future disconnect({ -// required String topic, -// required WalletConnectError reason, -// }) async { -// try { -// return await engine.disconnectSession( -// topic: topic, -// reason: reason, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// SessionData? find({ -// required Map requiredNamespaces, -// }) { -// try { -// return engine.find(requiredNamespaces: requiredNamespaces); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getActiveSessions() { -// try { -// return engine.getActiveSessions(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getSessionsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return engine.getSessionsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingSessionProposals() { -// try { -// return engine.getPendingSessionProposals(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingSessionRequests() { -// try { -// return engine.getPendingSessionRequests(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// IPairingStore get pairings => core.pairing.getStore(); -// } diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 70e5e008..2055db84 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -10,11 +10,15 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/utils/custom_credentials. 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/core/crypto/crypto_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; + class SignEngine implements ISignEngine { static const List> DEFAULT_METHODS = [ [ MethodConstants.WC_SESSION_PROPOSE, MethodConstants.WC_SESSION_REQUEST, + MethodConstants.WC_AUTH_REQUEST, ], ]; @@ -60,12 +64,34 @@ class SignEngine implements ISignEngine { List pendingProposals = []; + // FORMER AUTH ENGINE PROPERTY + @override + late IGenericStore authKeys; + @override + late IGenericStore authRequests; + @override + IGenericStore completeRequests; + @override + final Event onAuthRequest = Event(); + @override + final Event onAuthResponse = Event(); + @override + late IGenericStore pairingTopics; + + // FORMER AUTH ENGINE PROPERTY + List pendingAuthRequests = []; + SignEngine({ required this.core, required this.metadata, required this.proposals, required this.sessions, required this.pendingRequests, + // FORMER AUTH ENGINE PROPERTY + required this.authKeys, + required this.pairingTopics, + required this.authRequests, + required this.completeRequests, }); @override @@ -80,6 +106,12 @@ class SignEngine implements ISignEngine { await sessions.init(); await pendingRequests.init(); + // FORMER AUTH ENGINE PROPERTY + await authKeys.init(); + await pairingTopics.init(); + await authRequests.init(); + await completeRequests.init(); + _registerInternalEvents(); _registerRelayClientFunctions(); await _cleanup(); @@ -312,7 +344,6 @@ class SignEngine implements ISignEngine { sessionProperties: proposal.sessionProperties, ); - // print('session connect'); onSessionConnect.broadcast(SessionConnect(session)); await sessions.set(sessionTopic, session); @@ -931,6 +962,12 @@ class SignEngine implements ISignEngine { function: _onSessionEventRequest, type: ProtocolType.sign, ); + // FORMER AUTH ENGINE PROPERTY + core.pairing.register( + method: MethodConstants.WC_AUTH_REQUEST, + function: _onAuthRequest, + type: ProtocolType.auth, + ); } Future _onSessionProposeRequest( @@ -1776,4 +1813,353 @@ class SignEngine implements ISignEngine { ); } } + + // FORMER AUTH ENGINE PROPERTY + // Formats the message that is coming from requestAuth() + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + final header = + '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; + final walletAddress = AddressUtils.getDidAddress(iss); + final uri = 'URI: ${cacaoPayload.aud}'; + final version = 'Version: ${cacaoPayload.version}'; + final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; + final nonce = 'Nonce: ${cacaoPayload.nonce}'; + final issuedAt = 'Issued At: ${cacaoPayload.iat}'; + final resources = cacaoPayload.resources != null && + cacaoPayload.resources!.isNotEmpty + ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' + : null; + + final message = [ + header, + walletAddress, + '', + cacaoPayload.statement, + '', + uri, + version, + chainId, + nonce, + issuedAt, + resources, + ].where((element) => element != null).join('\n'); + + return message; + } + + // FORMER AUTH ENGINE PROPERTY + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + Map completedRequests = {}; + completeRequests + .getAll() + .where( + (e) => e.pairingTopic == pairingTopic, + ) + .forEach((key) { + completedRequests[key.id] = key; + }); + return completedRequests; + } + + // FORMER AUTH ENGINE PROPERTY + @override + Map getPendingAuthRequests() { + Map pendingRequests = {}; + authRequests.getAll().forEach((key) { + pendingRequests[key.id] = key; + }); + return pendingRequests; + } + + // FORMER AUTH ENGINE PROPERTY + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = DEFAULT_METHODS, + }) async { + _checkInitialized(); + + AuthApiValidators.isValidRequest(params); + String? pTopic = pairingTopic; + Uri? uri; + + if (pTopic == null) { + final CreateResponse newTopicAndUri = await core.pairing.create( + methods: methods, + ); + pTopic = newTopicAndUri.topic; + uri = newTopicAndUri.uri; + } else { + core.pairing.isValidPairingTopic(topic: pTopic); + } + + final publicKey = await core.crypto.generateKeyPair(); + // print('requestAuth, publicKey: $publicKey'); + final String responseTopic = core.crypto.getUtils().hashKey(publicKey); + final int id = JsonRpcUtils.payloadId(); + + WcAuthRequestRequest request = WcAuthRequestRequest( + payloadParams: AuthPayloadParams.fromRequestParams( + params, + ), + requester: ConnectionMetadata( + publicKey: publicKey, + metadata: metadata, + ), + ); + + final int expiry = params.expiry ?? WalletConnectConstants.FIVE_MINUTES; + + await authKeys.set( + AuthConstants.AUTH_CLIENT_PUBLIC_KEY_NAME, + AuthPublicKey(publicKey: publicKey), + ); + + await pairingTopics.set( + responseTopic, + pTopic, + ); + + // Set the one time use receiver public key for decoding the Type 1 envelope + await core.pairing.setReceiverPublicKey( + topic: responseTopic, + publicKey: publicKey, + expiry: expiry, + ); + + Completer completer = Completer(); + + _requestAuthResponseHandler( + pairingTopic: pTopic, + responseTopic: responseTopic, + request: request, + id: id, + expiry: expiry, + completer: completer, + ); + + return AuthRequestResponse( + id: id, + pairingTopic: pTopic, + completer: completer, + uri: uri, + ); + } + + // FORMER AUTH ENGINE PROPERTY + Future _requestAuthResponseHandler({ + required String pairingTopic, + required String responseTopic, + required WcAuthRequestRequest request, + required int id, + required int expiry, + required Completer completer, + }) async { + Map? resp; + + // Subscribe to the responseTopic because we expect the response to use this topic + // print('got here'); + await core.relayClient.subscribe(topic: responseTopic); + + try { + resp = await core.pairing.sendRequest( + pairingTopic, + MethodConstants.WC_AUTH_REQUEST, + request.toJson(), + id: id, + ttl: expiry, + ); + } on JsonRpcError catch (e) { + final resp = AuthResponse( + id: id, + topic: responseTopic, + jsonRpcError: e, + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + return; + } + + await core.pairing.activate(topic: pairingTopic); + + final Cacao cacao = Cacao.fromJson(resp!); + final CacaoSignature sig = cacao.s; + final CacaoPayload payload = cacao.p; + await completeRequests.set( + id.toString(), + StoredCacao.fromCacao( + id: id, + pairingTopic: pairingTopic, + cacao: cacao, + ), + ); + + final String reconstructed = formatAuthMessage( + iss: payload.iss, + cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), + ); + + final String walletAddress = AddressUtils.getDidAddress(payload.iss); + final String chainId = AddressUtils.getDidChainId(payload.iss); + + if (walletAddress.isEmpty) { + throw Errors.getSdkError( + Errors.MISSING_OR_INVALID, + context: 'authResponse walletAddress is empty', + ); + } + if (chainId.isEmpty) { + throw Errors.getSdkError( + Errors.MISSING_OR_INVALID, + context: 'authResponse chainId is empty', + ); + } + + final bool isValid = await AuthSignature.verifySignature( + walletAddress, + reconstructed, + sig, + chainId, + core.projectId, + ); + + if (!isValid) { + final resp = AuthResponse( + id: id, + topic: responseTopic, + error: const WalletConnectError( + code: -1, + message: 'Invalid signature', + ), + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + } else { + final resp = AuthResponse( + id: id, + topic: responseTopic, + result: cacao, + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + } + } + + // FORMER AUTH ENGINE PROPERTY + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + _checkInitialized(); + + Map pendingRequests = getPendingAuthRequests(); + AuthApiValidators.isValidRespond( + id: id, + pendingRequests: pendingRequests, + signature: signature, + error: error, + ); + + final PendingAuthRequest pendingRequest = pendingRequests[id]!; + final String receiverPublicKey = pendingRequest.metadata.publicKey; + final String senderPublicKey = await core.crypto.generateKeyPair(); + final String responseTopic = core.crypto.getUtils().hashKey( + receiverPublicKey, + ); + final EncodeOptions encodeOpts = EncodeOptions( + type: EncodeOptions.TYPE_1, + receiverPublicKey: receiverPublicKey, + senderPublicKey: senderPublicKey, + ); + + if (error != null) { + await core.pairing.sendError( + id, + responseTopic, + MethodConstants.WC_AUTH_REQUEST, + JsonRpcError.serverError(error.message), + encodeOptions: encodeOpts, + ); + } else { + final Cacao cacao = Cacao( + h: const CacaoHeader(), + p: CacaoPayload.fromRequestPayload( + issuer: iss, + payload: pendingRequest.cacaoPayload, + ), + s: signature!, + ); + + // print('auth res id: $id'); + await core.pairing.sendResult( + id, + responseTopic, + MethodConstants.WC_AUTH_REQUEST, + cacao.toJson(), + encodeOptions: encodeOpts, + ); + + await authRequests.delete(id.toString()); + + await completeRequests.set( + id.toString(), + StoredCacao.fromCacao( + id: id, + pairingTopic: pendingRequest.pairingTopic, + cacao: cacao, + ), + ); + } + } + + // FORMER AUTH ENGINE PROPERTY + void _onAuthRequest(String topic, JsonRpcRequest payload) async { + try { + final request = WcAuthRequestRequest.fromJson(payload.params); + + final CacaoRequestPayload cacaoPayload = + CacaoRequestPayload.fromPayloadParams( + request.payloadParams, + ); + + authRequests.set( + payload.id.toString(), + PendingAuthRequest( + id: payload.id, + pairingTopic: topic, + metadata: request.requester, + cacaoPayload: cacaoPayload, + ), + ); + + onAuthRequest.broadcast( + AuthRequest( + id: payload.id, + topic: topic, + requester: request.requester, + payloadParams: request.payloadParams, + ), + ); + } on WalletConnectError catch (err) { + await core.pairing.sendError( + payload.id, + topic, + payload.method, + JsonRpcError.invalidParams( + err.message, + ), + ); + } + } } diff --git a/lib/apis/sign_api/utils/auth/address_utils.dart b/lib/apis/sign_api/utils/auth/address_utils.dart new file mode 100644 index 00000000..77acd45e --- /dev/null +++ b/lib/apis/sign_api/utils/auth/address_utils.dart @@ -0,0 +1,13 @@ +class AddressUtils { + static String getDidAddress(String iss) { + return iss.split(':').last; + } + + static String getDidChainId(String iss) { + return iss.split(':')[3]; + } + + static String getNamespaceDidChainId(String iss) { + return iss.substring(iss.indexOf(RegExp(r':')) + 1); + } +} diff --git a/lib/apis/sign_api/utils/auth/auth_api_validators.dart b/lib/apis/sign_api/utils/auth/auth_api_validators.dart new file mode 100644 index 00000000..1f951ce1 --- /dev/null +++ b/lib/apis/sign_api/utils/auth/auth_api_validators.dart @@ -0,0 +1,78 @@ +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class AuthApiValidators { + static bool isValidRequestExpiry(int expiry) { + return AuthConstants.AUTH_REQUEST_EXPIRY_MIN <= expiry && + expiry <= AuthConstants.AUTH_REQUEST_EXPIRY_MAX; + } + + static bool isValidRequest(AuthRequestParams params) { + if (!NamespaceUtils.isValidUrl(params.aud)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'requestAuth() invalid aud: ${params.aud}. Must be a valid url.', + ); + } + // final validChainId = true; //NamespaceUtils.isValidChainId(params.chainId); + + if (!params.aud.contains(params.domain)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'requestAuth() invalid domain: ${params.domain}. aud must contain domain.', + ); + } + + if (params.nonce.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'requestAuth() nonce must be nonempty.', + ); + } + + // params.type == null || params.type == CacaoHeader.EIP4361 + if (params.type != null && params.type != CacaoHeader.EIP4361) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'requestAuth() type must null or ${CacaoHeader.EIP4361}.', + ); + } + + final expiry = params.expiry; + if (expiry != null && !isValidRequestExpiry(expiry)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'requestAuth() expiry: $expiry. Expiry must be a number (in seconds) between ${AuthConstants.AUTH_REQUEST_EXPIRY_MIN} and ${AuthConstants.AUTH_REQUEST_EXPIRY_MAX}', + ); + } + + return true; + } + + static bool isValidRespond({ + required int id, + required Map pendingRequests, + CacaoSignature? signature, + WalletConnectError? error, + }) { + if (!pendingRequests.containsKey(id)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'respondAuth() invalid id: $id. No pending request found.', + ); + } + + if (signature == null && error == null) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'respondAuth() invalid response. Must contain either signature or error.', + ); + } + + return true; + } +} diff --git a/lib/apis/sign_api/utils/auth/auth_constants.dart b/lib/apis/sign_api/utils/auth/auth_constants.dart new file mode 100644 index 00000000..9450479c --- /dev/null +++ b/lib/apis/sign_api/utils/auth/auth_constants.dart @@ -0,0 +1,10 @@ +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; + +class AuthConstants { + static const AUTH_REQUEST_EXPIRY_MIN = WalletConnectConstants.FIVE_MINUTES; + static const AUTH_REQUEST_EXPIRY_MAX = WalletConnectConstants.SEVEN_DAYS; + + static const AUTH_DEFAULT_URL = 'https://rpc.walletconnect.com/v1'; + + static const AUTH_CLIENT_PUBLIC_KEY_NAME = 'PUB_KEY'; +} diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart new file mode 100644 index 00000000..31d1e8df --- /dev/null +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -0,0 +1,190 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:convert/convert.dart'; +import 'package:http/http.dart' as http; + +import 'package:pointycastle/digests/keccak.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +import 'package:web3dart/crypto.dart' as crypto; + +class AuthSignature { + static final KeccakDigest keccakDigest = KeccakDigest(256); + static Uint8List keccak256(Uint8List input) { + keccakDigest.reset(); + return keccakDigest.process(input); + } + + static Uint8List hashMessage(String message) { + return keccak256( + Uint8List.fromList( + utf8.encode( + [ + '\x19Ethereum Signed Message:\n', + message.length.toString(), + message, + ].join(), + ), + ), + ); + } + + static int getNormalizedV(int v) { + if (v == 0 || v == 27) { + return 27; + } + if (v == 1 || v == 28) { + return 28; + } + return v & 1 == 1 ? 27 : 28; + } + + static bool isValidEip191Signature( + String address, + String message, + String sig, + ) { + // Get the sig bytes + // print(sig); + final sigBytes = Uint8List.fromList( + hex.decode(sig.substring(2)), + ); + + // If the sig bytes aren't 65 bytes long, throw an error + if (sigBytes.length != 65) { + throw Exception('Invalid signature length'); + } + + // Get the r and s values from the sig bytes + final r = BigInt.parse( + hex.encode(sigBytes.sublist(0, 32)), + radix: 16, + ); + final s = BigInt.parse( + hex.encode(sigBytes.sublist(32, 64)), + radix: 16, + ); + // print(sigBytes[64]); + final v = getNormalizedV(sigBytes[64]); + // print(r); + // print(s); + // print(v); + + // // Recover the public key from the signature + // Uint8List? publicKeyBytes = AuthSecp256k1.recoverPublicKeyFromSignature( + // v - 27, + // r, + // s, + // hashMessage(message), + // ); + + // // If the public key is null, return false + // if (publicKeyBytes == null) { + // print('Could not derive publicKey'); + // return false; + // } + + // Convert the public key to an address + final publicKeyBytes = crypto.ecRecover( + hashMessage(message), + crypto.MsgSignature(r, s, v), + ); + // print(hex.encode(publicKeyBytes)); + final hashedPubKeyBytes = keccak256(publicKeyBytes); + final addressBytes = hashedPubKeyBytes.sublist(12, 32); + final recoveredAddress = '0x${hex.encode(addressBytes)}'; + + // final String recoveredAddress = EthSigUtil.recoverSignature( + // signature: sig, + // message: hashMessage(message), + // // Uint8List.fromList( + // // ascii.encode(message), + // // ), + // ); + + // print(recoveredAddress.toLowerCase()); + // print(address.toLowerCase()); + + return recoveredAddress.toLowerCase() == address.toLowerCase(); + } + + static Future isValidEip1271Signature( + String address, + String reconstructedMessage, + String cacaoSignature, + String chainId, + String projectId, + ) async { + try { + const String eip1271MagicValue = '0x1626ba7e'; + const String dynamicTypeOffset = + '0000000000000000000000000000000000000000000000000000000000000040'; + const String dynamicTypeLength = + '0000000000000000000000000000000000000000000000000000000000000041'; + final String nonPrefixedSignature = cacaoSignature.substring(2); + final String nonPrefixedHashedMessage = + hex.encode(hashMessage(reconstructedMessage)).substring(2); + + final String data = eip1271MagicValue + + nonPrefixedHashedMessage + + dynamicTypeOffset + + dynamicTypeLength + + nonPrefixedSignature; + + final Uri url = Uri.parse( + '${AuthConstants.AUTH_DEFAULT_URL}/?chainId=$chainId&projectId=$projectId', + ); + final Map body = JsonRpcUtils.formatJsonRpcRequest( + 'eth_call', + { + 'to': address, + 'data': data, + }, + ); + + final http.Response response = await http.post( + url, + body: body, + ); + + // print(response.body); + // final jsonBody = jsonDecode(response.body); + final String recoveredValue = + response.body.substring(0, eip1271MagicValue.length); + return recoveredValue.toLowerCase() == eip1271MagicValue.toLowerCase(); + } catch (e) { + return false; + } + } + + // verifies CACAO signature + // Used by the wallet after formatting the message + static Future verifySignature( + String address, + String reconstructedMessage, + CacaoSignature cacaoSignature, + String chainId, + String projectId, + ) async { + if (cacaoSignature.t == 'eip191') { + return isValidEip191Signature( + address, + reconstructedMessage, + cacaoSignature.s, + ); + } else if (cacaoSignature.t == 'eip1271') { + return await isValidEip1271Signature( + address, + reconstructedMessage, + cacaoSignature.s, + chainId, + projectId, + ); + } else { + throw Exception( + 'verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${cacaoSignature.t}', + ); + } + } +} diff --git a/lib/apis/sign_api/utils/auth/auth_utils.dart b/lib/apis/sign_api/utils/auth/auth_utils.dart new file mode 100644 index 00000000..7f4e8016 --- /dev/null +++ b/lib/apis/sign_api/utils/auth/auth_utils.dart @@ -0,0 +1,5 @@ +class AuthUtils { + static String generateNonce() { + return DateTime.now().millisecondsSinceEpoch.toString(); + } +} diff --git a/lib/apis/sign_api/utils/auth/secp256k1/LICENSE b/lib/apis/sign_api/utils/auth/secp256k1/LICENSE new file mode 100644 index 00000000..5c8f2ec8 --- /dev/null +++ b/lib/apis/sign_api/utils/auth/secp256k1/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2021 Wakumo Vietnam + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/lib/apis/sign_api/utils/auth/secp256k1/auth_secp256k1.dart b/lib/apis/sign_api/utils/auth/secp256k1/auth_secp256k1.dart new file mode 100644 index 00000000..20475249 --- /dev/null +++ b/lib/apis/sign_api/utils/auth/secp256k1/auth_secp256k1.dart @@ -0,0 +1,115 @@ +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:convert/convert.dart'; +import 'package:pointycastle/ecc/api.dart'; +import 'package:pointycastle/ecc/curves/secp256k1.dart'; + +enum Endian { + be, +} + +class AuthSecp256k1 { + static final ECDomainParameters _params = ECCurve_secp256k1(); + static final BigInt _byteMask = BigInt.from(0xff); + + static BigInt decodeBigInt(List bytes) { + BigInt result = BigInt.from(0); + for (int i = 0; i < bytes.length; i++) { + result += BigInt.from(bytes[bytes.length - i - 1]) << (8 * i); + } + return result; + } + + static Uint8List encodeBigInt( + BigInt input, { + Endian endian = Endian.be, + int length = 0, + }) { + int byteLength = (input.bitLength + 7) >> 3; + int reqLength = length > 0 ? length : max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + var res = Uint8List(reqLength); + res.fillRange(0, reqLength - byteLength, 0); + + var q = input; + if (endian == Endian.be) { + for (int i = 0; i < byteLength; i++) { + res[reqLength - i - 1] = (q & _byteMask).toInt(); + q = q >> 8; + } + return res; + } + + return Uint8List(0); + } + + static ECPoint _decompressKey(BigInt xBN, bool yBit, ECCurve c) { + List x9IntegerToBytes(BigInt s, int qLength) { + //https://github.com/bcgit/bc-java/blob/master/core/src/main/java/org/bouncycastle/asn1/x9/X9IntegerConverter.java#L45 + String hexString = s.toRadixString(16); + if (hexString.length % 2 == 1) { + hexString = '0$hexString'; + } + final bytes = hex.decode(hexString); + + if (qLength < bytes.length) { + return bytes.sublist(0, bytes.length - qLength); + } else if (qLength > bytes.length) { + final tmp = List.filled(qLength, 0); + + final offset = qLength - bytes.length; + for (var i = 0; i < bytes.length; i++) { + tmp[i + offset] = bytes[i]; + } + + return tmp; + } + + return bytes; + } + + final compEnc = x9IntegerToBytes(xBN, 1 + ((c.fieldSize + 7) ~/ 8)); + compEnc[0] = yBit ? 0x03 : 0x02; + return c.decodePoint(compEnc)!; + } + + static Uint8List? recoverPublicKeyFromSignature( + int recId, + BigInt r, + BigInt s, + Uint8List message, + ) { + final n = _params.n; + final i = BigInt.from(recId ~/ 2); + final x = r + (i * n); + + //Parameter q of curve + final prime = BigInt.parse( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + radix: 16); + if (x.compareTo(prime) >= 0) return null; + + final R = _decompressKey(x, (recId & 1) == 1, _params.curve); + final ECPoint? ecPoint = R * n; + if (ecPoint == null || !ecPoint.isInfinity) return null; + + // print(bytesToHex(message)); + // final e = BigInt.parse(bytesToHex(message).substring(1)); + final e = decodeBigInt(message.toList()); + + final eInv = (BigInt.zero - e) % n; + final rInv = r.modInverse(n); + final srInv = (rInv * s) % n; + final eInvrInv = (rInv * eInv) % n; + + final preQ = (_params.G * eInvrInv); + if (preQ == null) return null; + final q = preQ + (R * srInv); + + final bytes = q?.getEncoded(false); + return bytes?.sublist(1); + } +} diff --git a/lib/apis/web3app/i_web3app.dart b/lib/apis/web3app/i_web3app.dart index 300a4df3..3394a3bf 100644 --- a/lib/apis/web3app/i_web3app.dart +++ b/lib/apis/web3app/i_web3app.dart @@ -1,11 +1,9 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_app.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine_app.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -abstract class IWeb3App implements ISignEngineApp, IAuthEngineApp { +abstract class IWeb3App implements ISignEngineApp { final String protocol = 'wc'; final int version = 2; abstract final ISignEngine signEngine; - abstract final IAuthEngine authEngine; } diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index 5252c7ac..ce33d15b 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -1,4 +1,3 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; @@ -85,11 +84,6 @@ class Web3App implements IWeb3App { return SessionRequest.fromJson(value); }, ), - ); - - authEngine = AuthEngine( - core: core, - metadata: metadata, authKeys: GenericStore( storage: core.storage, context: StoreVersions.CONTEXT_AUTH_KEYS, @@ -133,7 +127,6 @@ class Web3App implements IWeb3App { await core.start(); await signEngine.init(); - await authEngine.init(); _initialized = true; } @@ -335,18 +328,15 @@ class Web3App implements IWeb3App { ///---------- AUTH ENGINE ----------/// @override - Event get onAuthResponse => authEngine.onAuthResponse; + Event get onAuthResponse => signEngine.onAuthResponse; @override - IGenericStore get authKeys => authEngine.authKeys; + IGenericStore get authKeys => signEngine.authKeys; @override - IGenericStore get pairingTopics => authEngine.pairingTopics; + IGenericStore get pairingTopics => signEngine.pairingTopics; @override IGenericStore get completeRequests => - authEngine.completeRequests; - - @override - late IAuthEngine authEngine; + signEngine.completeRequests; @override Future requestAuth({ @@ -355,7 +345,7 @@ class Web3App implements IWeb3App { List>? methods = DEFAULT_METHODS, }) async { try { - return authEngine.requestAuth( + return signEngine.requestAuth( params: params, pairingTopic: pairingTopic, methods: methods, @@ -370,7 +360,7 @@ class Web3App implements IWeb3App { required String pairingTopic, }) { try { - return authEngine.getCompletedRequestsForPairing( + return signEngine.getCompletedRequestsForPairing( pairingTopic: pairingTopic, ); } catch (e) { @@ -384,7 +374,7 @@ class Web3App implements IWeb3App { required CacaoRequestPayload cacaoPayload, }) { try { - return authEngine.formatAuthMessage( + return signEngine.formatAuthMessage( iss: iss, cacaoPayload: cacaoPayload, ); diff --git a/lib/apis/web3wallet/i_web3wallet.dart b/lib/apis/web3wallet/i_web3wallet.dart index 20f0a0b8..2f7308ec 100644 --- a/lib/apis/web3wallet/i_web3wallet.dart +++ b/lib/apis/web3wallet/i_web3wallet.dart @@ -1,11 +1,9 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_wallet.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine_wallet.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -abstract class IWeb3Wallet implements ISignEngineWallet, IAuthEngineWallet { +abstract class IWeb3Wallet implements ISignEngineWallet { final String protocol = 'wc'; final int version = 2; abstract final ISignEngine signEngine; - abstract final IAuthEngine authEngine; } diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index d5d5a395..dd5825f6 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -1,4 +1,3 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; @@ -78,11 +77,6 @@ class Web3Wallet implements IWeb3Wallet { return SessionRequest.fromJson(value); }, ), - ); - - authEngine = AuthEngine( - core: core, - metadata: metadata, authKeys: GenericStore( storage: core.storage, context: StoreVersions.CONTEXT_AUTH_KEYS, @@ -126,7 +120,6 @@ class Web3Wallet implements IWeb3Wallet { await core.start(); await signEngine.init(); - await authEngine.init(); _initialized = true; } @@ -387,20 +380,17 @@ class Web3Wallet implements IWeb3Wallet { ///---------- AUTH ENGINE ----------/// @override - Event get onAuthRequest => authEngine.onAuthRequest; + Event get onAuthRequest => signEngine.onAuthRequest; @override - IGenericStore get authKeys => authEngine.authKeys; + IGenericStore get authKeys => signEngine.authKeys; @override - IGenericStore get pairingTopics => authEngine.pairingTopics; + IGenericStore get pairingTopics => signEngine.pairingTopics; @override - IGenericStore get authRequests => authEngine.authRequests; + IGenericStore get authRequests => signEngine.authRequests; @override IGenericStore get completeRequests => - authEngine.completeRequests; - - @override - late IAuthEngine authEngine; + signEngine.completeRequests; @override Future respondAuthRequest({ @@ -410,7 +400,7 @@ class Web3Wallet implements IWeb3Wallet { WalletConnectError? error, }) async { try { - return authEngine.respondAuthRequest( + return signEngine.respondAuthRequest( id: id, iss: iss, signature: signature, @@ -424,7 +414,7 @@ class Web3Wallet implements IWeb3Wallet { @override Map getPendingAuthRequests() { try { - return authEngine.getPendingAuthRequests(); + return signEngine.getPendingAuthRequests(); } catch (e) { rethrow; } @@ -435,7 +425,7 @@ class Web3Wallet implements IWeb3Wallet { required String pairingTopic, }) { try { - return authEngine.getCompletedRequestsForPairing( + return signEngine.getCompletedRequestsForPairing( pairingTopic: pairingTopic, ); } catch (e) { @@ -450,7 +440,7 @@ class Web3Wallet implements IWeb3Wallet { required CacaoRequestPayload cacaoPayload, }) { try { - return authEngine.formatAuthMessage( + return signEngine.formatAuthMessage( iss: iss, cacaoPayload: cacaoPayload, ); diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 4e6f2ba0..2bf03cbd 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -23,9 +23,9 @@ export 'apis/utils/log_level.dart'; export 'apis/utils/extensions.dart'; // Sign API -export 'apis/sign_api/i_sign_client.dart'; +// export 'apis/sign_api/i_sign_client.dart'; export 'apis/sign_api/i_sign_engine.dart'; -export 'apis/sign_api/sign_client.dart'; +// export 'apis/sign_api/sign_client.dart'; export 'apis/sign_api/sessions.dart'; export 'apis/sign_api/models/proposal_models.dart'; export 'apis/sign_api/models/session_models.dart'; @@ -34,16 +34,15 @@ export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; // Auth API -export 'apis/auth_api/models/auth_client_models.dart'; -export 'apis/auth_api/models/auth_client_events.dart'; -export 'apis/auth_api/models/json_rpc_models.dart'; -export 'apis/auth_api/utils/auth_utils.dart'; -export 'apis/auth_api/utils/address_utils.dart'; -export 'apis/auth_api/utils/auth_signature.dart'; -export 'apis/auth_api/utils/auth_api_validators.dart'; -export 'apis/auth_api/i_auth_engine.dart'; -export 'apis/auth_api/i_auth_client.dart'; -export 'apis/auth_api/auth_client.dart'; +export 'apis/sign_api/models/auth/auth_client_models.dart'; +export 'apis/sign_api/models/auth/auth_client_events.dart'; +export 'apis/sign_api/models/auth/json_rpc_models.dart'; +export 'apis/sign_api/utils/auth/auth_utils.dart'; +export 'apis/sign_api/utils/auth/address_utils.dart'; +export 'apis/sign_api/utils/auth/auth_signature.dart'; +export 'apis/sign_api/utils/auth/auth_api_validators.dart'; +// export 'apis/auth_api/i_auth_client.dart'; +// export 'apis/auth_api/auth_client.dart'; // Web3Wallet export 'apis/web3wallet/i_web3wallet.dart'; diff --git a/test/auth_api/address_utils_test.dart b/test/auth_api/address_utils_test.dart index 601a7c06..66b26921 100644 --- a/test/auth_api/address_utils_test.dart +++ b/test/auth_api/address_utils_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/address_utils.dart'; import '../shared/shared_test_values.dart'; import 'utils/signature_constants.dart'; diff --git a/test/auth_api/signature_test.dart b/test/auth_api/signature_test.dart index 884a504d..ad348871 100644 --- a/test/auth_api/signature_test.dart +++ b/test/auth_api/signature_test.dart @@ -2,7 +2,8 @@ import 'dart:convert'; import 'package:convert/convert.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; import '../shared/shared_test_values.dart'; import 'utils/signature_constants.dart'; diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index 699a1170..322c027e 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; import '../../shared/shared_test_values.dart'; diff --git a/test/auth_api/validation_test.dart b/test/auth_api/validation_test.dart index 72b1bb0a..1f556964 100644 --- a/test/auth_api/validation_test.dart +++ b/test/auth_api/validation_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/utils/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'utils/engine_constants.dart'; diff --git a/test/sign_api/sign_engine_test.dart b/test/sign_api/sign_engine_test.dart index 99e3c707..874dca8d 100644 --- a/test/sign_api/sign_engine_test.dart +++ b/test/sign_api/sign_engine_test.dart @@ -55,6 +55,38 @@ void main() { return SessionRequest.fromJson(value); }, ), + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), ); await core.start(); await e.init(); @@ -96,6 +128,38 @@ void main() { return SessionRequest.fromJson(value); }, ), + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), ); await core.start(); await e.init(); From 4facb2b8346bfbe3f7b6e5aa49ba012749c6e257 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 27 May 2024 16:08:32 +0200 Subject: [PATCH 04/29] revert some files --- lib/apis/auth_api/auth_client.dart | 386 ++++--- lib/apis/auth_api/i_auth_client.dart | 113 +- lib/apis/sign_api/i_sign_client.dart | 178 +++ lib/apis/sign_api/sign_client.dart | 599 ++++++++++ lib/apis/sign_api/sign_engine.dart | 4 +- lib/walletconnect_flutter_v2.dart | 4 +- test/auth_api/auth_client_test.dart | 1000 +++++++++-------- .../utils/auth_client_test_wrapper.dart | 278 +++-- test/sign_api/sign_client_test.dart | 79 +- .../utils/sign_client_test_wrapper.dart | 955 +++++++++------- 10 files changed, 2231 insertions(+), 1365 deletions(-) create mode 100644 lib/apis/sign_api/i_sign_client.dart create mode 100644 lib/apis/sign_api/sign_client.dart diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index c0a03002..e7b89e0a 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,197 +1,189 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; - -// class AuthClient implements IAuthClient { -// bool _initialized = false; - -// @override -// String get protocol => 'wc'; - -// @override -// int get version => 2; - -// @override -// Event get onAuthRequest => engine.onAuthRequest; -// @override -// Event get onAuthResponse => engine.onAuthResponse; - -// @override -// ICore get core => engine.core; -// @override -// PairingMetadata get metadata => engine.metadata; -// @override -// IGenericStore get authKeys => engine.authKeys; -// @override -// IGenericStore get pairingTopics => engine.pairingTopics; -// @override -// IGenericStore get authRequests => engine.authRequests; -// @override -// IGenericStore get completeRequests => engine.completeRequests; - -// @override -// late IAuthEngine engine; - -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// IHttpClient httpClient = const HttpWrapper(), -// LogLevel logLevel = LogLevel.nothing, -// }) async { -// final client = AuthClient( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// httpClient: httpClient, -// logLevel: logLevel, -// ), -// metadata: metadata, -// ); -// await client.init(); - -// return client; -// } - -// AuthClient({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// engine = AuthEngine( -// core: core, -// metadata: metadata, -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value as String; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// } - -// @override -// Future init() async { -// if (_initialized) { -// return; -// } - -// await core.start(); -// await engine.init(); - -// _initialized = true; -// } - -// @override -// Future request({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods = AuthEngine.DEFAULT_METHODS, -// }) async { -// try { -// return engine.requestAuth( -// params: params, -// pairingTopic: pairingTopic, -// methods: methods, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future respond({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }) async { -// try { -// return engine.respondAuthRequest( -// id: id, -// iss: iss, -// signature: signature, -// error: error, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingRequests() { -// try { -// return engine.getPendingAuthRequests(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return engine.getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// String formatMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }) { -// try { -// return engine.formatAuthMessage( -// iss: iss, -// cacaoPayload: cacaoPayload, -// ); -// } catch (e) { -// rethrow; -// } -// } -// } +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class AuthClient implements IAuthClient { + bool _initialized = false; + + @override + String get protocol => 'wc'; + + @override + int get version => 2; + + @override + Event get onAuthRequest => engine.onAuthRequest; + @override + Event get onAuthResponse => engine.onAuthResponse; + + @override + ICore get core => engine.core; + @override + PairingMetadata get metadata => engine.metadata; + @override + IGenericStore get authKeys => engine.authKeys; + @override + IGenericStore get pairingTopics => engine.pairingTopics; + @override + IGenericStore get authRequests => engine.authRequests; + @override + IGenericStore get completeRequests => engine.completeRequests; + + @override + late IAuthEngine engine; + + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + IHttpClient httpClient = const HttpWrapper(), + LogLevel logLevel = LogLevel.nothing, + }) async { + final client = AuthClient( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + httpClient: httpClient, + logLevel: logLevel, + ), + metadata: metadata, + ); + await client.init(); + + return client; + } + + AuthClient({ + required ICore core, + required PairingMetadata metadata, + }) { + engine = AuthEngine( + core: core, + metadata: metadata, + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value as String; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + } + + @override + Future init() async { + if (_initialized) { + return; + } + + await core.start(); + await engine.init(); + + _initialized = true; + } + + @override + Future request({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = AuthEngine.DEFAULT_METHODS, + }) async { + try { + return engine.requestAuth( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respond({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + try { + return engine.respondAuthRequest( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingRequests() { + try { + return engine.getPendingAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return engine.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + String formatMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return engine.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 848d0974..758f6b84 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,56 +1,57 @@ -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -// abstract class IAuthClient { -// final String protocol = 'wc'; -// final int version = 2; - -// abstract final IAuthEngine engine; - -// // Common -// abstract final ICore core; -// abstract final PairingMetadata metadata; - -// abstract final IGenericStore authKeys; -// abstract final IGenericStore pairingTopics; -// abstract final IGenericStore completeRequests; - -// // initializes the client with persisted storage and a network connection -// Future init(); - -// /// format payload to message string -// String formatMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }); - -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }); - -// // App -// abstract final Event onAuthResponse; - -// // request wallet authentication -// Future request({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods, -// }); - -// // Wallet -// abstract final Event onAuthRequest; - -// abstract final IGenericStore authRequests; - -// /// respond wallet authentication -// Future respond({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }); - -// // query all pending requests -// Map getPendingRequests(); -// } +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +abstract class IAuthClient { + final String protocol = 'wc'; + final int version = 2; + + abstract final IAuthEngine engine; + + // Common + abstract final ICore core; + abstract final PairingMetadata metadata; + + abstract final IGenericStore authKeys; + abstract final IGenericStore pairingTopics; + abstract final IGenericStore completeRequests; + + // initializes the client with persisted storage and a network connection + Future init(); + + /// format payload to message string + String formatMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }); + + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }); + + // App + abstract final Event onAuthResponse; + + // request wallet authentication + Future request({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }); + + // Wallet + abstract final Event onAuthRequest; + + abstract final IGenericStore authRequests; + + /// respond wallet authentication + Future respond({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }); + + // query all pending requests + Map getPendingRequests(); +} diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart new file mode 100644 index 00000000..9ffbb24e --- /dev/null +++ b/lib/apis/sign_api/i_sign_client.dart @@ -0,0 +1,178 @@ +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/walletconnect_flutter_v2.dart'; + +abstract class ISignClient { + final String protocol = 'wc'; + final int version = 2; + + abstract final ISignEngine engine; + + // Common + abstract final Event onSessionConnect; + abstract final Event onSessionDelete; + abstract final Event onSessionExpire; + abstract final Event onSessionPing; + abstract final Event onProposalExpire; + + abstract final ICore core; + abstract final PairingMetadata metadata; + abstract final IGenericStore proposals; + abstract final ISessions sessions; + abstract final IGenericStore pendingRequests; + + // FORMER AUTH ENGINE COMMON + abstract final IGenericStore authKeys; + abstract final IGenericStore pairingTopics; + abstract final IGenericStore completeRequests; + + // Wallet + abstract final Event onSessionProposal; + abstract final Event onSessionProposalError; + abstract final Event onSessionRequest; + // FORMER AUTH ENGINE PROPERTY + abstract final Event onAuthRequest; + abstract final IGenericStore authRequests; + + // App + abstract final Event onSessionUpdate; + abstract final Event onSessionExtend; + abstract final Event onSessionEvent; + // FORMER AUTH ENGINE PROPERTY + abstract final Event onAuthResponse; + + Future init(); + Future connect({ + Map? requiredNamespaces, + Map? optionalNamespaces, + Map? sessionProperties, + String? pairingTopic, + List? relays, + List>? methods, + }); + Future pair({ + required Uri uri, + }); + Future approve({ + required int id, + required Map namespaces, + Map? sessionProperties, + String? relayProtocol, + }); + Future reject({ + required int id, + required WalletConnectError reason, + }); + Future update({ + required String topic, + required Map namespaces, + }); + Future extend({ + required String topic, + }); + void registerRequestHandler({ + required String chainId, + required String method, + dynamic Function(String, dynamic)? handler, + }); + Future respond({ + required String topic, + required JsonRpcResponse response, + }); + Future emit({ + required String topic, + required String chainId, + required SessionEventParams event, + }); + Future request({ + required String topic, + required String chainId, + required SessionRequestParams request, + }); + Future> requestReadContract({ + required DeployedContract deployedContract, + required String functionName, + required String rpcUrl, + List parameters = const [], + }); + 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 [], + }); + + void registerEventHandler({ + required String chainId, + required String event, + required dynamic Function(String, dynamic)? handler, + }); + Future ping({ + required String topic, + }); + Future disconnect({ + required String topic, + required WalletConnectError reason, + }); + SessionData? find({ + required Map requiredNamespaces, + }); + Map getActiveSessions(); + Map getSessionsForPairing({ + required String pairingTopic, + }); + Map getPendingSessionProposals(); + Map getPendingSessionRequests(); + abstract final IPairingStore pairings; + + /// Register event emitters for a given namespace or chainId + /// Used to construct the Namespaces map for the session proposal + void registerEventEmitter({ + required String chainId, + required String event, + }); + + /// Register accounts for a given namespace or chainId. + /// Used to construct the Namespaces map for the session proposal. + /// Each account must follow the namespace:chainId:address format or this will throw an error. + void registerAccount({ + required String chainId, + required String accountAddress, + }); + + // FORMER AUTH ENGINE COMMON + /// format payload to message string + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }); + + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }); + + // FORMER AUTH ENGINE WALLET + // to be transformed into approveSessionAuthenticate({}) + // to be transformed into rejectSessionAuthenticate({}) + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }); + // FORMER AUTH ENGINE DAPP + // query all pending requests + Map getPendingAuthRequests(); + + // FORMER AUTH ENGINE PROPERTY + // to be transformed into authenticate({}); + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }); +} diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart new file mode 100644 index 00000000..2d504f56 --- /dev/null +++ b/lib/apis/sign_api/sign_client.dart @@ -0,0 +1,599 @@ +import 'package:event/event.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_pairing_store.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_client.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/sessions.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +import 'package:web3dart/web3dart.dart'; + +class SignClient implements ISignClient { + bool _initialized = false; + + @override + final String protocol = 'wc'; + @override + final int version = 2; + + @override + Event get onSessionDelete => engine.onSessionDelete; + @override + Event get onSessionConnect => engine.onSessionConnect; + @override + Event get onSessionEvent => engine.onSessionEvent; + @override + Event get onSessionExpire => engine.onSessionExpire; + @override + Event get onSessionExtend => engine.onSessionExtend; + @override + Event get onSessionPing => engine.onSessionPing; + @override + Event get onSessionProposal => engine.onSessionProposal; + @override + Event get onSessionProposalError => + engine.onSessionProposalError; + @override + Event get onProposalExpire => engine.onProposalExpire; + @override + Event get onSessionRequest => engine.onSessionRequest; + @override + Event get onSessionUpdate => engine.onSessionUpdate; + + @override + ICore get core => engine.core; + @override + PairingMetadata get metadata => engine.metadata; + @override + IGenericStore get proposals => engine.proposals; + @override + ISessions get sessions => engine.sessions; + @override + IGenericStore get pendingRequests => engine.pendingRequests; + + @override + late ISignEngine engine; + + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + LogLevel logLevel = LogLevel.nothing, + }) async { + final client = SignClient( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + logLevel: logLevel, + ), + metadata: metadata, + ); + await client.init(); + + return client; + } + + SignClient({ + required ICore core, + required PairingMetadata metadata, + }) { + engine = SignEngine( + core: core, + metadata: metadata, + proposals: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PROPOSALS, + version: StoreVersions.VERSION_PROPOSALS, + fromJson: (dynamic value) { + return ProposalData.fromJson(value); + }, + ), + sessions: Sessions( + storage: core.storage, + context: StoreVersions.CONTEXT_SESSIONS, + version: StoreVersions.VERSION_SESSIONS, + fromJson: (dynamic value) { + return SessionData.fromJson(value); + }, + ), + pendingRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PENDING_REQUESTS, + version: StoreVersions.VERSION_PENDING_REQUESTS, + fromJson: (dynamic value) { + return SessionRequest.fromJson(value); + }, + ), + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + } + + @override + Future init() async { + if (_initialized) { + return; + } + + await core.start(); + await engine.init(); + + _initialized = true; + } + + @override + Future connect({ + Map? requiredNamespaces, + Map? optionalNamespaces, + Map? sessionProperties, + String? pairingTopic, + List? relays, + List>? methods = SignEngine.DEFAULT_METHODS, + }) async { + try { + return await engine.connect( + requiredNamespaces: requiredNamespaces, + optionalNamespaces: optionalNamespaces, + sessionProperties: sessionProperties, + pairingTopic: pairingTopic, + relays: relays, + methods: methods, + ); + } catch (e) { + // print(e); + rethrow; + } + } + + @override + Future pair({ + required Uri uri, + }) async { + try { + return await engine.pair(uri: uri); + } catch (e) { + rethrow; + } + } + + @override + Future approve({ + required int id, + required Map namespaces, + Map? sessionProperties, + String? relayProtocol, + }) async { + try { + return await engine.approveSession( + id: id, + namespaces: namespaces, + sessionProperties: sessionProperties, + relayProtocol: relayProtocol, + ); + } catch (e) { + rethrow; + } + } + + @override + Future reject({ + required int id, + required WalletConnectError reason, + }) async { + try { + return await engine.rejectSession( + id: id, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + + @override + Future update({ + required String topic, + required Map namespaces, + }) async { + try { + return await engine.updateSession( + topic: topic, + namespaces: namespaces, + ); + } catch (e) { + // final error = e as WCError; + rethrow; + } + } + + @override + Future extend({ + required String topic, + }) async { + try { + return await engine.extendSession(topic: topic); + } catch (e) { + rethrow; + } + } + + @override + void registerRequestHandler({ + required String chainId, + required String method, + void Function(String, dynamic)? handler, + }) { + try { + return engine.registerRequestHandler( + chainId: chainId, + method: method, + handler: handler, + ); + } catch (e) { + rethrow; + } + } + + @override + Future request({ + required String topic, + required String chainId, + required SessionRequestParams request, + }) async { + try { + return await engine.request( + topic: topic, + chainId: chainId, + request: request, + ); + } catch (e) { + rethrow; + } + } + + @override + Future> requestReadContract({ + required DeployedContract deployedContract, + required String functionName, + required String rpcUrl, + List parameters = const [], + }) async { + try { + return await engine.requestReadContract( + deployedContract: deployedContract, + functionName: functionName, + rpcUrl: rpcUrl, + parameters: parameters, + ); + } catch (e) { + rethrow; + } + } + + @override + 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 [], + }) async { + try { + return await engine.requestWriteContract( + topic: topic, + chainId: chainId, + rpcUrl: rpcUrl, + deployedContract: deployedContract, + functionName: functionName, + transaction: transaction, + method: method, + parameters: parameters, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respond({ + required String topic, + required JsonRpcResponse response, + }) { + try { + return engine.respondSessionRequest( + topic: topic, + response: response, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerEventHandler({ + required String chainId, + required String event, + dynamic Function(String, dynamic)? handler, + }) { + try { + return engine.registerEventHandler( + chainId: chainId, + event: event, + handler: handler, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerEventEmitter({ + required String chainId, + required String event, + }) { + try { + return engine.registerEventEmitter( + chainId: chainId, + event: event, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerAccount({ + required String chainId, + required String accountAddress, + }) { + try { + return engine.registerAccount( + chainId: chainId, + accountAddress: accountAddress, + ); + } catch (e) { + rethrow; + } + } + + @override + Future emit({ + required String topic, + required String chainId, + required SessionEventParams event, + }) async { + try { + return await engine.emitSessionEvent( + topic: topic, + chainId: chainId, + event: event, + ); + } catch (e) { + rethrow; + } + } + + @override + Future ping({ + required String topic, + }) async { + try { + return await engine.ping(topic: topic); + } catch (e) { + rethrow; + } + } + + @override + Future disconnect({ + required String topic, + required WalletConnectError reason, + }) async { + try { + return await engine.disconnectSession( + topic: topic, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + + @override + SessionData? find({ + required Map requiredNamespaces, + }) { + try { + return engine.find(requiredNamespaces: requiredNamespaces); + } catch (e) { + rethrow; + } + } + + @override + Map getActiveSessions() { + try { + return engine.getActiveSessions(); + } catch (e) { + rethrow; + } + } + + @override + Map getSessionsForPairing({ + required String pairingTopic, + }) { + try { + return engine.getSessionsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingSessionProposals() { + try { + return engine.getPendingSessionProposals(); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingSessionRequests() { + try { + return engine.getPendingSessionRequests(); + } catch (e) { + rethrow; + } + } + + @override + IPairingStore get pairings => core.pairing.getStore(); + + // FORMER AUTH ENGINE METHODS + + @override + IGenericStore get authRequests => engine.authRequests; + + @override + Map getPendingAuthRequests() { + try { + return engine.getPendingAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + Event get onAuthRequest => engine.onAuthRequest; + + @override + Event get onAuthResponse => engine.onAuthResponse; + + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }) { + try { + return engine.requestAuth( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) { + try { + return engine.respondAuthRequest( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } + + @override + IGenericStore get authKeys => engine.authKeys; + + @override + IGenericStore get completeRequests => engine.completeRequests; + + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return engine.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return engine.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + IGenericStore get pairingTopics => engine.pairingTopics; +} diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 7900dbe1..2bdfa618 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -72,9 +72,9 @@ class SignEngine implements ISignEngine { @override IGenericStore completeRequests; @override - final Event onAuthRequest = Event(); + final Event onAuthRequest = Event(); @override - final Event onAuthResponse = Event(); + final Event onAuthResponse = Event(); @override late IGenericStore pairingTopics; diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 2bf03cbd..17f934aa 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -23,9 +23,9 @@ export 'apis/utils/log_level.dart'; export 'apis/utils/extensions.dart'; // Sign API -// export 'apis/sign_api/i_sign_client.dart'; +export 'apis/sign_api/i_sign_client.dart'; +export 'apis/sign_api/sign_client.dart'; export 'apis/sign_api/i_sign_engine.dart'; -// export 'apis/sign_api/sign_client.dart'; export 'apis/sign_api/sessions.dart'; export 'apis/sign_api/models/proposal_models.dart'; export 'apis/sign_api/models/session_models.dart'; diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index de143617..c03304fa 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -1,494 +1,506 @@ -// import 'dart:async'; -// import 'dart:typed_data'; - -// import 'package:eth_sig_util/eth_sig_util.dart'; -// import 'package:flutter_test/flutter_test.dart'; -// import 'package:package_info_plus/package_info_plus.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'; -// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -// import '../shared/shared_test_utils.dart'; -// import '../shared/shared_test_values.dart'; -// import 'utils/auth_client_test_wrapper.dart'; -// import 'utils/engine_constants.dart'; -// 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', -// ); - -// final List Function(PairingMetadata)> authAppCreators = -// [ -// (PairingMetadata metadata) async => -// await AuthClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// (PairingMetadata? self) async { -// final core = Core( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ); -// IAuthEngine e = AuthEngine( -// core: core, -// metadata: self ?? PairingMetadata.empty(), -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// await core.start(); -// await e.init(); - -// return e; -// }, -// (PairingMetadata metadata) async => -// await AuthClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// ]; - -// final List Function(PairingMetadata)> -// authWalletCreators = [ -// (PairingMetadata metadata) async => await Web3Wallet.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// (PairingMetadata metadata) async { -// final core = Core( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ); -// IAuthEngine e = AuthEngine( -// core: core, -// metadata: metadata, -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// await core.start(); -// await e.init(); - -// return e; -// }, -// (PairingMetadata metadata) async => await Web3Wallet.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// ]; - -// final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; - -// for (int i = 0; i < authAppCreators.length; i++) { -// runTests( -// context: contexts[i], -// engineAppCreator: authAppCreators[i], -// engineWalletCreator: authWalletCreators[i], -// ); -// } -// } - -// void runTests({ -// required String context, -// required Future Function(PairingMetadata) engineAppCreator, -// required Future Function(PairingMetadata) -// engineWalletCreator, -// }) { -// group(context, () { -// late IAuthEngineApp clientA; -// late IAuthEngineWallet clientB; - -// setUp(() async { -// clientA = await engineAppCreator( -// TEST_METADATA_REQUESTER, -// ); -// clientB = await engineWalletCreator( -// TEST_METADATA_RESPONDER, -// ); -// }); - -// tearDown(() async { -// await clientA.core.relayClient.disconnect(); -// await clientB.core.relayClient.disconnect(); -// }); - -// group('happy path', () { -// test('Initializes', () async { -// expect(clientA.core.pairing.getPairings().length, 0); -// expect(clientB.core.pairing.getPairings().length, 0); -// }); - -// test( -// 'connects and receives request, reconnects and receives another request, and emits proper events', -// () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: defaultRequestParams, -// ); -// final String pairingTopic = response.pairingTopic; - -// Completer completerAPairing = Completer(); -// Completer completerBPairing = Completer(); -// Completer completerA = Completer(); -// Completer completerB = Completer(); -// int counterAPairing = 0; -// int counterBPairing = 0; -// int counterA = 0; -// int counterB = 0; -// clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { -// expect(pairing != null, true); -// expect(pairing!.topic, pairingTopic); -// counterAPairing++; -// completerAPairing.complete(); -// }); -// clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { -// expect(pairing != null, true); -// expect(pairing!.topic, pairingTopic); -// counterBPairing++; -// completerBPairing.complete(); -// }); -// clientA.onAuthResponse.subscribe((AuthResponse? args) { -// counterA++; -// completerA.complete(); - -// expect(args!.result, isNotNull); -// }); -// clientB.onAuthRequest.subscribe((AuthRequest? args) async { -// counterB++; - -// int currReqCount = clientB.getPendingAuthRequests().length; - -// expect(args != null, true); - -// // Create the message to be signed -// String message = clientB.formatAuthMessage( -// iss: TEST_ISSUER_EIP191, -// cacaoPayload: CacaoRequestPayload.fromPayloadParams( -// args!.payloadParams, -// ), -// ); - -// String sig = EthSigUtil.signPersonalMessage( -// message: Uint8List.fromList(message.codeUnits), -// privateKey: TEST_PRIVATE_KEY_EIP191, -// ); - -// await clientB.respondAuthRequest( -// id: args.id, -// iss: TEST_ISSUER_EIP191, -// signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), -// ); - -// expect(clientB.getPendingAuthRequests().length, currReqCount - 1); - -// completerB.complete(); -// }); - -// expect(response.uri != null, true); - -// await clientB.core.pairing.pair(uri: response.uri!); -// expect(clientA.core.pairing.getPairings().length, 1); -// expect(clientB.core.pairing.getPairings().length, 1); -// // AuthResponse authResponse = await response.completer.future; - -// await clientA.core.pairing.ping(topic: pairingTopic); -// await clientB.core.pairing.ping(topic: pairingTopic); - -// if (!completerAPairing.isCompleted) { -// clientA.core.logger.i('Waiting for completerAPairing'); -// await completerAPairing.future; -// } -// if (!completerBPairing.isCompleted) { -// clientA.core.logger.i('Waiting for completerBPairing'); -// await completerBPairing.future; -// } -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } -// if (!completerB.isCompleted) { -// clientA.core.logger.i('Waiting for completerB'); -// await completerB.future; -// } - -// AuthResponse authResponse = await response.completer.future; -// expect(authResponse.result != null, true); - -// expect(counterAPairing, 1); -// expect(counterBPairing, 1); - -// expect(counterA, 1); -// expect(counterB, 1); - -// expect( -// clientA -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 1, -// ); -// expect( -// clientB -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 1, -// ); - -// completerA = Completer(); -// completerB = Completer(); - -// response = await clientA.requestAuth( -// params: defaultRequestParams, -// pairingTopic: pairingTopic, -// ); - -// expect(response.uri == null, true); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } -// if (!completerB.isCompleted) { -// clientA.core.logger.i('Waiting for completerB'); -// await completerB.future; -// } - -// authResponse = await response.completer.future; -// expect(authResponse.result != null, true); - -// // Got the second request and response -// expect(counterA, 2); -// expect(counterB, 2); - -// expect( -// clientA -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 2, -// ); -// expect( -// clientB -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 2, -// ); - -// clientA.onAuthResponse.unsubscribeAll(); -// clientB.onAuthRequest.unsubscribeAll(); -// clientA.core.pairing.onPairingPing.unsubscribeAll(); -// clientB.core.pairing.onPairingPing.unsubscribeAll(); -// }); - -// test('counts pendingAuthRequests properly', () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: defaultRequestParams, -// ); -// final String pairingTopic = response.pairingTopic; - -// await clientB.core.pairing.pair(uri: response.uri!); - -// Completer completerA = Completer(); -// clientB.onAuthRequest.subscribe((AuthRequest? args) async { -// // print('got here'); -// // print(clientB.getPendingAuthRequests().length); -// completerA.complete(); -// }); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } - -// expect(clientB.getPendingAuthRequests().length, 1); - -// completerA = Completer(); - -// response = await clientA.requestAuth( -// params: defaultRequestParams, -// pairingTopic: pairingTopic, -// ); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } - -// expect(clientB.getPendingAuthRequests().length, 2); -// }); -// }); - -// group('requestAuth', () { -// test('creates correct URI', () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: testAuthRequestParamsValid, -// ); - -// expect(response.uri != null, true); -// URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); -// expect(parsed.protocol, 'wc'); -// expect(parsed.version, URIVersion.v2); -// expect(parsed.topic, response.pairingTopic); -// expect(parsed.v2Data!.relay.protocol, 'irn'); -// if (clientA is IWeb3App) { -// expect(parsed.v2Data!.methods.length, 3); -// expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); -// expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); -// expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); -// } else { -// expect(parsed.v2Data!.methods.length, 1); -// expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); -// } - -// response = await clientA.requestAuth( -// params: testAuthRequestParamsValid, -// methods: [], -// ); - -// expect(response.uri != null, true); -// parsed = WalletConnectUtils.parseUri(response.uri!); -// expect(parsed.protocol, 'wc'); -// expect(parsed.version, URIVersion.v2); -// expect(parsed.v2Data!.relay.protocol, 'irn'); -// expect(parsed.v2Data!.methods.length, 0); -// }); - -// test('invalid request params', () async { -// expect( -// () => clientA.requestAuth( -// params: testAuthRequestParamsInvalidAud, -// ), -// throwsA( -// isA().having( -// (e) => e.message, -// 'message', -// 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', -// ), -// ), -// ); -// }); -// }); - -// group('respondAuth', () { -// test('invalid response params', () async { -// expect( -// () => clientB.respondAuthRequest( -// id: -1, -// iss: TEST_ISSUER_EIP191, -// ), -// throwsA( -// isA().having( -// (e) => e.message, -// 'message', -// 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', -// ), -// ), -// ); -// }); -// }); - -// group('formatAuthMessage', () { -// test('works', () { -// final String message = clientA.formatAuthMessage( -// iss: TEST_ISSUER_EIP191, -// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), -// ); -// expect(message, TEST_FORMATTED_MESSAGE); -// }); -// }); -// }); -// } +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:eth_sig_util/eth_sig_util.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_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'; +import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.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/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/walletconnect_utils.dart'; +import 'package:walletconnect_flutter_v2/apis/web3app/i_web3app.dart'; +// import 'package:walletconnect_flutter_v2/apis/web3wallet/web3wallet.dart'; + +import '../shared/shared_test_utils.dart'; +import '../shared/shared_test_values.dart'; +import 'utils/auth_client_test_wrapper.dart'; +import 'utils/engine_constants.dart'; +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', + ); + + final List Function(PairingMetadata)> authAppCreators = + [ + (PairingMetadata metadata) async => + await AuthClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + (PairingMetadata? self) async { + final core = Core( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ); + IAuthEngine e = AuthEngine( + core: core, + metadata: self ?? PairingMetadata.empty(), + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + await core.start(); + await e.init(); + + return e; + }, + (PairingMetadata metadata) async => + await AuthClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + ]; + + final List Function(PairingMetadata)> + authWalletCreators = [ + // (PairingMetadata metadata) async => await Web3Wallet.createInstance( + // projectId: TEST_PROJECT_ID, + // relayUrl: TEST_RELAY_URL, + // metadata: metadata, + // memoryStore: true, + // logLevel: LogLevel.info, + // httpClient: getHttpWrapper(), + // ), + (PairingMetadata metadata) async { + final core = Core( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ); + IAuthEngine e = AuthEngine( + core: core, + metadata: metadata, + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + await core.start(); + await e.init(); + + return e; + }, + // (PairingMetadata metadata) async => await Web3Wallet.createInstance( + // projectId: TEST_PROJECT_ID, + // relayUrl: TEST_RELAY_URL, + // metadata: metadata, + // memoryStore: true, + // logLevel: LogLevel.info, + // httpClient: getHttpWrapper(), + // ), + ]; + + final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; + + for (int i = 0; i < authAppCreators.length; i++) { + runTests( + context: contexts[i], + engineAppCreator: authAppCreators[i], + engineWalletCreator: authWalletCreators[i], + ); + } +} + +void runTests({ + required String context, + required Future Function(PairingMetadata) engineAppCreator, + required Future Function(PairingMetadata) + engineWalletCreator, +}) { + group(context, () { + late IAuthEngineApp clientA; + late IAuthEngineWallet clientB; + + setUp(() async { + clientA = await engineAppCreator( + TEST_METADATA_REQUESTER, + ); + clientB = await engineWalletCreator( + TEST_METADATA_RESPONDER, + ); + }); + + tearDown(() async { + await clientA.core.relayClient.disconnect(); + await clientB.core.relayClient.disconnect(); + }); + + group('happy path', () { + test('Initializes', () async { + expect(clientA.core.pairing.getPairings().length, 0); + expect(clientB.core.pairing.getPairings().length, 0); + }); + + test( + 'connects and receives request, reconnects and receives another request, and emits proper events', + () async { + AuthRequestResponse response = await clientA.requestAuth( + params: defaultRequestParams, + ); + final String pairingTopic = response.pairingTopic; + + Completer completerAPairing = Completer(); + Completer completerBPairing = Completer(); + Completer completerA = Completer(); + Completer completerB = Completer(); + int counterAPairing = 0; + int counterBPairing = 0; + int counterA = 0; + int counterB = 0; + clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { + expect(pairing != null, true); + expect(pairing!.topic, pairingTopic); + counterAPairing++; + completerAPairing.complete(); + }); + clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { + expect(pairing != null, true); + expect(pairing!.topic, pairingTopic); + counterBPairing++; + completerBPairing.complete(); + }); + clientA.onAuthResponse.subscribe((AuthResponse? args) { + counterA++; + completerA.complete(); + + expect(args!.result, isNotNull); + }); + clientB.onAuthRequest.subscribe((AuthRequest? args) async { + counterB++; + + int currReqCount = clientB.getPendingAuthRequests().length; + + expect(args != null, true); + + // Create the message to be signed + String message = clientB.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromPayloadParams( + args!.payloadParams, + ), + ); + + String sig = EthSigUtil.signPersonalMessage( + message: Uint8List.fromList(message.codeUnits), + privateKey: TEST_PRIVATE_KEY_EIP191, + ); + + await clientB.respondAuthRequest( + id: args.id, + iss: TEST_ISSUER_EIP191, + signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), + ); + + expect(clientB.getPendingAuthRequests().length, currReqCount - 1); + + completerB.complete(); + }); + + expect(response.uri != null, true); + + await clientB.core.pairing.pair(uri: response.uri!); + expect(clientA.core.pairing.getPairings().length, 1); + expect(clientB.core.pairing.getPairings().length, 1); + // AuthResponse authResponse = await response.completer.future; + + await clientA.core.pairing.ping(topic: pairingTopic); + await clientB.core.pairing.ping(topic: pairingTopic); + + if (!completerAPairing.isCompleted) { + clientA.core.logger.i('Waiting for completerAPairing'); + await completerAPairing.future; + } + if (!completerBPairing.isCompleted) { + clientA.core.logger.i('Waiting for completerBPairing'); + await completerBPairing.future; + } + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + if (!completerB.isCompleted) { + clientA.core.logger.i('Waiting for completerB'); + await completerB.future; + } + + AuthResponse authResponse = await response.completer.future; + expect(authResponse.result != null, true); + + expect(counterAPairing, 1); + expect(counterBPairing, 1); + + expect(counterA, 1); + expect(counterB, 1); + + expect( + clientA + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 1, + ); + expect( + clientB + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 1, + ); + + completerA = Completer(); + completerB = Completer(); + + response = await clientA.requestAuth( + params: defaultRequestParams, + pairingTopic: pairingTopic, + ); + + expect(response.uri == null, true); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + if (!completerB.isCompleted) { + clientA.core.logger.i('Waiting for completerB'); + await completerB.future; + } + + authResponse = await response.completer.future; + expect(authResponse.result != null, true); + + // Got the second request and response + expect(counterA, 2); + expect(counterB, 2); + + expect( + clientA + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 2, + ); + expect( + clientB + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 2, + ); + + clientA.onAuthResponse.unsubscribeAll(); + clientB.onAuthRequest.unsubscribeAll(); + clientA.core.pairing.onPairingPing.unsubscribeAll(); + clientB.core.pairing.onPairingPing.unsubscribeAll(); + }); + + test('counts pendingAuthRequests properly', () async { + AuthRequestResponse response = await clientA.requestAuth( + params: defaultRequestParams, + ); + final String pairingTopic = response.pairingTopic; + + await clientB.core.pairing.pair(uri: response.uri!); + + Completer completerA = Completer(); + clientB.onAuthRequest.subscribe((AuthRequest? args) async { + // print('got here'); + // print(clientB.getPendingAuthRequests().length); + completerA.complete(); + }); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + + expect(clientB.getPendingAuthRequests().length, 1); + + completerA = Completer(); + + response = await clientA.requestAuth( + params: defaultRequestParams, + pairingTopic: pairingTopic, + ); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + + expect(clientB.getPendingAuthRequests().length, 2); + }); + }); + + group('requestAuth', () { + test('creates correct URI', () async { + AuthRequestResponse response = await clientA.requestAuth( + params: testAuthRequestParamsValid, + ); + + expect(response.uri != null, true); + URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); + expect(parsed.protocol, 'wc'); + expect(parsed.version, URIVersion.v2); + expect(parsed.topic, response.pairingTopic); + expect(parsed.v2Data!.relay.protocol, 'irn'); + if (clientA is IWeb3App) { + expect(parsed.v2Data!.methods.length, 3); + expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); + expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); + expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); + } else { + expect(parsed.v2Data!.methods.length, 1); + expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); + } + + response = await clientA.requestAuth( + params: testAuthRequestParamsValid, + methods: [], + ); + + expect(response.uri != null, true); + parsed = WalletConnectUtils.parseUri(response.uri!); + expect(parsed.protocol, 'wc'); + expect(parsed.version, URIVersion.v2); + expect(parsed.v2Data!.relay.protocol, 'irn'); + expect(parsed.v2Data!.methods.length, 0); + }); + + test('invalid request params', () async { + expect( + () => clientA.requestAuth( + params: testAuthRequestParamsInvalidAud, + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', + ), + ), + ); + }); + }); + + group('respondAuth', () { + test('invalid response params', () async { + expect( + () => clientB.respondAuthRequest( + id: -1, + iss: TEST_ISSUER_EIP191, + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', + ), + ), + ); + }); + }); + + group('formatAuthMessage', () { + test('works', () { + final String message = clientA.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), + ); + expect(message, TEST_FORMATTED_MESSAGE); + }); + }); + }); +} diff --git a/test/auth_api/utils/auth_client_test_wrapper.dart b/test/auth_api/utils/auth_client_test_wrapper.dart index 730a7059..64f3ea9b 100644 --- a/test/auth_api/utils/auth_client_test_wrapper.dart +++ b/test/auth_api/utils/auth_client_test_wrapper.dart @@ -1,158 +1,150 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/models/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -// class AuthClientTestWrapper implements IAuthEngine { -// bool _initialized = false; +class AuthClientTestWrapper implements IAuthEngine { + bool _initialized = false; -// @override -// Event get onAuthRequest => client.onAuthRequest; -// @override -// Event get onAuthResponse => client.onAuthResponse; + @override + Event get onAuthRequest => client.onAuthRequest; + @override + Event get onAuthResponse => client.onAuthResponse; -// @override -// ICore get core => client.core; -// @override -// PairingMetadata get metadata => client.metadata; -// @override -// IGenericStore get authKeys => client.authKeys; -// @override -// IGenericStore get pairingTopics => client.pairingTopics; -// @override -// IGenericStore get authRequests => client.authRequests; -// @override -// IGenericStore get completeRequests => client.completeRequests; + @override + ICore get core => client.core; + @override + PairingMetadata get metadata => client.metadata; + @override + IGenericStore get authKeys => client.authKeys; + @override + IGenericStore get pairingTopics => client.pairingTopics; + @override + IGenericStore get authRequests => client.authRequests; + @override + IGenericStore get completeRequests => client.completeRequests; -// late IAuthClient client; + late IAuthClient client; -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// LogLevel logLevel = LogLevel.nothing, -// IHttpClient httpClient = const HttpWrapper(), -// }) async { -// final client = AuthClientTestWrapper( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// logLevel: logLevel, -// httpClient: httpClient, -// ), -// metadata: metadata, -// ); -// await client.init(); + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + LogLevel logLevel = LogLevel.nothing, + IHttpClient httpClient = const HttpWrapper(), + }) async { + final client = AuthClientTestWrapper( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + logLevel: logLevel, + httpClient: httpClient, + ), + metadata: metadata, + ); + await client.init(); -// return client; -// } + return client; + } -// AuthClientTestWrapper({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// client = AuthClient( -// core: core, -// metadata: metadata, -// ); -// } + AuthClientTestWrapper({ + required ICore core, + required PairingMetadata metadata, + }) { + client = AuthClient( + core: core, + metadata: metadata, + ); + } -// @override -// Future init() async { -// if (_initialized) { -// return; -// } + @override + Future init() async { + if (_initialized) { + return; + } -// await core.start(); -// await client.init(); + await core.start(); + await client.init(); -// _initialized = true; -// } + _initialized = true; + } -// @override -// Future requestAuth({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods = AuthEngine.DEFAULT_METHODS, -// }) async { -// try { -// return client.request( -// params: params, -// pairingTopic: pairingTopic, -// methods: methods, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = AuthEngine.DEFAULT_METHODS, + }) async { + try { + return client.request( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } -// @override -// Future respondAuthRequest({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }) async { -// try { -// return client.respond( -// id: id, -// iss: iss, -// signature: signature, -// error: error, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + try { + return client.respond( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } -// @override -// Map getPendingAuthRequests() { -// try { -// return client.getPendingRequests(); -// } catch (e) { -// rethrow; -// } -// } + @override + Map getPendingAuthRequests() { + try { + return client.getPendingRequests(); + } catch (e) { + rethrow; + } + } -// @override -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return client.getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return client.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } -// @override -// String formatAuthMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }) { -// try { -// return client.formatMessage( -// iss: iss, -// cacaoPayload: cacaoPayload, -// ); -// } catch (e) { -// rethrow; -// } -// } -// } + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return client.formatMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } +} diff --git a/test/sign_api/sign_client_test.dart b/test/sign_api/sign_client_test.dart index 4a97e16d..d8264d21 100644 --- a/test/sign_api/sign_client_test.dart +++ b/test/sign_api/sign_client_test.dart @@ -1,43 +1,44 @@ -// @Timeout(Duration(seconds: 45)) +@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 'package:flutter_test/flutter_test.dart'; +import 'package:logger/logger.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import '../shared/shared_test_utils.dart'; -// import '../shared/shared_test_values.dart'; -// import 'tests/sign_common.dart'; -// import 'utils/sign_client_test_wrapper.dart'; +import '../shared/shared_test_utils.dart'; +import '../shared/shared_test_values.dart'; +import 'tests/sign_common.dart'; +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', -// ); +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + PackageInfo.setMockInitialValues( + appName: 'walletconnect_flutter_v2', + packageName: 'com.walletconnect.flutterdapp', + version: '1.0', + buildNumber: '2', + buildSignature: 'buildSignature', + ); -// signEngineTests( -// context: 'SignClient', -// clientACreator: (PairingMetadata metadata) async => -// await SignClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: Level.info, -// httpClient: getHttpWrapper(), -// ), -// clientBCreator: (PairingMetadata metadata) async => -// await SignClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: Level.info, -// httpClient: getHttpWrapper(), -// ), -// ); -// } + signEngineTests( + context: 'SignClient', + clientACreator: (PairingMetadata metadata) async => + await SignClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: Level.info, + httpClient: getHttpWrapper(), + ), + clientBCreator: (PairingMetadata metadata) async => + await SignClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: Level.info, + httpClient: getHttpWrapper(), + ), + ); +} diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index 2b69514b..576534c5 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -1,432 +1,523 @@ -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.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/sign_engine.dart'; -// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -// class SignClientTestWrapper implements ISignEngine { -// bool _initialized = false; - -// @override -// Event get onSessionDelete => client.onSessionDelete; -// @override -// Event get onSessionConnect => client.onSessionConnect; -// @override -// Event get onSessionEvent => client.onSessionEvent; -// @override -// Event get onSessionExpire => client.onSessionExpire; -// @override -// Event get onSessionExtend => client.onSessionExtend; -// @override -// Event get onSessionPing => client.onSessionPing; -// @override -// Event get onSessionProposal => client.onSessionProposal; -// @override -// Event get onSessionProposalError => -// client.onSessionProposalError; -// @override -// Event get onProposalExpire => client.onProposalExpire; -// @override -// Event get onSessionRequest => client.onSessionRequest; -// @override -// Event get onSessionUpdate => client.onSessionUpdate; - -// @override -// ICore get core => client.core; -// @override -// PairingMetadata get metadata => client.metadata; -// @override -// IGenericStore get proposals => client.proposals; -// @override -// ISessions get sessions => client.sessions; -// @override -// IGenericStore get pendingRequests => client.pendingRequests; - -// late ISignClient client; - -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// Level logLevel = Level.off, -// IHttpClient httpClient = const HttpWrapper(), -// }) async { -// final client = SignClientTestWrapper( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// httpClient: httpClient, -// ), -// metadata: metadata, -// ); -// await client.init(); - -// return client; -// } - -// SignClientTestWrapper({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// client = SignClient( -// core: core, -// metadata: metadata, -// ); -// } - -// @override -// Future init() async { -// if (_initialized) { -// return; -// } - -// await core.start(); -// await client.init(); - -// _initialized = true; -// } - -// @override -// Future connect({ -// Map? requiredNamespaces, -// Map? optionalNamespaces, -// Map? sessionProperties, -// String? pairingTopic, -// List? relays, -// List>? methods = SignEngine.DEFAULT_METHODS, -// }) async { -// try { -// return await client.connect( -// requiredNamespaces: requiredNamespaces, -// optionalNamespaces: optionalNamespaces, -// sessionProperties: sessionProperties, -// pairingTopic: pairingTopic, -// relays: relays, -// methods: methods, -// ); -// } catch (e) { -// // print(e); -// rethrow; -// } -// } - -// @override -// Future pair({ -// required Uri uri, -// }) async { -// try { -// return await client.pair(uri: uri); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future approveSession({ -// required int id, -// required Map namespaces, -// Map? sessionProperties, -// String? relayProtocol, -// }) async { -// try { -// return await client.approve( -// id: id, -// namespaces: namespaces, -// relayProtocol: relayProtocol, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future rejectSession({ -// required int id, -// required WalletConnectError reason, -// }) async { -// try { -// return await client.reject( -// id: id, -// reason: reason, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future updateSession({ -// required String topic, -// required Map namespaces, -// }) async { -// try { -// return await client.update( -// topic: topic, -// namespaces: namespaces, -// ); -// } catch (e) { -// // final error = e as WCError; -// rethrow; -// } -// } - -// @override -// Future extendSession({ -// required String topic, -// }) async { -// try { -// return await client.extend(topic: topic); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerRequestHandler({ -// required String chainId, -// required String method, -// void Function(String, dynamic)? handler, -// }) { -// try { -// return client.registerRequestHandler( -// chainId: chainId, -// method: method, -// handler: handler, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future request({ -// required String topic, -// required String chainId, -// required SessionRequestParams request, -// }) async { -// try { -// return await client.request( -// topic: topic, -// chainId: chainId, -// request: request, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future> requestReadContract({ -// required DeployedContract deployedContract, -// required String functionName, -// required String rpcUrl, -// List parameters = const [], -// }) async { -// try { -// return await client.requestReadContract( -// deployedContract: deployedContract, -// functionName: functionName, -// rpcUrl: rpcUrl, -// parameters: parameters, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// 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 [], -// }) async { -// try { -// return await client.requestWriteContract( -// topic: topic, -// chainId: chainId, -// rpcUrl: rpcUrl, -// deployedContract: deployedContract, -// functionName: functionName, -// transaction: transaction, -// method: method, -// parameters: parameters, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future respondSessionRequest({ -// required String topic, -// required JsonRpcResponse response, -// }) { -// try { -// return client.respond( -// topic: topic, -// response: response, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerEventHandler({ -// required String chainId, -// required String event, -// dynamic Function(String, dynamic)? handler, -// }) { -// try { -// return client.registerEventHandler( -// chainId: chainId, -// event: event, -// handler: handler, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerEventEmitter({ -// required String chainId, -// required String event, -// }) { -// try { -// return client.registerEventEmitter( -// chainId: chainId, -// event: event, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// void registerAccount({ -// required String chainId, -// required String accountAddress, -// }) { -// try { -// return client.registerAccount( -// chainId: chainId, -// accountAddress: accountAddress, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future emitSessionEvent({ -// required String topic, -// required String chainId, -// required SessionEventParams event, -// }) async { -// try { -// return await client.emit( -// topic: topic, -// chainId: chainId, -// event: event, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future ping({ -// required String topic, -// }) async { -// try { -// return await client.ping(topic: topic); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future disconnectSession({ -// required String topic, -// required WalletConnectError reason, -// }) async { -// try { -// return await client.disconnect( -// topic: topic, -// reason: reason, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// SessionData? find({ -// required Map requiredNamespaces, -// }) { -// try { -// return client.find(requiredNamespaces: requiredNamespaces); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getActiveSessions() { -// try { -// return client.getActiveSessions(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getSessionsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return client.getSessionsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingSessionProposals() { -// try { -// return client.getPendingSessionProposals(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingSessionRequests() { -// try { -// return client.getPendingSessionRequests(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// IPairingStore get pairings => core.pairing.getStore(); - -// @override -// Future checkAndExpire() async { -// for (var session in sessions.getAll()) { -// await core.expirer.checkAndExpire(session.topic); -// } -// } -// } +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.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/sign_engine.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class SignClientTestWrapper implements ISignEngine { + bool _initialized = false; + + @override + Event get onSessionDelete => client.onSessionDelete; + @override + Event get onSessionConnect => client.onSessionConnect; + @override + Event get onSessionEvent => client.onSessionEvent; + @override + Event get onSessionExpire => client.onSessionExpire; + @override + Event get onSessionExtend => client.onSessionExtend; + @override + Event get onSessionPing => client.onSessionPing; + @override + Event get onSessionProposal => client.onSessionProposal; + @override + Event get onSessionProposalError => + client.onSessionProposalError; + @override + Event get onProposalExpire => client.onProposalExpire; + @override + Event get onSessionRequest => client.onSessionRequest; + @override + Event get onSessionUpdate => client.onSessionUpdate; + + @override + ICore get core => client.core; + @override + PairingMetadata get metadata => client.metadata; + @override + IGenericStore get proposals => client.proposals; + @override + ISessions get sessions => client.sessions; + @override + IGenericStore get pendingRequests => client.pendingRequests; + + late ISignClient client; + + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + Level logLevel = Level.off, + IHttpClient httpClient = const HttpWrapper(), + }) async { + final client = SignClientTestWrapper( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + httpClient: httpClient, + ), + metadata: metadata, + ); + await client.init(); + + return client; + } + + SignClientTestWrapper({ + required ICore core, + required PairingMetadata metadata, + }) { + client = SignClient( + core: core, + metadata: metadata, + ); + } + + @override + Future init() async { + if (_initialized) { + return; + } + + await core.start(); + await client.init(); + + _initialized = true; + } + + @override + Future connect({ + Map? requiredNamespaces, + Map? optionalNamespaces, + Map? sessionProperties, + String? pairingTopic, + List? relays, + List>? methods = SignEngine.DEFAULT_METHODS, + }) async { + try { + return await client.connect( + requiredNamespaces: requiredNamespaces, + optionalNamespaces: optionalNamespaces, + sessionProperties: sessionProperties, + pairingTopic: pairingTopic, + relays: relays, + methods: methods, + ); + } catch (e) { + // print(e); + rethrow; + } + } + + @override + Future pair({ + required Uri uri, + }) async { + try { + return await client.pair(uri: uri); + } catch (e) { + rethrow; + } + } + + @override + Future approveSession({ + required int id, + required Map namespaces, + Map? sessionProperties, + String? relayProtocol, + }) async { + try { + return await client.approve( + id: id, + namespaces: namespaces, + relayProtocol: relayProtocol, + ); + } catch (e) { + rethrow; + } + } + + @override + Future rejectSession({ + required int id, + required WalletConnectError reason, + }) async { + try { + return await client.reject( + id: id, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + + @override + Future updateSession({ + required String topic, + required Map namespaces, + }) async { + try { + return await client.update( + topic: topic, + namespaces: namespaces, + ); + } catch (e) { + // final error = e as WCError; + rethrow; + } + } + + @override + Future extendSession({ + required String topic, + }) async { + try { + return await client.extend(topic: topic); + } catch (e) { + rethrow; + } + } + + @override + void registerRequestHandler({ + required String chainId, + required String method, + void Function(String, dynamic)? handler, + }) { + try { + return client.registerRequestHandler( + chainId: chainId, + method: method, + handler: handler, + ); + } catch (e) { + rethrow; + } + } + + @override + Future request({ + required String topic, + required String chainId, + required SessionRequestParams request, + }) async { + try { + return await client.request( + topic: topic, + chainId: chainId, + request: request, + ); + } catch (e) { + rethrow; + } + } + + @override + Future> requestReadContract({ + required DeployedContract deployedContract, + required String functionName, + required String rpcUrl, + List parameters = const [], + }) async { + try { + return await client.requestReadContract( + deployedContract: deployedContract, + functionName: functionName, + rpcUrl: rpcUrl, + parameters: parameters, + ); + } catch (e) { + rethrow; + } + } + + @override + 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 [], + }) async { + try { + return await client.requestWriteContract( + topic: topic, + chainId: chainId, + rpcUrl: rpcUrl, + deployedContract: deployedContract, + functionName: functionName, + transaction: transaction, + method: method, + parameters: parameters, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respondSessionRequest({ + required String topic, + required JsonRpcResponse response, + }) { + try { + return client.respond( + topic: topic, + response: response, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerEventHandler({ + required String chainId, + required String event, + dynamic Function(String, dynamic)? handler, + }) { + try { + return client.registerEventHandler( + chainId: chainId, + event: event, + handler: handler, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerEventEmitter({ + required String chainId, + required String event, + }) { + try { + return client.registerEventEmitter( + chainId: chainId, + event: event, + ); + } catch (e) { + rethrow; + } + } + + @override + void registerAccount({ + required String chainId, + required String accountAddress, + }) { + try { + return client.registerAccount( + chainId: chainId, + accountAddress: accountAddress, + ); + } catch (e) { + rethrow; + } + } + + @override + Future emitSessionEvent({ + required String topic, + required String chainId, + required SessionEventParams event, + }) async { + try { + return await client.emit( + topic: topic, + chainId: chainId, + event: event, + ); + } catch (e) { + rethrow; + } + } + + @override + Future ping({ + required String topic, + }) async { + try { + return await client.ping(topic: topic); + } catch (e) { + rethrow; + } + } + + @override + Future disconnectSession({ + required String topic, + required WalletConnectError reason, + }) async { + try { + return await client.disconnect( + topic: topic, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + + @override + SessionData? find({ + required Map requiredNamespaces, + }) { + try { + return client.find(requiredNamespaces: requiredNamespaces); + } catch (e) { + rethrow; + } + } + + @override + Map getActiveSessions() { + try { + return client.getActiveSessions(); + } catch (e) { + rethrow; + } + } + + @override + Map getSessionsForPairing({ + required String pairingTopic, + }) { + try { + return client.getSessionsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingSessionProposals() { + try { + return client.getPendingSessionProposals(); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingSessionRequests() { + try { + return client.getPendingSessionRequests(); + } catch (e) { + rethrow; + } + } + + @override + IPairingStore get pairings => core.pairing.getStore(); + + @override + Future checkAndExpire() async { + for (var session in sessions.getAll()) { + await core.expirer.checkAndExpire(session.topic); + } + } + + @override + IGenericStore get authKeys => client.authKeys; + + @override + IGenericStore get authRequests => client.authRequests; + + @override + IGenericStore get completeRequests => client.completeRequests; + + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return client.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return client.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingAuthRequests() { + try { + return client.getPendingAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + Event get onAuthRequest => client.onAuthRequest; + + @override + Event get onAuthResponse => client.onAuthResponse; + + @override + IGenericStore get pairingTopics => client.pairingTopics; + + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }) async { + try { + return await client.requestAuth( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + try { + return await client.respondAuthRequest( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } +} From dbda6c72b54abe7ce0b9a5cb0868cfd927c18e0c Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 27 May 2024 16:40:22 +0200 Subject: [PATCH 05/29] revert some files --- lib/apis/auth_api/auth_client.dart | 10 +++++++++- lib/apis/core/pairing/pairing.dart | 2 +- lib/apis/core/relay_client/relay_client.dart | 14 +++++++------- lib/apis/core/verify/verify.dart | 5 +++-- lib/walletconnect_flutter_v2.dart | 6 +++--- test/auth_api/utils/auth_client_test_wrapper.dart | 10 +++++++++- test/auth_api/utils/signature_constants.dart | 2 +- test/sign_api/sign_client_test.dart | 4 ++-- 8 files changed, 35 insertions(+), 18 deletions(-) diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index e7b89e0a..ccf25c9e 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,11 +1,19 @@ +import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; class AuthClient implements IAuthClient { bool _initialized = false; diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index debab9c4..b97a3d22 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -649,7 +649,7 @@ class Pairing implements IPairing { // print(payloadString); Map data = jsonDecode(payloadString); - core.logger.t('Pairing _onMessageEvent, Received data: $data'); + core.logger.i('Pairing _onMessageEvent, Received data: $data'); // If it's an rpc request, handle it // print('Pairing: Received data: $data'); diff --git a/lib/apis/core/relay_client/relay_client.dart b/lib/apis/core/relay_client/relay_client.dart index 699e54a4..8e482da8 100644 --- a/lib/apis/core/relay_client/relay_client.dart +++ b/lib/apis/core/relay_client/relay_client.dart @@ -170,7 +170,7 @@ class RelayClient implements IRelayClient { Future connect({String? relayUrl}) async { _checkInitialized(); - core.logger.t('RelayClient: Connecting to relay'); + core.logger.i('RelayClient: Connecting to relay'); await _connect(relayUrl: relayUrl); } @@ -179,7 +179,7 @@ class RelayClient implements IRelayClient { Future disconnect() async { _checkInitialized(); - core.logger.t('RelayClient: Disconnecting from relay'); + core.logger.i('RelayClient: Disconnecting from relay'); await _disconnect(); } @@ -302,12 +302,12 @@ class RelayClient implements IRelayClient { Future _handleRelayClose(int? code, String? reason) async { if (_handledClose) { - core.logger.t('Relay close already handled'); + core.logger.i('Relay close already handled'); return; } _handledClose = true; - core.logger.t('Handling relay close, code: $code, reason: $reason'); + core.logger.i('Handling relay close, code: $code, reason: $reason'); // If the relay isn't active (Disconnected manually), don't do anything if (!_active) { return; @@ -364,7 +364,7 @@ class RelayClient implements IRelayClient { core.logger.t('Handling Publish Message: $topic, $message'); // If we want to ignore the message, stop if (await _shouldIgnoreMessageEvent(topic, message)) { - core.logger.e('Ignoring Message: $topic, $message'); + core.logger.w('Ignoring Message: $topic, $message'); return false; } @@ -392,7 +392,7 @@ class RelayClient implements IRelayClient { } void _handleUnsubscribe(Parameters params) { - core.logger.t('[$runtimeType] _handleUnsubscribe $params'); + core.logger.i('[$runtimeType] _handleUnsubscribe $params'); } /// MESSAGE HANDLING @@ -441,7 +441,7 @@ class RelayClient implements IRelayClient { JsonRpcUtils.payloadId(entropy: 6), ); } catch (e) { - core.logger.e('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); + core.logger.w('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); onRelayClientError.broadcast(ErrorEvent(e)); } diff --git a/lib/apis/core/verify/verify.dart b/lib/apis/core/verify/verify.dart index 4e63c5c6..0538c4de 100644 --- a/lib/apis/core/verify/verify.dart +++ b/lib/apis/core/verify/verify.dart @@ -30,7 +30,8 @@ class Verify implements IVerify { AttestationResponse? response; try { response = await _fetchAttestation(attestationId, _verifyUrl); - } on AttestationNotFound catch (_) { + } on AttestationNotFound catch (e) { + _core.logger.i(e.message); response = await _fetchAttestation( attestationId, WalletConnectConstants.VERIFY_FALLBACK_SERVER, @@ -74,7 +75,7 @@ class Verify implements IVerify { String url = verifyUrl ?? WalletConnectConstants.VERIFY_SERVER; if (!WalletConnectConstants.TRUSTED_VERIFY_URLS.contains(url)) { - _core.logger.t( + _core.logger.i( '[$runtimeType] verifyUrl $url not included in trusted list, ' 'assigning default: ${WalletConnectConstants.VERIFY_SERVER}', ); diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 17f934aa..6bd3af58 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -24,8 +24,8 @@ export 'apis/utils/extensions.dart'; // Sign API export 'apis/sign_api/i_sign_client.dart'; -export 'apis/sign_api/sign_client.dart'; export 'apis/sign_api/i_sign_engine.dart'; +export 'apis/sign_api/sign_client.dart'; export 'apis/sign_api/sessions.dart'; export 'apis/sign_api/models/proposal_models.dart'; export 'apis/sign_api/models/session_models.dart'; @@ -41,8 +41,8 @@ export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; export 'apis/sign_api/utils/auth/auth_api_validators.dart'; -// export 'apis/auth_api/i_auth_client.dart'; -// export 'apis/auth_api/auth_client.dart'; +export 'apis/auth_api/i_auth_client.dart'; +export 'apis/auth_api/auth_client.dart'; // Web3Wallet export 'apis/web3wallet/i_web3wallet.dart'; diff --git a/test/auth_api/utils/auth_client_test_wrapper.dart b/test/auth_api/utils/auth_client_test_wrapper.dart index 64f3ea9b..dcf69087 100644 --- a/test/auth_api/utils/auth_client_test_wrapper.dart +++ b/test/auth_api/utils/auth_client_test_wrapper.dart @@ -1,11 +1,19 @@ +import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; class AuthClientTestWrapper implements IAuthEngine { bool _initialized = false; diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index 322c027e..699a1170 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../../shared/shared_test_values.dart'; diff --git a/test/sign_api/sign_client_test.dart b/test/sign_api/sign_client_test.dart index d8264d21..d4b91b9c 100644 --- a/test/sign_api/sign_client_test.dart +++ b/test/sign_api/sign_client_test.dart @@ -1,9 +1,9 @@ @Timeout(Duration(seconds: 45)) import 'package:flutter_test/flutter_test.dart'; -import 'package:logger/logger.dart'; + import 'package:package_info_plus/package_info_plus.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_utils.dart'; import '../shared/shared_test_values.dart'; From 816364b1722eded7bb323ee69211bfb525b01c57 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 27 May 2024 17:00:56 +0200 Subject: [PATCH 06/29] revert some files --- example/dapp/lib/widgets/auth_item.dart | 3 +-- .../wc_auth_request_model.dart | 2 +- lib/apis/auth_api/i_auth_client.dart | 1 - lib/apis/sign_api/sign_client.dart | 22 +------------------ lib/walletconnect_flutter_v2.dart | 12 +++++++++- test/auth_api/address_utils_test.dart | 2 +- test/auth_api/auth_client_test.dart | 16 +++----------- test/auth_api/signature_test.dart | 3 +-- test/sign_api/sign_client_test.dart | 1 - 9 files changed, 19 insertions(+), 43 deletions(-) diff --git a/example/dapp/lib/widgets/auth_item.dart b/example/dapp/lib/widgets/auth_item.dart index 611e255f..26c1151d 100644 --- a/example/dapp/lib/widgets/auth_item.dart +++ b/example/dapp/lib/widgets/auth_item.dart @@ -1,8 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_dapp/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; - class AuthItem extends StatelessWidget { const AuthItem({ required Key key, diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart b/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart index 61df3e1d..cf5efd26 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; class WCAuthRequestModel { final String iss; diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 758f6b84..100fcd26 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,4 +1,3 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index 2d504f56..1f14088b 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -1,28 +1,8 @@ -import 'package:event/event.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_pairing_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_client.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/sessions.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/sign_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -import 'package:web3dart/web3dart.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; class SignClient implements ISignClient { bool _initialized = false; diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 6bd3af58..5fa35e0d 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -33,7 +33,7 @@ export 'apis/sign_api/models/json_rpc_models.dart'; export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; -// Auth API +// New Auth API export 'apis/sign_api/models/auth/auth_client_models.dart'; export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/json_rpc_models.dart'; @@ -41,6 +41,16 @@ export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; export 'apis/sign_api/utils/auth/auth_api_validators.dart'; + +// Auth API +export 'apis/auth_api/models/auth_client_models.dart'; +export 'apis/auth_api/models/auth_client_events.dart'; +export 'apis/auth_api/models/json_rpc_models.dart'; +export 'apis/auth_api/utils/auth_utils.dart'; +export 'apis/auth_api/utils/address_utils.dart'; +export 'apis/auth_api/utils/auth_signature.dart'; +export 'apis/auth_api/utils/auth_api_validators.dart'; +export 'apis/auth_api/i_auth_engine.dart'; export 'apis/auth_api/i_auth_client.dart'; export 'apis/auth_api/auth_client.dart'; diff --git a/test/auth_api/address_utils_test.dart b/test/auth_api/address_utils_test.dart index 66b26921..601a7c06 100644 --- a/test/auth_api/address_utils_test.dart +++ b/test/auth_api/address_utils_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/address_utils.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_values.dart'; import 'utils/signature_constants.dart'; diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index c03304fa..94b5f0f0 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -5,22 +5,12 @@ import 'package:eth_sig_util/eth_sig_util.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_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'; -import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; + import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.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/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/walletconnect_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/web3app/i_web3app.dart'; -// import 'package:walletconnect_flutter_v2/apis/web3wallet/web3wallet.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_utils.dart'; import '../shared/shared_test_values.dart'; diff --git a/test/auth_api/signature_test.dart b/test/auth_api/signature_test.dart index ad348871..884a504d 100644 --- a/test/auth_api/signature_test.dart +++ b/test/auth_api/signature_test.dart @@ -2,8 +2,7 @@ import 'dart:convert'; import 'package:convert/convert.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_values.dart'; import 'utils/signature_constants.dart'; diff --git a/test/sign_api/sign_client_test.dart b/test/sign_api/sign_client_test.dart index d4b91b9c..ced4babc 100644 --- a/test/sign_api/sign_client_test.dart +++ b/test/sign_api/sign_client_test.dart @@ -1,7 +1,6 @@ @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'; From e7fedb1cd23832f5d3835128ad785dbbf4ff6536 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 27 May 2024 19:00:19 +0200 Subject: [PATCH 07/29] final changes on setup --- lib/apis/auth_api/auth_client.dart | 394 +++---- lib/apis/auth_api/auth_engine.dart | 884 ++++++++-------- lib/apis/auth_api/i_auth_client.dart | 112 +- lib/apis/auth_api/i_auth_engine.dart | 6 +- lib/apis/auth_api/i_auth_engine_app.dart | 26 +- lib/apis/auth_api/i_auth_engine_common.dart | 42 +- lib/apis/auth_api/i_auth_engine_wallet.dart | 38 +- lib/apis/sign_api/sign_engine.dart | 2 +- lib/walletconnect_flutter_v2.dart | 18 +- test/auth_api/auth_client_test.dart | 978 +++++++++--------- .../utils/auth_client_test_wrapper.dart | 286 ++--- 11 files changed, 1389 insertions(+), 1397 deletions(-) diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index ccf25c9e..da42e041 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,197 +1,197 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; - -class AuthClient implements IAuthClient { - bool _initialized = false; - - @override - String get protocol => 'wc'; - - @override - int get version => 2; - - @override - Event get onAuthRequest => engine.onAuthRequest; - @override - Event get onAuthResponse => engine.onAuthResponse; - - @override - ICore get core => engine.core; - @override - PairingMetadata get metadata => engine.metadata; - @override - IGenericStore get authKeys => engine.authKeys; - @override - IGenericStore get pairingTopics => engine.pairingTopics; - @override - IGenericStore get authRequests => engine.authRequests; - @override - IGenericStore get completeRequests => engine.completeRequests; - - @override - late IAuthEngine engine; - - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - IHttpClient httpClient = const HttpWrapper(), - LogLevel logLevel = LogLevel.nothing, - }) async { - final client = AuthClient( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - httpClient: httpClient, - logLevel: logLevel, - ), - metadata: metadata, - ); - await client.init(); - - return client; - } - - AuthClient({ - required ICore core, - required PairingMetadata metadata, - }) { - engine = AuthEngine( - core: core, - metadata: metadata, - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value as String; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - } - - @override - Future init() async { - if (_initialized) { - return; - } - - await core.start(); - await engine.init(); - - _initialized = true; - } - - @override - Future request({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods = AuthEngine.DEFAULT_METHODS, - }) async { - try { - return engine.requestAuth( - params: params, - pairingTopic: pairingTopic, - methods: methods, - ); - } catch (e) { - rethrow; - } - } - - @override - Future respond({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }) async { - try { - return engine.respondAuthRequest( - id: id, - iss: iss, - signature: signature, - error: error, - ); - } catch (e) { - rethrow; - } - } - - @override - Map getPendingRequests() { - try { - return engine.getPendingAuthRequests(); - } catch (e) { - rethrow; - } - } - - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return engine.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - - @override - String formatMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }) { - try { - return engine.formatAuthMessage( - iss: iss, - cacaoPayload: cacaoPayload, - ); - } catch (e) { - rethrow; - } - } -} +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; + +// class AuthClient implements IAuthClient { +// bool _initialized = false; + +// @override +// String get protocol => 'wc'; + +// @override +// int get version => 2; + +// @override +// Event get onAuthRequest => engine.onAuthRequest; +// @override +// Event get onAuthResponse => engine.onAuthResponse; + +// @override +// ICore get core => engine.core; +// @override +// PairingMetadata get metadata => engine.metadata; +// @override +// IGenericStore get authKeys => engine.authKeys; +// @override +// IGenericStore get pairingTopics => engine.pairingTopics; +// @override +// IGenericStore get authRequests => engine.authRequests; +// @override +// IGenericStore get completeRequests => engine.completeRequests; + +// @override +// late IAuthEngine engine; + +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// IHttpClient httpClient = const HttpWrapper(), +// LogLevel logLevel = LogLevel.nothing, +// }) async { +// final client = AuthClient( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// httpClient: httpClient, +// logLevel: logLevel, +// ), +// metadata: metadata, +// ); +// await client.init(); + +// return client; +// } + +// AuthClient({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// engine = AuthEngine( +// core: core, +// metadata: metadata, +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value as String; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// } + +// @override +// Future init() async { +// if (_initialized) { +// return; +// } + +// await core.start(); +// await engine.init(); + +// _initialized = true; +// } + +// @override +// Future request({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods = AuthEngine.DEFAULT_METHODS, +// }) async { +// try { +// return engine.requestAuth( +// params: params, +// pairingTopic: pairingTopic, +// methods: methods, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Future respond({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) async { +// try { +// return engine.respondAuthRequest( +// id: id, +// iss: iss, +// signature: signature, +// error: error, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getPendingRequests() { +// try { +// return engine.getPendingAuthRequests(); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return engine.getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } + +// @override +// String formatMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }) { +// try { +// return engine.formatAuthMessage( +// iss: iss, +// cacaoPayload: cacaoPayload, +// ); +// } catch (e) { +// rethrow; +// } +// } +// } diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index 9c52e1bf..f39cb5af 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -1,442 +1,442 @@ -import 'dart:async'; - -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/json_rpc_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.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_api_validators.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; -import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; -import 'package:walletconnect_flutter_v2/apis/models/json_rpc_request.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; - -class AuthEngine implements IAuthEngine { - static const List> DEFAULT_METHODS = [ - [ - MethodConstants.WC_AUTH_REQUEST, - ] - ]; - - bool _initialized = false; - - @override - final Event onAuthRequest = Event(); - @override - final Event onAuthResponse = Event(); - - @override - final ICore core; - @override - final PairingMetadata metadata; - @override - late IGenericStore authKeys; - @override - late IGenericStore pairingTopics; - @override - late IGenericStore authRequests; - @override - late IGenericStore completeRequests; - - List pendingAuthRequests = []; - - AuthEngine({ - required this.core, - required this.metadata, - required this.authKeys, - required this.pairingTopics, - required this.authRequests, - required this.completeRequests, - }); - - @override - Future init() async { - if (_initialized) { - return; - } - - await core.pairing.init(); - await authKeys.init(); - await pairingTopics.init(); - await authRequests.init(); - await completeRequests.init(); - - _registerRelayClientFunctions(); - - _initialized = true; - } - - @override - Future requestAuth({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods = DEFAULT_METHODS, - }) async { - _checkInitialized(); - - AuthApiValidators.isValidRequest(params); - String? pTopic = pairingTopic; - Uri? uri; - - if (pTopic == null) { - final CreateResponse newTopicAndUri = await core.pairing.create( - methods: methods, - ); - pTopic = newTopicAndUri.topic; - uri = newTopicAndUri.uri; - } else { - core.pairing.isValidPairingTopic(topic: pTopic); - } - - final publicKey = await core.crypto.generateKeyPair(); - // print('requestAuth, publicKey: $publicKey'); - final String responseTopic = core.crypto.getUtils().hashKey(publicKey); - final int id = JsonRpcUtils.payloadId(); - - WcAuthRequestRequest request = WcAuthRequestRequest( - payloadParams: AuthPayloadParams.fromRequestParams( - params, - ), - requester: ConnectionMetadata( - publicKey: publicKey, - metadata: metadata, - ), - ); - - final int expiry = params.expiry ?? WalletConnectConstants.FIVE_MINUTES; - - await authKeys.set( - AuthConstants.AUTH_CLIENT_PUBLIC_KEY_NAME, - AuthPublicKey(publicKey: publicKey), - ); - - await pairingTopics.set( - responseTopic, - pTopic, - ); - - // Set the one time use receiver public key for decoding the Type 1 envelope - await core.pairing.setReceiverPublicKey( - topic: responseTopic, - publicKey: publicKey, - expiry: expiry, - ); - - Completer completer = Completer(); - - _requestAuthResponseHandler( - pairingTopic: pTopic, - responseTopic: responseTopic, - request: request, - id: id, - expiry: expiry, - completer: completer, - ); - - return AuthRequestResponse( - id: id, - pairingTopic: pTopic, - completer: completer, - uri: uri, - ); - } - - Future _requestAuthResponseHandler({ - required String pairingTopic, - required String responseTopic, - required WcAuthRequestRequest request, - required int id, - required int expiry, - required Completer completer, - }) async { - Map? resp; - - // Subscribe to the responseTopic because we expect the response to use this topic - // print('got here'); - await core.relayClient.subscribe(topic: responseTopic); - - try { - resp = await core.pairing.sendRequest( - pairingTopic, - MethodConstants.WC_AUTH_REQUEST, - request.toJson(), - id: id, - ttl: expiry, - ); - } on JsonRpcError catch (e) { - final resp = AuthResponse( - id: id, - topic: responseTopic, - jsonRpcError: e, - ); - onAuthResponse.broadcast(resp); - completer.complete(resp); - return; - } - - await core.pairing.activate(topic: pairingTopic); - - final Cacao cacao = Cacao.fromJson(resp!); - final CacaoSignature sig = cacao.s; - final CacaoPayload payload = cacao.p; - await completeRequests.set( - id.toString(), - StoredCacao.fromCacao( - id: id, - pairingTopic: pairingTopic, - cacao: cacao, - ), - ); - - final String reconstructed = formatAuthMessage( - iss: payload.iss, - cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), - ); - - final String walletAddress = AddressUtils.getDidAddress(payload.iss); - final String chainId = AddressUtils.getDidChainId(payload.iss); - - if (walletAddress.isEmpty) { - throw Errors.getSdkError( - Errors.MISSING_OR_INVALID, - context: 'authResponse walletAddress is empty', - ); - } - if (chainId.isEmpty) { - throw Errors.getSdkError( - Errors.MISSING_OR_INVALID, - context: 'authResponse chainId is empty', - ); - } - - final bool isValid = await AuthSignature.verifySignature( - walletAddress, - reconstructed, - sig, - chainId, - core.projectId, - ); - - if (!isValid) { - final resp = AuthResponse( - id: id, - topic: responseTopic, - error: const WalletConnectError( - code: -1, - message: 'Invalid signature', - ), - ); - onAuthResponse.broadcast(resp); - completer.complete(resp); - } else { - final resp = AuthResponse( - id: id, - topic: responseTopic, - result: cacao, - ); - onAuthResponse.broadcast(resp); - completer.complete(resp); - } - } - - @override - Future respondAuthRequest({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }) async { - _checkInitialized(); - - Map pendingRequests = getPendingAuthRequests(); - AuthApiValidators.isValidRespond( - id: id, - pendingRequests: pendingRequests, - signature: signature, - error: error, - ); - - final PendingAuthRequest pendingRequest = pendingRequests[id]!; - final String receiverPublicKey = pendingRequest.metadata.publicKey; - final String senderPublicKey = await core.crypto.generateKeyPair(); - final String responseTopic = core.crypto.getUtils().hashKey( - receiverPublicKey, - ); - final EncodeOptions encodeOpts = EncodeOptions( - type: EncodeOptions.TYPE_1, - receiverPublicKey: receiverPublicKey, - senderPublicKey: senderPublicKey, - ); - - if (error != null) { - await core.pairing.sendError( - id, - responseTopic, - MethodConstants.WC_AUTH_REQUEST, - JsonRpcError.serverError(error.message), - encodeOptions: encodeOpts, - ); - } else { - final Cacao cacao = Cacao( - h: const CacaoHeader(), - p: CacaoPayload.fromRequestPayload( - issuer: iss, - payload: pendingRequest.cacaoPayload, - ), - s: signature!, - ); - - // print('auth res id: $id'); - await core.pairing.sendResult( - id, - responseTopic, - MethodConstants.WC_AUTH_REQUEST, - cacao.toJson(), - encodeOptions: encodeOpts, - ); - - await authRequests.delete(id.toString()); - - await completeRequests.set( - id.toString(), - StoredCacao.fromCacao( - id: id, - pairingTopic: pendingRequest.pairingTopic, - cacao: cacao, - ), - ); - } - } - - @override - Map getPendingAuthRequests() { - Map pendingRequests = {}; - authRequests.getAll().forEach((key) { - pendingRequests[key.id] = key; - }); - return pendingRequests; - } - - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - Map completedRequests = {}; - completeRequests - .getAll() - .where( - (e) => e.pairingTopic == pairingTopic, - ) - .forEach((key) { - completedRequests[key.id] = key; - }); - return completedRequests; - } - - // kind of a core method to move to sign - // Formats the message that is coming from requestAuth() - @override - String formatAuthMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }) { - final header = - '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; - final walletAddress = AddressUtils.getDidAddress(iss); - final uri = 'URI: ${cacaoPayload.aud}'; - final version = 'Version: ${cacaoPayload.version}'; - final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; - final nonce = 'Nonce: ${cacaoPayload.nonce}'; - final issuedAt = 'Issued At: ${cacaoPayload.iat}'; - final resources = cacaoPayload.resources != null && - cacaoPayload.resources!.isNotEmpty - ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' - : null; - - final message = [ - header, - walletAddress, - '', - cacaoPayload.statement, - '', - uri, - version, - chainId, - nonce, - issuedAt, - resources, - ].where((element) => element != null).join('\n'); - - return message; - } - - /// ---- PRIVATE HELPERS ---- /// - - void _checkInitialized() { - if (!_initialized) { - throw Errors.getInternalError(Errors.NOT_INITIALIZED); - } - } - - /// ---- Relay Events ---- /// - - void _registerRelayClientFunctions() { - core.pairing.register( - method: MethodConstants.WC_AUTH_REQUEST, - function: _onAuthRequest, - type: ProtocolType.auth, - ); - } - - void _onAuthRequest( - String topic, - JsonRpcRequest payload, - ) async { - try { - final request = WcAuthRequestRequest.fromJson(payload.params); - - final CacaoRequestPayload cacaoPayload = - CacaoRequestPayload.fromPayloadParams( - request.payloadParams, - ); - - authRequests.set( - payload.id.toString(), - PendingAuthRequest( - id: payload.id, - pairingTopic: topic, - metadata: request.requester, - cacaoPayload: cacaoPayload, - ), - ); - - onAuthRequest.broadcast( - AuthRequest( - id: payload.id, - topic: topic, - requester: request.requester, - payloadParams: request.payloadParams, - ), - ); - } on WalletConnectError catch (err) { - await core.pairing.sendError( - payload.id, - topic, - payload.method, - JsonRpcError.invalidParams( - err.message, - ), - ); - } - } -} +// import 'dart:async'; + +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/json_rpc_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.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_api_validators.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_request.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; + +// class AuthEngine implements IAuthEngine { +// static const List> DEFAULT_METHODS = [ +// [ +// MethodConstants.WC_AUTH_REQUEST, +// ] +// ]; + +// bool _initialized = false; + +// @override +// final Event onAuthRequest = Event(); +// @override +// final Event onAuthResponse = Event(); + +// @override +// final ICore core; +// @override +// final PairingMetadata metadata; +// @override +// late IGenericStore authKeys; +// @override +// late IGenericStore pairingTopics; +// @override +// late IGenericStore authRequests; +// @override +// late IGenericStore completeRequests; + +// List pendingAuthRequests = []; + +// AuthEngine({ +// required this.core, +// required this.metadata, +// required this.authKeys, +// required this.pairingTopics, +// required this.authRequests, +// required this.completeRequests, +// }); + +// @override +// Future init() async { +// if (_initialized) { +// return; +// } + +// await core.pairing.init(); +// await authKeys.init(); +// await pairingTopics.init(); +// await authRequests.init(); +// await completeRequests.init(); + +// _registerRelayClientFunctions(); + +// _initialized = true; +// } + +// @override +// Future requestAuth({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods = DEFAULT_METHODS, +// }) async { +// _checkInitialized(); + +// AuthApiValidators.isValidRequest(params); +// String? pTopic = pairingTopic; +// Uri? uri; + +// if (pTopic == null) { +// final CreateResponse newTopicAndUri = await core.pairing.create( +// methods: methods, +// ); +// pTopic = newTopicAndUri.topic; +// uri = newTopicAndUri.uri; +// } else { +// core.pairing.isValidPairingTopic(topic: pTopic); +// } + +// final publicKey = await core.crypto.generateKeyPair(); +// // print('requestAuth, publicKey: $publicKey'); +// final String responseTopic = core.crypto.getUtils().hashKey(publicKey); +// final int id = JsonRpcUtils.payloadId(); + +// WcAuthRequestRequest request = WcAuthRequestRequest( +// payloadParams: AuthPayloadParams.fromRequestParams( +// params, +// ), +// requester: ConnectionMetadata( +// publicKey: publicKey, +// metadata: metadata, +// ), +// ); + +// final int expiry = params.expiry ?? WalletConnectConstants.FIVE_MINUTES; + +// await authKeys.set( +// AuthConstants.AUTH_CLIENT_PUBLIC_KEY_NAME, +// AuthPublicKey(publicKey: publicKey), +// ); + +// await pairingTopics.set( +// responseTopic, +// pTopic, +// ); + +// // Set the one time use receiver public key for decoding the Type 1 envelope +// await core.pairing.setReceiverPublicKey( +// topic: responseTopic, +// publicKey: publicKey, +// expiry: expiry, +// ); + +// Completer completer = Completer(); + +// _requestAuthResponseHandler( +// pairingTopic: pTopic, +// responseTopic: responseTopic, +// request: request, +// id: id, +// expiry: expiry, +// completer: completer, +// ); + +// return AuthRequestResponse( +// id: id, +// pairingTopic: pTopic, +// completer: completer, +// uri: uri, +// ); +// } + +// Future _requestAuthResponseHandler({ +// required String pairingTopic, +// required String responseTopic, +// required WcAuthRequestRequest request, +// required int id, +// required int expiry, +// required Completer completer, +// }) async { +// Map? resp; + +// // Subscribe to the responseTopic because we expect the response to use this topic +// // print('got here'); +// await core.relayClient.subscribe(topic: responseTopic); + +// try { +// resp = await core.pairing.sendRequest( +// pairingTopic, +// MethodConstants.WC_AUTH_REQUEST, +// request.toJson(), +// id: id, +// ttl: expiry, +// ); +// } on JsonRpcError catch (e) { +// final resp = AuthResponse( +// id: id, +// topic: responseTopic, +// jsonRpcError: e, +// ); +// onAuthResponse.broadcast(resp); +// completer.complete(resp); +// return; +// } + +// await core.pairing.activate(topic: pairingTopic); + +// final Cacao cacao = Cacao.fromJson(resp!); +// final CacaoSignature sig = cacao.s; +// final CacaoPayload payload = cacao.p; +// await completeRequests.set( +// id.toString(), +// StoredCacao.fromCacao( +// id: id, +// pairingTopic: pairingTopic, +// cacao: cacao, +// ), +// ); + +// final String reconstructed = formatAuthMessage( +// iss: payload.iss, +// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), +// ); + +// final String walletAddress = AddressUtils.getDidAddress(payload.iss); +// final String chainId = AddressUtils.getDidChainId(payload.iss); + +// if (walletAddress.isEmpty) { +// throw Errors.getSdkError( +// Errors.MISSING_OR_INVALID, +// context: 'authResponse walletAddress is empty', +// ); +// } +// if (chainId.isEmpty) { +// throw Errors.getSdkError( +// Errors.MISSING_OR_INVALID, +// context: 'authResponse chainId is empty', +// ); +// } + +// final bool isValid = await AuthSignature.verifySignature( +// walletAddress, +// reconstructed, +// sig, +// chainId, +// core.projectId, +// ); + +// if (!isValid) { +// final resp = AuthResponse( +// id: id, +// topic: responseTopic, +// error: const WalletConnectError( +// code: -1, +// message: 'Invalid signature', +// ), +// ); +// onAuthResponse.broadcast(resp); +// completer.complete(resp); +// } else { +// final resp = AuthResponse( +// id: id, +// topic: responseTopic, +// result: cacao, +// ); +// onAuthResponse.broadcast(resp); +// completer.complete(resp); +// } +// } + +// @override +// Future respondAuthRequest({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) async { +// _checkInitialized(); + +// Map pendingRequests = getPendingAuthRequests(); +// AuthApiValidators.isValidRespond( +// id: id, +// pendingRequests: pendingRequests, +// signature: signature, +// error: error, +// ); + +// final PendingAuthRequest pendingRequest = pendingRequests[id]!; +// final String receiverPublicKey = pendingRequest.metadata.publicKey; +// final String senderPublicKey = await core.crypto.generateKeyPair(); +// final String responseTopic = core.crypto.getUtils().hashKey( +// receiverPublicKey, +// ); +// final EncodeOptions encodeOpts = EncodeOptions( +// type: EncodeOptions.TYPE_1, +// receiverPublicKey: receiverPublicKey, +// senderPublicKey: senderPublicKey, +// ); + +// if (error != null) { +// await core.pairing.sendError( +// id, +// responseTopic, +// MethodConstants.WC_AUTH_REQUEST, +// JsonRpcError.serverError(error.message), +// encodeOptions: encodeOpts, +// ); +// } else { +// final Cacao cacao = Cacao( +// h: const CacaoHeader(), +// p: CacaoPayload.fromRequestPayload( +// issuer: iss, +// payload: pendingRequest.cacaoPayload, +// ), +// s: signature!, +// ); + +// // print('auth res id: $id'); +// await core.pairing.sendResult( +// id, +// responseTopic, +// MethodConstants.WC_AUTH_REQUEST, +// cacao.toJson(), +// encodeOptions: encodeOpts, +// ); + +// await authRequests.delete(id.toString()); + +// await completeRequests.set( +// id.toString(), +// StoredCacao.fromCacao( +// id: id, +// pairingTopic: pendingRequest.pairingTopic, +// cacao: cacao, +// ), +// ); +// } +// } + +// @override +// Map getPendingAuthRequests() { +// Map pendingRequests = {}; +// authRequests.getAll().forEach((key) { +// pendingRequests[key.id] = key; +// }); +// return pendingRequests; +// } + +// @override +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }) { +// Map completedRequests = {}; +// completeRequests +// .getAll() +// .where( +// (e) => e.pairingTopic == pairingTopic, +// ) +// .forEach((key) { +// completedRequests[key.id] = key; +// }); +// return completedRequests; +// } + +// // kind of a core method to move to sign +// // Formats the message that is coming from requestAuth() +// @override +// String formatAuthMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }) { +// final header = +// '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; +// final walletAddress = AddressUtils.getDidAddress(iss); +// final uri = 'URI: ${cacaoPayload.aud}'; +// final version = 'Version: ${cacaoPayload.version}'; +// final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; +// final nonce = 'Nonce: ${cacaoPayload.nonce}'; +// final issuedAt = 'Issued At: ${cacaoPayload.iat}'; +// final resources = cacaoPayload.resources != null && +// cacaoPayload.resources!.isNotEmpty +// ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' +// : null; + +// final message = [ +// header, +// walletAddress, +// '', +// cacaoPayload.statement, +// '', +// uri, +// version, +// chainId, +// nonce, +// issuedAt, +// resources, +// ].where((element) => element != null).join('\n'); + +// return message; +// } + +// /// ---- PRIVATE HELPERS ---- /// + +// void _checkInitialized() { +// if (!_initialized) { +// throw Errors.getInternalError(Errors.NOT_INITIALIZED); +// } +// } + +// /// ---- Relay Events ---- /// + +// void _registerRelayClientFunctions() { +// core.pairing.register( +// method: MethodConstants.WC_AUTH_REQUEST, +// function: _onAuthRequest, +// type: ProtocolType.auth, +// ); +// } + +// void _onAuthRequest( +// String topic, +// JsonRpcRequest payload, +// ) async { +// try { +// final request = WcAuthRequestRequest.fromJson(payload.params); + +// final CacaoRequestPayload cacaoPayload = +// CacaoRequestPayload.fromPayloadParams( +// request.payloadParams, +// ); + +// authRequests.set( +// payload.id.toString(), +// PendingAuthRequest( +// id: payload.id, +// pairingTopic: topic, +// metadata: request.requester, +// cacaoPayload: cacaoPayload, +// ), +// ); + +// onAuthRequest.broadcast( +// AuthRequest( +// id: payload.id, +// topic: topic, +// requester: request.requester, +// payloadParams: request.payloadParams, +// ), +// ); +// } on WalletConnectError catch (err) { +// await core.pairing.sendError( +// payload.id, +// topic, +// payload.method, +// JsonRpcError.invalidParams( +// err.message, +// ), +// ); +// } +// } +// } diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 100fcd26..848d0974 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,56 +1,56 @@ -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -abstract class IAuthClient { - final String protocol = 'wc'; - final int version = 2; - - abstract final IAuthEngine engine; - - // Common - abstract final ICore core; - abstract final PairingMetadata metadata; - - abstract final IGenericStore authKeys; - abstract final IGenericStore pairingTopics; - abstract final IGenericStore completeRequests; - - // initializes the client with persisted storage and a network connection - Future init(); - - /// format payload to message string - String formatMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }); - - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }); - - // App - abstract final Event onAuthResponse; - - // request wallet authentication - Future request({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods, - }); - - // Wallet - abstract final Event onAuthRequest; - - abstract final IGenericStore authRequests; - - /// respond wallet authentication - Future respond({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }); - - // query all pending requests - Map getPendingRequests(); -} +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +// abstract class IAuthClient { +// final String protocol = 'wc'; +// final int version = 2; + +// abstract final IAuthEngine engine; + +// // Common +// abstract final ICore core; +// abstract final PairingMetadata metadata; + +// abstract final IGenericStore authKeys; +// abstract final IGenericStore pairingTopics; +// abstract final IGenericStore completeRequests; + +// // initializes the client with persisted storage and a network connection +// Future init(); + +// /// format payload to message string +// String formatMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }); + +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }); + +// // App +// abstract final Event onAuthResponse; + +// // request wallet authentication +// Future request({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods, +// }); + +// // Wallet +// abstract final Event onAuthRequest; + +// abstract final IGenericStore authRequests; + +// /// respond wallet authentication +// Future respond({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }); + +// // query all pending requests +// Map getPendingRequests(); +// } diff --git a/lib/apis/auth_api/i_auth_engine.dart b/lib/apis/auth_api/i_auth_engine.dart index c48de6d5..5bea4d75 100644 --- a/lib/apis/auth_api/i_auth_engine.dart +++ b/lib/apis/auth_api/i_auth_engine.dart @@ -1,4 +1,4 @@ -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'; +// 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'; -abstract class IAuthEngine implements IAuthEngineWallet, IAuthEngineApp {} +// abstract class IAuthEngine implements IAuthEngineWallet, IAuthEngineApp {} diff --git a/lib/apis/auth_api/i_auth_engine_app.dart b/lib/apis/auth_api/i_auth_engine_app.dart index 4fa6ea19..6d505a59 100644 --- a/lib/apis/auth_api/i_auth_engine_app.dart +++ b/lib/apis/auth_api/i_auth_engine_app.dart @@ -1,15 +1,15 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -abstract class IAuthEngineApp extends IAuthEngineCommon { - abstract final Event onAuthResponse; +// abstract class IAuthEngineApp extends IAuthEngineCommon { +// abstract final Event onAuthResponse; - // request wallet authentication - Future requestAuth({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods, - }); -} +// // request wallet authentication +// Future requestAuth({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods, +// }); +// } diff --git a/lib/apis/auth_api/i_auth_engine_common.dart b/lib/apis/auth_api/i_auth_engine_common.dart index 36c9e9b2..70bca6a9 100644 --- a/lib/apis/auth_api/i_auth_engine_common.dart +++ b/lib/apis/auth_api/i_auth_engine_common.dart @@ -1,26 +1,26 @@ -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -abstract class IAuthEngineCommon { - abstract final ICore core; - abstract final PairingMetadata metadata; +// abstract class IAuthEngineCommon { +// abstract final ICore core; +// abstract final PairingMetadata metadata; - abstract final IGenericStore authKeys; - abstract final IGenericStore pairingTopics; - abstract final IGenericStore completeRequests; +// abstract final IGenericStore authKeys; +// abstract final IGenericStore pairingTopics; +// abstract final IGenericStore completeRequests; - // initializes the client with persisted storage and a network connection - Future init(); +// // initializes the client with persisted storage and a network connection +// Future init(); - /// format payload to message string - String formatAuthMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }); +// /// format payload to message string +// String formatAuthMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }); - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }); -} +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }); +// } diff --git a/lib/apis/auth_api/i_auth_engine_wallet.dart b/lib/apis/auth_api/i_auth_engine_wallet.dart index c35781cf..4c91c53b 100644 --- a/lib/apis/auth_api/i_auth_engine_wallet.dart +++ b/lib/apis/auth_api/i_auth_engine_wallet.dart @@ -1,23 +1,23 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -abstract class IAuthEngineWallet extends IAuthEngineCommon { - abstract final Event onAuthRequest; +// abstract class IAuthEngineWallet extends IAuthEngineCommon { +// abstract final Event onAuthRequest; - abstract final IGenericStore authRequests; +// abstract final IGenericStore authRequests; - /// respond wallet authentication - Future respondAuthRequest({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }); +// /// respond wallet authentication +// Future respondAuthRequest({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }); - // query all pending requests - Map getPendingAuthRequests(); -} +// // query all pending requests +// Map getPendingAuthRequests(); +// } diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 2bdfa618..bef8c547 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -18,7 +18,7 @@ class SignEngine implements ISignEngine { [ MethodConstants.WC_SESSION_PROPOSE, MethodConstants.WC_SESSION_REQUEST, - MethodConstants.WC_AUTH_REQUEST, + // MethodConstants.WC_AUTH_REQUEST, ], ]; diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 5fa35e0d..6f207761 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -33,7 +33,7 @@ export 'apis/sign_api/models/json_rpc_models.dart'; export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; -// New Auth API +// Auth API export 'apis/sign_api/models/auth/auth_client_models.dart'; export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/json_rpc_models.dart'; @@ -41,18 +41,10 @@ export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; export 'apis/sign_api/utils/auth/auth_api_validators.dart'; - -// Auth API -export 'apis/auth_api/models/auth_client_models.dart'; -export 'apis/auth_api/models/auth_client_events.dart'; -export 'apis/auth_api/models/json_rpc_models.dart'; -export 'apis/auth_api/utils/auth_utils.dart'; -export 'apis/auth_api/utils/address_utils.dart'; -export 'apis/auth_api/utils/auth_signature.dart'; -export 'apis/auth_api/utils/auth_api_validators.dart'; -export 'apis/auth_api/i_auth_engine.dart'; -export 'apis/auth_api/i_auth_client.dart'; -export 'apis/auth_api/auth_client.dart'; +// export 'apis/auth_api/i_auth_engine.dart'; +// export 'apis/auth_api/auth_engine.dart'; +// export 'apis/auth_api/i_auth_client.dart'; +// export 'apis/auth_api/auth_client.dart'; // Web3Wallet export 'apis/web3wallet/i_web3wallet.dart'; diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index 94b5f0f0..831aff17 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -1,496 +1,496 @@ -import 'dart:async'; -import 'dart:typed_data'; +// import 'dart:async'; +// import 'dart:typed_data'; -import 'package:eth_sig_util/eth_sig_util.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:package_info_plus/package_info_plus.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +// import 'package:eth_sig_util/eth_sig_util.dart'; +// import 'package:flutter_test/flutter_test.dart'; +// import 'package:package_info_plus/package_info_plus.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'; +// 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'; -import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -import '../shared/shared_test_utils.dart'; -import '../shared/shared_test_values.dart'; -import 'utils/auth_client_test_wrapper.dart'; -import 'utils/engine_constants.dart'; -import 'utils/signature_constants.dart'; +// import '../shared/shared_test_utils.dart'; +// import '../shared/shared_test_values.dart'; +// import 'utils/auth_client_test_wrapper.dart'; +// import 'utils/engine_constants.dart'; +// 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', - ); - - final List Function(PairingMetadata)> authAppCreators = - [ - (PairingMetadata metadata) async => - await AuthClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - (PairingMetadata? self) async { - final core = Core( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ); - IAuthEngine e = AuthEngine( - core: core, - metadata: self ?? PairingMetadata.empty(), - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - await core.start(); - await e.init(); - - return e; - }, - (PairingMetadata metadata) async => - await AuthClientTestWrapper.createInstance( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - metadata: metadata, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ), - ]; - - final List Function(PairingMetadata)> - authWalletCreators = [ - // (PairingMetadata metadata) async => await Web3Wallet.createInstance( - // projectId: TEST_PROJECT_ID, - // relayUrl: TEST_RELAY_URL, - // metadata: metadata, - // memoryStore: true, - // logLevel: LogLevel.info, - // httpClient: getHttpWrapper(), - // ), - (PairingMetadata metadata) async { - final core = Core( - projectId: TEST_PROJECT_ID, - relayUrl: TEST_RELAY_URL, - memoryStore: true, - logLevel: LogLevel.info, - httpClient: getHttpWrapper(), - ); - IAuthEngine e = AuthEngine( - core: core, - metadata: metadata, - authKeys: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_KEYS, - version: StoreVersions.VERSION_AUTH_KEYS, - fromJson: (dynamic value) { - return AuthPublicKey.fromJson(value); - }, - ), - pairingTopics: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_PAIRING_TOPICS, - version: StoreVersions.VERSION_PAIRING_TOPICS, - fromJson: (dynamic value) { - return value; - }, - ), - authRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_AUTH_REQUESTS, - version: StoreVersions.VERSION_AUTH_REQUESTS, - fromJson: (dynamic value) { - return PendingAuthRequest.fromJson(value); - }, - ), - completeRequests: GenericStore( - storage: core.storage, - context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, - version: StoreVersions.VERSION_COMPLETE_REQUESTS, - fromJson: (dynamic value) { - return StoredCacao.fromJson(value); - }, - ), - ); - await core.start(); - await e.init(); - - return e; - }, - // (PairingMetadata metadata) async => await Web3Wallet.createInstance( - // projectId: TEST_PROJECT_ID, - // relayUrl: TEST_RELAY_URL, - // metadata: metadata, - // memoryStore: true, - // logLevel: LogLevel.info, - // httpClient: getHttpWrapper(), - // ), - ]; - - final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; - - for (int i = 0; i < authAppCreators.length; i++) { - runTests( - context: contexts[i], - engineAppCreator: authAppCreators[i], - engineWalletCreator: authWalletCreators[i], - ); - } -} - -void runTests({ - required String context, - required Future Function(PairingMetadata) engineAppCreator, - required Future Function(PairingMetadata) - engineWalletCreator, -}) { - group(context, () { - late IAuthEngineApp clientA; - late IAuthEngineWallet clientB; - - setUp(() async { - clientA = await engineAppCreator( - TEST_METADATA_REQUESTER, - ); - clientB = await engineWalletCreator( - TEST_METADATA_RESPONDER, - ); - }); - - tearDown(() async { - await clientA.core.relayClient.disconnect(); - await clientB.core.relayClient.disconnect(); - }); - - group('happy path', () { - test('Initializes', () async { - expect(clientA.core.pairing.getPairings().length, 0); - expect(clientB.core.pairing.getPairings().length, 0); - }); - - test( - 'connects and receives request, reconnects and receives another request, and emits proper events', - () async { - AuthRequestResponse response = await clientA.requestAuth( - params: defaultRequestParams, - ); - final String pairingTopic = response.pairingTopic; - - Completer completerAPairing = Completer(); - Completer completerBPairing = Completer(); - Completer completerA = Completer(); - Completer completerB = Completer(); - int counterAPairing = 0; - int counterBPairing = 0; - int counterA = 0; - int counterB = 0; - clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { - expect(pairing != null, true); - expect(pairing!.topic, pairingTopic); - counterAPairing++; - completerAPairing.complete(); - }); - clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { - expect(pairing != null, true); - expect(pairing!.topic, pairingTopic); - counterBPairing++; - completerBPairing.complete(); - }); - clientA.onAuthResponse.subscribe((AuthResponse? args) { - counterA++; - completerA.complete(); - - expect(args!.result, isNotNull); - }); - clientB.onAuthRequest.subscribe((AuthRequest? args) async { - counterB++; - - int currReqCount = clientB.getPendingAuthRequests().length; - - expect(args != null, true); - - // Create the message to be signed - String message = clientB.formatAuthMessage( - iss: TEST_ISSUER_EIP191, - cacaoPayload: CacaoRequestPayload.fromPayloadParams( - args!.payloadParams, - ), - ); - - String sig = EthSigUtil.signPersonalMessage( - message: Uint8List.fromList(message.codeUnits), - privateKey: TEST_PRIVATE_KEY_EIP191, - ); - - await clientB.respondAuthRequest( - id: args.id, - iss: TEST_ISSUER_EIP191, - signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), - ); - - expect(clientB.getPendingAuthRequests().length, currReqCount - 1); - - completerB.complete(); - }); - - expect(response.uri != null, true); - - await clientB.core.pairing.pair(uri: response.uri!); - expect(clientA.core.pairing.getPairings().length, 1); - expect(clientB.core.pairing.getPairings().length, 1); - // AuthResponse authResponse = await response.completer.future; - - await clientA.core.pairing.ping(topic: pairingTopic); - await clientB.core.pairing.ping(topic: pairingTopic); - - if (!completerAPairing.isCompleted) { - clientA.core.logger.i('Waiting for completerAPairing'); - await completerAPairing.future; - } - if (!completerBPairing.isCompleted) { - clientA.core.logger.i('Waiting for completerBPairing'); - await completerBPairing.future; - } - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - if (!completerB.isCompleted) { - clientA.core.logger.i('Waiting for completerB'); - await completerB.future; - } - - AuthResponse authResponse = await response.completer.future; - expect(authResponse.result != null, true); - - expect(counterAPairing, 1); - expect(counterBPairing, 1); - - expect(counterA, 1); - expect(counterB, 1); - - expect( - clientA - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 1, - ); - expect( - clientB - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 1, - ); - - completerA = Completer(); - completerB = Completer(); - - response = await clientA.requestAuth( - params: defaultRequestParams, - pairingTopic: pairingTopic, - ); - - expect(response.uri == null, true); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - if (!completerB.isCompleted) { - clientA.core.logger.i('Waiting for completerB'); - await completerB.future; - } - - authResponse = await response.completer.future; - expect(authResponse.result != null, true); - - // Got the second request and response - expect(counterA, 2); - expect(counterB, 2); - - expect( - clientA - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 2, - ); - expect( - clientB - .getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ) - .length, - 2, - ); - - clientA.onAuthResponse.unsubscribeAll(); - clientB.onAuthRequest.unsubscribeAll(); - clientA.core.pairing.onPairingPing.unsubscribeAll(); - clientB.core.pairing.onPairingPing.unsubscribeAll(); - }); - - test('counts pendingAuthRequests properly', () async { - AuthRequestResponse response = await clientA.requestAuth( - params: defaultRequestParams, - ); - final String pairingTopic = response.pairingTopic; - - await clientB.core.pairing.pair(uri: response.uri!); - - Completer completerA = Completer(); - clientB.onAuthRequest.subscribe((AuthRequest? args) async { - // print('got here'); - // print(clientB.getPendingAuthRequests().length); - completerA.complete(); - }); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - - expect(clientB.getPendingAuthRequests().length, 1); - - completerA = Completer(); - - response = await clientA.requestAuth( - params: defaultRequestParams, - pairingTopic: pairingTopic, - ); - - if (!completerA.isCompleted) { - clientA.core.logger.i('Waiting for completerA'); - await completerA.future; - } - - expect(clientB.getPendingAuthRequests().length, 2); - }); - }); - - group('requestAuth', () { - test('creates correct URI', () async { - AuthRequestResponse response = await clientA.requestAuth( - params: testAuthRequestParamsValid, - ); - - expect(response.uri != null, true); - URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); - expect(parsed.protocol, 'wc'); - expect(parsed.version, URIVersion.v2); - expect(parsed.topic, response.pairingTopic); - expect(parsed.v2Data!.relay.protocol, 'irn'); - if (clientA is IWeb3App) { - expect(parsed.v2Data!.methods.length, 3); - expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); - expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); - expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); - } else { - expect(parsed.v2Data!.methods.length, 1); - expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); - } - - response = await clientA.requestAuth( - params: testAuthRequestParamsValid, - methods: [], - ); - - expect(response.uri != null, true); - parsed = WalletConnectUtils.parseUri(response.uri!); - expect(parsed.protocol, 'wc'); - expect(parsed.version, URIVersion.v2); - expect(parsed.v2Data!.relay.protocol, 'irn'); - expect(parsed.v2Data!.methods.length, 0); - }); - - test('invalid request params', () async { - expect( - () => clientA.requestAuth( - params: testAuthRequestParamsInvalidAud, - ), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', - ), - ), - ); - }); - }); - - group('respondAuth', () { - test('invalid response params', () async { - expect( - () => clientB.respondAuthRequest( - id: -1, - iss: TEST_ISSUER_EIP191, - ), - throwsA( - isA().having( - (e) => e.message, - 'message', - 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', - ), - ), - ); - }); - }); - - group('formatAuthMessage', () { - test('works', () { - final String message = clientA.formatAuthMessage( - iss: TEST_ISSUER_EIP191, - cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), - ); - expect(message, TEST_FORMATTED_MESSAGE); - }); - }); - }); +// TestWidgetsFlutterBinding.ensureInitialized(); +// PackageInfo.setMockInitialValues( +// appName: 'walletconnect_flutter_v2', +// packageName: 'com.walletconnect.flutterdapp', +// version: '1.0', +// buildNumber: '2', +// buildSignature: 'buildSignature', +// ); + +// final List Function(PairingMetadata)> authAppCreators = +// [ +// (PairingMetadata metadata) async => +// await AuthClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// (PairingMetadata? self) async { +// final core = Core( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ); +// IAuthEngine e = AuthEngine( +// core: core, +// metadata: self ?? PairingMetadata.empty(), +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// await core.start(); +// await e.init(); + +// return e; +// }, +// (PairingMetadata metadata) async => +// await AuthClientTestWrapper.createInstance( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// metadata: metadata, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ), +// ]; + +// final List Function(PairingMetadata)> +// authWalletCreators = [ +// // (PairingMetadata metadata) async => await Web3Wallet.createInstance( +// // projectId: TEST_PROJECT_ID, +// // relayUrl: TEST_RELAY_URL, +// // metadata: metadata, +// // memoryStore: true, +// // logLevel: LogLevel.info, +// // httpClient: getHttpWrapper(), +// // ), +// (PairingMetadata metadata) async { +// final core = Core( +// projectId: TEST_PROJECT_ID, +// relayUrl: TEST_RELAY_URL, +// memoryStore: true, +// logLevel: LogLevel.info, +// httpClient: getHttpWrapper(), +// ); +// IAuthEngine e = AuthEngine( +// core: core, +// metadata: metadata, +// authKeys: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_KEYS, +// version: StoreVersions.VERSION_AUTH_KEYS, +// fromJson: (dynamic value) { +// return AuthPublicKey.fromJson(value); +// }, +// ), +// pairingTopics: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_PAIRING_TOPICS, +// version: StoreVersions.VERSION_PAIRING_TOPICS, +// fromJson: (dynamic value) { +// return value; +// }, +// ), +// authRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_AUTH_REQUESTS, +// version: StoreVersions.VERSION_AUTH_REQUESTS, +// fromJson: (dynamic value) { +// return PendingAuthRequest.fromJson(value); +// }, +// ), +// completeRequests: GenericStore( +// storage: core.storage, +// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, +// version: StoreVersions.VERSION_COMPLETE_REQUESTS, +// fromJson: (dynamic value) { +// return StoredCacao.fromJson(value); +// }, +// ), +// ); +// await core.start(); +// await e.init(); + +// return e; +// }, +// // (PairingMetadata metadata) async => await Web3Wallet.createInstance( +// // projectId: TEST_PROJECT_ID, +// // relayUrl: TEST_RELAY_URL, +// // metadata: metadata, +// // memoryStore: true, +// // logLevel: LogLevel.info, +// // httpClient: getHttpWrapper(), +// // ), +// ]; + +// final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; + +// for (int i = 0; i < authAppCreators.length; i++) { +// runTests( +// context: contexts[i], +// engineAppCreator: authAppCreators[i], +// engineWalletCreator: authWalletCreators[i], +// ); +// } +// } + +// void runTests({ +// required String context, +// required Future Function(PairingMetadata) engineAppCreator, +// required Future Function(PairingMetadata) +// engineWalletCreator, +// }) { +// group(context, () { +// late IAuthEngineApp clientA; +// late IAuthEngineWallet clientB; + +// setUp(() async { +// clientA = await engineAppCreator( +// TEST_METADATA_REQUESTER, +// ); +// clientB = await engineWalletCreator( +// TEST_METADATA_RESPONDER, +// ); +// }); + +// tearDown(() async { +// await clientA.core.relayClient.disconnect(); +// await clientB.core.relayClient.disconnect(); +// }); + +// group('happy path', () { +// test('Initializes', () async { +// expect(clientA.core.pairing.getPairings().length, 0); +// expect(clientB.core.pairing.getPairings().length, 0); +// }); + +// test( +// 'connects and receives request, reconnects and receives another request, and emits proper events', +// () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: defaultRequestParams, +// ); +// final String pairingTopic = response.pairingTopic; + +// Completer completerAPairing = Completer(); +// Completer completerBPairing = Completer(); +// Completer completerA = Completer(); +// Completer completerB = Completer(); +// int counterAPairing = 0; +// int counterBPairing = 0; +// int counterA = 0; +// int counterB = 0; +// clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { +// expect(pairing != null, true); +// expect(pairing!.topic, pairingTopic); +// counterAPairing++; +// completerAPairing.complete(); +// }); +// clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { +// expect(pairing != null, true); +// expect(pairing!.topic, pairingTopic); +// counterBPairing++; +// completerBPairing.complete(); +// }); +// clientA.onAuthResponse.subscribe((AuthResponse? args) { +// counterA++; +// completerA.complete(); + +// expect(args!.result, isNotNull); +// }); +// clientB.onAuthRequest.subscribe((AuthRequest? args) async { +// counterB++; + +// int currReqCount = clientB.getPendingAuthRequests().length; + +// expect(args != null, true); + +// // Create the message to be signed +// String message = clientB.formatAuthMessage( +// iss: TEST_ISSUER_EIP191, +// cacaoPayload: CacaoRequestPayload.fromPayloadParams( +// args!.payloadParams, +// ), +// ); + +// String sig = EthSigUtil.signPersonalMessage( +// message: Uint8List.fromList(message.codeUnits), +// privateKey: TEST_PRIVATE_KEY_EIP191, +// ); + +// await clientB.respondAuthRequest( +// id: args.id, +// iss: TEST_ISSUER_EIP191, +// signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), +// ); + +// expect(clientB.getPendingAuthRequests().length, currReqCount - 1); + +// completerB.complete(); +// }); + +// expect(response.uri != null, true); + +// await clientB.core.pairing.pair(uri: response.uri!); +// expect(clientA.core.pairing.getPairings().length, 1); +// expect(clientB.core.pairing.getPairings().length, 1); +// // AuthResponse authResponse = await response.completer.future; + +// await clientA.core.pairing.ping(topic: pairingTopic); +// await clientB.core.pairing.ping(topic: pairingTopic); + +// if (!completerAPairing.isCompleted) { +// clientA.core.logger.i('Waiting for completerAPairing'); +// await completerAPairing.future; +// } +// if (!completerBPairing.isCompleted) { +// clientA.core.logger.i('Waiting for completerBPairing'); +// await completerBPairing.future; +// } +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } +// if (!completerB.isCompleted) { +// clientA.core.logger.i('Waiting for completerB'); +// await completerB.future; +// } + +// AuthResponse authResponse = await response.completer.future; +// expect(authResponse.result != null, true); + +// expect(counterAPairing, 1); +// expect(counterBPairing, 1); + +// expect(counterA, 1); +// expect(counterB, 1); + +// expect( +// clientA +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 1, +// ); +// expect( +// clientB +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 1, +// ); + +// completerA = Completer(); +// completerB = Completer(); + +// response = await clientA.requestAuth( +// params: defaultRequestParams, +// pairingTopic: pairingTopic, +// ); + +// expect(response.uri == null, true); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } +// if (!completerB.isCompleted) { +// clientA.core.logger.i('Waiting for completerB'); +// await completerB.future; +// } + +// authResponse = await response.completer.future; +// expect(authResponse.result != null, true); + +// // Got the second request and response +// expect(counterA, 2); +// expect(counterB, 2); + +// expect( +// clientA +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 2, +// ); +// expect( +// clientB +// .getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ) +// .length, +// 2, +// ); + +// clientA.onAuthResponse.unsubscribeAll(); +// clientB.onAuthRequest.unsubscribeAll(); +// clientA.core.pairing.onPairingPing.unsubscribeAll(); +// clientB.core.pairing.onPairingPing.unsubscribeAll(); +// }); + +// test('counts pendingAuthRequests properly', () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: defaultRequestParams, +// ); +// final String pairingTopic = response.pairingTopic; + +// await clientB.core.pairing.pair(uri: response.uri!); + +// Completer completerA = Completer(); +// clientB.onAuthRequest.subscribe((AuthRequest? args) async { +// // print('got here'); +// // print(clientB.getPendingAuthRequests().length); +// completerA.complete(); +// }); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } + +// expect(clientB.getPendingAuthRequests().length, 1); + +// completerA = Completer(); + +// response = await clientA.requestAuth( +// params: defaultRequestParams, +// pairingTopic: pairingTopic, +// ); + +// if (!completerA.isCompleted) { +// clientA.core.logger.i('Waiting for completerA'); +// await completerA.future; +// } + +// expect(clientB.getPendingAuthRequests().length, 2); +// }); +// }); + +// group('requestAuth', () { +// test('creates correct URI', () async { +// AuthRequestResponse response = await clientA.requestAuth( +// params: testAuthRequestParamsValid, +// ); + +// expect(response.uri != null, true); +// URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); +// expect(parsed.protocol, 'wc'); +// expect(parsed.version, URIVersion.v2); +// expect(parsed.topic, response.pairingTopic); +// expect(parsed.v2Data!.relay.protocol, 'irn'); +// if (clientA is IWeb3App) { +// expect(parsed.v2Data!.methods.length, 3); +// expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); +// expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); +// expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); +// } else { +// expect(parsed.v2Data!.methods.length, 1); +// expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); +// } + +// response = await clientA.requestAuth( +// params: testAuthRequestParamsValid, +// methods: [], +// ); + +// expect(response.uri != null, true); +// parsed = WalletConnectUtils.parseUri(response.uri!); +// expect(parsed.protocol, 'wc'); +// expect(parsed.version, URIVersion.v2); +// expect(parsed.v2Data!.relay.protocol, 'irn'); +// expect(parsed.v2Data!.methods.length, 0); +// }); + +// test('invalid request params', () async { +// expect( +// () => clientA.requestAuth( +// params: testAuthRequestParamsInvalidAud, +// ), +// throwsA( +// isA().having( +// (e) => e.message, +// 'message', +// 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', +// ), +// ), +// ); +// }); +// }); + +// group('respondAuth', () { +// test('invalid response params', () async { +// expect( +// () => clientB.respondAuthRequest( +// id: -1, +// iss: TEST_ISSUER_EIP191, +// ), +// throwsA( +// isA().having( +// (e) => e.message, +// 'message', +// 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', +// ), +// ), +// ); +// }); +// }); + +// group('formatAuthMessage', () { +// test('works', () { +// final String message = clientA.formatAuthMessage( +// iss: TEST_ISSUER_EIP191, +// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), +// ); +// expect(message, TEST_FORMATTED_MESSAGE); +// }); +// }); +// }); } diff --git a/test/auth_api/utils/auth_client_test_wrapper.dart b/test/auth_api/utils/auth_client_test_wrapper.dart index dcf69087..44766385 100644 --- a/test/auth_api/utils/auth_client_test_wrapper.dart +++ b/test/auth_api/utils/auth_client_test_wrapper.dart @@ -1,158 +1,158 @@ -import 'package:event/event.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +// import 'package:event/event.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -class AuthClientTestWrapper implements IAuthEngine { - bool _initialized = false; +// class AuthClientTestWrapper implements IAuthEngine { +// bool _initialized = false; - @override - Event get onAuthRequest => client.onAuthRequest; - @override - Event get onAuthResponse => client.onAuthResponse; +// @override +// Event get onAuthRequest => client.onAuthRequest; +// @override +// Event get onAuthResponse => client.onAuthResponse; - @override - ICore get core => client.core; - @override - PairingMetadata get metadata => client.metadata; - @override - IGenericStore get authKeys => client.authKeys; - @override - IGenericStore get pairingTopics => client.pairingTopics; - @override - IGenericStore get authRequests => client.authRequests; - @override - IGenericStore get completeRequests => client.completeRequests; +// @override +// ICore get core => client.core; +// @override +// PairingMetadata get metadata => client.metadata; +// @override +// IGenericStore get authKeys => client.authKeys; +// @override +// IGenericStore get pairingTopics => client.pairingTopics; +// @override +// IGenericStore get authRequests => client.authRequests; +// @override +// IGenericStore get completeRequests => client.completeRequests; - late IAuthClient client; +// late IAuthClient client; - static Future createInstance({ - required String projectId, - String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, - required PairingMetadata metadata, - bool memoryStore = false, - LogLevel logLevel = LogLevel.nothing, - IHttpClient httpClient = const HttpWrapper(), - }) async { - final client = AuthClientTestWrapper( - core: Core( - projectId: projectId, - relayUrl: relayUrl, - memoryStore: memoryStore, - logLevel: logLevel, - httpClient: httpClient, - ), - metadata: metadata, - ); - await client.init(); +// static Future createInstance({ +// required String projectId, +// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, +// required PairingMetadata metadata, +// bool memoryStore = false, +// LogLevel logLevel = LogLevel.nothing, +// IHttpClient httpClient = const HttpWrapper(), +// }) async { +// final client = AuthClientTestWrapper( +// core: Core( +// projectId: projectId, +// relayUrl: relayUrl, +// memoryStore: memoryStore, +// logLevel: logLevel, +// httpClient: httpClient, +// ), +// metadata: metadata, +// ); +// await client.init(); - return client; - } +// return client; +// } - AuthClientTestWrapper({ - required ICore core, - required PairingMetadata metadata, - }) { - client = AuthClient( - core: core, - metadata: metadata, - ); - } +// AuthClientTestWrapper({ +// required ICore core, +// required PairingMetadata metadata, +// }) { +// client = AuthClient( +// core: core, +// metadata: metadata, +// ); +// } - @override - Future init() async { - if (_initialized) { - return; - } +// @override +// Future init() async { +// if (_initialized) { +// return; +// } - await core.start(); - await client.init(); +// await core.start(); +// await client.init(); - _initialized = true; - } +// _initialized = true; +// } - @override - Future requestAuth({ - required AuthRequestParams params, - String? pairingTopic, - List>? methods = AuthEngine.DEFAULT_METHODS, - }) async { - try { - return client.request( - params: params, - pairingTopic: pairingTopic, - methods: methods, - ); - } catch (e) { - rethrow; - } - } +// @override +// Future requestAuth({ +// required AuthRequestParams params, +// String? pairingTopic, +// List>? methods = AuthEngine.DEFAULT_METHODS, +// }) async { +// try { +// return client.request( +// params: params, +// pairingTopic: pairingTopic, +// methods: methods, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - Future respondAuthRequest({ - required int id, - required String iss, - CacaoSignature? signature, - WalletConnectError? error, - }) async { - try { - return client.respond( - id: id, - iss: iss, - signature: signature, - error: error, - ); - } catch (e) { - rethrow; - } - } +// @override +// Future respondAuthRequest({ +// required int id, +// required String iss, +// CacaoSignature? signature, +// WalletConnectError? error, +// }) async { +// try { +// return client.respond( +// id: id, +// iss: iss, +// signature: signature, +// error: error, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - Map getPendingAuthRequests() { - try { - return client.getPendingRequests(); - } catch (e) { - rethrow; - } - } +// @override +// Map getPendingAuthRequests() { +// try { +// return client.getPendingRequests(); +// } catch (e) { +// rethrow; +// } +// } - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return client.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } +// @override +// Map getCompletedRequestsForPairing({ +// required String pairingTopic, +// }) { +// try { +// return client.getCompletedRequestsForPairing( +// pairingTopic: pairingTopic, +// ); +// } catch (e) { +// rethrow; +// } +// } - @override - String formatAuthMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, - }) { - try { - return client.formatMessage( - iss: iss, - cacaoPayload: cacaoPayload, - ); - } catch (e) { - rethrow; - } - } -} +// @override +// String formatAuthMessage({ +// required String iss, +// required CacaoRequestPayload cacaoPayload, +// }) { +// try { +// return client.formatMessage( +// iss: iss, +// cacaoPayload: cacaoPayload, +// ); +// } catch (e) { +// rethrow; +// } +// } +// } From 6b649f8e98ac9e08ede81907061938377d7ea438 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 4 Jun 2024 18:53:19 +0200 Subject: [PATCH 08/29] Implemented all the necessary to support 1CA from dapp side (no fallback to session proposal yet) --- .../android/app/src/main/AndroidManifest.xml | 2 +- example/dapp/ios/Runner/Info.plist | 1 + example/dapp/lib/main.dart | 9 + example/dapp/lib/pages/connect_page.dart | 148 +- example/dapp/lib/pages/sessions_page.dart | 2 +- example/dapp/lib/widgets/auth_item.dart | 2 +- example/dapp/lib/widgets/pairing_item.dart | 13 +- example/dapp/lib/widgets/session_item.dart | 11 +- .../lib/dependencies/web3wallet_service.dart | 2 +- .../wc_connection_request_widget.dart | 1 - .../wc_session_request_model.dart | 1 - lib/apis/core/pairing/pairing.dart | 2 +- .../core/pairing/utils/pairing_models.dart | 2 +- lib/apis/core/relay_client/relay_client.dart | 14 +- lib/apis/sign_api/i_sign_client.dart | 16 +- lib/apis/sign_api/i_sign_engine_app.dart | 11 +- lib/apis/sign_api/i_sign_engine_common.dart | 7 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 1 + .../models/auth/auth_client_events.dart | 13 +- .../models/auth/auth_client_models.dart | 180 +- .../auth/auth_client_models.freezed.dart | 1752 +---------------- .../models/auth/auth_client_models.g.dart | 165 +- .../models/auth/auth_common_models.dart | 193 ++ .../auth/auth_common_models.freezed.dart | 1633 +++++++++++++++ .../models/auth/auth_common_models.g.dart | 164 ++ .../models/auth/cacao_models.freezed.dart | 1494 ++++++++++++++ .../sign_api/models/auth/cacao_models.g.dart | 154 ++ .../sign_api/models/auth/json_rpc_models.dart | 28 + .../models/auth/json_rpc_models.freezed.dart | 389 ++++ .../models/auth/json_rpc_models.g.dart | 35 + .../models/auth/one_click_auth_events.dart | 43 + .../models/auth/one_click_auth_models.dart | 111 ++ .../auth/one_click_auth_models.freezed.dart | 410 ++++ .../models/auth/one_click_auth_models.g.dart | 53 + lib/apis/sign_api/sign_client.dart | 39 +- lib/apis/sign_api/sign_engine.dart | 416 +++- .../utils/auth/auth_api_validators.dart | 61 + .../sign_api/utils/auth/auth_constants.dart | 9 + .../sign_api/utils/auth/auth_signature.dart | 2 +- .../sign_api/utils/auth/recaps_utils.dart | 223 +++ lib/apis/utils/method_constants.dart | 37 +- lib/apis/utils/namespace_utils.dart | 64 +- lib/apis/web3app/web3app.dart | 38 + lib/apis/web3wallet/web3wallet.dart | 15 + lib/walletconnect_flutter_v2.dart | 6 +- test/auth_api/utils/signature_constants.dart | 2 +- .../utils/sign_client_test_wrapper.dart | 36 + 47 files changed, 5875 insertions(+), 2135 deletions(-) create mode 100644 lib/apis/sign_api/models/auth/auth_common_models.dart create mode 100644 lib/apis/sign_api/models/auth/auth_common_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/auth_common_models.g.dart create mode 100644 lib/apis/sign_api/models/auth/cacao_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/cacao_models.g.dart create mode 100644 lib/apis/sign_api/models/auth/one_click_auth_events.dart create mode 100644 lib/apis/sign_api/models/auth/one_click_auth_models.dart create mode 100644 lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/one_click_auth_models.g.dart create mode 100644 lib/apis/sign_api/utils/auth/recaps_utils.dart diff --git a/example/dapp/android/app/src/main/AndroidManifest.xml b/example/dapp/android/app/src/main/AndroidManifest.xml index 2b63c4b5..aad3033b 100644 --- a/example/dapp/android/app/src/main/AndroidManifest.xml +++ b/example/dapp/android/app/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ android:name="${applicationName}" android:icon="@mipmap/ic_launcher"> LSApplicationQueriesSchemes wcflutterwallet + walletapp LSRequiresIPhoneOS diff --git a/example/dapp/lib/main.dart b/example/dapp/lib/main.dart index b4c54505..3962d1ca 100644 --- a/example/dapp/lib/main.dart +++ b/example/dapp/lib/main.dart @@ -93,6 +93,7 @@ class _MyHomePageState extends State { _web3App!.onSessionEvent.subscribe(_onSessionEvent); _web3App!.onSessionUpdate.subscribe(_onSessionUpdate); + _web3App!.core.addLogListener(_logListener); _web3App!.core.relayClient.onRelayClientConnect.subscribe(_setState); _web3App!.core.relayClient.onRelayClientDisconnect.subscribe(_setState); _web3App!.core.relayClient.onRelayClientMessage.subscribe(_onRelayMessage); @@ -140,6 +141,7 @@ class _MyHomePageState extends State { _web3App!.onSessionEvent.unsubscribe(_onSessionEvent); _web3App!.onSessionUpdate.unsubscribe(_onSessionUpdate); + _web3App!.core.removeLogListener(_logListener); _web3App!.core.relayClient.onRelayClientConnect.unsubscribe(_setState); _web3App!.core.relayClient.onRelayClientDisconnect.unsubscribe(_setState); _web3App!.core.relayClient.onRelayClientMessage @@ -150,6 +152,13 @@ class _MyHomePageState extends State { super.dispose(); } + void _logListener(LogEvent event) { + debugPrint('[SampleDapp] ${event.level.name}: ${event.message}'); + if (event.level == Level.error) { + // TODO send to mixpanel + } + } + @override Widget build(BuildContext context) { if (_initializing) { diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 712c5ccb..5bd70f38 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -1,6 +1,7 @@ // ignore_for_file: use_build_context_synchronously import 'dart:async'; +import 'dart:convert'; import 'package:fl_toast/fl_toast.dart'; import 'package:flutter/foundation.dart'; @@ -165,6 +166,47 @@ class ConnectPageState extends State { ), ); + children.add(const SizedBox(height: 16.0)); + + children.add( + ElevatedButton( + onPressed: _selectedChains.isEmpty + ? null + : () => _oneClickAuth(showToast: (m) async { + await showPlatformToast(child: Text(m), context: context); + }, closeModal: () { + if (Navigator.canPop(context)) { + Navigator.of(context).pop(); + } + }), + style: ButtonStyle( + backgroundColor: MaterialStateProperty.resolveWith( + (states) { + if (states.contains(MaterialState.disabled)) { + return StyleConstants.grayColor; + } + return StyleConstants.primaryColor; + }, + ), + minimumSize: MaterialStateProperty.all(const Size( + 1000.0, + StyleConstants.linear48, + )), + shape: MaterialStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + StyleConstants.linear8, + ), + ), + ), + ), + child: const Text( + '1-Click Auth', + style: StyleConstants.buttonText, + ), + ), + ); + children.add(const SizedBox.square(dimension: 12.0)); return Center( @@ -275,21 +317,22 @@ class ConnectPageState extends State { if (openApp) { launchUrlString(uri, mode: LaunchMode.externalApplication); } else { - _showQrCode(connectResponse); + _showQrCode(connectResponse.uri.toString()); } } else { - _showQrCode(connectResponse); + _showQrCode(connectResponse.uri.toString()); } debugPrint('Awaiting session proposal settlement'); final _ = await connectResponse.session.future; showToast?.call(StringConstants.connectionEstablished); + closeModal?.call(); } - Future _showQrCode(ConnectResponse response) async { + Future _showQrCode(String uri) async { // Show the QR code - debugPrint('Showing QR Code: ${response.uri}'); + debugPrint('Showing QR Code: $uri'); _shouldDismissQrCode = true; if (kIsWeb) { await showDialog( @@ -307,7 +350,7 @@ class ConnectPageState extends State { child: Padding( padding: const EdgeInsets.all(20.0), child: _QRCodeView( - uri: response.uri.toString(), + uri: uri, ), ), ), @@ -328,22 +371,11 @@ class ConnectPageState extends State { context, MaterialPageRoute( fullscreenDialog: true, - builder: (context) => QRCodeScreen(response: response), + builder: (context) => QRCodeScreen(uri: uri), ), ); } - void _onSessionConnect(SessionConnect? event) async { - if (event == null) return; - - if (_shouldDismissQrCode && Navigator.canPop(context)) { - _shouldDismissQrCode = false; - Navigator.pop(context); - } - - _requestAuth(event); - } - void _requestAuth(SessionConnect? event) async { final shouldAuth = await showDialog( context: context, @@ -411,11 +443,87 @@ class ConnectPageState extends State { ); } } + + void _oneClickAuth({ + Function(String message)? showToast, + VoidCallback? closeModal, + }) async { + final methods = optionalNamespaces['eip155']?.methods ?? []; + final authResponse = await widget.web3App.authenticate( + params: OCARequestParams( + chains: _selectedChains.map((e) => e.chainId).toList(), + domain: Constants.domain, + nonce: AuthUtils.generateNonce(), + uri: Constants.aud, + statement: 'Welcome to example flutter app', + methods: methods, + ), + ); + // Legacy Auth Request + // final authResponse = await widget.web3App.requestAuth( + // params: AuthRequestParams( + // chainId: 'eip155:1', + // domain: Constants.domain, + // nonce: AuthUtils.generateNonce(), + // aud: Constants.aud, + // statement: 'Welcome to example flutter app', + // ), + // ); + + final encodedUri = Uri.encodeComponent(authResponse.uri.toString()); + final uri = 'walletapp://wc?uri=$encodedUri'; + + if (await canLaunchUrlString(uri)) { + final openApp = await showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + content: const Text('Do you want to open with Web3Wallet Flutter'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Show QR'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Open'), + ), + ], + ); + }, + ); + if (openApp) { + launchUrlString(uri, mode: LaunchMode.externalApplication); + } else { + _showQrCode(authResponse.uri.toString()); + } + } else { + _showQrCode(authResponse.uri.toString()); + } + + debugPrint('Awaiting session proposal settlement'); + final response = await authResponse.completer.future; + debugPrint('[SampleDapp] session ${jsonEncode(response.toJson())}'); + + showToast?.call(StringConstants.connectionEstablished); + closeModal?.call(); + } + + void _onSessionConnect(SessionConnect? event) async { + if (event == null) return; + + if (_shouldDismissQrCode && Navigator.canPop(context)) { + _shouldDismissQrCode = false; + Navigator.pop(context); + } + + _requestAuth(event); + } } class QRCodeScreen extends StatefulWidget { - const QRCodeScreen({super.key, required this.response}); - final ConnectResponse response; + const QRCodeScreen({super.key, required this.uri}); + final String uri; @override State createState() => _QRCodeScreenState(); @@ -428,7 +536,7 @@ class _QRCodeScreenState extends State { child: Scaffold( appBar: AppBar(title: const Text(StringConstants.scanQrCode)), body: _QRCodeView( - uri: widget.response.uri!.toString(), + uri: widget.uri, ), ), ); diff --git a/example/dapp/lib/pages/sessions_page.dart b/example/dapp/lib/pages/sessions_page.dart index 7f346c60..8309e730 100644 --- a/example/dapp/lib/pages/sessions_page.dart +++ b/example/dapp/lib/pages/sessions_page.dart @@ -61,7 +61,7 @@ class SessionsPageState extends State { (session) => ExpansionPanel( canTapOnHeader: true, isExpanded: _selectedSession == session.topic, - backgroundColor: Colors.black12, + backgroundColor: Colors.blue.withOpacity(0.2), headerBuilder: (context, isExpanded) { return SessionItem( key: ValueKey(session.topic), diff --git a/example/dapp/lib/widgets/auth_item.dart b/example/dapp/lib/widgets/auth_item.dart index 26c1151d..ea712584 100644 --- a/example/dapp/lib/widgets/auth_item.dart +++ b/example/dapp/lib/widgets/auth_item.dart @@ -18,7 +18,7 @@ class AuthItem extends StatelessWidget { onTap: onTap, child: Container( padding: const EdgeInsets.all(12.0), - color: Colors.green.withOpacity(0.2), + color: Colors.blue.withOpacity(0.2), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ diff --git a/example/dapp/lib/widgets/pairing_item.dart b/example/dapp/lib/widgets/pairing_item.dart index 11205c86..74e1f1b2 100644 --- a/example/dapp/lib/widgets/pairing_item.dart +++ b/example/dapp/lib/widgets/pairing_item.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_dapp/utils/constants.dart'; @@ -14,11 +15,19 @@ class PairingItem extends StatelessWidget { @override Widget build(BuildContext context) { + final expiryTimestamp = DateTime.fromMillisecondsSinceEpoch( + pairing.expiry * 1000, + ); + final dateFormat = DateFormat.yMd().add_jm(); + final expiryDate = dateFormat.format(expiryTimestamp); + final inDays = expiryTimestamp.difference(DateTime.now()).inDays + 1; return InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.all(12.0), - color: Colors.blue.withOpacity(0.2), + color: pairing.active + ? Colors.blue.withOpacity(0.2) + : Colors.red.withOpacity(0.2), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -27,7 +36,7 @@ class PairingItem extends StatelessWidget { style: StyleConstants.paragraph, ), Text( - pairing.peerMetadata?.url ?? 'Unknown', + pairing.peerMetadata?.url ?? 'Expiry: $expiryDate ($inDays days)', ), ], ), diff --git a/example/dapp/lib/widgets/session_item.dart b/example/dapp/lib/widgets/session_item.dart index 01e6a584..93a42531 100644 --- a/example/dapp/lib/widgets/session_item.dart +++ b/example/dapp/lib/widgets/session_item.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_dapp/utils/constants.dart'; @@ -12,6 +13,12 @@ class SessionItem extends StatelessWidget { @override Widget build(BuildContext context) { + final expiryTimestamp = DateTime.fromMillisecondsSinceEpoch( + session.expiry * 1000, + ); + final dateFormat = DateFormat.yMd().add_jm(); + final expiryDate = dateFormat.format(expiryTimestamp); + final inDays = expiryTimestamp.difference(DateTime.now()).inDays + 1; return Container( padding: const EdgeInsets.all(12.0), child: Column( @@ -21,9 +28,7 @@ class SessionItem extends StatelessWidget { session.peer.metadata.name, style: StyleConstants.paragraph, ), - Text( - session.peer.metadata.url, - ), + Text('Expiry: $expiryDate ($inDays days)'), ], ), ); diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index d900f032..827e7f67 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -96,7 +96,7 @@ class Web3WalletService extends IWeb3WalletService { } void _logListener(LogEvent event) { - debugPrint('${event.time} LogEvent ${event.level.name}: ${event.message}'); + debugPrint('[WALLET] ${event.level.name}: ${event.message}'); if (event.level == Level.error) { // TODO send to mixpanel } diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart index cca9deeb..72a9d967 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:walletconnect_flutter_v2/apis/core/verify/models/verify_context.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/namespace_model_builder.dart'; diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart b/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart index 5afd07a2..fdea6211 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart @@ -1,4 +1,3 @@ -import 'package:walletconnect_flutter_v2/apis/core/verify/models/verify_context.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; class WCSessionRequestModel { diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index b97a3d22..debab9c4 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -649,7 +649,7 @@ class Pairing implements IPairing { // print(payloadString); Map data = jsonDecode(payloadString); - core.logger.i('Pairing _onMessageEvent, Received data: $data'); + core.logger.t('Pairing _onMessageEvent, Received data: $data'); // If it's an rpc request, handle it // print('Pairing: Received data: $data'); diff --git a/lib/apis/core/pairing/utils/pairing_models.dart b/lib/apis/core/pairing/utils/pairing_models.dart index d7fda7ef..f6577412 100644 --- a/lib/apis/core/pairing/utils/pairing_models.dart +++ b/lib/apis/core/pairing/utils/pairing_models.dart @@ -76,7 +76,7 @@ class CreateResponse { @override String toString() { - return 'CreateResponse(topic: $topic, uri: $uri)'; + return 'CreateResponse(topic: $topic, uri: $uri, pairingInfo: ${pairingInfo.toJson()})'; } } diff --git a/lib/apis/core/relay_client/relay_client.dart b/lib/apis/core/relay_client/relay_client.dart index 8e482da8..699e54a4 100644 --- a/lib/apis/core/relay_client/relay_client.dart +++ b/lib/apis/core/relay_client/relay_client.dart @@ -170,7 +170,7 @@ class RelayClient implements IRelayClient { Future connect({String? relayUrl}) async { _checkInitialized(); - core.logger.i('RelayClient: Connecting to relay'); + core.logger.t('RelayClient: Connecting to relay'); await _connect(relayUrl: relayUrl); } @@ -179,7 +179,7 @@ class RelayClient implements IRelayClient { Future disconnect() async { _checkInitialized(); - core.logger.i('RelayClient: Disconnecting from relay'); + core.logger.t('RelayClient: Disconnecting from relay'); await _disconnect(); } @@ -302,12 +302,12 @@ class RelayClient implements IRelayClient { Future _handleRelayClose(int? code, String? reason) async { if (_handledClose) { - core.logger.i('Relay close already handled'); + core.logger.t('Relay close already handled'); return; } _handledClose = true; - core.logger.i('Handling relay close, code: $code, reason: $reason'); + core.logger.t('Handling relay close, code: $code, reason: $reason'); // If the relay isn't active (Disconnected manually), don't do anything if (!_active) { return; @@ -364,7 +364,7 @@ class RelayClient implements IRelayClient { core.logger.t('Handling Publish Message: $topic, $message'); // If we want to ignore the message, stop if (await _shouldIgnoreMessageEvent(topic, message)) { - core.logger.w('Ignoring Message: $topic, $message'); + core.logger.e('Ignoring Message: $topic, $message'); return false; } @@ -392,7 +392,7 @@ class RelayClient implements IRelayClient { } void _handleUnsubscribe(Parameters params) { - core.logger.i('[$runtimeType] _handleUnsubscribe $params'); + core.logger.t('[$runtimeType] _handleUnsubscribe $params'); } /// MESSAGE HANDLING @@ -441,7 +441,7 @@ class RelayClient implements IRelayClient { JsonRpcUtils.payloadId(entropy: 6), ); } catch (e) { - core.logger.w('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); + core.logger.e('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); onRelayClientError.broadcast(ErrorEvent(e)); } diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 9ffbb24e..01a9e7fa 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -41,6 +41,9 @@ abstract class ISignClient { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; + // NEW 1-CLICK AUTH METHOD + abstract final Event onOCAResponse; + Future init(); Future connect({ Map? requiredNamespaces, @@ -169,10 +172,21 @@ abstract class ISignClient { Map getPendingAuthRequests(); // FORMER AUTH ENGINE PROPERTY - // to be transformed into authenticate({}); Future requestAuth({ required AuthRequestParams params, String? pairingTopic, List>? methods, }); + + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods, + }); + + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index 206c9262..bb451c42 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -8,6 +8,9 @@ abstract class ISignEngineApp extends ISignEngineCommon { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; + // NEW 1-CLICK AUTH METHOD + abstract final Event onOCAResponse; + Future connect({ Map? requiredNamespaces, Map? optionalNamespaces, @@ -48,10 +51,16 @@ abstract class ISignEngineApp extends ISignEngineCommon { }); // FORMER AUTH ENGINE PROPERTY - // to be transformed into authenticate({}); Future requestAuth({ required AuthRequestParams params, String? pairingTopic, List>? methods, }); + + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index 37472c4e..bc5e9a78 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -8,7 +8,7 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; abstract class ISignEngineCommon { abstract final Event onSessionConnect; @@ -49,4 +49,9 @@ abstract class ISignEngineCommon { Map getCompletedRequestsForPairing({ required String pairingTopic, }); + + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index 6d93e11d..81fcc2a9 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -11,6 +11,7 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; abstract class ISignEngineWallet extends ISignEngineCommon { abstract final Event onSessionProposal; diff --git a/lib/apis/sign_api/models/auth/auth_client_events.dart b/lib/apis/sign_api/models/auth/auth_client_events.dart index e4bc7f3a..c45e926e 100644 --- a/lib/apis/sign_api/models/auth/auth_client_events.dart +++ b/lib/apis/sign_api/models/auth/auth_client_events.dart @@ -1,7 +1,10 @@ +import 'dart:convert'; + import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; class AuthRequest extends EventArgs { final int id; @@ -37,8 +40,16 @@ class AuthResponse extends EventArgs { this.jsonRpcError, }); + Map toJson() => { + 'id': id, + 'topic': topic, + if (result != null) 'result': result?.toJson(), + if (error != null) 'error': error!.toJson(), + if (jsonRpcError != null) 'jsonRpcError': jsonRpcError!.toJson(), + }; + @override String toString() { - return 'AuthResponse(id: $id, topic: $topic, result: $result, error: $error, jsonRpcError: $jsonRpcError)'; + return 'AuthResponse(${jsonEncode(toJson())})'; } } diff --git a/lib/apis/sign_api/models/auth/auth_client_models.dart b/lib/apis/sign_api/models/auth/auth_client_models.dart index d5df707d..b0e79799 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_utils.dart'; part 'auth_client_models.g.dart'; @@ -22,17 +23,6 @@ class AuthRequestResponse { }); } -@freezed -class AuthPublicKey with _$AuthPublicKey { - @JsonSerializable(includeIfNull: false) - const factory AuthPublicKey({ - required String publicKey, - }) = _AuthPublicKey; - - factory AuthPublicKey.fromJson(Map json) => - _$AuthPublicKeyFromJson(json); -} - class AuthRequestParams { /// The Chain ID. /// Examples: eip155:1 (Eth Mainnet), eip155:43114 (Avalanche) @@ -88,13 +78,15 @@ class AuthRequestParams { class AuthPayloadParams with _$AuthPayloadParams { @JsonSerializable(includeIfNull: false) const factory AuthPayloadParams({ - required String type, required String chainId, - required String domain, required String aud, - required String version, + required String domain, required String nonce, + required String type, + // + required String version, required String iat, + // String? nbf, String? exp, String? statement, @@ -123,166 +115,6 @@ class AuthPayloadParams with _$AuthPayloadParams { _$AuthPayloadParamsFromJson(json); } -@freezed -class CacaoRequestPayload with _$CacaoRequestPayload { - @JsonSerializable(includeIfNull: false) - const factory CacaoRequestPayload({ - required String domain, - required String aud, - required String version, - required String nonce, - required String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources, - }) = _CacaoRequestPayload; - - factory CacaoRequestPayload.fromPayloadParams(AuthPayloadParams params) { - return CacaoRequestPayload( - domain: params.domain, - aud: params.aud, - version: params.version, - nonce: params.nonce, - iat: params.iat, - nbf: params.nbf, - exp: params.exp, - statement: params.statement, - requestId: params.requestId, - resources: params.resources, - ); - } - - factory CacaoRequestPayload.fromCacaoPayload(CacaoPayload payload) { - return CacaoRequestPayload( - domain: payload.domain, - aud: payload.aud, - version: payload.version, - nonce: payload.nonce, - iat: payload.iat, - nbf: payload.nbf, - exp: payload.exp, - statement: payload.statement, - requestId: payload.requestId, - resources: payload.resources, - ); - } - - factory CacaoRequestPayload.fromJson(Map json) => - _$CacaoRequestPayloadFromJson(json); -} - -@freezed -class CacaoPayload with _$CacaoPayload { - @JsonSerializable(includeIfNull: false) - const factory CacaoPayload({ - required String iss, - required String domain, - required String aud, - required String version, - required String nonce, - required String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources, - }) = _CacaoPayload; - - factory CacaoPayload.fromRequestPayload({ - required String issuer, - required CacaoRequestPayload payload, - }) { - return CacaoPayload( - iss: issuer, - domain: payload.domain, - aud: payload.aud, - version: payload.version, - nonce: payload.nonce, - iat: payload.iat, - nbf: payload.nbf, - exp: payload.exp, - statement: payload.statement, - requestId: payload.requestId, - resources: payload.resources, - ); - } - - factory CacaoPayload.fromJson(Map json) => - _$CacaoPayloadFromJson(json); -} - -@freezed -class CacaoHeader with _$CacaoHeader { - static const EIP4361 = 'eip4361'; - - @JsonSerializable(includeIfNull: false) - const factory CacaoHeader({ - @Default('eip4361') String t, - }) = _CacaoHeader; - - factory CacaoHeader.fromJson(Map json) => - _$CacaoHeaderFromJson(json); -} - -@freezed -class CacaoSignature with _$CacaoSignature { - static const EIP191 = 'eip191'; - static const EIP1271 = 'eip1271'; - - @JsonSerializable(includeIfNull: false) - const factory CacaoSignature({ - required String t, - required String s, - String? m, - }) = _CacaoSignature; - - factory CacaoSignature.fromJson(Map json) => - _$CacaoSignatureFromJson(json); -} - -@freezed -class Cacao with _$Cacao { - @JsonSerializable(includeIfNull: false) - const factory Cacao({ - required CacaoHeader h, - required CacaoPayload p, - required CacaoSignature s, - }) = _Cacao; - - factory Cacao.fromJson(Map json) => _$CacaoFromJson(json); -} - -@freezed -class StoredCacao with _$StoredCacao { - @JsonSerializable(includeIfNull: false) - const factory StoredCacao({ - required int id, - required String pairingTopic, - required CacaoHeader h, - required CacaoPayload p, - required CacaoSignature s, - }) = _StoredCacao; - - factory StoredCacao.fromCacao({ - required int id, - required String pairingTopic, - required Cacao cacao, - }) { - return StoredCacao( - id: id, - pairingTopic: pairingTopic, - h: cacao.h, - p: cacao.p, - s: cacao.s, - ); - } - - factory StoredCacao.fromJson(Map json) => - _$StoredCacaoFromJson(json); -} - @freezed class PendingAuthRequest with _$PendingAuthRequest { @JsonSerializable(includeIfNull: false) 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 ad9219b0..05fbc985 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 @@ -14,158 +14,19 @@ 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'); -AuthPublicKey _$AuthPublicKeyFromJson(Map json) { - return _AuthPublicKey.fromJson(json); -} - -/// @nodoc -mixin _$AuthPublicKey { - String get publicKey => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $AuthPublicKeyCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $AuthPublicKeyCopyWith<$Res> { - factory $AuthPublicKeyCopyWith( - AuthPublicKey value, $Res Function(AuthPublicKey) then) = - _$AuthPublicKeyCopyWithImpl<$Res, AuthPublicKey>; - @useResult - $Res call({String publicKey}); -} - -/// @nodoc -class _$AuthPublicKeyCopyWithImpl<$Res, $Val extends AuthPublicKey> - implements $AuthPublicKeyCopyWith<$Res> { - _$AuthPublicKeyCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? publicKey = null, - }) { - return _then(_value.copyWith( - publicKey: null == publicKey - ? _value.publicKey - : publicKey // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$AuthPublicKeyImplCopyWith<$Res> - implements $AuthPublicKeyCopyWith<$Res> { - factory _$$AuthPublicKeyImplCopyWith( - _$AuthPublicKeyImpl value, $Res Function(_$AuthPublicKeyImpl) then) = - __$$AuthPublicKeyImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String publicKey}); -} - -/// @nodoc -class __$$AuthPublicKeyImplCopyWithImpl<$Res> - extends _$AuthPublicKeyCopyWithImpl<$Res, _$AuthPublicKeyImpl> - implements _$$AuthPublicKeyImplCopyWith<$Res> { - __$$AuthPublicKeyImplCopyWithImpl( - _$AuthPublicKeyImpl _value, $Res Function(_$AuthPublicKeyImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? publicKey = null, - }) { - return _then(_$AuthPublicKeyImpl( - publicKey: null == publicKey - ? _value.publicKey - : publicKey // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$AuthPublicKeyImpl implements _AuthPublicKey { - const _$AuthPublicKeyImpl({required this.publicKey}); - - factory _$AuthPublicKeyImpl.fromJson(Map json) => - _$$AuthPublicKeyImplFromJson(json); - - @override - final String publicKey; - - @override - String toString() { - return 'AuthPublicKey(publicKey: $publicKey)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$AuthPublicKeyImpl && - (identical(other.publicKey, publicKey) || - other.publicKey == publicKey)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, publicKey); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => - __$$AuthPublicKeyImplCopyWithImpl<_$AuthPublicKeyImpl>(this, _$identity); - - @override - Map toJson() { - return _$$AuthPublicKeyImplToJson( - this, - ); - } -} - -abstract class _AuthPublicKey implements AuthPublicKey { - const factory _AuthPublicKey({required final String publicKey}) = - _$AuthPublicKeyImpl; - - factory _AuthPublicKey.fromJson(Map json) = - _$AuthPublicKeyImpl.fromJson; - - @override - String get publicKey; - @override - @JsonKey(ignore: true) - _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => - throw _privateConstructorUsedError; -} - AuthPayloadParams _$AuthPayloadParamsFromJson(Map json) { return _AuthPayloadParams.fromJson(json); } /// @nodoc mixin _$AuthPayloadParams { - String get type => throw _privateConstructorUsedError; String get chainId => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; // + String get version => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; // String? get nbf => throw _privateConstructorUsedError; String? get exp => throw _privateConstructorUsedError; String? get statement => throw _privateConstructorUsedError; @@ -185,12 +46,12 @@ abstract class $AuthPayloadParamsCopyWith<$Res> { _$AuthPayloadParamsCopyWithImpl<$Res, AuthPayloadParams>; @useResult $Res call( - {String type, - String chainId, - String domain, + {String chainId, String aud, - String version, + String domain, String nonce, + String type, + String version, String iat, String? nbf, String? exp, @@ -212,12 +73,12 @@ class _$AuthPayloadParamsCopyWithImpl<$Res, $Val extends AuthPayloadParams> @pragma('vm:prefer-inline') @override $Res call({ - Object? type = null, Object? chainId = null, - Object? domain = null, Object? aud = null, - Object? version = null, + Object? domain = null, Object? nonce = null, + Object? type = null, + Object? version = null, Object? iat = null, Object? nbf = freezed, Object? exp = freezed, @@ -226,30 +87,30 @@ class _$AuthPayloadParamsCopyWithImpl<$Res, $Val extends AuthPayloadParams> Object? resources = freezed, }) { return _then(_value.copyWith( - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, chainId: null == chainId ? _value.chainId : chainId // ignore: cast_nullable_to_non_nullable as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, aud: null == aud ? _value.aud : aud // ignore: cast_nullable_to_non_nullable as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable as String, nonce: null == nonce ? _value.nonce : nonce // ignore: cast_nullable_to_non_nullable as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, iat: null == iat ? _value.iat : iat // ignore: cast_nullable_to_non_nullable @@ -287,12 +148,12 @@ abstract class _$$AuthPayloadParamsImplCopyWith<$Res> @override @useResult $Res call( - {String type, - String chainId, - String domain, + {String chainId, String aud, - String version, + String domain, String nonce, + String type, + String version, String iat, String? nbf, String? exp, @@ -312,12 +173,12 @@ class __$$AuthPayloadParamsImplCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? type = null, Object? chainId = null, - Object? domain = null, Object? aud = null, - Object? version = null, + Object? domain = null, Object? nonce = null, + Object? type = null, + Object? version = null, Object? iat = null, Object? nbf = freezed, Object? exp = freezed, @@ -326,30 +187,30 @@ class __$$AuthPayloadParamsImplCopyWithImpl<$Res> Object? resources = freezed, }) { return _then(_$AuthPayloadParamsImpl( - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, chainId: null == chainId ? _value.chainId : chainId // ignore: cast_nullable_to_non_nullable as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, aud: null == aud ? _value.aud : aud // ignore: cast_nullable_to_non_nullable as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable as String, nonce: null == nonce ? _value.nonce : nonce // ignore: cast_nullable_to_non_nullable as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, iat: null == iat ? _value.iat : iat // ignore: cast_nullable_to_non_nullable @@ -383,12 +244,12 @@ class __$$AuthPayloadParamsImplCopyWithImpl<$Res> @JsonSerializable(includeIfNull: false) class _$AuthPayloadParamsImpl implements _AuthPayloadParams { const _$AuthPayloadParamsImpl( - {required this.type, - required this.chainId, - required this.domain, + {required this.chainId, required this.aud, - required this.version, + required this.domain, required this.nonce, + required this.type, + required this.version, required this.iat, this.nbf, this.exp, @@ -400,20 +261,22 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { factory _$AuthPayloadParamsImpl.fromJson(Map json) => _$$AuthPayloadParamsImplFromJson(json); - @override - final String type; @override final String chainId; @override - final String domain; - @override final String aud; @override - final String version; + final String domain; @override final String nonce; @override + final String type; +// + @override + final String version; + @override final String iat; +// @override final String? nbf; @override @@ -434,7 +297,7 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { @override String toString() { - return 'AuthPayloadParams(type: $type, chainId: $chainId, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + return 'AuthPayloadParams(chainId: $chainId, aud: $aud, domain: $domain, nonce: $nonce, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; } @override @@ -442,12 +305,12 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { return identical(this, other) || (other.runtimeType == runtimeType && other is _$AuthPayloadParamsImpl && - (identical(other.type, type) || other.type == type) && (identical(other.chainId, chainId) || other.chainId == chainId) && - (identical(other.domain, domain) || other.domain == domain) && (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && + (identical(other.domain, domain) || other.domain == domain) && (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.type, type) || other.type == type) && + (identical(other.version, version) || other.version == version) && (identical(other.iat, iat) || other.iat == iat) && (identical(other.nbf, nbf) || other.nbf == nbf) && (identical(other.exp, exp) || other.exp == exp) && @@ -463,12 +326,12 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { @override int get hashCode => Object.hash( runtimeType, - type, chainId, - domain, aud, - version, + domain, nonce, + type, + version, iat, nbf, exp, @@ -493,12 +356,12 @@ class _$AuthPayloadParamsImpl implements _AuthPayloadParams { abstract class _AuthPayloadParams implements AuthPayloadParams { const factory _AuthPayloadParams( - {required final String type, - required final String chainId, - required final String domain, + {required final String chainId, required final String aud, - required final String version, + required final String domain, required final String nonce, + required final String type, + required final String version, required final String iat, final String? nbf, final String? exp, @@ -509,21 +372,21 @@ abstract class _AuthPayloadParams implements AuthPayloadParams { factory _AuthPayloadParams.fromJson(Map json) = _$AuthPayloadParamsImpl.fromJson; - @override - String get type; @override String get chainId; @override - String get domain; - @override String get aud; @override - String get version; + String get domain; @override String get nonce; @override - String get iat; + String get type; + @override // + String get version; @override + String get iat; + @override // String? get nbf; @override String? get exp; @@ -539,1485 +402,6 @@ abstract class _AuthPayloadParams implements AuthPayloadParams { throw _privateConstructorUsedError; } -CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { - return _CacaoRequestPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoRequestPayload { - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoRequestPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoRequestPayloadCopyWith<$Res> { - factory $CacaoRequestPayloadCopyWith( - CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = - _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> - implements $CacaoRequestPayloadCopyWith<$Res> { - _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> - implements $CacaoRequestPayloadCopyWith<$Res> { - factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, - $Res Function(_$CacaoRequestPayloadImpl) then) = - __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> - extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> - implements _$$CacaoRequestPayloadImplCopyWith<$Res> { - __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, - $Res Function(_$CacaoRequestPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoRequestPayloadImpl( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { - const _$CacaoRequestPayloadImpl( - {required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoRequestPayloadImpl.fromJson(Map json) => - _$$CacaoRequestPayloadImplFromJson(json); - - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoRequestPayloadImpl && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoRequestPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoRequestPayload implements CacaoRequestPayload { - const factory _CacaoRequestPayload( - {required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoRequestPayloadImpl; - - factory _CacaoRequestPayload.fromJson(Map json) = - _$CacaoRequestPayloadImpl.fromJson; - - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoPayload _$CacaoPayloadFromJson(Map json) { - return _CacaoPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoPayload { - String get iss => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoPayloadCopyWith<$Res> { - factory $CacaoPayloadCopyWith( - CacaoPayload value, $Res Function(CacaoPayload) then) = - _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> - implements $CacaoPayloadCopyWith<$Res> { - _$CacaoPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoPayloadImplCopyWith<$Res> - implements $CacaoPayloadCopyWith<$Res> { - factory _$$CacaoPayloadImplCopyWith( - _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = - __$$CacaoPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoPayloadImplCopyWithImpl<$Res> - extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> - implements _$$CacaoPayloadImplCopyWith<$Res> { - __$$CacaoPayloadImplCopyWithImpl( - _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoPayloadImpl( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoPayloadImpl implements _CacaoPayload { - const _$CacaoPayloadImpl( - {required this.iss, - required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoPayloadImpl.fromJson(Map json) => - _$$CacaoPayloadImplFromJson(json); - - @override - final String iss; - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoPayloadImpl && - (identical(other.iss, iss) || other.iss == iss) && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - iss, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoPayload implements CacaoPayload { - const factory _CacaoPayload( - {required final String iss, - required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoPayloadImpl; - - factory _CacaoPayload.fromJson(Map json) = - _$CacaoPayloadImpl.fromJson; - - @override - String get iss; - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoHeader _$CacaoHeaderFromJson(Map json) { - return _CacaoHeader.fromJson(json); -} - -/// @nodoc -mixin _$CacaoHeader { - String get t => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoHeaderCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoHeaderCopyWith<$Res> { - factory $CacaoHeaderCopyWith( - CacaoHeader value, $Res Function(CacaoHeader) then) = - _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; - @useResult - $Res call({String t}); -} - -/// @nodoc -class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> - implements $CacaoHeaderCopyWith<$Res> { - _$CacaoHeaderCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoHeaderImplCopyWith<$Res> - implements $CacaoHeaderCopyWith<$Res> { - factory _$$CacaoHeaderImplCopyWith( - _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = - __$$CacaoHeaderImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t}); -} - -/// @nodoc -class __$$CacaoHeaderImplCopyWithImpl<$Res> - extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> - implements _$$CacaoHeaderImplCopyWith<$Res> { - __$$CacaoHeaderImplCopyWithImpl( - _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_$CacaoHeaderImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoHeaderImpl implements _CacaoHeader { - const _$CacaoHeaderImpl({this.t = 'eip4361'}); - - factory _$CacaoHeaderImpl.fromJson(Map json) => - _$$CacaoHeaderImplFromJson(json); - - @override - @JsonKey() - final String t; - - @override - String toString() { - return 'CacaoHeader(t: $t)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoHeaderImpl && - (identical(other.t, t) || other.t == t)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoHeaderImplToJson( - this, - ); - } -} - -abstract class _CacaoHeader implements CacaoHeader { - const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; - - factory _CacaoHeader.fromJson(Map json) = - _$CacaoHeaderImpl.fromJson; - - @override - String get t; - @override - @JsonKey(ignore: true) - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoSignature _$CacaoSignatureFromJson(Map json) { - return _CacaoSignature.fromJson(json); -} - -/// @nodoc -mixin _$CacaoSignature { - String get t => throw _privateConstructorUsedError; - String get s => throw _privateConstructorUsedError; - String? get m => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoSignatureCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoSignatureCopyWith<$Res> { - factory $CacaoSignatureCopyWith( - CacaoSignature value, $Res Function(CacaoSignature) then) = - _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> - implements $CacaoSignatureCopyWith<$Res> { - _$CacaoSignatureCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoSignatureImplCopyWith<$Res> - implements $CacaoSignatureCopyWith<$Res> { - factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, - $Res Function(_$CacaoSignatureImpl) then) = - __$$CacaoSignatureImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class __$$CacaoSignatureImplCopyWithImpl<$Res> - extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> - implements _$$CacaoSignatureImplCopyWith<$Res> { - __$$CacaoSignatureImplCopyWithImpl( - _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_$CacaoSignatureImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoSignatureImpl implements _CacaoSignature { - const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); - - factory _$CacaoSignatureImpl.fromJson(Map json) => - _$$CacaoSignatureImplFromJson(json); - - @override - final String t; - @override - final String s; - @override - final String? m; - - @override - String toString() { - return 'CacaoSignature(t: $t, s: $s, m: $m)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoSignatureImpl && - (identical(other.t, t) || other.t == t) && - (identical(other.s, s) || other.s == s) && - (identical(other.m, m) || other.m == m)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t, s, m); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoSignatureImplToJson( - this, - ); - } -} - -abstract class _CacaoSignature implements CacaoSignature { - const factory _CacaoSignature( - {required final String t, - required final String s, - final String? m}) = _$CacaoSignatureImpl; - - factory _CacaoSignature.fromJson(Map json) = - _$CacaoSignatureImpl.fromJson; - - @override - String get t; - @override - String get s; - @override - String? get m; - @override - @JsonKey(ignore: true) - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - throw _privateConstructorUsedError; -} - -Cacao _$CacaoFromJson(Map json) { - return _Cacao.fromJson(json); -} - -/// @nodoc -mixin _$Cacao { - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoCopyWith<$Res> { - factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = - _$CacaoCopyWithImpl<$Res, Cacao>; - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> - implements $CacaoCopyWith<$Res> { - _$CacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { - factory _$$CacaoImplCopyWith( - _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = - __$$CacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$CacaoImplCopyWithImpl<$Res> - extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> - implements _$$CacaoImplCopyWith<$Res> { - __$$CacaoImplCopyWithImpl( - _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$CacaoImpl( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoImpl implements _Cacao { - const _$CacaoImpl({required this.h, required this.p, required this.s}); - - factory _$CacaoImpl.fromJson(Map json) => - _$$CacaoImplFromJson(json); - - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'Cacao(h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoImpl && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoImplToJson( - this, - ); - } -} - -abstract class _Cacao implements Cacao { - const factory _Cacao( - {required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$CacaoImpl; - - factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; - - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} - -StoredCacao _$StoredCacaoFromJson(Map json) { - return _StoredCacao.fromJson(json); -} - -/// @nodoc -mixin _$StoredCacao { - int get id => throw _privateConstructorUsedError; - String get pairingTopic => throw _privateConstructorUsedError; - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $StoredCacaoCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $StoredCacaoCopyWith<$Res> { - factory $StoredCacaoCopyWith( - StoredCacao value, $Res Function(StoredCacao) then) = - _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> - implements $StoredCacaoCopyWith<$Res> { - _$StoredCacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$StoredCacaoImplCopyWith<$Res> - implements $StoredCacaoCopyWith<$Res> { - factory _$$StoredCacaoImplCopyWith( - _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = - __$$StoredCacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$StoredCacaoImplCopyWithImpl<$Res> - extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> - implements _$$StoredCacaoImplCopyWith<$Res> { - __$$StoredCacaoImplCopyWithImpl( - _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$StoredCacaoImpl( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$StoredCacaoImpl implements _StoredCacao { - const _$StoredCacaoImpl( - {required this.id, - required this.pairingTopic, - required this.h, - required this.p, - required this.s}); - - factory _$StoredCacaoImpl.fromJson(Map json) => - _$$StoredCacaoImplFromJson(json); - - @override - final int id; - @override - final String pairingTopic; - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$StoredCacaoImpl && - (identical(other.id, id) || other.id == id) && - (identical(other.pairingTopic, pairingTopic) || - other.pairingTopic == pairingTopic) && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$StoredCacaoImplToJson( - this, - ); - } -} - -abstract class _StoredCacao implements StoredCacao { - const factory _StoredCacao( - {required final int id, - required final String pairingTopic, - required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$StoredCacaoImpl; - - factory _StoredCacao.fromJson(Map json) = - _$StoredCacaoImpl.fromJson; - - @override - int get id; - @override - String get pairingTopic; - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} - PendingAuthRequest _$PendingAuthRequestFromJson(Map json) { return _PendingAuthRequest.fromJson(json); } 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 db73cc6d..d75b386a 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 @@ -6,25 +6,15 @@ part of 'auth_client_models.dart'; // JsonSerializableGenerator // ************************************************************************** -_$AuthPublicKeyImpl _$$AuthPublicKeyImplFromJson(Map json) => - _$AuthPublicKeyImpl( - publicKey: json['publicKey'] as String, - ); - -Map _$$AuthPublicKeyImplToJson(_$AuthPublicKeyImpl instance) => - { - 'publicKey': instance.publicKey, - }; - _$AuthPayloadParamsImpl _$$AuthPayloadParamsImplFromJson( Map json) => _$AuthPayloadParamsImpl( - type: json['type'] as String, chainId: json['chainId'] as String, - domain: json['domain'] as String, aud: json['aud'] as String, - version: json['version'] as String, + domain: json['domain'] as String, nonce: json['nonce'] as String, + type: json['type'] as String, + version: json['version'] as String, iat: json['iat'] as String, nbf: json['nbf'] as String?, exp: json['exp'] as String?, @@ -38,94 +28,12 @@ _$AuthPayloadParamsImpl _$$AuthPayloadParamsImplFromJson( Map _$$AuthPayloadParamsImplToJson( _$AuthPayloadParamsImpl instance) { final val = { - 'type': instance.type, 'chainId': instance.chainId, - 'domain': instance.domain, 'aud': instance.aud, - 'version': instance.version, - 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( - Map json) => - _$CacaoRequestPayloadImpl( - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoRequestPayloadImplToJson( - _$CacaoRequestPayloadImpl instance) { - final val = { 'domain': instance.domain, - 'aud': instance.aud, - 'version': instance.version, 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => - _$CacaoPayloadImpl( - iss: json['iss'] as String, - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { - final val = { - 'iss': instance.iss, - 'domain': instance.domain, - 'aud': instance.aud, + 'type': instance.type, 'version': instance.version, - 'nonce': instance.nonce, 'iat': instance.iat, }; @@ -143,71 +51,6 @@ Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { return val; } -_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => - _$CacaoHeaderImpl( - t: json['t'] as String? ?? 'eip4361', - ); - -Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => - { - 't': instance.t, - }; - -_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => - _$CacaoSignatureImpl( - t: json['t'] as String, - s: json['s'] as String, - m: json['m'] as String?, - ); - -Map _$$CacaoSignatureImplToJson( - _$CacaoSignatureImpl instance) { - final val = { - 't': instance.t, - 's': instance.s, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('m', instance.m); - return val; -} - -_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$CacaoImplToJson(_$CacaoImpl instance) => - { - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; - -_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => - _$StoredCacaoImpl( - id: json['id'] as int, - pairingTopic: json['pairingTopic'] as String, - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => - { - 'id': instance.id, - 'pairingTopic': instance.pairingTopic, - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; - _$PendingAuthRequestImpl _$$PendingAuthRequestImplFromJson( Map json) => _$PendingAuthRequestImpl( diff --git a/lib/apis/sign_api/models/auth/auth_common_models.dart b/lib/apis/sign_api/models/auth/auth_common_models.dart new file mode 100644 index 00000000..29348aec --- /dev/null +++ b/lib/apis/sign_api/models/auth/auth_common_models.dart @@ -0,0 +1,193 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_models.dart'; + +part 'auth_common_models.g.dart'; +part 'auth_common_models.freezed.dart'; + +@freezed +class AuthPublicKey with _$AuthPublicKey { + @JsonSerializable(includeIfNull: false) + const factory AuthPublicKey({ + required String publicKey, + }) = _AuthPublicKey; + + factory AuthPublicKey.fromJson(Map json) => + _$AuthPublicKeyFromJson(json); +} + +@freezed +class CacaoRequestPayload with _$CacaoRequestPayload { + @JsonSerializable(includeIfNull: false) + const factory CacaoRequestPayload({ + required String domain, + required String aud, + required String version, + required String nonce, + required String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _CacaoRequestPayload; + + factory CacaoRequestPayload.fromPayloadParams(AuthPayloadParams params) { + return CacaoRequestPayload( + domain: params.domain, + aud: params.aud, + version: params.version, + nonce: params.nonce, + iat: params.iat, + nbf: params.nbf, + exp: params.exp, + statement: params.statement, + requestId: params.requestId, + resources: params.resources, + ); + } + + factory CacaoRequestPayload.fromOCAPayloadParams(OCAPayloadParams params) { + return CacaoRequestPayload( + domain: params.domain, + aud: params.aud, + version: params.version, + nonce: params.nonce, + iat: params.iat, + nbf: params.nbf, + exp: params.exp, + statement: params.statement, + requestId: params.requestId, + resources: params.resources, + ); + } + + factory CacaoRequestPayload.fromCacaoPayload(CacaoPayload payload) { + return CacaoRequestPayload( + domain: payload.domain, + aud: payload.aud, + version: payload.version, + nonce: payload.nonce, + iat: payload.iat, + nbf: payload.nbf, + exp: payload.exp, + statement: payload.statement, + requestId: payload.requestId, + resources: payload.resources, + ); + } + + factory CacaoRequestPayload.fromJson(Map json) => + _$CacaoRequestPayloadFromJson(json); +} + +@freezed +class CacaoPayload with _$CacaoPayload { + @JsonSerializable(includeIfNull: false) + const factory CacaoPayload({ + required String iss, + required String domain, + required String aud, + required String version, + required String nonce, + required String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _CacaoPayload; + + factory CacaoPayload.fromRequestPayload({ + required String issuer, + required CacaoRequestPayload payload, + }) { + return CacaoPayload( + iss: issuer, + domain: payload.domain, + aud: payload.aud, + version: payload.version, + nonce: payload.nonce, + iat: payload.iat, + nbf: payload.nbf, + exp: payload.exp, + statement: payload.statement, + requestId: payload.requestId, + resources: payload.resources, + ); + } + + factory CacaoPayload.fromJson(Map json) => + _$CacaoPayloadFromJson(json); +} + +@freezed +class CacaoHeader with _$CacaoHeader { + static const EIP4361 = 'eip4361'; + + @JsonSerializable(includeIfNull: false) + const factory CacaoHeader({ + @Default('eip4361') String t, + }) = _CacaoHeader; + + factory CacaoHeader.fromJson(Map json) => + _$CacaoHeaderFromJson(json); +} + +@freezed +class CacaoSignature with _$CacaoSignature { + static const EIP191 = 'eip191'; + static const EIP1271 = 'eip1271'; + + @JsonSerializable(includeIfNull: false) + const factory CacaoSignature({ + required String t, + required String s, + String? m, + }) = _CacaoSignature; + + factory CacaoSignature.fromJson(Map json) => + _$CacaoSignatureFromJson(json); +} + +@freezed +class Cacao with _$Cacao { + @JsonSerializable(includeIfNull: false) + const factory Cacao({ + required CacaoHeader h, + required CacaoPayload p, + required CacaoSignature s, + }) = _Cacao; + + factory Cacao.fromJson(Map json) => _$CacaoFromJson(json); +} + +@freezed +class StoredCacao with _$StoredCacao { + @JsonSerializable(includeIfNull: false) + const factory StoredCacao({ + required int id, + required String pairingTopic, + required CacaoHeader h, + required CacaoPayload p, + required CacaoSignature s, + }) = _StoredCacao; + + factory StoredCacao.fromCacao({ + required int id, + required String pairingTopic, + required Cacao cacao, + }) { + return StoredCacao( + id: id, + pairingTopic: pairingTopic, + h: cacao.h, + p: cacao.p, + s: cacao.s, + ); + } + + factory StoredCacao.fromJson(Map json) => + _$StoredCacaoFromJson(json); +} diff --git a/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart b/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart new file mode 100644 index 00000000..ce14e4ff --- /dev/null +++ b/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart @@ -0,0 +1,1633 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'auth_common_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +AuthPublicKey _$AuthPublicKeyFromJson(Map json) { + return _AuthPublicKey.fromJson(json); +} + +/// @nodoc +mixin _$AuthPublicKey { + String get publicKey => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $AuthPublicKeyCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AuthPublicKeyCopyWith<$Res> { + factory $AuthPublicKeyCopyWith( + AuthPublicKey value, $Res Function(AuthPublicKey) then) = + _$AuthPublicKeyCopyWithImpl<$Res, AuthPublicKey>; + @useResult + $Res call({String publicKey}); +} + +/// @nodoc +class _$AuthPublicKeyCopyWithImpl<$Res, $Val extends AuthPublicKey> + implements $AuthPublicKeyCopyWith<$Res> { + _$AuthPublicKeyCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? publicKey = null, + }) { + return _then(_value.copyWith( + publicKey: null == publicKey + ? _value.publicKey + : publicKey // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$AuthPublicKeyImplCopyWith<$Res> + implements $AuthPublicKeyCopyWith<$Res> { + factory _$$AuthPublicKeyImplCopyWith( + _$AuthPublicKeyImpl value, $Res Function(_$AuthPublicKeyImpl) then) = + __$$AuthPublicKeyImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String publicKey}); +} + +/// @nodoc +class __$$AuthPublicKeyImplCopyWithImpl<$Res> + extends _$AuthPublicKeyCopyWithImpl<$Res, _$AuthPublicKeyImpl> + implements _$$AuthPublicKeyImplCopyWith<$Res> { + __$$AuthPublicKeyImplCopyWithImpl( + _$AuthPublicKeyImpl _value, $Res Function(_$AuthPublicKeyImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? publicKey = null, + }) { + return _then(_$AuthPublicKeyImpl( + publicKey: null == publicKey + ? _value.publicKey + : publicKey // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$AuthPublicKeyImpl implements _AuthPublicKey { + const _$AuthPublicKeyImpl({required this.publicKey}); + + factory _$AuthPublicKeyImpl.fromJson(Map json) => + _$$AuthPublicKeyImplFromJson(json); + + @override + final String publicKey; + + @override + String toString() { + return 'AuthPublicKey(publicKey: $publicKey)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AuthPublicKeyImpl && + (identical(other.publicKey, publicKey) || + other.publicKey == publicKey)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, publicKey); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => + __$$AuthPublicKeyImplCopyWithImpl<_$AuthPublicKeyImpl>(this, _$identity); + + @override + Map toJson() { + return _$$AuthPublicKeyImplToJson( + this, + ); + } +} + +abstract class _AuthPublicKey implements AuthPublicKey { + const factory _AuthPublicKey({required final String publicKey}) = + _$AuthPublicKeyImpl; + + factory _AuthPublicKey.fromJson(Map json) = + _$AuthPublicKeyImpl.fromJson; + + @override + String get publicKey; + @override + @JsonKey(ignore: true) + _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { + return _CacaoRequestPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoRequestPayload { + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoRequestPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoRequestPayloadCopyWith<$Res> { + factory $CacaoRequestPayloadCopyWith( + CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = + _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> + implements $CacaoRequestPayloadCopyWith<$Res> { + _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> + implements $CacaoRequestPayloadCopyWith<$Res> { + factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, + $Res Function(_$CacaoRequestPayloadImpl) then) = + __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> + extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> + implements _$$CacaoRequestPayloadImplCopyWith<$Res> { + __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, + $Res Function(_$CacaoRequestPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoRequestPayloadImpl( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { + const _$CacaoRequestPayloadImpl( + {required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoRequestPayloadImpl.fromJson(Map json) => + _$$CacaoRequestPayloadImplFromJson(json); + + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoRequestPayloadImpl && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoRequestPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoRequestPayload implements CacaoRequestPayload { + const factory _CacaoRequestPayload( + {required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoRequestPayloadImpl; + + factory _CacaoRequestPayload.fromJson(Map json) = + _$CacaoRequestPayloadImpl.fromJson; + + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoPayload _$CacaoPayloadFromJson(Map json) { + return _CacaoPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoPayload { + String get iss => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoPayloadCopyWith<$Res> { + factory $CacaoPayloadCopyWith( + CacaoPayload value, $Res Function(CacaoPayload) then) = + _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> + implements $CacaoPayloadCopyWith<$Res> { + _$CacaoPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoPayloadImplCopyWith<$Res> + implements $CacaoPayloadCopyWith<$Res> { + factory _$$CacaoPayloadImplCopyWith( + _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = + __$$CacaoPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoPayloadImplCopyWithImpl<$Res> + extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> + implements _$$CacaoPayloadImplCopyWith<$Res> { + __$$CacaoPayloadImplCopyWithImpl( + _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoPayloadImpl( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoPayloadImpl implements _CacaoPayload { + const _$CacaoPayloadImpl( + {required this.iss, + required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoPayloadImpl.fromJson(Map json) => + _$$CacaoPayloadImplFromJson(json); + + @override + final String iss; + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoPayloadImpl && + (identical(other.iss, iss) || other.iss == iss) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + iss, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoPayload implements CacaoPayload { + const factory _CacaoPayload( + {required final String iss, + required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoPayloadImpl; + + factory _CacaoPayload.fromJson(Map json) = + _$CacaoPayloadImpl.fromJson; + + @override + String get iss; + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoHeader _$CacaoHeaderFromJson(Map json) { + return _CacaoHeader.fromJson(json); +} + +/// @nodoc +mixin _$CacaoHeader { + String get t => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoHeaderCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoHeaderCopyWith<$Res> { + factory $CacaoHeaderCopyWith( + CacaoHeader value, $Res Function(CacaoHeader) then) = + _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; + @useResult + $Res call({String t}); +} + +/// @nodoc +class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> + implements $CacaoHeaderCopyWith<$Res> { + _$CacaoHeaderCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoHeaderImplCopyWith<$Res> + implements $CacaoHeaderCopyWith<$Res> { + factory _$$CacaoHeaderImplCopyWith( + _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = + __$$CacaoHeaderImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t}); +} + +/// @nodoc +class __$$CacaoHeaderImplCopyWithImpl<$Res> + extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> + implements _$$CacaoHeaderImplCopyWith<$Res> { + __$$CacaoHeaderImplCopyWithImpl( + _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_$CacaoHeaderImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoHeaderImpl implements _CacaoHeader { + const _$CacaoHeaderImpl({this.t = 'eip4361'}); + + factory _$CacaoHeaderImpl.fromJson(Map json) => + _$$CacaoHeaderImplFromJson(json); + + @override + @JsonKey() + final String t; + + @override + String toString() { + return 'CacaoHeader(t: $t)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoHeaderImpl && + (identical(other.t, t) || other.t == t)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoHeaderImplToJson( + this, + ); + } +} + +abstract class _CacaoHeader implements CacaoHeader { + const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; + + factory _CacaoHeader.fromJson(Map json) = + _$CacaoHeaderImpl.fromJson; + + @override + String get t; + @override + @JsonKey(ignore: true) + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoSignature _$CacaoSignatureFromJson(Map json) { + return _CacaoSignature.fromJson(json); +} + +/// @nodoc +mixin _$CacaoSignature { + String get t => throw _privateConstructorUsedError; + String get s => throw _privateConstructorUsedError; + String? get m => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoSignatureCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoSignatureCopyWith<$Res> { + factory $CacaoSignatureCopyWith( + CacaoSignature value, $Res Function(CacaoSignature) then) = + _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> + implements $CacaoSignatureCopyWith<$Res> { + _$CacaoSignatureCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoSignatureImplCopyWith<$Res> + implements $CacaoSignatureCopyWith<$Res> { + factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, + $Res Function(_$CacaoSignatureImpl) then) = + __$$CacaoSignatureImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class __$$CacaoSignatureImplCopyWithImpl<$Res> + extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> + implements _$$CacaoSignatureImplCopyWith<$Res> { + __$$CacaoSignatureImplCopyWithImpl( + _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_$CacaoSignatureImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoSignatureImpl implements _CacaoSignature { + const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); + + factory _$CacaoSignatureImpl.fromJson(Map json) => + _$$CacaoSignatureImplFromJson(json); + + @override + final String t; + @override + final String s; + @override + final String? m; + + @override + String toString() { + return 'CacaoSignature(t: $t, s: $s, m: $m)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoSignatureImpl && + (identical(other.t, t) || other.t == t) && + (identical(other.s, s) || other.s == s) && + (identical(other.m, m) || other.m == m)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t, s, m); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoSignatureImplToJson( + this, + ); + } +} + +abstract class _CacaoSignature implements CacaoSignature { + const factory _CacaoSignature( + {required final String t, + required final String s, + final String? m}) = _$CacaoSignatureImpl; + + factory _CacaoSignature.fromJson(Map json) = + _$CacaoSignatureImpl.fromJson; + + @override + String get t; + @override + String get s; + @override + String? get m; + @override + @JsonKey(ignore: true) + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Cacao _$CacaoFromJson(Map json) { + return _Cacao.fromJson(json); +} + +/// @nodoc +mixin _$Cacao { + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoCopyWith<$Res> { + factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = + _$CacaoCopyWithImpl<$Res, Cacao>; + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> + implements $CacaoCopyWith<$Res> { + _$CacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { + factory _$$CacaoImplCopyWith( + _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = + __$$CacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$CacaoImplCopyWithImpl<$Res> + extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> + implements _$$CacaoImplCopyWith<$Res> { + __$$CacaoImplCopyWithImpl( + _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$CacaoImpl( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoImpl implements _Cacao { + const _$CacaoImpl({required this.h, required this.p, required this.s}); + + factory _$CacaoImpl.fromJson(Map json) => + _$$CacaoImplFromJson(json); + + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'Cacao(h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoImpl && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoImplToJson( + this, + ); + } +} + +abstract class _Cacao implements Cacao { + const factory _Cacao( + {required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$CacaoImpl; + + factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; + + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} + +StoredCacao _$StoredCacaoFromJson(Map json) { + return _StoredCacao.fromJson(json); +} + +/// @nodoc +mixin _$StoredCacao { + int get id => throw _privateConstructorUsedError; + String get pairingTopic => throw _privateConstructorUsedError; + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $StoredCacaoCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StoredCacaoCopyWith<$Res> { + factory $StoredCacaoCopyWith( + StoredCacao value, $Res Function(StoredCacao) then) = + _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> + implements $StoredCacaoCopyWith<$Res> { + _$StoredCacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$StoredCacaoImplCopyWith<$Res> + implements $StoredCacaoCopyWith<$Res> { + factory _$$StoredCacaoImplCopyWith( + _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = + __$$StoredCacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$StoredCacaoImplCopyWithImpl<$Res> + extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> + implements _$$StoredCacaoImplCopyWith<$Res> { + __$$StoredCacaoImplCopyWithImpl( + _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$StoredCacaoImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$StoredCacaoImpl implements _StoredCacao { + const _$StoredCacaoImpl( + {required this.id, + required this.pairingTopic, + required this.h, + required this.p, + required this.s}); + + factory _$StoredCacaoImpl.fromJson(Map json) => + _$$StoredCacaoImplFromJson(json); + + @override + final int id; + @override + final String pairingTopic; + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StoredCacaoImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.pairingTopic, pairingTopic) || + other.pairingTopic == pairingTopic) && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$StoredCacaoImplToJson( + this, + ); + } +} + +abstract class _StoredCacao implements StoredCacao { + const factory _StoredCacao( + {required final int id, + required final String pairingTopic, + required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$StoredCacaoImpl; + + factory _StoredCacao.fromJson(Map json) = + _$StoredCacaoImpl.fromJson; + + @override + int get id; + @override + String get pairingTopic; + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/auth_common_models.g.dart b/lib/apis/sign_api/models/auth/auth_common_models.g.dart new file mode 100644 index 00000000..cc175fa9 --- /dev/null +++ b/lib/apis/sign_api/models/auth/auth_common_models.g.dart @@ -0,0 +1,164 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'auth_common_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$AuthPublicKeyImpl _$$AuthPublicKeyImplFromJson(Map json) => + _$AuthPublicKeyImpl( + publicKey: json['publicKey'] as String, + ); + +Map _$$AuthPublicKeyImplToJson(_$AuthPublicKeyImpl instance) => + { + 'publicKey': instance.publicKey, + }; + +_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( + Map json) => + _$CacaoRequestPayloadImpl( + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoRequestPayloadImplToJson( + _$CacaoRequestPayloadImpl instance) { + final val = { + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => + _$CacaoPayloadImpl( + iss: json['iss'] as String, + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { + final val = { + 'iss': instance.iss, + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => + _$CacaoHeaderImpl( + t: json['t'] as String? ?? 'eip4361', + ); + +Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => + { + 't': instance.t, + }; + +_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => + _$CacaoSignatureImpl( + t: json['t'] as String, + s: json['s'] as String, + m: json['m'] as String?, + ); + +Map _$$CacaoSignatureImplToJson( + _$CacaoSignatureImpl instance) { + final val = { + 't': instance.t, + 's': instance.s, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('m', instance.m); + return val; +} + +_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$CacaoImplToJson(_$CacaoImpl instance) => + { + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; + +_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => + _$StoredCacaoImpl( + id: json['id'] as int, + pairingTopic: json['pairingTopic'] as String, + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => + { + 'id': instance.id, + 'pairingTopic': instance.pairingTopic, + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; diff --git a/lib/apis/sign_api/models/auth/cacao_models.freezed.dart b/lib/apis/sign_api/models/auth/cacao_models.freezed.dart new file mode 100644 index 00000000..998b2364 --- /dev/null +++ b/lib/apis/sign_api/models/auth/cacao_models.freezed.dart @@ -0,0 +1,1494 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'cacao_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { + return _CacaoRequestPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoRequestPayload { + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoRequestPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoRequestPayloadCopyWith<$Res> { + factory $CacaoRequestPayloadCopyWith( + CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = + _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> + implements $CacaoRequestPayloadCopyWith<$Res> { + _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> + implements $CacaoRequestPayloadCopyWith<$Res> { + factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, + $Res Function(_$CacaoRequestPayloadImpl) then) = + __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> + extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> + implements _$$CacaoRequestPayloadImplCopyWith<$Res> { + __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, + $Res Function(_$CacaoRequestPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoRequestPayloadImpl( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { + const _$CacaoRequestPayloadImpl( + {required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoRequestPayloadImpl.fromJson(Map json) => + _$$CacaoRequestPayloadImplFromJson(json); + + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoRequestPayloadImpl && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoRequestPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoRequestPayload implements CacaoRequestPayload { + const factory _CacaoRequestPayload( + {required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoRequestPayloadImpl; + + factory _CacaoRequestPayload.fromJson(Map json) = + _$CacaoRequestPayloadImpl.fromJson; + + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoPayload _$CacaoPayloadFromJson(Map json) { + return _CacaoPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoPayload { + String get iss => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoPayloadCopyWith<$Res> { + factory $CacaoPayloadCopyWith( + CacaoPayload value, $Res Function(CacaoPayload) then) = + _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> + implements $CacaoPayloadCopyWith<$Res> { + _$CacaoPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoPayloadImplCopyWith<$Res> + implements $CacaoPayloadCopyWith<$Res> { + factory _$$CacaoPayloadImplCopyWith( + _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = + __$$CacaoPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoPayloadImplCopyWithImpl<$Res> + extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> + implements _$$CacaoPayloadImplCopyWith<$Res> { + __$$CacaoPayloadImplCopyWithImpl( + _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoPayloadImpl( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoPayloadImpl implements _CacaoPayload { + const _$CacaoPayloadImpl( + {required this.iss, + required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoPayloadImpl.fromJson(Map json) => + _$$CacaoPayloadImplFromJson(json); + + @override + final String iss; + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoPayloadImpl && + (identical(other.iss, iss) || other.iss == iss) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + iss, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoPayload implements CacaoPayload { + const factory _CacaoPayload( + {required final String iss, + required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoPayloadImpl; + + factory _CacaoPayload.fromJson(Map json) = + _$CacaoPayloadImpl.fromJson; + + @override + String get iss; + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoHeader _$CacaoHeaderFromJson(Map json) { + return _CacaoHeader.fromJson(json); +} + +/// @nodoc +mixin _$CacaoHeader { + String get t => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoHeaderCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoHeaderCopyWith<$Res> { + factory $CacaoHeaderCopyWith( + CacaoHeader value, $Res Function(CacaoHeader) then) = + _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; + @useResult + $Res call({String t}); +} + +/// @nodoc +class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> + implements $CacaoHeaderCopyWith<$Res> { + _$CacaoHeaderCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoHeaderImplCopyWith<$Res> + implements $CacaoHeaderCopyWith<$Res> { + factory _$$CacaoHeaderImplCopyWith( + _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = + __$$CacaoHeaderImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t}); +} + +/// @nodoc +class __$$CacaoHeaderImplCopyWithImpl<$Res> + extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> + implements _$$CacaoHeaderImplCopyWith<$Res> { + __$$CacaoHeaderImplCopyWithImpl( + _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_$CacaoHeaderImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoHeaderImpl implements _CacaoHeader { + const _$CacaoHeaderImpl({this.t = 'eip4361'}); + + factory _$CacaoHeaderImpl.fromJson(Map json) => + _$$CacaoHeaderImplFromJson(json); + + @override + @JsonKey() + final String t; + + @override + String toString() { + return 'CacaoHeader(t: $t)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoHeaderImpl && + (identical(other.t, t) || other.t == t)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoHeaderImplToJson( + this, + ); + } +} + +abstract class _CacaoHeader implements CacaoHeader { + const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; + + factory _CacaoHeader.fromJson(Map json) = + _$CacaoHeaderImpl.fromJson; + + @override + String get t; + @override + @JsonKey(ignore: true) + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoSignature _$CacaoSignatureFromJson(Map json) { + return _CacaoSignature.fromJson(json); +} + +/// @nodoc +mixin _$CacaoSignature { + String get t => throw _privateConstructorUsedError; + String get s => throw _privateConstructorUsedError; + String? get m => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoSignatureCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoSignatureCopyWith<$Res> { + factory $CacaoSignatureCopyWith( + CacaoSignature value, $Res Function(CacaoSignature) then) = + _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> + implements $CacaoSignatureCopyWith<$Res> { + _$CacaoSignatureCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoSignatureImplCopyWith<$Res> + implements $CacaoSignatureCopyWith<$Res> { + factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, + $Res Function(_$CacaoSignatureImpl) then) = + __$$CacaoSignatureImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class __$$CacaoSignatureImplCopyWithImpl<$Res> + extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> + implements _$$CacaoSignatureImplCopyWith<$Res> { + __$$CacaoSignatureImplCopyWithImpl( + _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_$CacaoSignatureImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoSignatureImpl implements _CacaoSignature { + const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); + + factory _$CacaoSignatureImpl.fromJson(Map json) => + _$$CacaoSignatureImplFromJson(json); + + @override + final String t; + @override + final String s; + @override + final String? m; + + @override + String toString() { + return 'CacaoSignature(t: $t, s: $s, m: $m)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoSignatureImpl && + (identical(other.t, t) || other.t == t) && + (identical(other.s, s) || other.s == s) && + (identical(other.m, m) || other.m == m)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t, s, m); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoSignatureImplToJson( + this, + ); + } +} + +abstract class _CacaoSignature implements CacaoSignature { + const factory _CacaoSignature( + {required final String t, + required final String s, + final String? m}) = _$CacaoSignatureImpl; + + factory _CacaoSignature.fromJson(Map json) = + _$CacaoSignatureImpl.fromJson; + + @override + String get t; + @override + String get s; + @override + String? get m; + @override + @JsonKey(ignore: true) + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Cacao _$CacaoFromJson(Map json) { + return _Cacao.fromJson(json); +} + +/// @nodoc +mixin _$Cacao { + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoCopyWith<$Res> { + factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = + _$CacaoCopyWithImpl<$Res, Cacao>; + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> + implements $CacaoCopyWith<$Res> { + _$CacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { + factory _$$CacaoImplCopyWith( + _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = + __$$CacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$CacaoImplCopyWithImpl<$Res> + extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> + implements _$$CacaoImplCopyWith<$Res> { + __$$CacaoImplCopyWithImpl( + _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$CacaoImpl( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoImpl implements _Cacao { + const _$CacaoImpl({required this.h, required this.p, required this.s}); + + factory _$CacaoImpl.fromJson(Map json) => + _$$CacaoImplFromJson(json); + + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'Cacao(h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoImpl && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoImplToJson( + this, + ); + } +} + +abstract class _Cacao implements Cacao { + const factory _Cacao( + {required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$CacaoImpl; + + factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; + + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} + +StoredCacao _$StoredCacaoFromJson(Map json) { + return _StoredCacao.fromJson(json); +} + +/// @nodoc +mixin _$StoredCacao { + int get id => throw _privateConstructorUsedError; + String get pairingTopic => throw _privateConstructorUsedError; + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $StoredCacaoCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StoredCacaoCopyWith<$Res> { + factory $StoredCacaoCopyWith( + StoredCacao value, $Res Function(StoredCacao) then) = + _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> + implements $StoredCacaoCopyWith<$Res> { + _$StoredCacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$StoredCacaoImplCopyWith<$Res> + implements $StoredCacaoCopyWith<$Res> { + factory _$$StoredCacaoImplCopyWith( + _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = + __$$StoredCacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$StoredCacaoImplCopyWithImpl<$Res> + extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> + implements _$$StoredCacaoImplCopyWith<$Res> { + __$$StoredCacaoImplCopyWithImpl( + _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$StoredCacaoImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$StoredCacaoImpl implements _StoredCacao { + const _$StoredCacaoImpl( + {required this.id, + required this.pairingTopic, + required this.h, + required this.p, + required this.s}); + + factory _$StoredCacaoImpl.fromJson(Map json) => + _$$StoredCacaoImplFromJson(json); + + @override + final int id; + @override + final String pairingTopic; + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StoredCacaoImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.pairingTopic, pairingTopic) || + other.pairingTopic == pairingTopic) && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$StoredCacaoImplToJson( + this, + ); + } +} + +abstract class _StoredCacao implements StoredCacao { + const factory _StoredCacao( + {required final int id, + required final String pairingTopic, + required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$StoredCacaoImpl; + + factory _StoredCacao.fromJson(Map json) = + _$StoredCacaoImpl.fromJson; + + @override + int get id; + @override + String get pairingTopic; + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/cacao_models.g.dart b/lib/apis/sign_api/models/auth/cacao_models.g.dart new file mode 100644 index 00000000..0dc187d8 --- /dev/null +++ b/lib/apis/sign_api/models/auth/cacao_models.g.dart @@ -0,0 +1,154 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'cacao_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( + Map json) => + _$CacaoRequestPayloadImpl( + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoRequestPayloadImplToJson( + _$CacaoRequestPayloadImpl instance) { + final val = { + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => + _$CacaoPayloadImpl( + iss: json['iss'] as String, + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { + final val = { + 'iss': instance.iss, + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => + _$CacaoHeaderImpl( + t: json['t'] as String? ?? 'eip4361', + ); + +Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => + { + 't': instance.t, + }; + +_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => + _$CacaoSignatureImpl( + t: json['t'] as String, + s: json['s'] as String, + m: json['m'] as String?, + ); + +Map _$$CacaoSignatureImplToJson( + _$CacaoSignatureImpl instance) { + final val = { + 't': instance.t, + 's': instance.s, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('m', instance.m); + return val; +} + +_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$CacaoImplToJson(_$CacaoImpl instance) => + { + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; + +_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => + _$StoredCacaoImpl( + id: json['id'] as int, + pairingTopic: json['pairingTopic'] as String, + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => + { + 'id': instance.id, + 'pairingTopic': instance.pairingTopic, + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.dart b/lib/apis/sign_api/models/auth/json_rpc_models.dart index 232ac842..06d31233 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.dart @@ -1,6 +1,8 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_models.dart'; part 'json_rpc_models.g.dart'; part 'json_rpc_models.freezed.dart'; @@ -27,3 +29,29 @@ class WcAuthRequestResult with _$WcAuthRequestResult { factory WcAuthRequestResult.fromJson(Map json) => _$WcAuthRequestResultFromJson(json); } + +@freezed +// TODO should be renamed to WcOCARequestParams +class WcOCARequestRequest with _$WcOCARequestRequest { + @JsonSerializable() + const factory WcOCARequestRequest({ + required OCAPayloadParams authPayload, + required ConnectionMetadata requester, + required int expiryTimestamp, + }) = _WcOCARequestRequest; + + factory WcOCARequestRequest.fromJson(Map json) => + _$WcOCARequestRequestFromJson(json); +} + +@freezed +class WcOCARequestResult with _$WcOCARequestResult { + @JsonSerializable() + const factory WcOCARequestResult({ + required List cacaos, + required ConnectionMetadata responder, + }) = _WcOCARequestResult; + + factory WcOCARequestResult.fromJson(Map json) => + _$WcOCARequestResultFromJson(json); +} diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart index c78feec1..6e2eaf2b 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart @@ -351,3 +351,392 @@ abstract class _WcAuthRequestResult implements WcAuthRequestResult { _$$WcAuthRequestResultImplCopyWith<_$WcAuthRequestResultImpl> get copyWith => throw _privateConstructorUsedError; } + +WcOCARequestRequest _$WcOCARequestRequestFromJson(Map json) { + return _WcOCARequestRequest.fromJson(json); +} + +/// @nodoc +mixin _$WcOCARequestRequest { + OCAPayloadParams get authPayload => throw _privateConstructorUsedError; + ConnectionMetadata get requester => throw _privateConstructorUsedError; + int get expiryTimestamp => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcOCARequestRequestCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcOCARequestRequestCopyWith<$Res> { + factory $WcOCARequestRequestCopyWith( + WcOCARequestRequest value, $Res Function(WcOCARequestRequest) then) = + _$WcOCARequestRequestCopyWithImpl<$Res, WcOCARequestRequest>; + @useResult + $Res call( + {OCAPayloadParams authPayload, + ConnectionMetadata requester, + int expiryTimestamp}); + + $OCAPayloadParamsCopyWith<$Res> get authPayload; + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class _$WcOCARequestRequestCopyWithImpl<$Res, $Val extends WcOCARequestRequest> + implements $WcOCARequestRequestCopyWith<$Res> { + _$WcOCARequestRequestCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authPayload = null, + Object? requester = null, + Object? expiryTimestamp = null, + }) { + return _then(_value.copyWith( + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as OCAPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $OCAPayloadParamsCopyWith<$Res> get authPayload { + return $OCAPayloadParamsCopyWith<$Res>(_value.authPayload, (value) { + return _then(_value.copyWith(authPayload: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get requester { + return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { + return _then(_value.copyWith(requester: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcOCARequestRequestImplCopyWith<$Res> + implements $WcOCARequestRequestCopyWith<$Res> { + factory _$$WcOCARequestRequestImplCopyWith(_$WcOCARequestRequestImpl value, + $Res Function(_$WcOCARequestRequestImpl) then) = + __$$WcOCARequestRequestImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {OCAPayloadParams authPayload, + ConnectionMetadata requester, + int expiryTimestamp}); + + @override + $OCAPayloadParamsCopyWith<$Res> get authPayload; + @override + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class __$$WcOCARequestRequestImplCopyWithImpl<$Res> + extends _$WcOCARequestRequestCopyWithImpl<$Res, _$WcOCARequestRequestImpl> + implements _$$WcOCARequestRequestImplCopyWith<$Res> { + __$$WcOCARequestRequestImplCopyWithImpl(_$WcOCARequestRequestImpl _value, + $Res Function(_$WcOCARequestRequestImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authPayload = null, + Object? requester = null, + Object? expiryTimestamp = null, + }) { + return _then(_$WcOCARequestRequestImpl( + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as OCAPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcOCARequestRequestImpl implements _WcOCARequestRequest { + const _$WcOCARequestRequestImpl( + {required this.authPayload, + required this.requester, + required this.expiryTimestamp}); + + factory _$WcOCARequestRequestImpl.fromJson(Map json) => + _$$WcOCARequestRequestImplFromJson(json); + + @override + final OCAPayloadParams authPayload; + @override + final ConnectionMetadata requester; + @override + final int expiryTimestamp; + + @override + String toString() { + return 'WcOCARequestRequest(authPayload: $authPayload, requester: $requester, expiryTimestamp: $expiryTimestamp)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcOCARequestRequestImpl && + (identical(other.authPayload, authPayload) || + other.authPayload == authPayload) && + (identical(other.requester, requester) || + other.requester == requester) && + (identical(other.expiryTimestamp, expiryTimestamp) || + other.expiryTimestamp == expiryTimestamp)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => + Object.hash(runtimeType, authPayload, requester, expiryTimestamp); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcOCARequestRequestImplCopyWith<_$WcOCARequestRequestImpl> get copyWith => + __$$WcOCARequestRequestImplCopyWithImpl<_$WcOCARequestRequestImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$WcOCARequestRequestImplToJson( + this, + ); + } +} + +abstract class _WcOCARequestRequest implements WcOCARequestRequest { + const factory _WcOCARequestRequest( + {required final OCAPayloadParams authPayload, + required final ConnectionMetadata requester, + required final int expiryTimestamp}) = _$WcOCARequestRequestImpl; + + factory _WcOCARequestRequest.fromJson(Map json) = + _$WcOCARequestRequestImpl.fromJson; + + @override + OCAPayloadParams get authPayload; + @override + ConnectionMetadata get requester; + @override + int get expiryTimestamp; + @override + @JsonKey(ignore: true) + _$$WcOCARequestRequestImplCopyWith<_$WcOCARequestRequestImpl> get copyWith => + throw _privateConstructorUsedError; +} + +WcOCARequestResult _$WcOCARequestResultFromJson(Map json) { + return _WcOCARequestResult.fromJson(json); +} + +/// @nodoc +mixin _$WcOCARequestResult { + List get cacaos => throw _privateConstructorUsedError; + ConnectionMetadata get responder => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcOCARequestResultCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcOCARequestResultCopyWith<$Res> { + factory $WcOCARequestResultCopyWith( + WcOCARequestResult value, $Res Function(WcOCARequestResult) then) = + _$WcOCARequestResultCopyWithImpl<$Res, WcOCARequestResult>; + @useResult + $Res call({List cacaos, ConnectionMetadata responder}); + + $ConnectionMetadataCopyWith<$Res> get responder; +} + +/// @nodoc +class _$WcOCARequestResultCopyWithImpl<$Res, $Val extends WcOCARequestResult> + implements $WcOCARequestResultCopyWith<$Res> { + _$WcOCARequestResultCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacaos = null, + Object? responder = null, + }) { + return _then(_value.copyWith( + cacaos: null == cacaos + ? _value.cacaos + : cacaos // ignore: cast_nullable_to_non_nullable + as List, + responder: null == responder + ? _value.responder + : responder // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get responder { + return $ConnectionMetadataCopyWith<$Res>(_value.responder, (value) { + return _then(_value.copyWith(responder: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcOCARequestResultImplCopyWith<$Res> + implements $WcOCARequestResultCopyWith<$Res> { + factory _$$WcOCARequestResultImplCopyWith(_$WcOCARequestResultImpl value, + $Res Function(_$WcOCARequestResultImpl) then) = + __$$WcOCARequestResultImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({List cacaos, ConnectionMetadata responder}); + + @override + $ConnectionMetadataCopyWith<$Res> get responder; +} + +/// @nodoc +class __$$WcOCARequestResultImplCopyWithImpl<$Res> + extends _$WcOCARequestResultCopyWithImpl<$Res, _$WcOCARequestResultImpl> + implements _$$WcOCARequestResultImplCopyWith<$Res> { + __$$WcOCARequestResultImplCopyWithImpl(_$WcOCARequestResultImpl _value, + $Res Function(_$WcOCARequestResultImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacaos = null, + Object? responder = null, + }) { + return _then(_$WcOCARequestResultImpl( + cacaos: null == cacaos + ? _value._cacaos + : cacaos // ignore: cast_nullable_to_non_nullable + as List, + responder: null == responder + ? _value.responder + : responder // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcOCARequestResultImpl implements _WcOCARequestResult { + const _$WcOCARequestResultImpl( + {required final List cacaos, required this.responder}) + : _cacaos = cacaos; + + factory _$WcOCARequestResultImpl.fromJson(Map json) => + _$$WcOCARequestResultImplFromJson(json); + + final List _cacaos; + @override + List get cacaos { + if (_cacaos is EqualUnmodifiableListView) return _cacaos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_cacaos); + } + + @override + final ConnectionMetadata responder; + + @override + String toString() { + return 'WcOCARequestResult(cacaos: $cacaos, responder: $responder)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcOCARequestResultImpl && + const DeepCollectionEquality().equals(other._cacaos, _cacaos) && + (identical(other.responder, responder) || + other.responder == responder)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_cacaos), responder); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcOCARequestResultImplCopyWith<_$WcOCARequestResultImpl> get copyWith => + __$$WcOCARequestResultImplCopyWithImpl<_$WcOCARequestResultImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$WcOCARequestResultImplToJson( + this, + ); + } +} + +abstract class _WcOCARequestResult implements WcOCARequestResult { + const factory _WcOCARequestResult( + {required final List cacaos, + required final ConnectionMetadata responder}) = _$WcOCARequestResultImpl; + + factory _WcOCARequestResult.fromJson(Map json) = + _$WcOCARequestResultImpl.fromJson; + + @override + List get cacaos; + @override + ConnectionMetadata get responder; + @override + @JsonKey(ignore: true) + _$$WcOCARequestResultImplCopyWith<_$WcOCARequestResultImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart index a7bde781..98faebe4 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart @@ -33,3 +33,38 @@ Map _$$WcAuthRequestResultImplToJson( { 'cacao': instance.cacao.toJson(), }; + +_$WcOCARequestRequestImpl _$$WcOCARequestRequestImplFromJson( + Map json) => + _$WcOCARequestRequestImpl( + authPayload: OCAPayloadParams.fromJson( + json['authPayload'] as Map), + requester: ConnectionMetadata.fromJson( + json['requester'] as Map), + expiryTimestamp: json['expiryTimestamp'] as int, + ); + +Map _$$WcOCARequestRequestImplToJson( + _$WcOCARequestRequestImpl instance) => + { + 'authPayload': instance.authPayload.toJson(), + 'requester': instance.requester.toJson(), + 'expiryTimestamp': instance.expiryTimestamp, + }; + +_$WcOCARequestResultImpl _$$WcOCARequestResultImplFromJson( + Map json) => + _$WcOCARequestResultImpl( + cacaos: (json['cacaos'] as List) + .map((e) => Cacao.fromJson(e as Map)) + .toList(), + responder: ConnectionMetadata.fromJson( + json['responder'] as Map), + ); + +Map _$$WcOCARequestResultImplToJson( + _$WcOCARequestResultImpl instance) => + { + 'cacaos': instance.cacaos.map((e) => e.toJson()).toList(), + 'responder': instance.responder.toJson(), + }; diff --git a/lib/apis/sign_api/models/auth/one_click_auth_events.dart b/lib/apis/sign_api/models/auth/one_click_auth_events.dart new file mode 100644 index 00000000..0e5b184c --- /dev/null +++ b/lib/apis/sign_api/models/auth/one_click_auth_events.dart @@ -0,0 +1,43 @@ +import 'dart:convert'; + +import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; + +class OCARequest extends EventArgs { + // TODO to be implemented for wallet usage +} + +class OCAResponse extends EventArgs { + final int id; + final String topic; + final List? auths; + final SessionData? session; + final WalletConnectError? error; + final JsonRpcError? jsonRpcError; + + OCAResponse({ + required this.id, + required this.topic, + this.auths, + this.session, + this.error, + this.jsonRpcError, + }); + + Map toJson() => { + 'id': id, + 'topic': topic, + if (auths != null) 'auths': auths, + if (session != null) 'session': session!.toJson(), + if (error != null) 'error': error!.toJson(), + if (jsonRpcError != null) 'jsonRpcError': jsonRpcError!.toJson(), + }; + + @override + String toString() { + return 'OCAResponse(${jsonEncode(toJson())})'; + } +} diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.dart new file mode 100644 index 00000000..f1adfa10 --- /dev/null +++ b/lib/apis/sign_api/models/auth/one_click_auth_models.dart @@ -0,0 +1,111 @@ +import 'dart:async'; + +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_events.dart'; + +part 'one_click_auth_models.g.dart'; +part 'one_click_auth_models.freezed.dart'; + +class OCARequestResponse { + final int id; + final String pairingTopic; + final Completer completer; + final Uri? uri; + + OCARequestResponse({ + required this.id, + required this.pairingTopic, + required this.completer, + this.uri, + }); +} + +class OCARequestParams { + final List chains; + final String domain; + final String nonce; + final String uri; + // + final CacaoHeader? type; + final String? nbf; + final String? exp; + final String? statement; + final String? requestId; + final List? resources; + final int? expiry; + final List? methods; + // + + OCARequestParams({ + required this.chains, + required this.domain, + required this.nonce, + required this.uri, + this.type, + this.nbf, + this.exp, + this.statement, + this.requestId, + this.resources, + this.expiry, + this.methods = const [], + }); + + Map toJson() => { + 'chains': chains, + 'domain': domain, + 'nonce': nonce, + 'uri': uri, + if (type != null) 'type': type, + if (nbf != null) 'nbf': nbf, + if (exp != null) 'exp': exp, + if (statement != null) 'statement': statement, + if (requestId != null) 'requestId': requestId, + if (resources != null) 'resources': resources, + if (expiry != null) 'expiry': expiry, + }; +} + +@freezed +class OCAPayloadParams with _$OCAPayloadParams { + @JsonSerializable(includeIfNull: false) + const factory OCAPayloadParams({ + required List chains, + required String domain, + required String nonce, + required String aud, + required String type, + // + required String version, + required String iat, + // + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + }) = _OCAPayloadParams; + + factory OCAPayloadParams.fromRequestParams(OCARequestParams params) { + return OCAPayloadParams( + chains: params.chains, + domain: params.domain, + nonce: params.nonce, + aud: params.uri, + type: params.type?.t ?? 'eip4361', + version: '1', + iat: DateTime.now().toIso8601String(), + // + nbf: params.nbf, + exp: params.exp, + statement: params.statement, + requestId: params.requestId, + resources: params.resources, + ); + } + + factory OCAPayloadParams.fromJson(Map json) => + _$OCAPayloadParamsFromJson(json); +} diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart new file mode 100644 index 00000000..93f62b1f --- /dev/null +++ b/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart @@ -0,0 +1,410 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'one_click_auth_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +OCAPayloadParams _$OCAPayloadParamsFromJson(Map json) { + return _OCAPayloadParams.fromJson(json); +} + +/// @nodoc +mixin _$OCAPayloadParams { + List get chains => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; // + String get version => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; // + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $OCAPayloadParamsCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OCAPayloadParamsCopyWith<$Res> { + factory $OCAPayloadParamsCopyWith( + OCAPayloadParams value, $Res Function(OCAPayloadParams) then) = + _$OCAPayloadParamsCopyWithImpl<$Res, OCAPayloadParams>; + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$OCAPayloadParamsCopyWithImpl<$Res, $Val extends OCAPayloadParams> + implements $OCAPayloadParamsCopyWith<$Res> { + _$OCAPayloadParamsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + chains: null == chains + ? _value.chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$OCAPayloadParamsImplCopyWith<$Res> + implements $OCAPayloadParamsCopyWith<$Res> { + factory _$$OCAPayloadParamsImplCopyWith(_$OCAPayloadParamsImpl value, + $Res Function(_$OCAPayloadParamsImpl) then) = + __$$OCAPayloadParamsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$OCAPayloadParamsImplCopyWithImpl<$Res> + extends _$OCAPayloadParamsCopyWithImpl<$Res, _$OCAPayloadParamsImpl> + implements _$$OCAPayloadParamsImplCopyWith<$Res> { + __$$OCAPayloadParamsImplCopyWithImpl(_$OCAPayloadParamsImpl _value, + $Res Function(_$OCAPayloadParamsImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$OCAPayloadParamsImpl( + chains: null == chains + ? _value._chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$OCAPayloadParamsImpl implements _OCAPayloadParams { + const _$OCAPayloadParamsImpl( + {required final List chains, + required this.domain, + required this.nonce, + required this.aud, + required this.type, + required this.version, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _chains = chains, + _resources = resources; + + factory _$OCAPayloadParamsImpl.fromJson(Map json) => + _$$OCAPayloadParamsImplFromJson(json); + + final List _chains; + @override + List get chains { + if (_chains is EqualUnmodifiableListView) return _chains; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_chains); + } + + @override + final String domain; + @override + final String nonce; + @override + final String aud; + @override + final String type; +// + @override + final String version; + @override + final String iat; +// + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'OCAPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$OCAPayloadParamsImpl && + const DeepCollectionEquality().equals(other._chains, _chains) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.type, type) || other.type == type) && + (identical(other.version, version) || other.version == version) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_chains), + domain, + nonce, + aud, + type, + version, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => + __$$OCAPayloadParamsImplCopyWithImpl<_$OCAPayloadParamsImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$OCAPayloadParamsImplToJson( + this, + ); + } +} + +abstract class _OCAPayloadParams implements OCAPayloadParams { + const factory _OCAPayloadParams( + {required final List chains, + required final String domain, + required final String nonce, + required final String aud, + required final String type, + required final String version, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$OCAPayloadParamsImpl; + + factory _OCAPayloadParams.fromJson(Map json) = + _$OCAPayloadParamsImpl.fromJson; + + @override + List get chains; + @override + String get domain; + @override + String get nonce; + @override + String get aud; + @override + String get type; + @override // + String get version; + @override + String get iat; + @override // + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart new file mode 100644 index 00000000..b3b76a9e --- /dev/null +++ b/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'one_click_auth_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$OCAPayloadParamsImpl _$$OCAPayloadParamsImplFromJson( + Map json) => + _$OCAPayloadParamsImpl( + chains: + (json['chains'] as List).map((e) => e as String).toList(), + domain: json['domain'] as String, + nonce: json['nonce'] as String, + aud: json['aud'] as String, + type: json['type'] as String, + version: json['version'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$OCAPayloadParamsImplToJson( + _$OCAPayloadParamsImpl instance) { + final val = { + 'chains': instance.chains, + 'domain': instance.domain, + 'nonce': instance.nonce, + 'aud': instance.aud, + 'type': instance.type, + 'version': instance.version, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index 1f14088b..ef12a9c4 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -504,11 +504,15 @@ class SignClient implements ISignClient { @override Event get onAuthResponse => engine.onAuthResponse; + // NEW 1-CLICK AUTH METHOD + @override + Event get onOCAResponse => engine.onOCAResponse; + @override Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods, + List>? methods = SignEngine.DEFAULT_METHODS_AUTH, }) { try { return engine.requestAuth( @@ -521,6 +525,24 @@ class SignClient implements ISignClient { } } + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + @override + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods, + }) { + try { + return engine.authenticate( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + @override Future respondAuthRequest({ required int id, @@ -546,6 +568,21 @@ class SignClient implements ISignClient { @override IGenericStore get completeRequests => engine.completeRequests; + @override + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }) { + try { + return engine.validateSignedCacao( + cacao: cacao, + projectId: projectId, + ); + } catch (e) { + rethrow; + } + } + @override String formatAuthMessage({ required String iss, diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index bef8c547..23dd7183 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -1,15 +1,15 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:math'; 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/core/verify/models/verify_context.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'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; @@ -18,7 +18,13 @@ class SignEngine implements ISignEngine { [ MethodConstants.WC_SESSION_PROPOSE, MethodConstants.WC_SESSION_REQUEST, - // MethodConstants.WC_AUTH_REQUEST, + ], + ]; + + static const List> DEFAULT_METHODS_AUTH = [ + [ + MethodConstants.WC_AUTH_REQUEST, + MethodConstants.WC_SESSION_AUTHENTICATE, ], ]; @@ -78,8 +84,12 @@ class SignEngine implements ISignEngine { @override late IGenericStore pairingTopics; - // FORMER AUTH ENGINE PROPERTY - List pendingAuthRequests = []; + // NEW 1-CLICK AUTH METHOD + @override + final Event onOCAResponse = Event(); + + // // FORMER AUTH ENGINE PROPERTY + // List pendingAuthRequests = []; SignEngine({ required this.core, @@ -964,6 +974,11 @@ class SignEngine implements ISignEngine { function: _onAuthRequest, type: ProtocolType.auth, ); + core.pairing.register( + method: MethodConstants.WC_SESSION_AUTHENTICATE, + function: _onOCARequest, + type: ProtocolType.auth, + ); } Future _onSessionProposeRequest( @@ -1808,6 +1823,33 @@ class SignEngine implements ISignEngine { } } + @override + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }) async { + final CacaoSignature signature = cacao.s; + final CacaoPayload payload = cacao.p; + + final reconstructed = formatAuthMessage( + iss: payload.iss, + cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), + ); + + final walletAddress = AddressUtils.getDidAddress(payload.iss); + final chainId = AddressUtils.getDidChainId(payload.iss); + + final isValid = await AuthSignature.verifySignature( + walletAddress, + reconstructed, + signature, + chainId, + projectId, + ); + + return isValid; + } + // FORMER AUTH ENGINE PROPERTY // Formats the message that is coming from requestAuth() @override @@ -1877,7 +1919,7 @@ class SignEngine implements ISignEngine { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = DEFAULT_METHODS, + List>? methods = DEFAULT_METHODS_AUTH, }) async { _checkInitialized(); @@ -1900,7 +1942,7 @@ class SignEngine implements ISignEngine { final String responseTopic = core.crypto.getUtils().hashKey(publicKey); final int id = JsonRpcUtils.payloadId(); - WcAuthRequestRequest request = WcAuthRequestRequest( + final request = WcAuthRequestRequest( payloadParams: AuthPayloadParams.fromRequestParams( params, ), @@ -1957,36 +1999,35 @@ class SignEngine implements ISignEngine { required int expiry, required Completer completer, }) async { - Map? resp; + // // Subscribe to the responseTopic because we expect the response to use this topic - // print('got here'); await core.relayClient.subscribe(topic: responseTopic); + late WcAuthRequestResult result; try { - resp = await core.pairing.sendRequest( + final response = await core.pairing.sendRequest( pairingTopic, MethodConstants.WC_AUTH_REQUEST, request.toJson(), id: id, ttl: expiry, ); + result = WcAuthRequestResult.fromJson(response); } on JsonRpcError catch (e) { - final resp = AuthResponse( + final response = AuthResponse( id: id, topic: responseTopic, jsonRpcError: e, ); - onAuthResponse.broadcast(resp); - completer.complete(resp); + onAuthResponse.broadcast(response); + completer.complete(response); return; } await core.pairing.activate(topic: pairingTopic); - final Cacao cacao = Cacao.fromJson(resp!); - final CacaoSignature sig = cacao.s; - final CacaoPayload payload = cacao.p; + final Cacao cacao = result.cacao; await completeRequests.set( id.toString(), StoredCacao.fromCacao( @@ -1996,33 +2037,9 @@ class SignEngine implements ISignEngine { ), ); - final String reconstructed = formatAuthMessage( - iss: payload.iss, - cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), - ); - - final String walletAddress = AddressUtils.getDidAddress(payload.iss); - final String chainId = AddressUtils.getDidChainId(payload.iss); - - if (walletAddress.isEmpty) { - throw Errors.getSdkError( - Errors.MISSING_OR_INVALID, - context: 'authResponse walletAddress is empty', - ); - } - if (chainId.isEmpty) { - throw Errors.getSdkError( - Errors.MISSING_OR_INVALID, - context: 'authResponse chainId is empty', - ); - } - - final bool isValid = await AuthSignature.verifySignature( - walletAddress, - reconstructed, - sig, - chainId, - core.projectId, + final isValid = await validateSignedCacao( + cacao: cacao, + projectId: core.projectId, ); if (!isValid) { @@ -2047,6 +2064,278 @@ class SignEngine implements ISignEngine { } } + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + @override + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods = DEFAULT_METHODS_AUTH, + }) async { + _checkInitialized(); + + AuthApiValidators.isValidAuthenticate(params); + + final chains = params.chains; + final resources = params.resources ?? []; + final requestMethods = params.methods ?? []; + + String? pTopic = pairingTopic; + Uri? connectionUri; + + if (pTopic == null) { + final CreateResponse pairing = await core.pairing.create( + methods: methods, + ); + pTopic = pairing.topic; + connectionUri = pairing.uri; + } else { + // TODO this doesn't look correct + core.pairing.isValidPairingTopic(topic: pTopic); + } + + final publicKey = await core.crypto.generateKeyPair(); + final responseTopic = core.crypto.getUtils().hashKey(publicKey); + + await Future.wait([ + authKeys.set( + AuthConstants.OCAUTH_CLIENT_PUBLIC_KEY_NAME, + AuthPublicKey(publicKey: publicKey), + ), + pairingTopics.set(responseTopic, pTopic), + ]); + + // Subscribe to the responseTopic because we expect the response to use this topic + await core.relayClient.subscribe(topic: responseTopic); + + if (requestMethods.isNotEmpty) { + final namespace = NamespaceUtils.getNamespaceFromChain(chains.first); + String recap = ReCapsUtils.createEncodedRecap( + namespace, + 'request', + requestMethods, + ); + final existingRecap = ReCapsUtils.getRecapFromResources( + resources: resources, + ); + if (existingRecap != null) { + // per Recaps spec, recap must occupy the last position in the resources array + // using .removeLast() to remove the element given we already checked it's a recap and will replace it + recap = ReCapsUtils.mergeEncodedRecaps(recap, resources.removeLast()); + } + resources.add(recap); + } + + // Ensure the expiry is greater than the minimum required for the request - currently 1h + final method = MethodConstants.WC_SESSION_AUTHENTICATE; + final opts = MethodConstants.RPC_OPTS[method]!['req']!; + final authRequestExpiry = max((params.expiry ?? 0), opts.ttl); + final expiryTimestamp = DateTime.now().add( + Duration(seconds: authRequestExpiry), + ); + + final request = WcOCARequestRequest( + authPayload: OCAPayloadParams.fromRequestParams(params).copyWith( + resources: resources, + ), + requester: ConnectionMetadata( + publicKey: publicKey, + metadata: metadata, + ), + expiryTimestamp: expiryTimestamp.millisecondsSinceEpoch, + ); + + // ----- build namespaces for fallback session proposal ----- // TODO + // const namespaces = { + // eip155: { + // chains, + // // request `personal_sign` method by default to allow for fallback siwe + // methods: [...new Set(["personal_sign", ...methods])], + // events: ["chainChanged", "accountsChanged"], + // }, + // }; + + // const proposal = { + // requiredNamespaces: {}, + // optionalNamespaces: namespaces, + // relays: [{ protocol: "irn" }], + // proposer: { + // publicKey, + // metadata: this.client.metadata, + // }, + // expiryTimestamp: calcExpiry(ENGINE_RPC_OPTS.wc_sessionPropose.req.ttl), + // }; + + // Set the one time use receiver public key for decoding the Type 1 envelope + // TODO check this + await core.pairing.setReceiverPublicKey( + topic: responseTopic, + publicKey: publicKey, + expiry: authRequestExpiry, + ); + + final id = JsonRpcUtils.payloadId(); + final fallbackId = JsonRpcUtils.payloadId(); + Completer completer = Completer(); + + _requestOCAResponseHandler( + id: id, + fallbackId: fallbackId, + publicKey: publicKey, + pairingTopic: pTopic, + responseTopic: responseTopic, + requestParams: request, + expiry: authRequestExpiry, + completer: completer, + ); + + return OCARequestResponse( + id: id, + pairingTopic: pTopic, + completer: completer, + uri: connectionUri, + ); + } + + Future _requestOCAResponseHandler({ + required int id, + required int fallbackId, + required String publicKey, + required String pairingTopic, + required String responseTopic, + required WcOCARequestRequest requestParams, + required int expiry, + required Completer completer, + }) async { + // + late WcOCARequestResult result; + try { + final response = await core.pairing.sendRequest( + pairingTopic, + MethodConstants.WC_SESSION_AUTHENTICATE, + requestParams.toJson(), + id: id, + ttl: expiry, + ); + result = WcOCARequestResult.fromJson(response); + } on JsonRpcError catch (error) { + core.relayClient.unsubscribe(topic: responseTopic); + final response = OCAResponse( + id: id, + topic: responseTopic, + jsonRpcError: error, + ); + onOCAResponse.broadcast(response); + completer.complete(response); + return; + } + + await core.pairing.activate(topic: pairingTopic); + + final List cacaos = result.cacaos; + final ConnectionMetadata responder = result.responder; + + final approvedMethods = {}; + final approvedAccounts = {}; + + try { + for (final Cacao cacao in cacaos) { + final isValid = await validateSignedCacao( + cacao: cacao, + projectId: core.projectId, + ); + if (!isValid) { + throw Errors.getSdkError( + Errors.SIGNATURE_VERIFICATION_FAILED, + context: 'Invalid signature', + ); + } + + // TODO CHECK THIS + // await completeRequests.set( + // id.toString(), + // StoredCacao.fromCacao( + // id: id, + // pairingTopic: pairingTopic, + // cacao: cacao, + // ), + // ); + + final CacaoPayload payload = cacao.p; + final chainId = AddressUtils.getDidChainId(payload.iss); + final approvedChains = ['eip155:$chainId']; + + final recap = ReCapsUtils.getRecapFromResources( + resources: payload.resources, + ); + if (recap != null) { + final methodsfromRecap = ReCapsUtils.getMethodsFromRecap(recap); + final chainsFromRecap = ReCapsUtils.getChainsFromRecap(recap); + approvedMethods.addAll(methodsfromRecap); + approvedChains.addAll(chainsFromRecap); + } + + final parsedAddress = AddressUtils.getDidAddress(payload.iss); + for (var chain in approvedChains.toSet()) { + approvedAccounts.add('$chain:$parsedAddress'); + } + } + } on WalletConnectError catch (e) { + final resp = OCAResponse( + id: id, + topic: responseTopic, + error: WalletConnectError( + code: e.code, + message: e.message, + ), + ); + onOCAResponse.broadcast(resp); + completer.complete(resp); + return; + } + + final sessionTopic = await core.crypto.generateSharedKey( + publicKey, + responder.publicKey, + ); + + late SessionData? session; + if (approvedMethods.isNotEmpty) { + session = SessionData( + topic: sessionTopic, + acknowledged: true, + self: ConnectionMetadata( + publicKey: publicKey, + metadata: metadata, + ), + peer: responder, + controller: publicKey, + expiry: WalletConnectUtils.calculateExpiry( + WalletConnectConstants.SEVEN_DAYS, + ), + relay: Relay(WalletConnectConstants.RELAYER_DEFAULT_PROTOCOL), + pairingTopic: pairingTopic, + namespaces: NamespaceUtils.buildNamespacesFromAuth( + accounts: approvedAccounts, + methods: approvedMethods, + ), + ); + + await core.relayClient.subscribe(topic: sessionTopic); + await sessions.set(sessionTopic, session); + + session = sessions.get(sessionTopic); + } + + final resp = OCAResponse( + id: id, + topic: responseTopic, + auths: cacaos, + session: session, + ); + onOCAResponse.broadcast(resp); + completer.complete(resp); + } + // FORMER AUTH ENGINE PROPERTY @override Future respondAuthRequest({ @@ -2156,4 +2445,45 @@ class SignEngine implements ISignEngine { ); } } + + // TODO + void _onOCARequest(String topic, JsonRpcRequest payload) async { + // TODO to be implemented for Wallet usage + // try { + // final request = WcOCARequestRequest.fromJson(payload.params); + + // final CacaoRequestPayload cacaoPayload = + // CacaoRequestPayload.fromPayloadParams( + // request.payloadParams, + // ); + + // authRequests.set( + // payload.id.toString(), + // PendingAuthRequest( + // id: payload.id, + // pairingTopic: topic, + // metadata: request.requester, + // cacaoPayload: cacaoPayload, + // ), + // ); + + // onAuthRequest.broadcast( + // AuthRequest( + // id: payload.id, + // topic: topic, + // requester: request.requester, + // payloadParams: request.payloadParams, + // ), + // ); + // } on WalletConnectError catch (err) { + // await core.pairing.sendError( + // payload.id, + // topic, + // payload.method, + // JsonRpcError.invalidParams( + // err.message, + // ), + // ); + // } + } } diff --git a/lib/apis/sign_api/utils/auth/auth_api_validators.dart b/lib/apis/sign_api/utils/auth/auth_api_validators.dart index 1f951ce1..0c1bda59 100644 --- a/lib/apis/sign_api/utils/auth/auth_api_validators.dart +++ b/lib/apis/sign_api/utils/auth/auth_api_validators.dart @@ -75,4 +75,65 @@ class AuthApiValidators { return true; } + + static bool isValidAuthenticate(OCARequestParams params) { + if (params.chains.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'authenticate() invalid chains: Must not be emtpy.', + ); + } + + if (!NamespaceUtils.isValidUrl(params.uri)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'authenticate() invalid uri: ${params.uri}. Must be a valid url.', + ); + } + + if (!params.uri.contains(params.domain)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'authenticate() invalid domain: ${params.domain}. aud must contain domain.', + ); + } + + if (params.nonce.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'authenticate() nonce must be nonempty.', + ); + } + + if (params.type != null && params.type!.t != CacaoHeader.EIP4361) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'authenticate() type must null or ${CacaoHeader.EIP4361}.', + ); + } + + final uniqueNamespaces = params.chains.map((chain) { + return NamespaceUtils.getNamespaceFromChain(chain); + }).toSet(); + if (uniqueNamespaces.length > 1) { + throw Errors.getInternalError( + Errors.NON_CONFORMING_NAMESPACES, + context: + 'authenticate() Multi-namespace requests are not supported. Please request single namespace only.', + ); + } + + final namespace = NamespaceUtils.getNamespaceFromChain(params.chains.first); + if (namespace != 'eip155') { + throw Errors.getInternalError( + Errors.NON_CONFORMING_NAMESPACES, + context: + 'authenticate() Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.', + ); + } + + return true; + } } diff --git a/lib/apis/sign_api/utils/auth/auth_constants.dart b/lib/apis/sign_api/utils/auth/auth_constants.dart index 9450479c..cdddca3e 100644 --- a/lib/apis/sign_api/utils/auth/auth_constants.dart +++ b/lib/apis/sign_api/utils/auth/auth_constants.dart @@ -6,5 +6,14 @@ class AuthConstants { static const AUTH_DEFAULT_URL = 'https://rpc.walletconnect.com/v1'; + static const AUTH_PROTOCOL = 'wc'; + static const AUTH_VERSION = 1.5; + static const AUTH_CONTEXT = 'auth'; + static const AUTH_STORAGE_PREFIX = + '$AUTH_PROTOCOL@$AUTH_VERSION:$AUTH_CONTEXT:'; + static const AUTH_CLIENT_PUBLIC_KEY_NAME = 'PUB_KEY'; + + static const OCAUTH_CLIENT_PUBLIC_KEY_NAME = + '$AUTH_STORAGE_PREFIX:$AUTH_CLIENT_PUBLIC_KEY_NAME'; } diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index 31d1e8df..eabcccd1 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -5,7 +5,7 @@ import 'package:http/http.dart' as http; import 'package:pointycastle/digests/keccak.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; import 'package:web3dart/crypto.dart' as crypto; diff --git a/lib/apis/sign_api/utils/auth/recaps_utils.dart b/lib/apis/sign_api/utils/auth/recaps_utils.dart new file mode 100644 index 00000000..7fe4bab2 --- /dev/null +++ b/lib/apis/sign_api/utils/auth/recaps_utils.dart @@ -0,0 +1,223 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; + +class ReCapsUtils { + static String? getRecapFromResources({List? resources}) { + final resourcesList = resources ?? []; + if (resourcesList.isEmpty) return null; + // per spec, recap is always the last resource + final recap = resourcesList.last; + return isRecap(recap) ? recap : null; + } + + static bool isRecap(String resource) { + return resource.contains('urn:recap:'); + } + + static List getMethodsFromRecap(String recap) { + final decodedRecap = decodeRecap(recap); + if (!isValidRecap(decodedRecap)) return []; + + try { + // methods are only available for eip155 as per the current implementation + final resource = decodedRecap['att']?['eip155'] as Map?; + if (resource == null) return []; + + return resource.keys.map((k) => k.split('/').last).toList(); + } catch (e) { + return []; + } + } + + static List getChainsFromRecap(String recap) { + final decodedRecap = decodeRecap(recap); + if (!isValidRecap(decodedRecap)) return []; + + final List recapChains = []; + try { + final att = + decodedRecap['att'] as Map? ?? {}; + + for (var resources in att.values) { + final resourcesMap = resources as Map; + final resourcesValues = resourcesMap.values.first as List; + for (var value in resourcesValues) { + final chainValues = value as Map; + final chains = chainValues['chains'] as List; + recapChains.addAll(chains); + } + } + return recapChains.map((e) => e.toString()).toSet().toList(); + } catch (e) { + return []; + } + } + + static Map decodeRecap(String recap) { + // Add the padding that was removed during encoding + String paddedRecap = recap.replaceAll('urn:recap:', ''); + final padding = paddedRecap.length % 4; + if (padding > 0) { + paddedRecap += '=' * (4 - padding); + } + + final decoded = utf8.decode(base64.decode(paddedRecap)); + final decodedRecap = jsonDecode(decoded) as Map; + isValidRecap(decodedRecap); + return decodedRecap; + } + + static bool isValidRecap(Map recap) { + final att = recap['att'] as Map?; + if (att == null) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. No `att` property found', + ); + } + // + final resources = att.keys; + if (resources.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. No resources found in `att` property', + ); + } + // + for (var resource in resources) { + final abilities = att[resource]; + if (abilities is! Map) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. Resource must be an object: $resource', + ); + } + final resourceAbilities = (abilities as Map).keys; + if (resourceAbilities.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. Resource object is empty: $resource', + ); + } + // + for (var ability in resourceAbilities) { + final limits = abilities[ability]; + debugPrint('limits $limits'); + if (limits is! List) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. Ability limits $ability must be an array ' + 'of objects, found: $limits', + ); + } + if ((limits).isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: 'Invalid ReCap. Value of $ability is empty array, must be ' + 'an array with objects', + ); + } + // + for (var limit in limits) { + if (limit is! Map) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'Invalid ReCap. Ability limits ($ability) must be an array ' + 'of objects, found: $limit', + ); + } + } + } + } + + return true; + } + + static String createEncodedRecap( + String namespace, + String ability, + List methods, + ) { + final recap = createRecap(namespace, ability, methods); + return encodeRecap(recap); + } + + static String encodeRecap(Map recap) { + isValidRecap(recap); + final jsonRecap = jsonEncode(recap); + final bytes = utf8.encode(jsonRecap).toList(); + // remove the padding from the base64 string as per recap spec + return 'urn:recap:${base64.encode(bytes).replaceAll('/=/g', '')}'; + } + + static Map createRecap( + String namespace, + String ability, + List methods, { + Map limits = const {}, + }) { + try { + final sortedMethods = List.from(methods) + ..sort((a, b) => a.compareTo(b)); + + Map abilities = {}; + for (var method in sortedMethods) { + abilities['$ability/$method'] = [ + ...(abilities['$ability/$method'] ?? []), + limits, + ]; + } + + return { + 'att': { + namespace: Map.fromEntries(abilities.entries), + } + }; + } catch (e) { + rethrow; + } + } + + static String mergeEncodedRecaps(String recap1, String recap2) { + final decoded1 = decodeRecap(recap1); + final decoded2 = decodeRecap(recap2); + final merged = mergeRecaps(decoded1, decoded2); + return encodeRecap(merged); + } + + static Map mergeRecaps( + Map recap1, + Map recap2, + ) { + isValidRecap(recap1); + isValidRecap(recap2); + final att1 = recap1['att'] as Map; + final att2 = recap2['att'] as Map; + final keys = [...att1.keys, ...att2.keys]..sort( + (a, b) => a.compareTo(b), + ); + final mergedRecap = {'att': {}}; + + for (var key in keys) { + final actions1 = att1[key] as Map? ?? {}; + final actions1Keys = actions1.keys; + final actions2 = att2[key] as Map? ?? {}; + final actions2Keys = actions2.keys; + final actions = [...actions1Keys, ...actions2Keys]..sort( + (a, b) => a.compareTo(b), + ); + + for (var action in actions) { + mergedRecap['att']![key] = { + ...mergedRecap['att']?[key], + [action]: recap1['att'][key]?[action] || recap2['att'][key]?[action], + }; + } + } + + return mergedRecap; + } +} diff --git a/lib/apis/utils/method_constants.dart b/lib/apis/utils/method_constants.dart index 01b3e80c..71dfc851 100644 --- a/lib/apis/utils/method_constants.dart +++ b/lib/apis/utils/method_constants.dart @@ -14,10 +14,11 @@ class MethodConstants { static const WC_SESSION_EVENT = 'wc_sessionEvent'; static const WC_SESSION_DELETE = 'wc_sessionDelete'; static const WC_SESSION_PING = 'wc_sessionPing'; - // static const WC_SESSION_AUTHENTICATE = 'wc_sessionAuthenticate'; TODO static const WC_AUTH_REQUEST = 'wc_authRequest'; + static const WC_SESSION_AUTHENTICATE = 'wc_sessionAuthenticate'; + static const Map> RPC_OPTS = { WC_PAIRING_PING: { 'req': RpcOptions( @@ -151,18 +152,28 @@ class MethodConstants { tag: 1115, ), }, - // WC_SESSION_AUTHENTICATE: { TODO - // 'req': RpcOptions( - // ttl: WalletConnectConstants.ONE_HOUR, - // prompt: false, - // tag: 1116, - // ), - // 'res': RpcOptions( - // ttl: WalletConnectConstants.ONE_HOUR, - // prompt: false, - // tag: 1117, - // ), - // }, + WC_SESSION_AUTHENTICATE: { + 'req': RpcOptions( + ttl: WalletConnectConstants.ONE_HOUR, + prompt: false, + tag: 1116, + ), + 'res': RpcOptions( + ttl: WalletConnectConstants.ONE_HOUR, + prompt: false, + tag: 1117, + ), + 'reject': RpcOptions( + ttl: WalletConnectConstants.FIVE_MINUTES, + prompt: false, + tag: 1118, + ), + 'autoReject': RpcOptions( + ttl: WalletConnectConstants.FIVE_MINUTES, + prompt: false, + tag: 1119, + ), + }, WC_AUTH_REQUEST: { 'req': RpcOptions( ttl: WalletConnectConstants.ONE_DAY, diff --git a/lib/apis/utils/namespace_utils.dart b/lib/apis/utils/namespace_utils.dart index 243cdb29..e1ad9c7f 100644 --- a/lib/apis/utils/namespace_utils.dart +++ b/lib/apis/utils/namespace_utils.dart @@ -1,5 +1,6 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; class NamespaceUtils { /// Checks if the string is a chain @@ -75,18 +76,34 @@ class NamespaceUtils { /// Gets all unique namespaces from the provided list of accounts /// This function assumes that all accounts are valid - // static List getNamespacesFromAccounts(List accounts) { - // Set namespaces = {}; - // accounts.forEach((account) { - // chains.add( - // getChainFromAccount( - // account, - // ), - // ); - // }); - - // return chains.toList(); - // } + static Map getNamespacesFromAccounts( + List accounts, + ) { + Map namespaces = {}; + for (var account in accounts) { + final ns = account.split(':')[0]; + final cid = account.split(':')[1]; + if (namespaces[ns] == null) { + namespaces[ns] = Namespace( + accounts: [], + methods: [], + events: [], + ); + } + namespaces[ns] = namespaces[ns]!.copyWith( + accounts: [ + ...namespaces[ns]!.accounts, + account, + ], + chains: [ + ...(namespaces[ns]?.chains ?? []), + '$ns:$cid', + ], + ); + } + + return namespaces; + } /// Gets the chains from the namespace. /// If the namespace is a chain, then it returns the chain. @@ -271,6 +288,29 @@ class NamespaceUtils { }; } + static Map buildNamespacesFromAuth({ + required Set methods, + required Set accounts, + }) { + final parsedAccounts = accounts.map( + (account) => account.replaceAll('did:pkh:', ''), + ); + + final namespaces = getNamespacesFromAccounts(parsedAccounts.toList()); + + final entries = namespaces.entries.map((e) { + return MapEntry( + e.key, + Namespace.fromJson(e.value.toJson()).copyWith( + methods: methods.toList(), + events: EventsConstants.allEvents, + ), + ); + }); + + return Map.fromEntries(entries); + } + /// Gets the matching items from the available items using the chainId /// This function assumes that each element in the available items is in the format of chainId:itemId static Set _getMatching({ diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index ce33d15b..418ffb17 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -13,6 +13,7 @@ class Web3App implements IWeb3App { ], [ MethodConstants.WC_AUTH_REQUEST, + MethodConstants.WC_SESSION_AUTHENTICATE, ] ]; @@ -330,6 +331,10 @@ class Web3App implements IWeb3App { @override Event get onAuthResponse => signEngine.onAuthResponse; + // NEW 1-CLICK AUTH METHOD + @override + Event get onOCAResponse => signEngine.onOCAResponse; + @override IGenericStore get authKeys => signEngine.authKeys; @override @@ -355,6 +360,24 @@ class Web3App implements IWeb3App { } } + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + @override + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods = DEFAULT_METHODS, + }) async { + try { + return signEngine.authenticate( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + @override Map getCompletedRequestsForPairing({ required String pairingTopic, @@ -368,6 +391,21 @@ class Web3App implements IWeb3App { } } + @override + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }) { + try { + return signEngine.validateSignedCacao( + cacao: cacao, + projectId: projectId, + ); + } catch (e) { + rethrow; + } + } + @override String formatAuthMessage({ required String iss, diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index dd5825f6..ca3e516f 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -433,6 +433,21 @@ class Web3Wallet implements IWeb3Wallet { } } + @override + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }) { + try { + return signEngine.validateSignedCacao( + cacao: cacao, + projectId: projectId, + ); + } catch (e) { + rethrow; + } + } + /// format payload to message string before signing @override String formatAuthMessage({ diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 6f207761..73fcbeec 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -9,6 +9,7 @@ export 'apis/core/relay_client/relay_client_models.dart'; export 'apis/core/pairing/i_pairing_store.dart'; export 'apis/core/pairing/utils/pairing_models.dart'; export 'apis/core/store/store_models.dart'; +export 'apis/core/verify/models/verify_context.dart'; export 'apis/models/basic_models.dart'; export 'apis/utils/errors.dart'; export 'apis/utils/walletconnect_utils.dart'; @@ -34,9 +35,12 @@ export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; // Auth API -export 'apis/sign_api/models/auth/auth_client_models.dart'; export 'apis/sign_api/models/auth/auth_client_events.dart'; +export 'apis/sign_api/models/auth/auth_client_models.dart'; +export 'apis/sign_api/models/auth/auth_common_models.dart'; export 'apis/sign_api/models/auth/json_rpc_models.dart'; +export 'apis/sign_api/models/auth/one_click_auth_events.dart'; +export 'apis/sign_api/models/auth/one_click_auth_models.dart'; export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index 699a1170..0b09b4c7 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; import '../../shared/shared_test_values.dart'; diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index 576534c5..f67924e7 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -439,6 +439,21 @@ class SignClientTestWrapper implements ISignEngine { @override IGenericStore get completeRequests => client.completeRequests; + @override + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }) { + try { + return client.validateSignedCacao( + cacao: cacao, + projectId: projectId, + ); + } catch (e) { + rethrow; + } + } + @override String formatAuthMessage({ required String iss, @@ -482,6 +497,9 @@ class SignClientTestWrapper implements ISignEngine { @override Event get onAuthResponse => client.onAuthResponse; + @override + Event get onOCAResponse => client.onOCAResponse; + @override IGenericStore get pairingTopics => client.pairingTopics; @@ -502,6 +520,24 @@ class SignClientTestWrapper implements ISignEngine { } } + // NEW ONE-CLICK AUTH METHOD FOR DAPPS + @override + Future authenticate({ + required OCARequestParams params, + String? pairingTopic, + List>? methods, + }) async { + try { + return await client.authenticate( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + @override Future respondAuthRequest({ required int id, From 8f9772fe85021d13129e0d28fb3e8acfe81eea1b Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 4 Jun 2024 19:39:41 +0200 Subject: [PATCH 09/29] fixed tests --- lib/apis/sign_api/sign_engine.dart | 8 +++----- test/sign_api/tests/sign_connect.dart | 6 +++++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 23dd7183..08c4b5a8 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -1999,21 +1999,19 @@ class SignEngine implements ISignEngine { required int expiry, required Completer completer, }) async { - // - // Subscribe to the responseTopic because we expect the response to use this topic await core.relayClient.subscribe(topic: responseTopic); late WcAuthRequestResult result; try { - final response = await core.pairing.sendRequest( + final Map response = await core.pairing.sendRequest( pairingTopic, MethodConstants.WC_AUTH_REQUEST, request.toJson(), id: id, ttl: expiry, ); - result = WcAuthRequestResult.fromJson(response); + result = WcAuthRequestResult.fromJson({'cacao': response}); } on JsonRpcError catch (e) { final response = AuthResponse( id: id, @@ -2209,7 +2207,7 @@ class SignEngine implements ISignEngine { // late WcOCARequestResult result; try { - final response = await core.pairing.sendRequest( + final Map response = await core.pairing.sendRequest( pairingTopic, MethodConstants.WC_SESSION_AUTHENTICATE, requestParams.toJson(), diff --git a/test/sign_api/tests/sign_connect.dart b/test/sign_api/tests/sign_connect.dart index 8898a88d..49860fe4 100644 --- a/test/sign_api/tests/sign_connect.dart +++ b/test/sign_api/tests/sign_connect.dart @@ -47,10 +47,14 @@ void signConnect({ expect(parsed.topic, response.pairingTopic); expect(parsed.v2Data!.relay.protocol, 'irn'); if (clientA is IWeb3App) { - expect(parsed.v2Data!.methods.length, 3); + expect(parsed.v2Data!.methods.length, 4); expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); + expect( + parsed.v2Data!.methods[3], + MethodConstants.WC_SESSION_AUTHENTICATE, + ); } else { expect(parsed.v2Data!.methods.length, 2); expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); From d5aa1f6c80d58c9c82efed43dec141f2057d25c9 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Thu, 6 Jun 2024 18:56:34 +0200 Subject: [PATCH 10/29] minor changes --- example/dapp/lib/pages/connect_page.dart | 19 ++--- .../sign_api/models/auth/json_rpc_models.dart | 11 ++- .../models/auth/json_rpc_models.freezed.dart | 74 +++++++++---------- .../models/auth/json_rpc_models.g.dart | 8 +- lib/apis/sign_api/sign_client.dart | 8 +- lib/apis/sign_api/sign_engine.dart | 50 ++++++++----- .../sign_api/utils/auth/recaps_utils.dart | 2 - 7 files changed, 89 insertions(+), 83 deletions(-) diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 5bd70f38..0834b42a 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -459,19 +459,9 @@ class ConnectPageState extends State { methods: methods, ), ); - // Legacy Auth Request - // final authResponse = await widget.web3App.requestAuth( - // params: AuthRequestParams( - // chainId: 'eip155:1', - // domain: Constants.domain, - // nonce: AuthUtils.generateNonce(), - // aud: Constants.aud, - // statement: 'Welcome to example flutter app', - // ), - // ); final encodedUri = Uri.encodeComponent(authResponse.uri.toString()); - final uri = 'walletapp://wc?uri=$encodedUri'; + final uri = 'wcflutterwallet://wc?uri=$encodedUri'; if (await canLaunchUrlString(uri)) { final openApp = await showDialog( @@ -505,7 +495,12 @@ class ConnectPageState extends State { final response = await authResponse.completer.future; debugPrint('[SampleDapp] session ${jsonEncode(response.toJson())}'); - showToast?.call(StringConstants.connectionEstablished); + if (response.session != null) { + showToast?.call(StringConstants.connectionEstablished); + } else { + final error = response.error ?? response.jsonRpcError; + showToast?.call(error.toString()); + } closeModal?.call(); } diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.dart b/lib/apis/sign_api/models/auth/json_rpc_models.dart index 06d31233..c0459c2c 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.dart @@ -31,17 +31,16 @@ class WcAuthRequestResult with _$WcAuthRequestResult { } @freezed -// TODO should be renamed to WcOCARequestParams -class WcOCARequestRequest with _$WcOCARequestRequest { +class WcOCARequestParams with _$WcOCARequestParams { @JsonSerializable() - const factory WcOCARequestRequest({ + const factory WcOCARequestParams({ required OCAPayloadParams authPayload, required ConnectionMetadata requester, required int expiryTimestamp, - }) = _WcOCARequestRequest; + }) = _WcOCARequestParams; - factory WcOCARequestRequest.fromJson(Map json) => - _$WcOCARequestRequestFromJson(json); + factory WcOCARequestParams.fromJson(Map json) => + _$WcOCARequestParamsFromJson(json); } @freezed diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart index 6e2eaf2b..62eb4727 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart @@ -352,27 +352,27 @@ abstract class _WcAuthRequestResult implements WcAuthRequestResult { throw _privateConstructorUsedError; } -WcOCARequestRequest _$WcOCARequestRequestFromJson(Map json) { - return _WcOCARequestRequest.fromJson(json); +WcOCARequestParams _$WcOCARequestParamsFromJson(Map json) { + return _WcOCARequestParams.fromJson(json); } /// @nodoc -mixin _$WcOCARequestRequest { +mixin _$WcOCARequestParams { OCAPayloadParams get authPayload => throw _privateConstructorUsedError; ConnectionMetadata get requester => throw _privateConstructorUsedError; int get expiryTimestamp => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $WcOCARequestRequestCopyWith get copyWith => + $WcOCARequestParamsCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class $WcOCARequestRequestCopyWith<$Res> { - factory $WcOCARequestRequestCopyWith( - WcOCARequestRequest value, $Res Function(WcOCARequestRequest) then) = - _$WcOCARequestRequestCopyWithImpl<$Res, WcOCARequestRequest>; +abstract class $WcOCARequestParamsCopyWith<$Res> { + factory $WcOCARequestParamsCopyWith( + WcOCARequestParams value, $Res Function(WcOCARequestParams) then) = + _$WcOCARequestParamsCopyWithImpl<$Res, WcOCARequestParams>; @useResult $Res call( {OCAPayloadParams authPayload, @@ -384,9 +384,9 @@ abstract class $WcOCARequestRequestCopyWith<$Res> { } /// @nodoc -class _$WcOCARequestRequestCopyWithImpl<$Res, $Val extends WcOCARequestRequest> - implements $WcOCARequestRequestCopyWith<$Res> { - _$WcOCARequestRequestCopyWithImpl(this._value, this._then); +class _$WcOCARequestParamsCopyWithImpl<$Res, $Val extends WcOCARequestParams> + implements $WcOCARequestParamsCopyWith<$Res> { + _$WcOCARequestParamsCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; @@ -434,11 +434,11 @@ class _$WcOCARequestRequestCopyWithImpl<$Res, $Val extends WcOCARequestRequest> } /// @nodoc -abstract class _$$WcOCARequestRequestImplCopyWith<$Res> - implements $WcOCARequestRequestCopyWith<$Res> { - factory _$$WcOCARequestRequestImplCopyWith(_$WcOCARequestRequestImpl value, - $Res Function(_$WcOCARequestRequestImpl) then) = - __$$WcOCARequestRequestImplCopyWithImpl<$Res>; +abstract class _$$WcOCARequestParamsImplCopyWith<$Res> + implements $WcOCARequestParamsCopyWith<$Res> { + factory _$$WcOCARequestParamsImplCopyWith(_$WcOCARequestParamsImpl value, + $Res Function(_$WcOCARequestParamsImpl) then) = + __$$WcOCARequestParamsImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -453,11 +453,11 @@ abstract class _$$WcOCARequestRequestImplCopyWith<$Res> } /// @nodoc -class __$$WcOCARequestRequestImplCopyWithImpl<$Res> - extends _$WcOCARequestRequestCopyWithImpl<$Res, _$WcOCARequestRequestImpl> - implements _$$WcOCARequestRequestImplCopyWith<$Res> { - __$$WcOCARequestRequestImplCopyWithImpl(_$WcOCARequestRequestImpl _value, - $Res Function(_$WcOCARequestRequestImpl) _then) +class __$$WcOCARequestParamsImplCopyWithImpl<$Res> + extends _$WcOCARequestParamsCopyWithImpl<$Res, _$WcOCARequestParamsImpl> + implements _$$WcOCARequestParamsImplCopyWith<$Res> { + __$$WcOCARequestParamsImplCopyWithImpl(_$WcOCARequestParamsImpl _value, + $Res Function(_$WcOCARequestParamsImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -467,7 +467,7 @@ class __$$WcOCARequestRequestImplCopyWithImpl<$Res> Object? requester = null, Object? expiryTimestamp = null, }) { - return _then(_$WcOCARequestRequestImpl( + return _then(_$WcOCARequestParamsImpl( authPayload: null == authPayload ? _value.authPayload : authPayload // ignore: cast_nullable_to_non_nullable @@ -487,14 +487,14 @@ class __$$WcOCARequestRequestImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() -class _$WcOCARequestRequestImpl implements _WcOCARequestRequest { - const _$WcOCARequestRequestImpl( +class _$WcOCARequestParamsImpl implements _WcOCARequestParams { + const _$WcOCARequestParamsImpl( {required this.authPayload, required this.requester, required this.expiryTimestamp}); - factory _$WcOCARequestRequestImpl.fromJson(Map json) => - _$$WcOCARequestRequestImplFromJson(json); + factory _$WcOCARequestParamsImpl.fromJson(Map json) => + _$$WcOCARequestParamsImplFromJson(json); @override final OCAPayloadParams authPayload; @@ -505,14 +505,14 @@ class _$WcOCARequestRequestImpl implements _WcOCARequestRequest { @override String toString() { - return 'WcOCARequestRequest(authPayload: $authPayload, requester: $requester, expiryTimestamp: $expiryTimestamp)'; + return 'WcOCARequestParams(authPayload: $authPayload, requester: $requester, expiryTimestamp: $expiryTimestamp)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$WcOCARequestRequestImpl && + other is _$WcOCARequestParamsImpl && (identical(other.authPayload, authPayload) || other.authPayload == authPayload) && (identical(other.requester, requester) || @@ -529,26 +529,26 @@ class _$WcOCARequestRequestImpl implements _WcOCARequestRequest { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$WcOCARequestRequestImplCopyWith<_$WcOCARequestRequestImpl> get copyWith => - __$$WcOCARequestRequestImplCopyWithImpl<_$WcOCARequestRequestImpl>( + _$$WcOCARequestParamsImplCopyWith<_$WcOCARequestParamsImpl> get copyWith => + __$$WcOCARequestParamsImplCopyWithImpl<_$WcOCARequestParamsImpl>( this, _$identity); @override Map toJson() { - return _$$WcOCARequestRequestImplToJson( + return _$$WcOCARequestParamsImplToJson( this, ); } } -abstract class _WcOCARequestRequest implements WcOCARequestRequest { - const factory _WcOCARequestRequest( +abstract class _WcOCARequestParams implements WcOCARequestParams { + const factory _WcOCARequestParams( {required final OCAPayloadParams authPayload, required final ConnectionMetadata requester, - required final int expiryTimestamp}) = _$WcOCARequestRequestImpl; + required final int expiryTimestamp}) = _$WcOCARequestParamsImpl; - factory _WcOCARequestRequest.fromJson(Map json) = - _$WcOCARequestRequestImpl.fromJson; + factory _WcOCARequestParams.fromJson(Map json) = + _$WcOCARequestParamsImpl.fromJson; @override OCAPayloadParams get authPayload; @@ -558,7 +558,7 @@ abstract class _WcOCARequestRequest implements WcOCARequestRequest { int get expiryTimestamp; @override @JsonKey(ignore: true) - _$$WcOCARequestRequestImplCopyWith<_$WcOCARequestRequestImpl> get copyWith => + _$$WcOCARequestParamsImplCopyWith<_$WcOCARequestParamsImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart index 98faebe4..09e95e45 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart @@ -34,9 +34,9 @@ Map _$$WcAuthRequestResultImplToJson( 'cacao': instance.cacao.toJson(), }; -_$WcOCARequestRequestImpl _$$WcOCARequestRequestImplFromJson( +_$WcOCARequestParamsImpl _$$WcOCARequestParamsImplFromJson( Map json) => - _$WcOCARequestRequestImpl( + _$WcOCARequestParamsImpl( authPayload: OCAPayloadParams.fromJson( json['authPayload'] as Map), requester: ConnectionMetadata.fromJson( @@ -44,8 +44,8 @@ _$WcOCARequestRequestImpl _$$WcOCARequestRequestImplFromJson( expiryTimestamp: json['expiryTimestamp'] as int, ); -Map _$$WcOCARequestRequestImplToJson( - _$WcOCARequestRequestImpl instance) => +Map _$$WcOCARequestParamsImplToJson( + _$WcOCARequestParamsImpl instance) => { 'authPayload': instance.authPayload.toJson(), 'requester': instance.requester.toJson(), diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index ef12a9c4..a54a22b2 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -512,7 +512,9 @@ class SignClient implements ISignClient { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = SignEngine.DEFAULT_METHODS_AUTH, + List>? methods = const [ + [MethodConstants.WC_AUTH_REQUEST], + ], }) { try { return engine.requestAuth( @@ -530,7 +532,9 @@ class SignClient implements ISignClient { Future authenticate({ required OCARequestParams params, String? pairingTopic, - List>? methods, + List>? methods = const [ + [MethodConstants.WC_SESSION_AUTHENTICATE], + ], }) { try { return engine.authenticate( diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 08c4b5a8..07ab771c 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -21,13 +21,6 @@ class SignEngine implements ISignEngine { ], ]; - static const List> DEFAULT_METHODS_AUTH = [ - [ - MethodConstants.WC_AUTH_REQUEST, - MethodConstants.WC_SESSION_AUTHENTICATE, - ], - ]; - bool _initialized = false; @override @@ -974,11 +967,12 @@ class SignEngine implements ISignEngine { function: _onAuthRequest, type: ProtocolType.auth, ); - core.pairing.register( - method: MethodConstants.WC_SESSION_AUTHENTICATE, - function: _onOCARequest, - type: ProtocolType.auth, - ); + // TODO on following PR to be used by Wallet + // core.pairing.register( + // method: MethodConstants.WC_SESSION_AUTHENTICATE, + // function: _onOCARequest, + // type: ProtocolType.auth, + // ); } Future _onSessionProposeRequest( @@ -1919,7 +1913,9 @@ class SignEngine implements ISignEngine { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = DEFAULT_METHODS_AUTH, + List>? methods = const [ + [MethodConstants.WC_AUTH_REQUEST], + ], }) async { _checkInitialized(); @@ -2012,11 +2008,17 @@ class SignEngine implements ISignEngine { ttl: expiry, ); result = WcAuthRequestResult.fromJson({'cacao': response}); - } on JsonRpcError catch (e) { + } catch (error) { final response = AuthResponse( id: id, topic: responseTopic, - jsonRpcError: e, + jsonRpcError: (error is JsonRpcError) ? error : null, + error: (error is! JsonRpcError) + ? WalletConnectError( + code: -1, + message: error.toString(), + ) + : null, ); onAuthResponse.broadcast(response); completer.complete(response); @@ -2067,7 +2069,9 @@ class SignEngine implements ISignEngine { Future authenticate({ required OCARequestParams params, String? pairingTopic, - List>? methods = DEFAULT_METHODS_AUTH, + List>? methods = const [ + [MethodConstants.WC_SESSION_AUTHENTICATE], + ], }) async { _checkInitialized(); @@ -2131,7 +2135,7 @@ class SignEngine implements ISignEngine { Duration(seconds: authRequestExpiry), ); - final request = WcOCARequestRequest( + final request = WcOCARequestParams( authPayload: OCAPayloadParams.fromRequestParams(params).copyWith( resources: resources, ), @@ -2200,7 +2204,7 @@ class SignEngine implements ISignEngine { required String publicKey, required String pairingTopic, required String responseTopic, - required WcOCARequestRequest requestParams, + required WcOCARequestParams requestParams, required int expiry, required Completer completer, }) async { @@ -2215,12 +2219,18 @@ class SignEngine implements ISignEngine { ttl: expiry, ); result = WcOCARequestResult.fromJson(response); - } on JsonRpcError catch (error) { + } catch (error) { core.relayClient.unsubscribe(topic: responseTopic); final response = OCAResponse( id: id, topic: responseTopic, - jsonRpcError: error, + jsonRpcError: (error is JsonRpcError) ? error : null, + error: (error is! JsonRpcError) + ? WalletConnectError( + code: -1, + message: error.toString(), + ) + : null, ); onOCAResponse.broadcast(response); completer.complete(response); diff --git a/lib/apis/sign_api/utils/auth/recaps_utils.dart b/lib/apis/sign_api/utils/auth/recaps_utils.dart index 7fe4bab2..bafc96d2 100644 --- a/lib/apis/sign_api/utils/auth/recaps_utils.dart +++ b/lib/apis/sign_api/utils/auth/recaps_utils.dart @@ -1,6 +1,5 @@ import 'dart:convert'; -import 'package:flutter/foundation.dart'; import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; class ReCapsUtils { @@ -104,7 +103,6 @@ class ReCapsUtils { // for (var ability in resourceAbilities) { final limits = abilities[ability]; - debugPrint('limits $limits'); if (limits is! List) { throw Errors.getInternalError( Errors.MISSING_OR_INVALID, From 35c7989d63c968a1b5300a61c386b40947415de3 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Fri, 7 Jun 2024 11:41:33 +0200 Subject: [PATCH 11/29] minor changes --- example/dapp/lib/pages/connect_page.dart | 81 ++++++++++++-------- lib/apis/core/pairing/pairing.dart | 2 +- lib/apis/core/relay_client/relay_client.dart | 14 ++-- lib/apis/sign_api/i_sign_client.dart | 20 ++--- lib/apis/sign_api/i_sign_engine_app.dart | 5 +- lib/apis/sign_api/i_sign_engine_common.dart | 1 + lib/apis/sign_api/i_sign_engine_wallet.dart | 3 +- lib/apis/sign_api/sign_engine.dart | 18 +++-- 8 files changed, 81 insertions(+), 63 deletions(-) diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 0834b42a..5fdcea11 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -172,13 +172,13 @@ class ConnectPageState extends State { ElevatedButton( onPressed: _selectedChains.isEmpty ? null - : () => _oneClickAuth(showToast: (m) async { - await showPlatformToast(child: Text(m), context: context); - }, closeModal: () { - if (Navigator.canPop(context)) { - Navigator.of(context).pop(); - } - }), + : () => _oneClickAuth( + closeModal: () { + if (Navigator.canPop(context)) { + Navigator.of(context).pop(); + } + }, + ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) { @@ -404,39 +404,42 @@ class ConnectPageState extends State { if (!shouldAuth) return; try { - final scheme = - event?.session.peer.metadata.redirect?.native ?? 'wcflutterwallet://'; - launchUrlString(scheme, mode: LaunchMode.externalApplication); - final pairingTopic = event?.session.pairingTopic; // Send off an auth request now that the pairing/session is established - debugPrint('Requesting authentication'); - final authRes = await widget.web3App.requestAuth( + final authResponse = await widget.web3App.requestAuth( pairingTopic: pairingTopic, params: AuthRequestParams( chainId: _selectedChains[0].chainId, domain: Constants.domain, aud: Constants.aud, - // statement: 'Welcome to example flutter app', + statement: 'Welcome to example flutter app', ), ); - debugPrint('Awaiting authentication response'); - final authResponse = await authRes.completer.future; + final scheme = event?.session.peer.metadata.redirect?.native; + launchUrlString( + scheme ?? 'wcflutterwallet://', + mode: LaunchMode.externalApplication, + ); + + debugPrint('[SampleDapp] Awaiting authentication response'); + final response = await authResponse.completer.future; + debugPrint('[SampleDapp] response ${jsonEncode(response.toJson())}'); - if (authResponse.error != null) { - debugPrint('Authentication failed: ${authResponse.error}'); + if (response.result != null) { showPlatformToast( - child: const Text(StringConstants.authFailed), + child: const Text(StringConstants.authSucceeded), context: context, ); } else { + final error = response.error ?? response.jsonRpcError; showPlatformToast( - child: const Text(StringConstants.authSucceeded), + child: Text(error.toString()), context: context, ); } } catch (e) { + debugPrint('[SampleDapp] auth $e'); showPlatformToast( child: const Text(StringConstants.connectionFailed), context: context, @@ -444,10 +447,7 @@ class ConnectPageState extends State { } } - void _oneClickAuth({ - Function(String message)? showToast, - VoidCallback? closeModal, - }) async { + void _oneClickAuth({VoidCallback? closeModal}) async { final methods = optionalNamespaces['eip155']?.methods ?? []; final authResponse = await widget.web3App.authenticate( params: OCARequestParams( @@ -491,15 +491,32 @@ class ConnectPageState extends State { _showQrCode(authResponse.uri.toString()); } - debugPrint('Awaiting session proposal settlement'); - final response = await authResponse.completer.future; - debugPrint('[SampleDapp] session ${jsonEncode(response.toJson())}'); + try { + debugPrint('[SampleDapp] Awaiting 1-CA session'); + final response = await authResponse.completer.future; + debugPrint('[SampleDapp] response ${jsonEncode(response.toJson())}'); - if (response.session != null) { - showToast?.call(StringConstants.connectionEstablished); - } else { - final error = response.error ?? response.jsonRpcError; - showToast?.call(error.toString()); + if (response.session != null) { + showPlatformToast( + child: const Text( + '${StringConstants.authSucceeded} and ' + '${StringConstants.connectionEstablished}', + ), + context: context, + ); + } else { + final error = response.error ?? response.jsonRpcError; + showPlatformToast( + child: Text(error.toString()), + context: context, + ); + } + } catch (e) { + debugPrint('[SampleDapp] 1-CA $e'); + showPlatformToast( + child: const Text(StringConstants.connectionFailed), + context: context, + ); } closeModal?.call(); } diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index debab9c4..b97a3d22 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -649,7 +649,7 @@ class Pairing implements IPairing { // print(payloadString); Map data = jsonDecode(payloadString); - core.logger.t('Pairing _onMessageEvent, Received data: $data'); + core.logger.i('Pairing _onMessageEvent, Received data: $data'); // If it's an rpc request, handle it // print('Pairing: Received data: $data'); diff --git a/lib/apis/core/relay_client/relay_client.dart b/lib/apis/core/relay_client/relay_client.dart index 699e54a4..8e482da8 100644 --- a/lib/apis/core/relay_client/relay_client.dart +++ b/lib/apis/core/relay_client/relay_client.dart @@ -170,7 +170,7 @@ class RelayClient implements IRelayClient { Future connect({String? relayUrl}) async { _checkInitialized(); - core.logger.t('RelayClient: Connecting to relay'); + core.logger.i('RelayClient: Connecting to relay'); await _connect(relayUrl: relayUrl); } @@ -179,7 +179,7 @@ class RelayClient implements IRelayClient { Future disconnect() async { _checkInitialized(); - core.logger.t('RelayClient: Disconnecting from relay'); + core.logger.i('RelayClient: Disconnecting from relay'); await _disconnect(); } @@ -302,12 +302,12 @@ class RelayClient implements IRelayClient { Future _handleRelayClose(int? code, String? reason) async { if (_handledClose) { - core.logger.t('Relay close already handled'); + core.logger.i('Relay close already handled'); return; } _handledClose = true; - core.logger.t('Handling relay close, code: $code, reason: $reason'); + core.logger.i('Handling relay close, code: $code, reason: $reason'); // If the relay isn't active (Disconnected manually), don't do anything if (!_active) { return; @@ -364,7 +364,7 @@ class RelayClient implements IRelayClient { core.logger.t('Handling Publish Message: $topic, $message'); // If we want to ignore the message, stop if (await _shouldIgnoreMessageEvent(topic, message)) { - core.logger.e('Ignoring Message: $topic, $message'); + core.logger.w('Ignoring Message: $topic, $message'); return false; } @@ -392,7 +392,7 @@ class RelayClient implements IRelayClient { } void _handleUnsubscribe(Parameters params) { - core.logger.t('[$runtimeType] _handleUnsubscribe $params'); + core.logger.i('[$runtimeType] _handleUnsubscribe $params'); } /// MESSAGE HANDLING @@ -441,7 +441,7 @@ class RelayClient implements IRelayClient { JsonRpcUtils.payloadId(entropy: 6), ); } catch (e) { - core.logger.e('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); + core.logger.w('RelayClient, onSubscribe error. Topic: $topic, Error: $e'); onRelayClientError.broadcast(ErrorEvent(e)); } diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 01a9e7fa..f74963c1 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -21,7 +21,7 @@ abstract class ISignClient { abstract final ISessions sessions; abstract final IGenericStore pendingRequests; - // FORMER AUTH ENGINE COMMON + // FORMER AUTH ENGINE PROPERTY abstract final IGenericStore authKeys; abstract final IGenericStore pairingTopics; abstract final IGenericStore completeRequests; @@ -40,8 +40,7 @@ abstract class ISignClient { abstract final Event onSessionEvent; // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; - - // NEW 1-CLICK AUTH METHOD + // NEW 1-CA PROPERTY abstract final Event onOCAResponse; Future init(); @@ -147,7 +146,7 @@ abstract class ISignClient { required String accountAddress, }); - // FORMER AUTH ENGINE COMMON + // FORMER AUTH ENGINE PROPERTY COMMON /// format payload to message string String formatAuthMessage({ required String iss, @@ -158,33 +157,34 @@ abstract class ISignClient { required String pairingTopic, }); - // FORMER AUTH ENGINE WALLET - // to be transformed into approveSessionAuthenticate({}) - // to be transformed into rejectSessionAuthenticate({}) + // FORMER AUTH ENGINE PROPERTY WALLET + // TODO to be transformed into approveSessionAuthenticate({}) and rejectSessionAuthenticate({}) Future respondAuthRequest({ required int id, required String iss, CacaoSignature? signature, WalletConnectError? error, }); - // FORMER AUTH ENGINE DAPP + + // FORMER AUTH ENGINE METHOD DAPP // query all pending requests Map getPendingAuthRequests(); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHOD DAPP Future requestAuth({ required AuthRequestParams params, String? pairingTopic, List>? methods, }); - // NEW ONE-CLICK AUTH METHOD FOR DAPPS + // NEW 1-CA METHOD FOR DAPP Future authenticate({ required OCARequestParams params, String? pairingTopic, List>? methods, }); + // NEW 1-CA METHOD FOR DAPP Future validateSignedCacao({ required Cacao cacao, required String projectId, diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index bb451c42..c1bcdd43 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -7,8 +7,7 @@ abstract class ISignEngineApp extends ISignEngineCommon { abstract final Event onSessionEvent; // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; - - // NEW 1-CLICK AUTH METHOD + // NEW 1-CA PROPERTY abstract final Event onOCAResponse; Future connect({ @@ -57,7 +56,7 @@ abstract class ISignEngineApp extends ISignEngineCommon { List>? methods, }); - // NEW ONE-CLICK AUTH METHOD FOR DAPPS + // NEW 1-CA METHOD FOR DAPPS Future authenticate({ required OCARequestParams params, String? pairingTopic, diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index bc5e9a78..b3ba3e08 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -50,6 +50,7 @@ abstract class ISignEngineCommon { required String pairingTopic, }); + // NEW 1-CA METHOD Future validateSignedCacao({ required Cacao cacao, required String projectId, diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index 81fcc2a9..8381d1b4 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -86,8 +86,7 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // }); // FORMER AUTH ENGINE PROPERTY - // to be transformed into approveSessionAuthenticate({}) - // to be transformed into rejectSessionAuthenticate({}) + // TODO to be transformed into approveSessionAuthenticate({}) and rejectSessionAuthenticate({}) Future respondAuthRequest({ required int id, required String iss, diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 07ab771c..4dba9a93 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -77,11 +77,11 @@ class SignEngine implements ISignEngine { @override late IGenericStore pairingTopics; - // NEW 1-CLICK AUTH METHOD + // NEW 1-CA METHOD @override final Event onOCAResponse = Event(); - // // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE PROPERTY (apparently not used befor and not used now) // List pendingAuthRequests = []; SignEngine({ @@ -90,7 +90,7 @@ class SignEngine implements ISignEngine { required this.proposals, required this.sessions, required this.pendingRequests, - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE PROPERTIES required this.authKeys, required this.pairingTopics, required this.authRequests, @@ -109,7 +109,7 @@ class SignEngine implements ISignEngine { await sessions.init(); await pendingRequests.init(); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE PROPERTIES await authKeys.init(); await pairingTopics.init(); await authRequests.init(); @@ -1817,6 +1817,7 @@ class SignEngine implements ISignEngine { } } + // NEW 1-CA METHOD (Should this be private?) @override Future validateSignedCacao({ required Cacao cacao, @@ -1930,6 +1931,8 @@ class SignEngine implements ISignEngine { pTopic = newTopicAndUri.topic; uri = newTopicAndUri.uri; } else { + // TODO this should be used when pairingTopic is passed (existent pairing topic case) + // but it does not seems right core.pairing.isValidPairingTopic(topic: pTopic); } @@ -2146,7 +2149,7 @@ class SignEngine implements ISignEngine { expiryTimestamp: expiryTimestamp.millisecondsSinceEpoch, ); - // ----- build namespaces for fallback session proposal ----- // TODO + // TODO fallback to session proposal to be implemented in following PR // const namespaces = { // eip155: { // chains, @@ -2168,7 +2171,6 @@ class SignEngine implements ISignEngine { // }; // Set the one time use receiver public key for decoding the Type 1 envelope - // TODO check this await core.pairing.setReceiverPublicKey( topic: responseTopic, publicKey: publicKey, @@ -2258,7 +2260,7 @@ class SignEngine implements ISignEngine { ); } - // TODO CHECK THIS + // This is used on Auth request, would it be needed on 1-CA? // await completeRequests.set( // id.toString(), // StoredCacao.fromCacao( @@ -2456,7 +2458,7 @@ class SignEngine implements ISignEngine { // TODO void _onOCARequest(String topic, JsonRpcRequest payload) async { - // TODO to be implemented for Wallet usage + // TODO to be implemented for Wallet usage on following PR // try { // final request = WcOCARequestRequest.fromJson(payload.params); From 19d6f8060cc03aafcb9c1987921357d24ab8d5b8 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 10 Jun 2024 15:09:03 +0200 Subject: [PATCH 12/29] fallback method implemeted --- example/dapp/lib/main.dart | 18 +-- example/dapp/lib/pages/connect_page.dart | 10 +- example/dapp/lib/pages/pairings_page.dart | 2 +- example/dapp/lib/utils/crypto/helpers.dart | 4 +- example/dapp/lib/widgets/auth_item.dart | 5 +- .../lib/dependencies/web3wallet_service.dart | 27 ++-- lib/apis/core/pairing/pairing.dart | 1 + lib/apis/sign_api/sign_client.dart | 6 +- lib/apis/sign_api/sign_engine.dart | 123 +++++++++++------- lib/apis/utils/walletconnect_utils.dart | 19 ++- lib/apis/web3app/web3app.dart | 5 +- test/core_api/pairing_test.dart | 4 +- test/sign_api/tests/sign_connect.dart | 6 +- 13 files changed, 124 insertions(+), 106 deletions(-) diff --git a/example/dapp/lib/main.dart b/example/dapp/lib/main.dart index 3962d1ca..bc74973b 100644 --- a/example/dapp/lib/main.dart +++ b/example/dapp/lib/main.dart @@ -57,11 +57,9 @@ class _MyHomePageState extends State { } Future initialize() async { - // try { - debugPrint('Project ID: ${DartDefines.projectId}'); _web3App = await Web3App.createInstance( projectId: DartDefines.projectId, - logLevel: LogLevel.info, + logLevel: LogLevel.error, metadata: const PairingMetadata( name: 'Sample dApp Flutter', description: 'WalletConnect\'s sample dapp with Flutter', @@ -80,7 +78,6 @@ class _MyHomePageState extends State { for (final ChainMetadata chain in ChainData.allChains) { // Loop through the events for that chain for (final event in getChainEvents(chain.type)) { - debugPrint('registerEventHandler $event for chain ${chain.chainId}'); _web3App!.registerEventHandler( chainId: chain.chainId, event: event, @@ -127,9 +124,6 @@ class _MyHomePageState extends State { _initializing = false; }); - // } on WalletConnectError catch (e) { - // print(e.message); - // } } void _setState(dynamic args) => setState(() {}); @@ -240,7 +234,7 @@ class _MyHomePageState extends State { } void _onSessionPing(SessionPing? args) { - debugPrint('[$runtimeType] _onSessionPing $args'); + debugPrint('[SampleDapp] _onSessionPing $args'); showDialog( context: context, builder: (BuildContext context) { @@ -253,7 +247,7 @@ class _MyHomePageState extends State { } void _onSessionEvent(SessionEvent? args) { - debugPrint('[$runtimeType] _onSessionEvent $args'); + debugPrint('[SampleDapp] _onSessionEvent $args'); showDialog( context: context, builder: (BuildContext context) { @@ -267,7 +261,7 @@ class _MyHomePageState extends State { } void _onSessionUpdate(SessionUpdate? args) { - debugPrint('[$runtimeType] _onSessionUpdate $args'); + debugPrint('[SampleDapp] _onSessionUpdate $args'); } void _onRelayMessage(MessageEvent? args) async { @@ -278,9 +272,9 @@ class _MyHomePageState extends State { args.message, ); final data = jsonDecode(payloadString ?? '{}') as Map; - debugPrint('[$runtimeType] _onRelayMessage data $data'); + debugPrint('[SampleDapp] _onRelayMessage data $data'); } catch (e) { - debugPrint('[$runtimeType] _onRelayMessage error $e'); + debugPrint('[SampleDapp] _onRelayMessage error $e'); } } } diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 5fdcea11..c77f043f 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -64,7 +64,7 @@ class ConnectPageState extends State { } _updateNamespaces(); - debugPrint('$optionalNamespaces'); + debugPrint('[SampleDapp] ${jsonEncode(optionalNamespaces)}'); }); } @@ -285,7 +285,7 @@ class ConnectPageState extends State { Function(String message)? showToast, VoidCallback? closeModal, }) async { - debugPrint('Creating connection and session'); + debugPrint('[SampleDapp] Creating connection and session'); // It is currently safer to send chains approvals on optionalNamespaces // but depending on Wallet implementation you may need to send some (for innstance eip155:1) as required final connectResponse = await widget.web3App.connect( @@ -323,7 +323,7 @@ class ConnectPageState extends State { _showQrCode(connectResponse.uri.toString()); } - debugPrint('Awaiting session proposal settlement'); + debugPrint('[SampleDapp] Awaiting session proposal settlement'); final _ = await connectResponse.session.future; showToast?.call(StringConstants.connectionEstablished); @@ -332,7 +332,7 @@ class ConnectPageState extends State { Future _showQrCode(String uri) async { // Show the QR code - debugPrint('Showing QR Code: $uri'); + debugPrint('[SampleDapp] Showing QR Code: $uri'); _shouldDismissQrCode = true; if (kIsWeb) { await showDialog( @@ -401,7 +401,7 @@ class ConnectPageState extends State { ); }, ); - if (!shouldAuth) return; + if (shouldAuth != true) return; try { final pairingTopic = event?.session.pairingTopic; diff --git a/example/dapp/lib/pages/pairings_page.dart b/example/dapp/lib/pages/pairings_page.dart index 50f67183..4a58f75a 100644 --- a/example/dapp/lib/pages/pairings_page.dart +++ b/example/dapp/lib/pages/pairings_page.dart @@ -75,7 +75,7 @@ class PairingsPageState extends State { ); Navigator.of(context).pop(); } catch (e) { - debugPrint(e.toString()); + debugPrint('[SampleDapp] ${e.toString()}'); } }, ), diff --git a/example/dapp/lib/utils/crypto/helpers.dart b/example/dapp/lib/utils/crypto/helpers.dart index 64705660..a37dfbbb 100644 --- a/example/dapp/lib/utils/crypto/helpers.dart +++ b/example/dapp/lib/utils/crypto/helpers.dart @@ -12,7 +12,7 @@ String getChainName(String chain) { .first .name; } catch (e) { - debugPrint('Invalid chain'); + debugPrint('[SampleDapp] Invalid chain'); } return 'Unknown'; } @@ -23,7 +23,7 @@ ChainMetadata getChainMetadataFromChain(String chain) { .where((element) => element.chainId == chain) .first; } catch (e) { - debugPrint('Invalid chain'); + debugPrint('[SampleDapp] Invalid chain'); } return ChainData.eip155Chains[0]; } diff --git a/example/dapp/lib/widgets/auth_item.dart b/example/dapp/lib/widgets/auth_item.dart index ea712584..df27fd61 100644 --- a/example/dapp/lib/widgets/auth_item.dart +++ b/example/dapp/lib/widgets/auth_item.dart @@ -26,9 +26,8 @@ class AuthItem extends StatelessWidget { auth.p.domain, style: StyleConstants.paragraph, ), - Text( - auth.p.iss, - ), + Text(auth.p.iss), + Text('iat: ${auth.p.iat}'), ], ), ), diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 827e7f67..a82aff86 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -56,14 +56,14 @@ class Web3WalletService extends IWeb3WalletService { for (final chainId in chainKey.chains) { if (chainId.startsWith('kadena')) { final account = '$chainId:k**${chainKey.address}'; - debugPrint('[$runtimeType] registerAccount $account'); + debugPrint('[SampleWallet] registerAccount $account'); _web3Wallet!.registerAccount( chainId: chainId, accountAddress: 'k**${chainKey.address}', ); } else { final account = '$chainId:${chainKey.address}'; - debugPrint('[$runtimeType] registerAccount $account'); + debugPrint('[SampleWallet] registerAccount $account'); _web3Wallet!.registerAccount( chainId: chainId, accountAddress: chainKey.address, @@ -73,7 +73,7 @@ class Web3WalletService extends IWeb3WalletService { } // Setup our listeners - debugPrint('[WALLET] [$runtimeType] create'); + debugPrint('[SampleWallet] create'); _web3Wallet!.core.pairing.onPairingInvalid.subscribe(_onPairingInvalid); _web3Wallet!.core.pairing.onPairingCreate.subscribe(_onPairingCreate); _web3Wallet!.onSessionProposal.subscribe(_onSessionProposal); @@ -91,12 +91,11 @@ class Web3WalletService extends IWeb3WalletService { @override Future init() async { // Await the initialization of the web3wallet - debugPrint('[$runtimeType] [WALLET] init'); await _web3Wallet!.init(); } void _logListener(LogEvent event) { - debugPrint('[WALLET] ${event.level.name}: ${event.message}'); + debugPrint('[SampleWallet] ${event.level.name}: ${event.message}'); if (event.level == Level.error) { // TODO send to mixpanel } @@ -104,7 +103,6 @@ class Web3WalletService extends IWeb3WalletService { @override FutureOr onDispose() { - debugPrint('[$runtimeType] [WALLET] dispose'); _web3Wallet!.core.removeLogListener(_logListener); _web3Wallet!.core.pairing.onPairingInvalid.unsubscribe(_onPairingInvalid); _web3Wallet!.core.pairing.onPairingCreate.unsubscribe(_onPairingCreate); @@ -126,7 +124,7 @@ class Web3WalletService extends IWeb3WalletService { void _onRelayClientMessage(MessageEvent? event) async { if (event != null) { final jsonObject = await EthUtils.decodeMessageEvent(event); - debugPrint('[$runtimeType] [WALLET] _onRelayClientMessage $jsonObject'); + debugPrint('[SampleWallet] _onRelayClientMessage $jsonObject'); if (jsonObject is JsonRpcRequest) { if (jsonObject.method == 'wc_sessionPropose' || jsonObject.method == 'wc_sessionRequest') { @@ -150,7 +148,7 @@ class Web3WalletService extends IWeb3WalletService { void _onSessionProposal(SessionProposalEvent? args) async { if (args != null) { - log('[$runtimeType] [WALLET] _onSessionProposal ${jsonEncode(args.params)}'); + log('[SampleWallet] _onSessionProposal ${jsonEncode(args.params)}'); final approved = await _bottomSheetHandler.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionRequestWidget( @@ -191,7 +189,7 @@ class Web3WalletService extends IWeb3WalletService { } void _onSessionProposalError(SessionProposalErrorEvent? args) async { - debugPrint('[$runtimeType] [WALLET] _onSessionProposalError $args'); + log('[SampleWallet] _onSessionProposalError $args'); DeepLinkHandler.waiting.value = false; if (args != null) { String errorMessage = args.error.message; @@ -230,26 +228,27 @@ class Web3WalletService extends IWeb3WalletService { void _onSessionConnect(SessionConnect? args) { if (args != null) { - log('[$runtimeType] [WALLET] _onSessionConnect ${jsonEncode(args.session)}'); + log('[SampleWallet] _onSessionConnect ${jsonEncode(args.session)}'); final scheme = args.session.peer.metadata.redirect?.native ?? ''; DeepLinkHandler.goTo(scheme); } } void _onRelayClientError(ErrorEvent? args) { - debugPrint('[$runtimeType] [WALLET] _onRelayClientError ${args?.error}'); + debugPrint( + '[$runtimeType] [SampleWallet] _onRelayClientError ${args?.error}'); } void _onPairingInvalid(PairingInvalidEvent? args) { - debugPrint('[$runtimeType] [WALLET] _onPairingInvalid $args'); + debugPrint('[$runtimeType] [SampleWallet] _onPairingInvalid $args'); } void _onPairingCreate(PairingEvent? args) { - debugPrint('[$runtimeType] [WALLET] _onPairingCreate $args'); + debugPrint('[$runtimeType] [SampleWallet] _onPairingCreate $args'); } Future _onAuthRequest(AuthRequest? args) async { - debugPrint('[$runtimeType] [WALLET] _onAuthRequest $args'); + log('[SampleWallet] _onAuthRequest $args'); if (args != null) { final chainKeys = GetIt.I().getKeysForChain('eip155:1'); // Create the message to be signed diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index b97a3d22..c5b15ded 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -121,6 +121,7 @@ class Pairing implements IPairing { symKey: symKey, relay: relay, methods: methods, + expiry: expiry, ); onPairingCreate.broadcast( diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index a54a22b2..423d300e 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -512,9 +512,7 @@ class SignClient implements ISignClient { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = const [ - [MethodConstants.WC_AUTH_REQUEST], - ], + List>? methods = SignEngine.DEFAULT_METHODS_AUTH, }) { try { return engine.requestAuth( @@ -533,7 +531,7 @@ class SignClient implements ISignClient { required OCARequestParams params, String? pairingTopic, List>? methods = const [ - [MethodConstants.WC_SESSION_AUTHENTICATE], + [MethodConstants.WC_SESSION_AUTHENTICATE] ], }) { try { diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 4dba9a93..73247429 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -21,6 +21,12 @@ class SignEngine implements ISignEngine { ], ]; + static const List> DEFAULT_METHODS_AUTH = [ + [ + MethodConstants.WC_AUTH_REQUEST, + ] + ]; + bool _initialized = false; @override @@ -232,13 +238,13 @@ class SignEngine implements ISignEngine { // print("sending proposal for $topic"); // print('connectResponseHandler requestId: $requestId'); try { - final Map resp = await core.pairing.sendRequest( + final Map response = await core.pairing.sendRequest( topic, MethodConstants.WC_SESSION_PROPOSE, request, id: requestId, ); - final String peerPublicKey = resp['responderPublicKey']; + final String peerPublicKey = response['responderPublicKey']; final ProposalData proposal = proposals.get( requestId.toString(), @@ -968,11 +974,11 @@ class SignEngine implements ISignEngine { type: ProtocolType.auth, ); // TODO on following PR to be used by Wallet - // core.pairing.register( - // method: MethodConstants.WC_SESSION_AUTHENTICATE, - // function: _onOCARequest, - // type: ProtocolType.auth, - // ); + core.pairing.register( + method: MethodConstants.WC_SESSION_AUTHENTICATE, + function: _onOCARequest, + type: ProtocolType.auth, + ); } Future _onSessionProposeRequest( @@ -1914,9 +1920,7 @@ class SignEngine implements ISignEngine { Future requestAuth({ required AuthRequestParams params, String? pairingTopic, - List>? methods = const [ - [MethodConstants.WC_AUTH_REQUEST], - ], + List>? methods = DEFAULT_METHODS_AUTH, }) async { _checkInitialized(); @@ -2073,7 +2077,7 @@ class SignEngine implements ISignEngine { required OCARequestParams params, String? pairingTopic, List>? methods = const [ - [MethodConstants.WC_SESSION_AUTHENTICATE], + [MethodConstants.WC_SESSION_AUTHENTICATE] ], }) async { _checkInitialized(); @@ -2094,7 +2098,6 @@ class SignEngine implements ISignEngine { pTopic = pairing.topic; connectionUri = pairing.uri; } else { - // TODO this doesn't look correct core.pairing.isValidPairingTopic(topic: pTopic); } @@ -2109,9 +2112,6 @@ class SignEngine implements ISignEngine { pairingTopics.set(responseTopic, pTopic), ]); - // Subscribe to the responseTopic because we expect the response to use this topic - await core.relayClient.subscribe(topic: responseTopic); - if (requestMethods.isNotEmpty) { final namespace = NamespaceUtils.getNamespaceFromChain(chains.first); String recap = ReCapsUtils.createEncodedRecap( @@ -2130,6 +2130,12 @@ class SignEngine implements ISignEngine { resources.add(recap); } + // Subscribe to the responseTopic because we expect the response to use this topic + await core.relayClient.subscribe(topic: responseTopic); + + final id = JsonRpcUtils.payloadId(); + final proposalId = JsonRpcUtils.payloadId(); + // Ensure the expiry is greater than the minimum required for the request - currently 1h final method = MethodConstants.WC_SESSION_AUTHENTICATE; final opts = MethodConstants.RPC_OPTS[method]!['req']!; @@ -2149,27 +2155,6 @@ class SignEngine implements ISignEngine { expiryTimestamp: expiryTimestamp.millisecondsSinceEpoch, ); - // TODO fallback to session proposal to be implemented in following PR - // const namespaces = { - // eip155: { - // chains, - // // request `personal_sign` method by default to allow for fallback siwe - // methods: [...new Set(["personal_sign", ...methods])], - // events: ["chainChanged", "accountsChanged"], - // }, - // }; - - // const proposal = { - // requiredNamespaces: {}, - // optionalNamespaces: namespaces, - // relays: [{ protocol: "irn" }], - // proposer: { - // publicKey, - // metadata: this.client.metadata, - // }, - // expiryTimestamp: calcExpiry(ENGINE_RPC_OPTS.wc_sessionPropose.req.ttl), - // }; - // Set the one time use receiver public key for decoding the Type 1 envelope await core.pairing.setReceiverPublicKey( topic: responseTopic, @@ -2177,21 +2162,71 @@ class SignEngine implements ISignEngine { expiry: authRequestExpiry, ); - final id = JsonRpcUtils.payloadId(); - final fallbackId = JsonRpcUtils.payloadId(); - Completer completer = Completer(); + // ----- build fallback session proposal request ----- // + final fallbackMethod = MethodConstants.WC_SESSION_PROPOSE; + final fallbackOpts = MethodConstants.RPC_OPTS[fallbackMethod]!['req']!; + final fallbackExpiryTimestamp = DateTime.now().add( + Duration(seconds: fallbackOpts.ttl), + ); + final proposalData = ProposalData( + id: proposalId, + requiredNamespaces: {}, + optionalNamespaces: { + 'eip155': RequiredNamespace( + chains: chains, + methods: {'personal_sign', ...requestMethods}.toList(), + events: EventsConstants.requiredEvents, + ), + }, + relays: [Relay(WalletConnectConstants.RELAYER_DEFAULT_PROTOCOL)], + expiry: fallbackExpiryTimestamp.millisecondsSinceEpoch, + proposer: ConnectionMetadata( + publicKey: publicKey, + metadata: metadata, + ), + pairingTopic: pTopic, + ); + final proposeRequest = WcSessionProposeRequest( + relays: proposalData.relays, + requiredNamespaces: proposalData.requiredNamespaces, + optionalNamespaces: proposalData.optionalNamespaces, + proposer: proposalData.proposer, + ); + await _setProposal(proposalData.id, proposalData); + + // ------------------------------------------------------- // + + // Send One-Click Auth request + Completer completer = Completer(); _requestOCAResponseHandler( id: id, - fallbackId: fallbackId, publicKey: publicKey, pairingTopic: pTopic, responseTopic: responseTopic, - requestParams: request, + request: request, expiry: authRequestExpiry, completer: completer, ); + // Send Session Proposal request + Completer completerFallback = Completer(); + pendingProposals.add( + SessionProposalCompleter( + id: proposalData.id, + selfPublicKey: proposalData.proposer.publicKey, + pairingTopic: proposalData.pairingTopic, + requiredNamespaces: proposalData.requiredNamespaces, + optionalNamespaces: proposalData.optionalNamespaces, + completer: completerFallback, + ), + ); + _connectResponseHandler( + pTopic, + proposeRequest, + proposalData.id, + ); + return OCARequestResponse( id: id, pairingTopic: pTopic, @@ -2202,12 +2237,11 @@ class SignEngine implements ISignEngine { Future _requestOCAResponseHandler({ required int id, - required int fallbackId, required String publicKey, required String pairingTopic, required String responseTopic, - required WcOCARequestParams requestParams, required int expiry, + required WcOCARequestParams request, required Completer completer, }) async { // @@ -2216,13 +2250,12 @@ class SignEngine implements ISignEngine { final Map response = await core.pairing.sendRequest( pairingTopic, MethodConstants.WC_SESSION_AUTHENTICATE, - requestParams.toJson(), + request.toJson(), id: id, ttl: expiry, ); result = WcOCARequestResult.fromJson(response); } catch (error) { - core.relayClient.unsubscribe(topic: responseTopic); final response = OCAResponse( id: id, topic: responseTopic, diff --git a/lib/apis/utils/walletconnect_utils.dart b/lib/apis/utils/walletconnect_utils.dart index fd5c01c0..901b26f2 100644 --- a/lib/apis/utils/walletconnect_utils.dart +++ b/lib/apis/utils/walletconnect_utils.dart @@ -184,21 +184,18 @@ class WalletConnectUtils { required String symKey, required Relay relay, required List>? methods, + int? expiry, }) { Map params = formatRelayParams(relay); params['symKey'] = symKey; if (methods != null) { - params['methods'] = methods - .map((e) => jsonEncode(e)) - .join( - ',', - ) - .replaceAll( - '"', - '', - ); - } else { - params['methods'] = '[]'; + final uriMethods = methods.expand((e) => e).toList(); + params['methods'] = + uriMethods.map((e) => jsonEncode(e)).join(',').replaceAll('"', ''); + } + + if (expiry != null) { + params['expiryTimestamp'] = expiry.toString(); } return Uri( diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index 418ffb17..c9723c1d 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -13,7 +13,6 @@ class Web3App implements IWeb3App { ], [ MethodConstants.WC_AUTH_REQUEST, - MethodConstants.WC_SESSION_AUTHENTICATE, ] ]; @@ -365,7 +364,9 @@ class Web3App implements IWeb3App { Future authenticate({ required OCARequestParams params, String? pairingTopic, - List>? methods = DEFAULT_METHODS, + List>? methods = const [ + [MethodConstants.WC_SESSION_AUTHENTICATE] + ], }) async { try { return signEngine.authenticate( diff --git a/test/core_api/pairing_test.dart b/test/core_api/pairing_test.dart index d67990ca..a38c0c80 100644 --- a/test/core_api/pairing_test.dart +++ b/test/core_api/pairing_test.dart @@ -39,7 +39,7 @@ void main() { ]); expect( Uri.decodeFull(response.toString()), - 'wc:abc@2?relay-protocol=irn&symKey=xyz&methods=[wc_sessionPropose],[wc_authRequest,wc_authBatchRequest]', + 'wc:abc@2?relay-protocol=irn&symKey=xyz&methods=wc_sessionPropose,wc_authRequest,wc_authBatchRequest', ); URIParseResult parsed = WalletConnectUtils.parseUri(response); @@ -63,7 +63,7 @@ void main() { ); expect( Uri.decodeFull(response.toString()), - 'wc:abc@2?relay-protocol=irn&symKey=xyz&methods=[]', + 'wc:abc@2?relay-protocol=irn&symKey=xyz', ); parsed = WalletConnectUtils.parseUri(response); diff --git a/test/sign_api/tests/sign_connect.dart b/test/sign_api/tests/sign_connect.dart index 49860fe4..8898a88d 100644 --- a/test/sign_api/tests/sign_connect.dart +++ b/test/sign_api/tests/sign_connect.dart @@ -47,14 +47,10 @@ void signConnect({ expect(parsed.topic, response.pairingTopic); expect(parsed.v2Data!.relay.protocol, 'irn'); if (clientA is IWeb3App) { - expect(parsed.v2Data!.methods.length, 4); + expect(parsed.v2Data!.methods.length, 3); expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); - expect( - parsed.v2Data!.methods[3], - MethodConstants.WC_SESSION_AUTHENTICATE, - ); } else { expect(parsed.v2Data!.methods.length, 2); expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); From d27f9238519f46b348663a0a8c38e5260e2dd80d Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 11 Jun 2024 10:11:48 +0200 Subject: [PATCH 13/29] minor change --- lib/apis/sign_api/i_sign_client.dart | 4 +- lib/apis/sign_api/i_sign_engine_app.dart | 2 +- .../models/auth/auth_client_models.dart | 54 +++++++++---------- .../models/auth/one_click_auth_events.dart | 6 +-- .../models/auth/one_click_auth_models.dart | 3 +- lib/apis/sign_api/sign_client.dart | 2 +- lib/apis/sign_api/sign_engine.dart | 18 +++---- lib/apis/web3app/web3app.dart | 2 +- .../utils/sign_client_test_wrapper.dart | 2 +- 9 files changed, 47 insertions(+), 46 deletions(-) diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index f74963c1..961ac139 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -41,7 +41,7 @@ abstract class ISignClient { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; // NEW 1-CA PROPERTY - abstract final Event onOCAResponse; + abstract final Event onOCAuthResponse; Future init(); Future connect({ @@ -166,7 +166,7 @@ abstract class ISignClient { WalletConnectError? error, }); - // FORMER AUTH ENGINE METHOD DAPP + // FORMER AUTH ENGINE METHOD WALLET // query all pending requests Map getPendingAuthRequests(); diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index c1bcdd43..fd462c48 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -8,7 +8,7 @@ abstract class ISignEngineApp extends ISignEngineCommon { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; // NEW 1-CA PROPERTY - abstract final Event onOCAResponse; + abstract final Event onOCAuthResponse; Future connect({ Map? requiredNamespaces, diff --git a/lib/apis/sign_api/models/auth/auth_client_models.dart b/lib/apis/sign_api/models/auth/auth_client_models.dart index b0e79799..6cb8e74e 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.dart @@ -129,30 +129,30 @@ class PendingAuthRequest with _$PendingAuthRequest { _$PendingAuthRequestFromJson(json); } -class AuthRequestCompleter { - final int id; - final String pairingTopic; - final String responseTopic; - final PendingAuthRequest request; - final Completer completer; - - AuthRequestCompleter({ - required this.id, - required this.pairingTopic, - required this.responseTopic, - required this.request, - required this.completer, - }); -} - -class RespondParams { - final int id; - final CacaoSignature? signature; - final WalletConnectError? error; - - RespondParams({ - required this.id, - this.signature, - this.error, - }); -} +// class AuthRequestCompleter { +// final int id; +// final String pairingTopic; +// final String responseTopic; +// final PendingAuthRequest request; +// final Completer completer; + +// AuthRequestCompleter({ +// required this.id, +// required this.pairingTopic, +// required this.responseTopic, +// required this.request, +// required this.completer, +// }); +// } + +// class RespondParams { +// final int id; +// final CacaoSignature? signature; +// final WalletConnectError? error; + +// RespondParams({ +// required this.id, +// this.signature, +// this.error, +// }); +// } diff --git a/lib/apis/sign_api/models/auth/one_click_auth_events.dart b/lib/apis/sign_api/models/auth/one_click_auth_events.dart index 0e5b184c..5d6bd2b2 100644 --- a/lib/apis/sign_api/models/auth/one_click_auth_events.dart +++ b/lib/apis/sign_api/models/auth/one_click_auth_events.dart @@ -6,11 +6,11 @@ import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; -class OCARequest extends EventArgs { +class OCAuthRequest extends EventArgs { // TODO to be implemented for wallet usage } -class OCAResponse extends EventArgs { +class OCAuthResponse extends EventArgs { final int id; final String topic; final List? auths; @@ -18,7 +18,7 @@ class OCAResponse extends EventArgs { final WalletConnectError? error; final JsonRpcError? jsonRpcError; - OCAResponse({ + OCAuthResponse({ required this.id, required this.topic, this.auths, diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.dart index f1adfa10..0ce8042e 100644 --- a/lib/apis/sign_api/models/auth/one_click_auth_models.dart +++ b/lib/apis/sign_api/models/auth/one_click_auth_models.dart @@ -8,10 +8,11 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_aut part 'one_click_auth_models.g.dart'; part 'one_click_auth_models.freezed.dart'; +// TODO this should be under sign_client_models.dart probably class OCARequestResponse { final int id; final String pairingTopic; - final Completer completer; + final Completer completer; final Uri? uri; OCARequestResponse({ diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index 423d300e..7e02bc9b 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -506,7 +506,7 @@ class SignClient implements ISignClient { // NEW 1-CLICK AUTH METHOD @override - Event get onOCAResponse => engine.onOCAResponse; + Event get onOCAuthResponse => engine.onOCAuthResponse; @override Future requestAuth({ diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 73247429..81bc65f1 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -85,7 +85,7 @@ class SignEngine implements ISignEngine { // NEW 1-CA METHOD @override - final Event onOCAResponse = Event(); + final Event onOCAuthResponse = Event(); // FORMER AUTH ENGINE PROPERTY (apparently not used befor and not used now) // List pendingAuthRequests = []; @@ -2198,7 +2198,7 @@ class SignEngine implements ISignEngine { // ------------------------------------------------------- // // Send One-Click Auth request - Completer completer = Completer(); + Completer completer = Completer(); _requestOCAResponseHandler( id: id, publicKey: publicKey, @@ -2242,7 +2242,7 @@ class SignEngine implements ISignEngine { required String responseTopic, required int expiry, required WcOCARequestParams request, - required Completer completer, + required Completer completer, }) async { // late WcOCARequestResult result; @@ -2256,7 +2256,7 @@ class SignEngine implements ISignEngine { ); result = WcOCARequestResult.fromJson(response); } catch (error) { - final response = OCAResponse( + final response = OCAuthResponse( id: id, topic: responseTopic, jsonRpcError: (error is JsonRpcError) ? error : null, @@ -2267,7 +2267,7 @@ class SignEngine implements ISignEngine { ) : null, ); - onOCAResponse.broadcast(response); + onOCAuthResponse.broadcast(response); completer.complete(response); return; } @@ -2323,7 +2323,7 @@ class SignEngine implements ISignEngine { } } } on WalletConnectError catch (e) { - final resp = OCAResponse( + final resp = OCAuthResponse( id: id, topic: responseTopic, error: WalletConnectError( @@ -2331,7 +2331,7 @@ class SignEngine implements ISignEngine { message: e.message, ), ); - onOCAResponse.broadcast(resp); + onOCAuthResponse.broadcast(resp); completer.complete(resp); return; } @@ -2369,13 +2369,13 @@ class SignEngine implements ISignEngine { session = sessions.get(sessionTopic); } - final resp = OCAResponse( + final resp = OCAuthResponse( id: id, topic: responseTopic, auths: cacaos, session: session, ); - onOCAResponse.broadcast(resp); + onOCAuthResponse.broadcast(resp); completer.complete(resp); } diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index c9723c1d..eb33a051 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -332,7 +332,7 @@ class Web3App implements IWeb3App { // NEW 1-CLICK AUTH METHOD @override - Event get onOCAResponse => signEngine.onOCAResponse; + Event get onOCAuthResponse => signEngine.onOCAuthResponse; @override IGenericStore get authKeys => signEngine.authKeys; diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index f67924e7..e3d2a93d 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -498,7 +498,7 @@ class SignClientTestWrapper implements ISignEngine { Event get onAuthResponse => client.onAuthResponse; @override - Event get onOCAResponse => client.onOCAResponse; + Event get onOCAuthResponse => client.onOCAuthResponse; @override IGenericStore get pairingTopics => client.pairingTopics; From ad938e71e55fdb6035aa506f3065e0efc8a721bb Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 11 Jun 2024 11:12:51 +0200 Subject: [PATCH 14/29] minor change and version upgrade --- CHANGELOG.md | 4 +++ example/dapp/lib/pages/connect_page.dart | 2 +- lib/apis/sign_api/sign_engine.dart | 31 +++++++++++++----------- lib/src/version.dart | 2 +- pubspec.yaml | 2 +- 5 files changed, 24 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1df04810..0edc3513 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2.3.0-alpha01 + +- One-Click Auth support (dApp side) + ## 2.2.3 - Full web support diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index c77f043f..1ddb28e7 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -201,7 +201,7 @@ class ConnectPageState extends State { ), ), child: const Text( - '1-Click Auth', + 'One-Click Auth', style: StyleConstants.buttonText, ), ), diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 81bc65f1..9464f40c 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -2162,6 +2162,8 @@ class SignEngine implements ISignEngine { expiry: authRequestExpiry, ); + Completer completer = Completer(); + // ----- build fallback session proposal request ----- // final fallbackMethod = MethodConstants.WC_SESSION_PROPOSE; @@ -2195,11 +2197,23 @@ class SignEngine implements ISignEngine { ); await _setProposal(proposalData.id, proposalData); + Completer completerFallback = Completer(); + + pendingProposals.add( + SessionProposalCompleter( + id: proposalData.id, + selfPublicKey: proposalData.proposer.publicKey, + pairingTopic: proposalData.pairingTopic, + requiredNamespaces: proposalData.requiredNamespaces, + optionalNamespaces: proposalData.optionalNamespaces, + completer: completerFallback, + ), + ); + // ------------------------------------------------------- // // Send One-Click Auth request - Completer completer = Completer(); - _requestOCAResponseHandler( + _ocAuthResponseHandler( id: id, publicKey: publicKey, pairingTopic: pTopic, @@ -2210,17 +2224,6 @@ class SignEngine implements ISignEngine { ); // Send Session Proposal request - Completer completerFallback = Completer(); - pendingProposals.add( - SessionProposalCompleter( - id: proposalData.id, - selfPublicKey: proposalData.proposer.publicKey, - pairingTopic: proposalData.pairingTopic, - requiredNamespaces: proposalData.requiredNamespaces, - optionalNamespaces: proposalData.optionalNamespaces, - completer: completerFallback, - ), - ); _connectResponseHandler( pTopic, proposeRequest, @@ -2235,7 +2238,7 @@ class SignEngine implements ISignEngine { ); } - Future _requestOCAResponseHandler({ + Future _ocAuthResponseHandler({ required int id, required String publicKey, required String pairingTopic, diff --git a/lib/src/version.dart b/lib/src/version.dart index c168df12..a8bfab2f 100644 --- a/lib/src/version.dart +++ b/lib/src/version.dart @@ -1,2 +1,2 @@ // Generated code. Do not modify. -const packageVersion = '2.2.3'; +const packageVersion = '2.3.0-alpha01'; diff --git a/pubspec.yaml b/pubspec.yaml index e3f176a7..7288fd7c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: walletconnect_flutter_v2 description: This repository contains oficial implementation of WalletConnect v2 protocols for Flutter applications. The communications protocol for web3. -version: 2.2.3 +version: 2.3.0-alpha01 repository: https://github.com/WalletConnect/WalletConnectFlutterV2 environment: From 291381d02349881979dce0b9d6e60854b8f49bd8 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 11 Jun 2024 15:52:26 +0200 Subject: [PATCH 15/29] some file renaming and moving --- lib/apis/auth_api/auth_client.dart | 386 ++-- lib/apis/auth_api/auth_engine.dart | 870 +++++---- lib/apis/auth_api/i_auth_client.dart | 113 +- lib/apis/auth_api/i_auth_engine.dart | 6 +- lib/apis/auth_api/i_auth_engine_app.dart | 29 +- lib/apis/auth_api/i_auth_engine_common.dart | 40 +- lib/apis/auth_api/i_auth_engine_wallet.dart | 35 +- lib/apis/sign_api/i_sign_engine_common.dart | 3 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 2 +- .../models/auth/auth_client_events.dart | 2 +- .../models/auth/auth_client_models.dart | 56 +- ...on_models.dart => common_auth_models.dart} | 6 +- .../auth/common_auth_models.freezed.dart | 1633 +++++++++++++++++ .../models/auth/common_auth_models.g.dart | 164 ++ .../sign_api/models/auth/json_rpc_models.dart | 4 +- ...ck_auth_events.dart => ocauth_events.dart} | 2 +- ...ck_auth_models.dart => ocauth_models.dart} | 8 +- .../models/auth/ocauth_models.freezed.dart | 410 +++++ .../sign_api/models/auth/ocauth_models.g.dart | 53 + lib/apis/sign_api/sign_engine.dart | 2 +- .../sign_api/utils/auth/auth_signature.dart | 2 +- lib/walletconnect_flutter_v2.dart | 13 +- test/auth_api/utils/signature_constants.dart | 2 +- 23 files changed, 3036 insertions(+), 805 deletions(-) rename lib/apis/sign_api/models/auth/{auth_common_models.dart => common_auth_models.dart} (97%) create mode 100644 lib/apis/sign_api/models/auth/common_auth_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/common_auth_models.g.dart rename lib/apis/sign_api/models/auth/{one_click_auth_events.dart => ocauth_events.dart} (97%) rename lib/apis/sign_api/models/auth/{one_click_auth_models.dart => ocauth_models.dart} (95%) create mode 100644 lib/apis/sign_api/models/auth/ocauth_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/ocauth_models.g.dart diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index da42e041..e7b89e0a 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,197 +1,189 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; - -// class AuthClient implements IAuthClient { -// bool _initialized = false; - -// @override -// String get protocol => 'wc'; - -// @override -// int get version => 2; - -// @override -// Event get onAuthRequest => engine.onAuthRequest; -// @override -// Event get onAuthResponse => engine.onAuthResponse; - -// @override -// ICore get core => engine.core; -// @override -// PairingMetadata get metadata => engine.metadata; -// @override -// IGenericStore get authKeys => engine.authKeys; -// @override -// IGenericStore get pairingTopics => engine.pairingTopics; -// @override -// IGenericStore get authRequests => engine.authRequests; -// @override -// IGenericStore get completeRequests => engine.completeRequests; - -// @override -// late IAuthEngine engine; - -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// IHttpClient httpClient = const HttpWrapper(), -// LogLevel logLevel = LogLevel.nothing, -// }) async { -// final client = AuthClient( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// httpClient: httpClient, -// logLevel: logLevel, -// ), -// metadata: metadata, -// ); -// await client.init(); - -// return client; -// } - -// AuthClient({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// engine = AuthEngine( -// core: core, -// metadata: metadata, -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value as String; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// } - -// @override -// Future init() async { -// if (_initialized) { -// return; -// } - -// await core.start(); -// await engine.init(); - -// _initialized = true; -// } - -// @override -// Future request({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods = AuthEngine.DEFAULT_METHODS, -// }) async { -// try { -// return engine.requestAuth( -// params: params, -// pairingTopic: pairingTopic, -// methods: methods, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Future respond({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }) async { -// try { -// return engine.respondAuthRequest( -// id: id, -// iss: iss, -// signature: signature, -// error: error, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getPendingRequests() { -// try { -// return engine.getPendingAuthRequests(); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return engine.getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } - -// @override -// String formatMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }) { -// try { -// return engine.formatAuthMessage( -// iss: iss, -// cacaoPayload: cacaoPayload, -// ); -// } catch (e) { -// rethrow; -// } -// } -// } +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class AuthClient implements IAuthClient { + bool _initialized = false; + + @override + String get protocol => 'wc'; + + @override + int get version => 2; + + @override + Event get onAuthRequest => engine.onAuthRequest; + @override + Event get onAuthResponse => engine.onAuthResponse; + + @override + ICore get core => engine.core; + @override + PairingMetadata get metadata => engine.metadata; + @override + IGenericStore get authKeys => engine.authKeys; + @override + IGenericStore get pairingTopics => engine.pairingTopics; + @override + IGenericStore get authRequests => engine.authRequests; + @override + IGenericStore get completeRequests => engine.completeRequests; + + @override + late IAuthEngine engine; + + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + IHttpClient httpClient = const HttpWrapper(), + LogLevel logLevel = LogLevel.nothing, + }) async { + final client = AuthClient( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + httpClient: httpClient, + logLevel: logLevel, + ), + metadata: metadata, + ); + await client.init(); + + return client; + } + + AuthClient({ + required ICore core, + required PairingMetadata metadata, + }) { + engine = AuthEngine( + core: core, + metadata: metadata, + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value as String; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + } + + @override + Future init() async { + if (_initialized) { + return; + } + + await core.start(); + await engine.init(); + + _initialized = true; + } + + @override + Future request({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = AuthEngine.DEFAULT_METHODS, + }) async { + try { + return engine.requestAuth( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } + + @override + Future respond({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + try { + return engine.respondAuthRequest( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingRequests() { + try { + return engine.getPendingAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return engine.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + @override + String formatMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return engine.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index f39cb5af..8380902a 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -1,442 +1,428 @@ -// import 'dart:async'; - -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/json_rpc_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.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_api_validators.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/json_rpc_request.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; - -// class AuthEngine implements IAuthEngine { -// static const List> DEFAULT_METHODS = [ -// [ -// MethodConstants.WC_AUTH_REQUEST, -// ] -// ]; - -// bool _initialized = false; - -// @override -// final Event onAuthRequest = Event(); -// @override -// final Event onAuthResponse = Event(); - -// @override -// final ICore core; -// @override -// final PairingMetadata metadata; -// @override -// late IGenericStore authKeys; -// @override -// late IGenericStore pairingTopics; -// @override -// late IGenericStore authRequests; -// @override -// late IGenericStore completeRequests; - -// List pendingAuthRequests = []; - -// AuthEngine({ -// required this.core, -// required this.metadata, -// required this.authKeys, -// required this.pairingTopics, -// required this.authRequests, -// required this.completeRequests, -// }); - -// @override -// Future init() async { -// if (_initialized) { -// return; -// } - -// await core.pairing.init(); -// await authKeys.init(); -// await pairingTopics.init(); -// await authRequests.init(); -// await completeRequests.init(); - -// _registerRelayClientFunctions(); - -// _initialized = true; -// } - -// @override -// Future requestAuth({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods = DEFAULT_METHODS, -// }) async { -// _checkInitialized(); - -// AuthApiValidators.isValidRequest(params); -// String? pTopic = pairingTopic; -// Uri? uri; - -// if (pTopic == null) { -// final CreateResponse newTopicAndUri = await core.pairing.create( -// methods: methods, -// ); -// pTopic = newTopicAndUri.topic; -// uri = newTopicAndUri.uri; -// } else { -// core.pairing.isValidPairingTopic(topic: pTopic); -// } - -// final publicKey = await core.crypto.generateKeyPair(); -// // print('requestAuth, publicKey: $publicKey'); -// final String responseTopic = core.crypto.getUtils().hashKey(publicKey); -// final int id = JsonRpcUtils.payloadId(); - -// WcAuthRequestRequest request = WcAuthRequestRequest( -// payloadParams: AuthPayloadParams.fromRequestParams( -// params, -// ), -// requester: ConnectionMetadata( -// publicKey: publicKey, -// metadata: metadata, -// ), -// ); - -// final int expiry = params.expiry ?? WalletConnectConstants.FIVE_MINUTES; - -// await authKeys.set( -// AuthConstants.AUTH_CLIENT_PUBLIC_KEY_NAME, -// AuthPublicKey(publicKey: publicKey), -// ); - -// await pairingTopics.set( -// responseTopic, -// pTopic, -// ); - -// // Set the one time use receiver public key for decoding the Type 1 envelope -// await core.pairing.setReceiverPublicKey( -// topic: responseTopic, -// publicKey: publicKey, -// expiry: expiry, -// ); - -// Completer completer = Completer(); - -// _requestAuthResponseHandler( -// pairingTopic: pTopic, -// responseTopic: responseTopic, -// request: request, -// id: id, -// expiry: expiry, -// completer: completer, -// ); - -// return AuthRequestResponse( -// id: id, -// pairingTopic: pTopic, -// completer: completer, -// uri: uri, -// ); -// } - -// Future _requestAuthResponseHandler({ -// required String pairingTopic, -// required String responseTopic, -// required WcAuthRequestRequest request, -// required int id, -// required int expiry, -// required Completer completer, -// }) async { -// Map? resp; - -// // Subscribe to the responseTopic because we expect the response to use this topic -// // print('got here'); -// await core.relayClient.subscribe(topic: responseTopic); - -// try { -// resp = await core.pairing.sendRequest( -// pairingTopic, -// MethodConstants.WC_AUTH_REQUEST, -// request.toJson(), -// id: id, -// ttl: expiry, -// ); -// } on JsonRpcError catch (e) { -// final resp = AuthResponse( -// id: id, -// topic: responseTopic, -// jsonRpcError: e, -// ); -// onAuthResponse.broadcast(resp); -// completer.complete(resp); -// return; -// } - -// await core.pairing.activate(topic: pairingTopic); - -// final Cacao cacao = Cacao.fromJson(resp!); -// final CacaoSignature sig = cacao.s; -// final CacaoPayload payload = cacao.p; -// await completeRequests.set( -// id.toString(), -// StoredCacao.fromCacao( -// id: id, -// pairingTopic: pairingTopic, -// cacao: cacao, -// ), -// ); - -// final String reconstructed = formatAuthMessage( -// iss: payload.iss, -// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), -// ); - -// final String walletAddress = AddressUtils.getDidAddress(payload.iss); -// final String chainId = AddressUtils.getDidChainId(payload.iss); - -// if (walletAddress.isEmpty) { -// throw Errors.getSdkError( -// Errors.MISSING_OR_INVALID, -// context: 'authResponse walletAddress is empty', -// ); -// } -// if (chainId.isEmpty) { -// throw Errors.getSdkError( -// Errors.MISSING_OR_INVALID, -// context: 'authResponse chainId is empty', -// ); -// } - -// final bool isValid = await AuthSignature.verifySignature( -// walletAddress, -// reconstructed, -// sig, -// chainId, -// core.projectId, -// ); - -// if (!isValid) { -// final resp = AuthResponse( -// id: id, -// topic: responseTopic, -// error: const WalletConnectError( -// code: -1, -// message: 'Invalid signature', -// ), -// ); -// onAuthResponse.broadcast(resp); -// completer.complete(resp); -// } else { -// final resp = AuthResponse( -// id: id, -// topic: responseTopic, -// result: cacao, -// ); -// onAuthResponse.broadcast(resp); -// completer.complete(resp); -// } -// } - -// @override -// Future respondAuthRequest({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }) async { -// _checkInitialized(); - -// Map pendingRequests = getPendingAuthRequests(); -// AuthApiValidators.isValidRespond( -// id: id, -// pendingRequests: pendingRequests, -// signature: signature, -// error: error, -// ); - -// final PendingAuthRequest pendingRequest = pendingRequests[id]!; -// final String receiverPublicKey = pendingRequest.metadata.publicKey; -// final String senderPublicKey = await core.crypto.generateKeyPair(); -// final String responseTopic = core.crypto.getUtils().hashKey( -// receiverPublicKey, -// ); -// final EncodeOptions encodeOpts = EncodeOptions( -// type: EncodeOptions.TYPE_1, -// receiverPublicKey: receiverPublicKey, -// senderPublicKey: senderPublicKey, -// ); - -// if (error != null) { -// await core.pairing.sendError( -// id, -// responseTopic, -// MethodConstants.WC_AUTH_REQUEST, -// JsonRpcError.serverError(error.message), -// encodeOptions: encodeOpts, -// ); -// } else { -// final Cacao cacao = Cacao( -// h: const CacaoHeader(), -// p: CacaoPayload.fromRequestPayload( -// issuer: iss, -// payload: pendingRequest.cacaoPayload, -// ), -// s: signature!, -// ); - -// // print('auth res id: $id'); -// await core.pairing.sendResult( -// id, -// responseTopic, -// MethodConstants.WC_AUTH_REQUEST, -// cacao.toJson(), -// encodeOptions: encodeOpts, -// ); - -// await authRequests.delete(id.toString()); - -// await completeRequests.set( -// id.toString(), -// StoredCacao.fromCacao( -// id: id, -// pairingTopic: pendingRequest.pairingTopic, -// cacao: cacao, -// ), -// ); -// } -// } - -// @override -// Map getPendingAuthRequests() { -// Map pendingRequests = {}; -// authRequests.getAll().forEach((key) { -// pendingRequests[key.id] = key; -// }); -// return pendingRequests; -// } - -// @override -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }) { -// Map completedRequests = {}; -// completeRequests -// .getAll() -// .where( -// (e) => e.pairingTopic == pairingTopic, -// ) -// .forEach((key) { -// completedRequests[key.id] = key; -// }); -// return completedRequests; -// } - -// // kind of a core method to move to sign -// // Formats the message that is coming from requestAuth() -// @override -// String formatAuthMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }) { -// final header = -// '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; -// final walletAddress = AddressUtils.getDidAddress(iss); -// final uri = 'URI: ${cacaoPayload.aud}'; -// final version = 'Version: ${cacaoPayload.version}'; -// final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; -// final nonce = 'Nonce: ${cacaoPayload.nonce}'; -// final issuedAt = 'Issued At: ${cacaoPayload.iat}'; -// final resources = cacaoPayload.resources != null && -// cacaoPayload.resources!.isNotEmpty -// ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' -// : null; - -// final message = [ -// header, -// walletAddress, -// '', -// cacaoPayload.statement, -// '', -// uri, -// version, -// chainId, -// nonce, -// issuedAt, -// resources, -// ].where((element) => element != null).join('\n'); - -// return message; -// } - -// /// ---- PRIVATE HELPERS ---- /// - -// void _checkInitialized() { -// if (!_initialized) { -// throw Errors.getInternalError(Errors.NOT_INITIALIZED); -// } -// } - -// /// ---- Relay Events ---- /// - -// void _registerRelayClientFunctions() { -// core.pairing.register( -// method: MethodConstants.WC_AUTH_REQUEST, -// function: _onAuthRequest, -// type: ProtocolType.auth, -// ); -// } - -// void _onAuthRequest( -// String topic, -// JsonRpcRequest payload, -// ) async { -// try { -// final request = WcAuthRequestRequest.fromJson(payload.params); - -// final CacaoRequestPayload cacaoPayload = -// CacaoRequestPayload.fromPayloadParams( -// request.payloadParams, -// ); - -// authRequests.set( -// payload.id.toString(), -// PendingAuthRequest( -// id: payload.id, -// pairingTopic: topic, -// metadata: request.requester, -// cacaoPayload: cacaoPayload, -// ), -// ); - -// onAuthRequest.broadcast( -// AuthRequest( -// id: payload.id, -// topic: topic, -// requester: request.requester, -// payloadParams: request.payloadParams, -// ), -// ); -// } on WalletConnectError catch (err) { -// await core.pairing.sendError( -// payload.id, -// topic, -// payload.method, -// JsonRpcError.invalidParams( -// err.message, -// ), -// ); -// } -// } -// } +import 'dart:async'; + +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +class AuthEngine implements IAuthEngine { + static const List> DEFAULT_METHODS = [ + [ + MethodConstants.WC_AUTH_REQUEST, + ] + ]; + + bool _initialized = false; + + @override + final Event onAuthRequest = Event(); + @override + final Event onAuthResponse = Event(); + + @override + final ICore core; + @override + final PairingMetadata metadata; + @override + late IGenericStore authKeys; + @override + late IGenericStore pairingTopics; + @override + late IGenericStore authRequests; + @override + late IGenericStore completeRequests; + + List pendingAuthRequests = []; + + AuthEngine({ + required this.core, + required this.metadata, + required this.authKeys, + required this.pairingTopics, + required this.authRequests, + required this.completeRequests, + }); + + @override + Future init() async { + if (_initialized) { + return; + } + + await core.pairing.init(); + await authKeys.init(); + await pairingTopics.init(); + await authRequests.init(); + await completeRequests.init(); + + _registerRelayClientFunctions(); + + _initialized = true; + } + + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = DEFAULT_METHODS, + }) async { + _checkInitialized(); + + AuthApiValidators.isValidRequest(params); + String? pTopic = pairingTopic; + Uri? uri; + + if (pTopic == null) { + final CreateResponse newTopicAndUri = await core.pairing.create( + methods: methods, + ); + pTopic = newTopicAndUri.topic; + uri = newTopicAndUri.uri; + } else { + core.pairing.isValidPairingTopic(topic: pTopic); + } + + final publicKey = await core.crypto.generateKeyPair(); + // print('requestAuth, publicKey: $publicKey'); + final String responseTopic = core.crypto.getUtils().hashKey(publicKey); + final int id = JsonRpcUtils.payloadId(); + + WcAuthRequestRequest request = WcAuthRequestRequest( + payloadParams: AuthPayloadParams.fromRequestParams( + params, + ), + requester: ConnectionMetadata( + publicKey: publicKey, + metadata: metadata, + ), + ); + + final int expiry = params.expiry ?? WalletConnectConstants.FIVE_MINUTES; + + await authKeys.set( + AuthConstants.AUTH_CLIENT_PUBLIC_KEY_NAME, + AuthPublicKey(publicKey: publicKey), + ); + + await pairingTopics.set( + responseTopic, + pTopic, + ); + + // Set the one time use receiver public key for decoding the Type 1 envelope + await core.pairing.setReceiverPublicKey( + topic: responseTopic, + publicKey: publicKey, + expiry: expiry, + ); + + Completer completer = Completer(); + + _requestAuthResponseHandler( + pairingTopic: pTopic, + responseTopic: responseTopic, + request: request, + id: id, + expiry: expiry, + completer: completer, + ); + + return AuthRequestResponse( + id: id, + pairingTopic: pTopic, + completer: completer, + uri: uri, + ); + } + + Future _requestAuthResponseHandler({ + required String pairingTopic, + required String responseTopic, + required WcAuthRequestRequest request, + required int id, + required int expiry, + required Completer completer, + }) async { + Map? resp; + + // Subscribe to the responseTopic because we expect the response to use this topic + // print('got here'); + await core.relayClient.subscribe(topic: responseTopic); + + try { + resp = await core.pairing.sendRequest( + pairingTopic, + MethodConstants.WC_AUTH_REQUEST, + request.toJson(), + id: id, + ttl: expiry, + ); + } on JsonRpcError catch (e) { + final resp = AuthResponse( + id: id, + topic: responseTopic, + jsonRpcError: e, + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + return; + } + + await core.pairing.activate(topic: pairingTopic); + + final Cacao cacao = Cacao.fromJson(resp!); + final CacaoSignature sig = cacao.s; + final CacaoPayload payload = cacao.p; + await completeRequests.set( + id.toString(), + StoredCacao.fromCacao( + id: id, + pairingTopic: pairingTopic, + cacao: cacao, + ), + ); + + final String reconstructed = formatAuthMessage( + iss: payload.iss, + cacaoPayload: CacaoRequestPayload.fromCacaoPayload(payload), + ); + + final String walletAddress = AddressUtils.getDidAddress(payload.iss); + final String chainId = AddressUtils.getDidChainId(payload.iss); + + if (walletAddress.isEmpty) { + throw Errors.getSdkError( + Errors.MISSING_OR_INVALID, + context: 'authResponse walletAddress is empty', + ); + } + if (chainId.isEmpty) { + throw Errors.getSdkError( + Errors.MISSING_OR_INVALID, + context: 'authResponse chainId is empty', + ); + } + + final bool isValid = await AuthSignature.verifySignature( + walletAddress, + reconstructed, + sig, + chainId, + core.projectId, + ); + + if (!isValid) { + final resp = AuthResponse( + id: id, + topic: responseTopic, + error: const WalletConnectError( + code: -1, + message: 'Invalid signature', + ), + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + } else { + final resp = AuthResponse( + id: id, + topic: responseTopic, + result: cacao, + ); + onAuthResponse.broadcast(resp); + completer.complete(resp); + } + } + + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + _checkInitialized(); + + Map pendingRequests = getPendingAuthRequests(); + AuthApiValidators.isValidRespond( + id: id, + pendingRequests: pendingRequests, + signature: signature, + error: error, + ); + + final PendingAuthRequest pendingRequest = pendingRequests[id]!; + final String receiverPublicKey = pendingRequest.metadata.publicKey; + final String senderPublicKey = await core.crypto.generateKeyPair(); + final String responseTopic = core.crypto.getUtils().hashKey( + receiverPublicKey, + ); + final EncodeOptions encodeOpts = EncodeOptions( + type: EncodeOptions.TYPE_1, + receiverPublicKey: receiverPublicKey, + senderPublicKey: senderPublicKey, + ); + + if (error != null) { + await core.pairing.sendError( + id, + responseTopic, + MethodConstants.WC_AUTH_REQUEST, + JsonRpcError.serverError(error.message), + encodeOptions: encodeOpts, + ); + } else { + final Cacao cacao = Cacao( + h: const CacaoHeader(), + p: CacaoPayload.fromRequestPayload( + issuer: iss, + payload: pendingRequest.cacaoPayload, + ), + s: signature!, + ); + + // print('auth res id: $id'); + await core.pairing.sendResult( + id, + responseTopic, + MethodConstants.WC_AUTH_REQUEST, + cacao.toJson(), + encodeOptions: encodeOpts, + ); + + await authRequests.delete(id.toString()); + + await completeRequests.set( + id.toString(), + StoredCacao.fromCacao( + id: id, + pairingTopic: pendingRequest.pairingTopic, + cacao: cacao, + ), + ); + } + } + + @override + Map getPendingAuthRequests() { + Map pendingRequests = {}; + authRequests.getAll().forEach((key) { + pendingRequests[key.id] = key; + }); + return pendingRequests; + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + Map completedRequests = {}; + completeRequests + .getAll() + .where( + (e) => e.pairingTopic == pairingTopic, + ) + .forEach((key) { + completedRequests[key.id] = key; + }); + return completedRequests; + } + + // kind of a core method to move to sign + // Formats the message that is coming from requestAuth() + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + final header = + '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; + final walletAddress = AddressUtils.getDidAddress(iss); + final uri = 'URI: ${cacaoPayload.aud}'; + final version = 'Version: ${cacaoPayload.version}'; + final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; + final nonce = 'Nonce: ${cacaoPayload.nonce}'; + final issuedAt = 'Issued At: ${cacaoPayload.iat}'; + final resources = cacaoPayload.resources != null && + cacaoPayload.resources!.isNotEmpty + ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' + : null; + + final message = [ + header, + walletAddress, + '', + cacaoPayload.statement, + '', + uri, + version, + chainId, + nonce, + issuedAt, + resources, + ].where((element) => element != null).join('\n'); + + return message; + } + + /// ---- PRIVATE HELPERS ---- /// + + void _checkInitialized() { + if (!_initialized) { + throw Errors.getInternalError(Errors.NOT_INITIALIZED); + } + } + + /// ---- Relay Events ---- /// + + void _registerRelayClientFunctions() { + core.pairing.register( + method: MethodConstants.WC_AUTH_REQUEST, + function: _onAuthRequest, + type: ProtocolType.auth, + ); + } + + void _onAuthRequest( + String topic, + JsonRpcRequest payload, + ) async { + try { + final request = WcAuthRequestRequest.fromJson(payload.params); + + final CacaoRequestPayload cacaoPayload = + CacaoRequestPayload.fromPayloadParams( + request.payloadParams, + ); + + authRequests.set( + payload.id.toString(), + PendingAuthRequest( + id: payload.id, + pairingTopic: topic, + metadata: request.requester, + cacaoPayload: cacaoPayload, + ), + ); + + onAuthRequest.broadcast( + AuthRequest( + id: payload.id, + topic: topic, + requester: request.requester, + payloadParams: request.payloadParams, + ), + ); + } on WalletConnectError catch (err) { + await core.pairing.sendError( + payload.id, + topic, + payload.method, + JsonRpcError.invalidParams( + err.message, + ), + ); + } + } +} diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 848d0974..758f6b84 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,56 +1,57 @@ -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -// abstract class IAuthClient { -// final String protocol = 'wc'; -// final int version = 2; - -// abstract final IAuthEngine engine; - -// // Common -// abstract final ICore core; -// abstract final PairingMetadata metadata; - -// abstract final IGenericStore authKeys; -// abstract final IGenericStore pairingTopics; -// abstract final IGenericStore completeRequests; - -// // initializes the client with persisted storage and a network connection -// Future init(); - -// /// format payload to message string -// String formatMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }); - -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }); - -// // App -// abstract final Event onAuthResponse; - -// // request wallet authentication -// Future request({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods, -// }); - -// // Wallet -// abstract final Event onAuthRequest; - -// abstract final IGenericStore authRequests; - -// /// respond wallet authentication -// Future respond({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }); - -// // query all pending requests -// Map getPendingRequests(); -// } +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +abstract class IAuthClient { + final String protocol = 'wc'; + final int version = 2; + + abstract final IAuthEngine engine; + + // Common + abstract final ICore core; + abstract final PairingMetadata metadata; + + abstract final IGenericStore authKeys; + abstract final IGenericStore pairingTopics; + abstract final IGenericStore completeRequests; + + // initializes the client with persisted storage and a network connection + Future init(); + + /// format payload to message string + String formatMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }); + + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }); + + // App + abstract final Event onAuthResponse; + + // request wallet authentication + Future request({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }); + + // Wallet + abstract final Event onAuthRequest; + + abstract final IGenericStore authRequests; + + /// respond wallet authentication + Future respond({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }); + + // query all pending requests + Map getPendingRequests(); +} diff --git a/lib/apis/auth_api/i_auth_engine.dart b/lib/apis/auth_api/i_auth_engine.dart index 5bea4d75..c48de6d5 100644 --- a/lib/apis/auth_api/i_auth_engine.dart +++ b/lib/apis/auth_api/i_auth_engine.dart @@ -1,4 +1,4 @@ -// 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'; +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'; -// abstract class IAuthEngine implements IAuthEngineWallet, IAuthEngineApp {} +abstract class IAuthEngine implements IAuthEngineWallet, IAuthEngineApp {} diff --git a/lib/apis/auth_api/i_auth_engine_app.dart b/lib/apis/auth_api/i_auth_engine_app.dart index 6d505a59..9d071ad1 100644 --- a/lib/apis/auth_api/i_auth_engine_app.dart +++ b/lib/apis/auth_api/i_auth_engine_app.dart @@ -1,15 +1,18 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// abstract class IAuthEngineApp extends IAuthEngineCommon { -// abstract final Event onAuthResponse; +abstract class IAuthEngineApp extends IAuthEngineCommon { + abstract final Event onAuthResponse; -// // request wallet authentication -// Future requestAuth({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods, -// }); -// } + @Deprecated( + 'AuthEngine/AuthClient is deprecated and will be removed soon. ' + 'Please use authenticate() method from SignEngine/SignClient instead', + ) + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods, + }); +} diff --git a/lib/apis/auth_api/i_auth_engine_common.dart b/lib/apis/auth_api/i_auth_engine_common.dart index 70bca6a9..406dcd87 100644 --- a/lib/apis/auth_api/i_auth_engine_common.dart +++ b/lib/apis/auth_api/i_auth_engine_common.dart @@ -1,26 +1,24 @@ -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -// abstract class IAuthEngineCommon { -// abstract final ICore core; -// abstract final PairingMetadata metadata; +abstract class IAuthEngineCommon { + abstract final ICore core; + abstract final PairingMetadata metadata; -// abstract final IGenericStore authKeys; -// abstract final IGenericStore pairingTopics; -// abstract final IGenericStore completeRequests; + abstract final IGenericStore authKeys; + abstract final IGenericStore pairingTopics; + abstract final IGenericStore completeRequests; -// // initializes the client with persisted storage and a network connection -// Future init(); + // initializes the client with persisted storage and a network connection + Future init(); -// /// format payload to message string -// String formatAuthMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }); + /// format payload to message string + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }); -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }); -// } + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }); +} diff --git a/lib/apis/auth_api/i_auth_engine_wallet.dart b/lib/apis/auth_api/i_auth_engine_wallet.dart index 4c91c53b..fc25132a 100644 --- a/lib/apis/auth_api/i_auth_engine_wallet.dart +++ b/lib/apis/auth_api/i_auth_engine_wallet.dart @@ -1,23 +1,20 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -// abstract class IAuthEngineWallet extends IAuthEngineCommon { -// abstract final Event onAuthRequest; +abstract class IAuthEngineWallet extends IAuthEngineCommon { + abstract final Event onAuthRequest; -// abstract final IGenericStore authRequests; + abstract final IGenericStore authRequests; -// /// respond wallet authentication -// Future respondAuthRequest({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }); + /// respond wallet authentication + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }); -// // query all pending requests -// Map getPendingAuthRequests(); -// } + // query all pending requests + Map getPendingAuthRequests(); +} diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index b3ba3e08..63f7666c 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -8,7 +8,7 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/i_sessions.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; abstract class ISignEngineCommon { abstract final Event onSessionConnect; @@ -49,7 +49,6 @@ abstract class ISignEngineCommon { Map getCompletedRequestsForPairing({ required String pairingTopic, }); - // NEW 1-CA METHOD Future validateSignedCacao({ required Cacao cacao, diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index 8381d1b4..c1ac55ba 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -3,6 +3,7 @@ import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models. import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_response.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine_common.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; @@ -11,7 +12,6 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/sign_client_models import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; abstract class ISignEngineWallet extends ISignEngineCommon { abstract final Event onSessionProposal; diff --git a/lib/apis/sign_api/models/auth/auth_client_events.dart b/lib/apis/sign_api/models/auth/auth_client_events.dart index c45e926e..3741e014 100644 --- a/lib/apis/sign_api/models/auth/auth_client_events.dart +++ b/lib/apis/sign_api/models/auth/auth_client_events.dart @@ -4,7 +4,7 @@ import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; class AuthRequest extends EventArgs { final int id; diff --git a/lib/apis/sign_api/models/auth/auth_client_models.dart b/lib/apis/sign_api/models/auth/auth_client_models.dart index 6cb8e74e..dcff6757 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_utils.dart'; part 'auth_client_models.g.dart'; @@ -129,30 +129,30 @@ class PendingAuthRequest with _$PendingAuthRequest { _$PendingAuthRequestFromJson(json); } -// class AuthRequestCompleter { -// final int id; -// final String pairingTopic; -// final String responseTopic; -// final PendingAuthRequest request; -// final Completer completer; - -// AuthRequestCompleter({ -// required this.id, -// required this.pairingTopic, -// required this.responseTopic, -// required this.request, -// required this.completer, -// }); -// } - -// class RespondParams { -// final int id; -// final CacaoSignature? signature; -// final WalletConnectError? error; - -// RespondParams({ -// required this.id, -// this.signature, -// this.error, -// }); -// } +class AuthRequestCompleter { + final int id; + final String pairingTopic; + final String responseTopic; + final PendingAuthRequest request; + final Completer completer; + + AuthRequestCompleter({ + required this.id, + required this.pairingTopic, + required this.responseTopic, + required this.request, + required this.completer, + }); +} + +class RespondParams { + final int id; + final CacaoSignature? signature; + final WalletConnectError? error; + + RespondParams({ + required this.id, + this.signature, + this.error, + }); +} diff --git a/lib/apis/sign_api/models/auth/auth_common_models.dart b/lib/apis/sign_api/models/auth/common_auth_models.dart similarity index 97% rename from lib/apis/sign_api/models/auth/auth_common_models.dart rename to lib/apis/sign_api/models/auth/common_auth_models.dart index 29348aec..99adc23c 100644 --- a/lib/apis/sign_api/models/auth/auth_common_models.dart +++ b/lib/apis/sign_api/models/auth/common_auth_models.dart @@ -1,10 +1,10 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/ocauth_models.dart'; -part 'auth_common_models.g.dart'; -part 'auth_common_models.freezed.dart'; +part 'common_auth_models.g.dart'; +part 'common_auth_models.freezed.dart'; @freezed class AuthPublicKey with _$AuthPublicKey { 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 new file mode 100644 index 00000000..55109512 --- /dev/null +++ b/lib/apis/sign_api/models/auth/common_auth_models.freezed.dart @@ -0,0 +1,1633 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'common_auth_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +AuthPublicKey _$AuthPublicKeyFromJson(Map json) { + return _AuthPublicKey.fromJson(json); +} + +/// @nodoc +mixin _$AuthPublicKey { + String get publicKey => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $AuthPublicKeyCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AuthPublicKeyCopyWith<$Res> { + factory $AuthPublicKeyCopyWith( + AuthPublicKey value, $Res Function(AuthPublicKey) then) = + _$AuthPublicKeyCopyWithImpl<$Res, AuthPublicKey>; + @useResult + $Res call({String publicKey}); +} + +/// @nodoc +class _$AuthPublicKeyCopyWithImpl<$Res, $Val extends AuthPublicKey> + implements $AuthPublicKeyCopyWith<$Res> { + _$AuthPublicKeyCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? publicKey = null, + }) { + return _then(_value.copyWith( + publicKey: null == publicKey + ? _value.publicKey + : publicKey // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$AuthPublicKeyImplCopyWith<$Res> + implements $AuthPublicKeyCopyWith<$Res> { + factory _$$AuthPublicKeyImplCopyWith( + _$AuthPublicKeyImpl value, $Res Function(_$AuthPublicKeyImpl) then) = + __$$AuthPublicKeyImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String publicKey}); +} + +/// @nodoc +class __$$AuthPublicKeyImplCopyWithImpl<$Res> + extends _$AuthPublicKeyCopyWithImpl<$Res, _$AuthPublicKeyImpl> + implements _$$AuthPublicKeyImplCopyWith<$Res> { + __$$AuthPublicKeyImplCopyWithImpl( + _$AuthPublicKeyImpl _value, $Res Function(_$AuthPublicKeyImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? publicKey = null, + }) { + return _then(_$AuthPublicKeyImpl( + publicKey: null == publicKey + ? _value.publicKey + : publicKey // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$AuthPublicKeyImpl implements _AuthPublicKey { + const _$AuthPublicKeyImpl({required this.publicKey}); + + factory _$AuthPublicKeyImpl.fromJson(Map json) => + _$$AuthPublicKeyImplFromJson(json); + + @override + final String publicKey; + + @override + String toString() { + return 'AuthPublicKey(publicKey: $publicKey)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AuthPublicKeyImpl && + (identical(other.publicKey, publicKey) || + other.publicKey == publicKey)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, publicKey); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => + __$$AuthPublicKeyImplCopyWithImpl<_$AuthPublicKeyImpl>(this, _$identity); + + @override + Map toJson() { + return _$$AuthPublicKeyImplToJson( + this, + ); + } +} + +abstract class _AuthPublicKey implements AuthPublicKey { + const factory _AuthPublicKey({required final String publicKey}) = + _$AuthPublicKeyImpl; + + factory _AuthPublicKey.fromJson(Map json) = + _$AuthPublicKeyImpl.fromJson; + + @override + String get publicKey; + @override + @JsonKey(ignore: true) + _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { + return _CacaoRequestPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoRequestPayload { + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoRequestPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoRequestPayloadCopyWith<$Res> { + factory $CacaoRequestPayloadCopyWith( + CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = + _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> + implements $CacaoRequestPayloadCopyWith<$Res> { + _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> + implements $CacaoRequestPayloadCopyWith<$Res> { + factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, + $Res Function(_$CacaoRequestPayloadImpl) then) = + __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> + extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> + implements _$$CacaoRequestPayloadImplCopyWith<$Res> { + __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, + $Res Function(_$CacaoRequestPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoRequestPayloadImpl( + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { + const _$CacaoRequestPayloadImpl( + {required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoRequestPayloadImpl.fromJson(Map json) => + _$$CacaoRequestPayloadImplFromJson(json); + + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoRequestPayloadImpl && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoRequestPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoRequestPayload implements CacaoRequestPayload { + const factory _CacaoRequestPayload( + {required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoRequestPayloadImpl; + + factory _CacaoRequestPayload.fromJson(Map json) = + _$CacaoRequestPayloadImpl.fromJson; + + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoPayload _$CacaoPayloadFromJson(Map json) { + return _CacaoPayload.fromJson(json); +} + +/// @nodoc +mixin _$CacaoPayload { + String get iss => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get version => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoPayloadCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoPayloadCopyWith<$Res> { + factory $CacaoPayloadCopyWith( + CacaoPayload value, $Res Function(CacaoPayload) then) = + _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> + implements $CacaoPayloadCopyWith<$Res> { + _$CacaoPayloadCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoPayloadImplCopyWith<$Res> + implements $CacaoPayloadCopyWith<$Res> { + factory _$$CacaoPayloadImplCopyWith( + _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = + __$$CacaoPayloadImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String iss, + String domain, + String aud, + String version, + String nonce, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$CacaoPayloadImplCopyWithImpl<$Res> + extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> + implements _$$CacaoPayloadImplCopyWith<$Res> { + __$$CacaoPayloadImplCopyWithImpl( + _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? iss = null, + Object? domain = null, + Object? aud = null, + Object? version = null, + Object? nonce = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$CacaoPayloadImpl( + iss: null == iss + ? _value.iss + : iss // ignore: cast_nullable_to_non_nullable + as String, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoPayloadImpl implements _CacaoPayload { + const _$CacaoPayloadImpl( + {required this.iss, + required this.domain, + required this.aud, + required this.version, + required this.nonce, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _resources = resources; + + factory _$CacaoPayloadImpl.fromJson(Map json) => + _$$CacaoPayloadImplFromJson(json); + + @override + final String iss; + @override + final String domain; + @override + final String aud; + @override + final String version; + @override + final String nonce; + @override + final String iat; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoPayloadImpl && + (identical(other.iss, iss) || other.iss == iss) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.version, version) || other.version == version) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + iss, + domain, + aud, + version, + nonce, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoPayloadImplToJson( + this, + ); + } +} + +abstract class _CacaoPayload implements CacaoPayload { + const factory _CacaoPayload( + {required final String iss, + required final String domain, + required final String aud, + required final String version, + required final String nonce, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$CacaoPayloadImpl; + + factory _CacaoPayload.fromJson(Map json) = + _$CacaoPayloadImpl.fromJson; + + @override + String get iss; + @override + String get domain; + @override + String get aud; + @override + String get version; + @override + String get nonce; + @override + String get iat; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoHeader _$CacaoHeaderFromJson(Map json) { + return _CacaoHeader.fromJson(json); +} + +/// @nodoc +mixin _$CacaoHeader { + String get t => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoHeaderCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoHeaderCopyWith<$Res> { + factory $CacaoHeaderCopyWith( + CacaoHeader value, $Res Function(CacaoHeader) then) = + _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; + @useResult + $Res call({String t}); +} + +/// @nodoc +class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> + implements $CacaoHeaderCopyWith<$Res> { + _$CacaoHeaderCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoHeaderImplCopyWith<$Res> + implements $CacaoHeaderCopyWith<$Res> { + factory _$$CacaoHeaderImplCopyWith( + _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = + __$$CacaoHeaderImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t}); +} + +/// @nodoc +class __$$CacaoHeaderImplCopyWithImpl<$Res> + extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> + implements _$$CacaoHeaderImplCopyWith<$Res> { + __$$CacaoHeaderImplCopyWithImpl( + _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + }) { + return _then(_$CacaoHeaderImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoHeaderImpl implements _CacaoHeader { + const _$CacaoHeaderImpl({this.t = 'eip4361'}); + + factory _$CacaoHeaderImpl.fromJson(Map json) => + _$$CacaoHeaderImplFromJson(json); + + @override + @JsonKey() + final String t; + + @override + String toString() { + return 'CacaoHeader(t: $t)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoHeaderImpl && + (identical(other.t, t) || other.t == t)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoHeaderImplToJson( + this, + ); + } +} + +abstract class _CacaoHeader implements CacaoHeader { + const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; + + factory _CacaoHeader.fromJson(Map json) = + _$CacaoHeaderImpl.fromJson; + + @override + String get t; + @override + @JsonKey(ignore: true) + _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +CacaoSignature _$CacaoSignatureFromJson(Map json) { + return _CacaoSignature.fromJson(json); +} + +/// @nodoc +mixin _$CacaoSignature { + String get t => throw _privateConstructorUsedError; + String get s => throw _privateConstructorUsedError; + String? get m => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoSignatureCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoSignatureCopyWith<$Res> { + factory $CacaoSignatureCopyWith( + CacaoSignature value, $Res Function(CacaoSignature) then) = + _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> + implements $CacaoSignatureCopyWith<$Res> { + _$CacaoSignatureCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_value.copyWith( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CacaoSignatureImplCopyWith<$Res> + implements $CacaoSignatureCopyWith<$Res> { + factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, + $Res Function(_$CacaoSignatureImpl) then) = + __$$CacaoSignatureImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String t, String s, String? m}); +} + +/// @nodoc +class __$$CacaoSignatureImplCopyWithImpl<$Res> + extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> + implements _$$CacaoSignatureImplCopyWith<$Res> { + __$$CacaoSignatureImplCopyWithImpl( + _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? t = null, + Object? s = null, + Object? m = freezed, + }) { + return _then(_$CacaoSignatureImpl( + t: null == t + ? _value.t + : t // ignore: cast_nullable_to_non_nullable + as String, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as String, + m: freezed == m + ? _value.m + : m // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoSignatureImpl implements _CacaoSignature { + const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); + + factory _$CacaoSignatureImpl.fromJson(Map json) => + _$$CacaoSignatureImplFromJson(json); + + @override + final String t; + @override + final String s; + @override + final String? m; + + @override + String toString() { + return 'CacaoSignature(t: $t, s: $s, m: $m)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoSignatureImpl && + (identical(other.t, t) || other.t == t) && + (identical(other.s, s) || other.s == s) && + (identical(other.m, m) || other.m == m)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, t, s, m); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$CacaoSignatureImplToJson( + this, + ); + } +} + +abstract class _CacaoSignature implements CacaoSignature { + const factory _CacaoSignature( + {required final String t, + required final String s, + final String? m}) = _$CacaoSignatureImpl; + + factory _CacaoSignature.fromJson(Map json) = + _$CacaoSignatureImpl.fromJson; + + @override + String get t; + @override + String get s; + @override + String? get m; + @override + @JsonKey(ignore: true) + _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Cacao _$CacaoFromJson(Map json) { + return _Cacao.fromJson(json); +} + +/// @nodoc +mixin _$Cacao { + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CacaoCopyWith<$Res> { + factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = + _$CacaoCopyWithImpl<$Res, Cacao>; + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> + implements $CacaoCopyWith<$Res> { + _$CacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { + factory _$$CacaoImplCopyWith( + _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = + __$$CacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$CacaoImplCopyWithImpl<$Res> + extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> + implements _$$CacaoImplCopyWith<$Res> { + __$$CacaoImplCopyWithImpl( + _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$CacaoImpl( + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$CacaoImpl implements _Cacao { + const _$CacaoImpl({required this.h, required this.p, required this.s}); + + factory _$CacaoImpl.fromJson(Map json) => + _$$CacaoImplFromJson(json); + + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'Cacao(h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CacaoImpl && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CacaoImplToJson( + this, + ); + } +} + +abstract class _Cacao implements Cacao { + const factory _Cacao( + {required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$CacaoImpl; + + factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; + + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} + +StoredCacao _$StoredCacaoFromJson(Map json) { + return _StoredCacao.fromJson(json); +} + +/// @nodoc +mixin _$StoredCacao { + int get id => throw _privateConstructorUsedError; + String get pairingTopic => throw _privateConstructorUsedError; + CacaoHeader get h => throw _privateConstructorUsedError; + CacaoPayload get p => throw _privateConstructorUsedError; + CacaoSignature get s => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $StoredCacaoCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StoredCacaoCopyWith<$Res> { + factory $StoredCacaoCopyWith( + StoredCacao value, $Res Function(StoredCacao) then) = + _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + $CacaoHeaderCopyWith<$Res> get h; + $CacaoPayloadCopyWith<$Res> get p; + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> + implements $StoredCacaoCopyWith<$Res> { + _$StoredCacaoCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res> get h { + return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { + return _then(_value.copyWith(h: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoPayloadCopyWith<$Res> get p { + return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { + return _then(_value.copyWith(p: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoSignatureCopyWith<$Res> get s { + return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { + return _then(_value.copyWith(s: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$StoredCacaoImplCopyWith<$Res> + implements $StoredCacaoCopyWith<$Res> { + factory _$$StoredCacaoImplCopyWith( + _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = + __$$StoredCacaoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String pairingTopic, + CacaoHeader h, + CacaoPayload p, + CacaoSignature s}); + + @override + $CacaoHeaderCopyWith<$Res> get h; + @override + $CacaoPayloadCopyWith<$Res> get p; + @override + $CacaoSignatureCopyWith<$Res> get s; +} + +/// @nodoc +class __$$StoredCacaoImplCopyWithImpl<$Res> + extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> + implements _$$StoredCacaoImplCopyWith<$Res> { + __$$StoredCacaoImplCopyWithImpl( + _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? h = null, + Object? p = null, + Object? s = null, + }) { + return _then(_$StoredCacaoImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + h: null == h + ? _value.h + : h // ignore: cast_nullable_to_non_nullable + as CacaoHeader, + p: null == p + ? _value.p + : p // ignore: cast_nullable_to_non_nullable + as CacaoPayload, + s: null == s + ? _value.s + : s // ignore: cast_nullable_to_non_nullable + as CacaoSignature, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$StoredCacaoImpl implements _StoredCacao { + const _$StoredCacaoImpl( + {required this.id, + required this.pairingTopic, + required this.h, + required this.p, + required this.s}); + + factory _$StoredCacaoImpl.fromJson(Map json) => + _$$StoredCacaoImplFromJson(json); + + @override + final int id; + @override + final String pairingTopic; + @override + final CacaoHeader h; + @override + final CacaoPayload p; + @override + final CacaoSignature s; + + @override + String toString() { + return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StoredCacaoImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.pairingTopic, pairingTopic) || + other.pairingTopic == pairingTopic) && + (identical(other.h, h) || other.h == h) && + (identical(other.p, p) || other.p == p) && + (identical(other.s, s) || other.s == s)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$StoredCacaoImplToJson( + this, + ); + } +} + +abstract class _StoredCacao implements StoredCacao { + const factory _StoredCacao( + {required final int id, + required final String pairingTopic, + required final CacaoHeader h, + required final CacaoPayload p, + required final CacaoSignature s}) = _$StoredCacaoImpl; + + factory _StoredCacao.fromJson(Map json) = + _$StoredCacaoImpl.fromJson; + + @override + int get id; + @override + String get pairingTopic; + @override + CacaoHeader get h; + @override + CacaoPayload get p; + @override + CacaoSignature get s; + @override + @JsonKey(ignore: true) + _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => + throw _privateConstructorUsedError; +} 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 new file mode 100644 index 00000000..23fd94e6 --- /dev/null +++ b/lib/apis/sign_api/models/auth/common_auth_models.g.dart @@ -0,0 +1,164 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'common_auth_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$AuthPublicKeyImpl _$$AuthPublicKeyImplFromJson(Map json) => + _$AuthPublicKeyImpl( + publicKey: json['publicKey'] as String, + ); + +Map _$$AuthPublicKeyImplToJson(_$AuthPublicKeyImpl instance) => + { + 'publicKey': instance.publicKey, + }; + +_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( + Map json) => + _$CacaoRequestPayloadImpl( + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoRequestPayloadImplToJson( + _$CacaoRequestPayloadImpl instance) { + final val = { + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => + _$CacaoPayloadImpl( + iss: json['iss'] as String, + domain: json['domain'] as String, + aud: json['aud'] as String, + version: json['version'] as String, + nonce: json['nonce'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { + final val = { + 'iss': instance.iss, + 'domain': instance.domain, + 'aud': instance.aud, + 'version': instance.version, + 'nonce': instance.nonce, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => + _$CacaoHeaderImpl( + t: json['t'] as String? ?? 'eip4361', + ); + +Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => + { + 't': instance.t, + }; + +_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => + _$CacaoSignatureImpl( + t: json['t'] as String, + s: json['s'] as String, + m: json['m'] as String?, + ); + +Map _$$CacaoSignatureImplToJson( + _$CacaoSignatureImpl instance) { + final val = { + 't': instance.t, + 's': instance.s, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('m', instance.m); + return val; +} + +_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$CacaoImplToJson(_$CacaoImpl instance) => + { + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; + +_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => + _$StoredCacaoImpl( + id: json['id'] as int, + pairingTopic: json['pairingTopic'] as String, + h: CacaoHeader.fromJson(json['h'] as Map), + p: CacaoPayload.fromJson(json['p'] as Map), + s: CacaoSignature.fromJson(json['s'] as Map), + ); + +Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => + { + 'id': instance.id, + 'pairingTopic': instance.pairingTopic, + 'h': instance.h.toJson(), + 'p': instance.p.toJson(), + 's': instance.s.toJson(), + }; diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.dart b/lib/apis/sign_api/models/auth/json_rpc_models.dart index c0459c2c..86cc595d 100644 --- a/lib/apis/sign_api/models/auth/json_rpc_models.dart +++ b/lib/apis/sign_api/models/auth/json_rpc_models.dart @@ -1,8 +1,8 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_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/ocauth_models.dart'; part 'json_rpc_models.g.dart'; part 'json_rpc_models.freezed.dart'; diff --git a/lib/apis/sign_api/models/auth/one_click_auth_events.dart b/lib/apis/sign_api/models/auth/ocauth_events.dart similarity index 97% rename from lib/apis/sign_api/models/auth/one_click_auth_events.dart rename to lib/apis/sign_api/models/auth/ocauth_events.dart index 5d6bd2b2..adf84971 100644 --- a/lib/apis/sign_api/models/auth/one_click_auth_events.dart +++ b/lib/apis/sign_api/models/auth/ocauth_events.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_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/session_models.dart'; class OCAuthRequest extends EventArgs { diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.dart b/lib/apis/sign_api/models/auth/ocauth_models.dart similarity index 95% rename from lib/apis/sign_api/models/auth/one_click_auth_models.dart rename to lib/apis/sign_api/models/auth/ocauth_models.dart index 0ce8042e..23e4e7c6 100644 --- a/lib/apis/sign_api/models/auth/one_click_auth_models.dart +++ b/lib/apis/sign_api/models/auth/ocauth_models.dart @@ -2,11 +2,11 @@ import 'dart:async'; import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/one_click_auth_events.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/ocauth_events.dart'; -part 'one_click_auth_models.g.dart'; -part 'one_click_auth_models.freezed.dart'; +part 'ocauth_models.g.dart'; +part 'ocauth_models.freezed.dart'; // TODO this should be under sign_client_models.dart probably class OCARequestResponse { diff --git a/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart b/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart new file mode 100644 index 00000000..42d1b29e --- /dev/null +++ b/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart @@ -0,0 +1,410 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'ocauth_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +OCAPayloadParams _$OCAPayloadParamsFromJson(Map json) { + return _OCAPayloadParams.fromJson(json); +} + +/// @nodoc +mixin _$OCAPayloadParams { + List get chains => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; // + String get version => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; // + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $OCAPayloadParamsCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OCAPayloadParamsCopyWith<$Res> { + factory $OCAPayloadParamsCopyWith( + OCAPayloadParams value, $Res Function(OCAPayloadParams) then) = + _$OCAPayloadParamsCopyWithImpl<$Res, OCAPayloadParams>; + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$OCAPayloadParamsCopyWithImpl<$Res, $Val extends OCAPayloadParams> + implements $OCAPayloadParamsCopyWith<$Res> { + _$OCAPayloadParamsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + chains: null == chains + ? _value.chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$OCAPayloadParamsImplCopyWith<$Res> + implements $OCAPayloadParamsCopyWith<$Res> { + factory _$$OCAPayloadParamsImplCopyWith(_$OCAPayloadParamsImpl value, + $Res Function(_$OCAPayloadParamsImpl) then) = + __$$OCAPayloadParamsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$OCAPayloadParamsImplCopyWithImpl<$Res> + extends _$OCAPayloadParamsCopyWithImpl<$Res, _$OCAPayloadParamsImpl> + implements _$$OCAPayloadParamsImplCopyWith<$Res> { + __$$OCAPayloadParamsImplCopyWithImpl(_$OCAPayloadParamsImpl _value, + $Res Function(_$OCAPayloadParamsImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$OCAPayloadParamsImpl( + chains: null == chains + ? _value._chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$OCAPayloadParamsImpl implements _OCAPayloadParams { + const _$OCAPayloadParamsImpl( + {required final List chains, + required this.domain, + required this.nonce, + required this.aud, + required this.type, + required this.version, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _chains = chains, + _resources = resources; + + factory _$OCAPayloadParamsImpl.fromJson(Map json) => + _$$OCAPayloadParamsImplFromJson(json); + + final List _chains; + @override + List get chains { + if (_chains is EqualUnmodifiableListView) return _chains; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_chains); + } + + @override + final String domain; + @override + final String nonce; + @override + final String aud; + @override + final String type; +// + @override + final String version; + @override + final String iat; +// + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'OCAPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$OCAPayloadParamsImpl && + const DeepCollectionEquality().equals(other._chains, _chains) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.type, type) || other.type == type) && + (identical(other.version, version) || other.version == version) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_chains), + domain, + nonce, + aud, + type, + version, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => + __$$OCAPayloadParamsImplCopyWithImpl<_$OCAPayloadParamsImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$OCAPayloadParamsImplToJson( + this, + ); + } +} + +abstract class _OCAPayloadParams implements OCAPayloadParams { + const factory _OCAPayloadParams( + {required final List chains, + required final String domain, + required final String nonce, + required final String aud, + required final String type, + required final String version, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$OCAPayloadParamsImpl; + + factory _OCAPayloadParams.fromJson(Map json) = + _$OCAPayloadParamsImpl.fromJson; + + @override + List get chains; + @override + String get domain; + @override + String get nonce; + @override + String get aud; + @override + String get type; + @override // + String get version; + @override + String get iat; + @override // + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/ocauth_models.g.dart b/lib/apis/sign_api/models/auth/ocauth_models.g.dart new file mode 100644 index 00000000..a808b9b6 --- /dev/null +++ b/lib/apis/sign_api/models/auth/ocauth_models.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'ocauth_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$OCAPayloadParamsImpl _$$OCAPayloadParamsImplFromJson( + Map json) => + _$OCAPayloadParamsImpl( + chains: + (json['chains'] as List).map((e) => e as String).toList(), + domain: json['domain'] as String, + nonce: json['nonce'] as String, + aud: json['aud'] as String, + type: json['type'] as String, + version: json['version'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$OCAPayloadParamsImplToJson( + _$OCAPayloadParamsImpl instance) { + final val = { + 'chains': instance.chains, + 'domain': instance.domain, + 'nonce': instance.nonce, + 'aud': instance.aud, + 'type': instance.type, + 'version': instance.version, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 9464f40c..e03a3266 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -88,7 +88,7 @@ class SignEngine implements ISignEngine { final Event onOCAuthResponse = Event(); // FORMER AUTH ENGINE PROPERTY (apparently not used befor and not used now) - // List pendingAuthRequests = []; + List pendingAuthRequests = []; SignEngine({ required this.core, diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index eabcccd1..de642765 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -5,7 +5,7 @@ import 'package:http/http.dart' as http; import 'package:pointycastle/digests/keccak.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; import 'package:web3dart/crypto.dart' as crypto; diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index 73fcbeec..fc6af0b0 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -33,22 +33,17 @@ export 'apis/sign_api/models/session_models.dart'; export 'apis/sign_api/models/json_rpc_models.dart'; export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; - -// Auth API +// Former Auth API export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/auth_client_models.dart'; -export 'apis/sign_api/models/auth/auth_common_models.dart'; +export 'apis/sign_api/models/auth/common_auth_models.dart'; export 'apis/sign_api/models/auth/json_rpc_models.dart'; -export 'apis/sign_api/models/auth/one_click_auth_events.dart'; -export 'apis/sign_api/models/auth/one_click_auth_models.dart'; +export 'apis/sign_api/models/auth/ocauth_events.dart'; +export 'apis/sign_api/models/auth/ocauth_models.dart'; export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; export 'apis/sign_api/utils/auth/auth_api_validators.dart'; -// export 'apis/auth_api/i_auth_engine.dart'; -// export 'apis/auth_api/auth_engine.dart'; -// export 'apis/auth_api/i_auth_client.dart'; -// export 'apis/auth_api/auth_client.dart'; // Web3Wallet export 'apis/web3wallet/i_web3wallet.dart'; diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index 0b09b4c7..f757f548 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_common_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import '../../shared/shared_test_values.dart'; From 2dec71b63f949b7ea662a9d6b8676536ba6902f8 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 11 Jun 2024 18:49:06 +0200 Subject: [PATCH 16/29] renabled authegine for backward compatibility --- lib/apis/auth_api/auth_client.dart | 2 - lib/apis/auth_api/auth_engine.dart | 1 - lib/apis/auth_api/i_auth_client.dart | 1 - lib/apis/sign_api/sign_engine.dart | 88 +- lib/apis/web3app/i_web3app.dart | 5 +- lib/apis/web3app/web3app.dart | 34 +- lib/apis/web3wallet/i_web3wallet.dart | 5 +- lib/apis/web3wallet/web3wallet.dart | 59 +- lib/walletconnect_flutter_v2.dart | 14 +- test/auth_api/auth_client_test.dart | 984 +++++++++--------- .../utils/auth_client_test_wrapper.dart | 287 ++--- test/auth_api/utils/signature_constants.dart | 2 +- 12 files changed, 764 insertions(+), 718 deletions(-) diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index e7b89e0a..b77d7411 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,6 +1,4 @@ import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index 8380902a..b4b74b6e 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -1,6 +1,5 @@ import 'dart:async'; -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; diff --git a/lib/apis/auth_api/i_auth_client.dart b/lib/apis/auth_api/i_auth_client.dart index 758f6b84..100fcd26 100644 --- a/lib/apis/auth_api/i_auth_client.dart +++ b/lib/apis/auth_api/i_auth_client.dart @@ -1,4 +1,3 @@ -import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index e03a3266..0da5e2ee 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -968,11 +968,11 @@ class SignEngine implements ISignEngine { type: ProtocolType.sign, ); // FORMER AUTH ENGINE PROPERTY - core.pairing.register( - method: MethodConstants.WC_AUTH_REQUEST, - function: _onAuthRequest, - type: ProtocolType.auth, - ); + // core.pairing.register( + // method: MethodConstants.WC_AUTH_REQUEST, + // function: _onAuthRequest, + // type: ProtocolType.auth, + // ); // TODO on following PR to be used by Wallet core.pairing.register( method: MethodConstants.WC_SESSION_AUTHENTICATE, @@ -2452,45 +2452,45 @@ class SignEngine implements ISignEngine { } } - // FORMER AUTH ENGINE PROPERTY - void _onAuthRequest(String topic, JsonRpcRequest payload) async { - try { - final request = WcAuthRequestRequest.fromJson(payload.params); - - final CacaoRequestPayload cacaoPayload = - CacaoRequestPayload.fromPayloadParams( - request.payloadParams, - ); - - authRequests.set( - payload.id.toString(), - PendingAuthRequest( - id: payload.id, - pairingTopic: topic, - metadata: request.requester, - cacaoPayload: cacaoPayload, - ), - ); - - onAuthRequest.broadcast( - AuthRequest( - id: payload.id, - topic: topic, - requester: request.requester, - payloadParams: request.payloadParams, - ), - ); - } on WalletConnectError catch (err) { - await core.pairing.sendError( - payload.id, - topic, - payload.method, - JsonRpcError.invalidParams( - err.message, - ), - ); - } - } + // // FORMER AUTH ENGINE PROPERTY + // void _onAuthRequest(String topic, JsonRpcRequest payload) async { + // try { + // final request = WcAuthRequestRequest.fromJson(payload.params); + + // final CacaoRequestPayload cacaoPayload = + // CacaoRequestPayload.fromPayloadParams( + // request.payloadParams, + // ); + + // authRequests.set( + // payload.id.toString(), + // PendingAuthRequest( + // id: payload.id, + // pairingTopic: topic, + // metadata: request.requester, + // cacaoPayload: cacaoPayload, + // ), + // ); + + // onAuthRequest.broadcast( + // AuthRequest( + // id: payload.id, + // topic: topic, + // requester: request.requester, + // payloadParams: request.payloadParams, + // ), + // ); + // } on WalletConnectError catch (err) { + // await core.pairing.sendError( + // payload.id, + // topic, + // payload.method, + // JsonRpcError.invalidParams( + // err.message, + // ), + // ); + // } + // } // TODO void _onOCARequest(String topic, JsonRpcRequest payload) async { diff --git a/lib/apis/web3app/i_web3app.dart b/lib/apis/web3app/i_web3app.dart index 3394a3bf..4e8b9f2f 100644 --- a/lib/apis/web3app/i_web3app.dart +++ b/lib/apis/web3app/i_web3app.dart @@ -1,9 +1,12 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine_app.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -abstract class IWeb3App implements ISignEngineApp { +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_app.dart'; + +abstract class IWeb3App implements ISignEngineApp, IAuthEngineApp { final String protocol = 'wc'; final int version = 2; abstract final ISignEngine signEngine; + abstract final IAuthEngine authEngine; } diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index eb33a051..c51b842b 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -1,3 +1,4 @@ +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; @@ -117,6 +118,15 @@ class Web3App implements IWeb3App { }, ), ); + + authEngine = AuthEngine( + core: core, + metadata: metadata, + authKeys: signEngine.authKeys, + pairingTopics: signEngine.pairingTopics, + authRequests: signEngine.authRequests, + completeRequests: signEngine.completeRequests, + ); } @override @@ -127,6 +137,7 @@ class Web3App implements IWeb3App { await core.start(); await signEngine.init(); + await authEngine.init(); _initialized = true; } @@ -328,19 +339,24 @@ class Web3App implements IWeb3App { ///---------- AUTH ENGINE ----------/// @override - Event get onAuthResponse => signEngine.onAuthResponse; - - // NEW 1-CLICK AUTH METHOD + Event get onAuthResponse => authEngine.onAuthResponse; @override Event get onOCAuthResponse => signEngine.onOCAuthResponse; @override - IGenericStore get authKeys => signEngine.authKeys; + IGenericStore get authKeys => authEngine.authKeys; @override - IGenericStore get pairingTopics => signEngine.pairingTopics; + IGenericStore get pairingTopics => authEngine.pairingTopics; @override IGenericStore get completeRequests => - signEngine.completeRequests; + authEngine.completeRequests; + + @Deprecated( + 'AuthEngine/AuthClient is deprecated and will be removed soon.\n' + 'Please use authentication methods from SignEngine/SignClient instead', + ) + @override + late IAuthEngine authEngine; @override Future requestAuth({ @@ -349,7 +365,7 @@ class Web3App implements IWeb3App { List>? methods = DEFAULT_METHODS, }) async { try { - return signEngine.requestAuth( + return authEngine.requestAuth( params: params, pairingTopic: pairingTopic, methods: methods, @@ -384,7 +400,7 @@ class Web3App implements IWeb3App { required String pairingTopic, }) { try { - return signEngine.getCompletedRequestsForPairing( + return authEngine.getCompletedRequestsForPairing( pairingTopic: pairingTopic, ); } catch (e) { @@ -413,7 +429,7 @@ class Web3App implements IWeb3App { required CacaoRequestPayload cacaoPayload, }) { try { - return signEngine.formatAuthMessage( + return authEngine.formatAuthMessage( iss: iss, cacaoPayload: cacaoPayload, ); diff --git a/lib/apis/web3wallet/i_web3wallet.dart b/lib/apis/web3wallet/i_web3wallet.dart index 2f7308ec..86b07a66 100644 --- a/lib/apis/web3wallet/i_web3wallet.dart +++ b/lib/apis/web3wallet/i_web3wallet.dart @@ -1,9 +1,12 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/i_sign_engine_wallet.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -abstract class IWeb3Wallet implements ISignEngineWallet { +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_wallet.dart'; + +abstract class IWeb3Wallet implements ISignEngineWallet, IAuthEngineWallet { final String protocol = 'wc'; final int version = 2; abstract final ISignEngine signEngine; + abstract final IAuthEngine authEngine; } diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index ca3e516f..08719d91 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -1,3 +1,4 @@ +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; @@ -110,6 +111,15 @@ class Web3Wallet implements IWeb3Wallet { }, ), ); + + authEngine = AuthEngine( + core: core, + metadata: metadata, + authKeys: signEngine.authKeys, + pairingTopics: signEngine.pairingTopics, + authRequests: signEngine.authRequests, + completeRequests: signEngine.completeRequests, + ); } @override @@ -120,6 +130,7 @@ class Web3Wallet implements IWeb3Wallet { await core.start(); await signEngine.init(); + await authEngine.init(); _initialized = true; } @@ -380,17 +391,24 @@ class Web3Wallet implements IWeb3Wallet { ///---------- AUTH ENGINE ----------/// @override - Event get onAuthRequest => signEngine.onAuthRequest; + Event get onAuthRequest => authEngine.onAuthRequest; @override - IGenericStore get authKeys => signEngine.authKeys; + IGenericStore get authKeys => authEngine.authKeys; @override - IGenericStore get pairingTopics => signEngine.pairingTopics; + IGenericStore get pairingTopics => authEngine.pairingTopics; @override - IGenericStore get authRequests => signEngine.authRequests; + IGenericStore get authRequests => authEngine.authRequests; @override IGenericStore get completeRequests => - signEngine.completeRequests; + authEngine.completeRequests; + + @Deprecated( + 'AuthEngine/AuthClient is deprecated and will be removed soon.\n' + 'Please use authentication methods from SignEngine/SignClient instead', + ) + @override + late IAuthEngine authEngine; @override Future respondAuthRequest({ @@ -400,7 +418,7 @@ class Web3Wallet implements IWeb3Wallet { WalletConnectError? error, }) async { try { - return signEngine.respondAuthRequest( + return authEngine.respondAuthRequest( id: id, iss: iss, signature: signature, @@ -414,7 +432,7 @@ class Web3Wallet implements IWeb3Wallet { @override Map getPendingAuthRequests() { try { - return signEngine.getPendingAuthRequests(); + return authEngine.getPendingAuthRequests(); } catch (e) { rethrow; } @@ -425,7 +443,7 @@ class Web3Wallet implements IWeb3Wallet { required String pairingTopic, }) { try { - return signEngine.getCompletedRequestsForPairing( + return authEngine.getCompletedRequestsForPairing( pairingTopic: pairingTopic, ); } catch (e) { @@ -434,30 +452,29 @@ class Web3Wallet implements IWeb3Wallet { } @override - Future validateSignedCacao({ - required Cacao cacao, - required String projectId, + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, }) { try { - return signEngine.validateSignedCacao( - cacao: cacao, - projectId: projectId, + return authEngine.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, ); } catch (e) { rethrow; } } - /// format payload to message string before signing @override - String formatAuthMessage({ - required String iss, - required CacaoRequestPayload cacaoPayload, + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, }) { try { - return signEngine.formatAuthMessage( - iss: iss, - cacaoPayload: cacaoPayload, + return signEngine.validateSignedCacao( + cacao: cacao, + projectId: projectId, ); } catch (e) { rethrow; diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index fc6af0b0..ed86fded 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -34,8 +34,8 @@ export 'apis/sign_api/models/json_rpc_models.dart'; export 'apis/sign_api/models/sign_client_models.dart'; export 'apis/sign_api/models/sign_client_events.dart'; // Former Auth API -export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/auth_client_models.dart'; +export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/common_auth_models.dart'; export 'apis/sign_api/models/auth/json_rpc_models.dart'; export 'apis/sign_api/models/auth/ocauth_events.dart'; @@ -45,6 +45,18 @@ export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; export 'apis/sign_api/utils/auth/auth_api_validators.dart'; +// Auth API +// export 'apis/auth_api/models/auth_client_models.dart'; +// export 'apis/auth_api/models/auth_client_events.dart'; +// export 'apis/auth_api/models/json_rpc_models.dart'; +// export 'apis/auth_api/utils/auth_utils.dart'; +// export 'apis/auth_api/utils/address_utils.dart'; +// export 'apis/auth_api/utils/auth_signature.dart'; +// export 'apis/auth_api/utils/auth_api_validators.dart'; +export 'apis/auth_api/i_auth_engine.dart'; +export 'apis/auth_api/i_auth_client.dart'; +export 'apis/auth_api/auth_client.dart'; + // Web3Wallet export 'apis/web3wallet/i_web3wallet.dart'; export 'apis/web3wallet/web3wallet.dart'; diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index 831aff17..2333782d 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -1,496 +1,494 @@ -// import 'dart:async'; -// import 'dart:typed_data'; - -// import 'package:eth_sig_util/eth_sig_util.dart'; -// import 'package:flutter_test/flutter_test.dart'; -// import 'package:package_info_plus/package_info_plus.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'; - -// import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; -// import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -// import '../shared/shared_test_utils.dart'; -// import '../shared/shared_test_values.dart'; -// import 'utils/auth_client_test_wrapper.dart'; -// import 'utils/engine_constants.dart'; -// import 'utils/signature_constants.dart'; +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:eth_sig_util/eth_sig_util.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:package_info_plus/package_info_plus.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'; +import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; + +import '../shared/shared_test_utils.dart'; +import '../shared/shared_test_values.dart'; +import 'utils/auth_client_test_wrapper.dart'; +import 'utils/engine_constants.dart'; +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', -// ); - -// final List Function(PairingMetadata)> authAppCreators = -// [ -// (PairingMetadata metadata) async => -// await AuthClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// (PairingMetadata? self) async { -// final core = Core( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ); -// IAuthEngine e = AuthEngine( -// core: core, -// metadata: self ?? PairingMetadata.empty(), -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// await core.start(); -// await e.init(); - -// return e; -// }, -// (PairingMetadata metadata) async => -// await AuthClientTestWrapper.createInstance( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// metadata: metadata, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ), -// ]; - -// final List Function(PairingMetadata)> -// authWalletCreators = [ -// // (PairingMetadata metadata) async => await Web3Wallet.createInstance( -// // projectId: TEST_PROJECT_ID, -// // relayUrl: TEST_RELAY_URL, -// // metadata: metadata, -// // memoryStore: true, -// // logLevel: LogLevel.info, -// // httpClient: getHttpWrapper(), -// // ), -// (PairingMetadata metadata) async { -// final core = Core( -// projectId: TEST_PROJECT_ID, -// relayUrl: TEST_RELAY_URL, -// memoryStore: true, -// logLevel: LogLevel.info, -// httpClient: getHttpWrapper(), -// ); -// IAuthEngine e = AuthEngine( -// core: core, -// metadata: metadata, -// authKeys: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_KEYS, -// version: StoreVersions.VERSION_AUTH_KEYS, -// fromJson: (dynamic value) { -// return AuthPublicKey.fromJson(value); -// }, -// ), -// pairingTopics: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_PAIRING_TOPICS, -// version: StoreVersions.VERSION_PAIRING_TOPICS, -// fromJson: (dynamic value) { -// return value; -// }, -// ), -// authRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_AUTH_REQUESTS, -// version: StoreVersions.VERSION_AUTH_REQUESTS, -// fromJson: (dynamic value) { -// return PendingAuthRequest.fromJson(value); -// }, -// ), -// completeRequests: GenericStore( -// storage: core.storage, -// context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, -// version: StoreVersions.VERSION_COMPLETE_REQUESTS, -// fromJson: (dynamic value) { -// return StoredCacao.fromJson(value); -// }, -// ), -// ); -// await core.start(); -// await e.init(); - -// return e; -// }, -// // (PairingMetadata metadata) async => await Web3Wallet.createInstance( -// // projectId: TEST_PROJECT_ID, -// // relayUrl: TEST_RELAY_URL, -// // metadata: metadata, -// // memoryStore: true, -// // logLevel: LogLevel.info, -// // httpClient: getHttpWrapper(), -// // ), -// ]; - -// final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; - -// for (int i = 0; i < authAppCreators.length; i++) { -// runTests( -// context: contexts[i], -// engineAppCreator: authAppCreators[i], -// engineWalletCreator: authWalletCreators[i], -// ); -// } -// } - -// void runTests({ -// required String context, -// required Future Function(PairingMetadata) engineAppCreator, -// required Future Function(PairingMetadata) -// engineWalletCreator, -// }) { -// group(context, () { -// late IAuthEngineApp clientA; -// late IAuthEngineWallet clientB; - -// setUp(() async { -// clientA = await engineAppCreator( -// TEST_METADATA_REQUESTER, -// ); -// clientB = await engineWalletCreator( -// TEST_METADATA_RESPONDER, -// ); -// }); - -// tearDown(() async { -// await clientA.core.relayClient.disconnect(); -// await clientB.core.relayClient.disconnect(); -// }); - -// group('happy path', () { -// test('Initializes', () async { -// expect(clientA.core.pairing.getPairings().length, 0); -// expect(clientB.core.pairing.getPairings().length, 0); -// }); - -// test( -// 'connects and receives request, reconnects and receives another request, and emits proper events', -// () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: defaultRequestParams, -// ); -// final String pairingTopic = response.pairingTopic; - -// Completer completerAPairing = Completer(); -// Completer completerBPairing = Completer(); -// Completer completerA = Completer(); -// Completer completerB = Completer(); -// int counterAPairing = 0; -// int counterBPairing = 0; -// int counterA = 0; -// int counterB = 0; -// clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { -// expect(pairing != null, true); -// expect(pairing!.topic, pairingTopic); -// counterAPairing++; -// completerAPairing.complete(); -// }); -// clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { -// expect(pairing != null, true); -// expect(pairing!.topic, pairingTopic); -// counterBPairing++; -// completerBPairing.complete(); -// }); -// clientA.onAuthResponse.subscribe((AuthResponse? args) { -// counterA++; -// completerA.complete(); - -// expect(args!.result, isNotNull); -// }); -// clientB.onAuthRequest.subscribe((AuthRequest? args) async { -// counterB++; - -// int currReqCount = clientB.getPendingAuthRequests().length; - -// expect(args != null, true); - -// // Create the message to be signed -// String message = clientB.formatAuthMessage( -// iss: TEST_ISSUER_EIP191, -// cacaoPayload: CacaoRequestPayload.fromPayloadParams( -// args!.payloadParams, -// ), -// ); - -// String sig = EthSigUtil.signPersonalMessage( -// message: Uint8List.fromList(message.codeUnits), -// privateKey: TEST_PRIVATE_KEY_EIP191, -// ); - -// await clientB.respondAuthRequest( -// id: args.id, -// iss: TEST_ISSUER_EIP191, -// signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), -// ); - -// expect(clientB.getPendingAuthRequests().length, currReqCount - 1); - -// completerB.complete(); -// }); - -// expect(response.uri != null, true); - -// await clientB.core.pairing.pair(uri: response.uri!); -// expect(clientA.core.pairing.getPairings().length, 1); -// expect(clientB.core.pairing.getPairings().length, 1); -// // AuthResponse authResponse = await response.completer.future; - -// await clientA.core.pairing.ping(topic: pairingTopic); -// await clientB.core.pairing.ping(topic: pairingTopic); - -// if (!completerAPairing.isCompleted) { -// clientA.core.logger.i('Waiting for completerAPairing'); -// await completerAPairing.future; -// } -// if (!completerBPairing.isCompleted) { -// clientA.core.logger.i('Waiting for completerBPairing'); -// await completerBPairing.future; -// } -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } -// if (!completerB.isCompleted) { -// clientA.core.logger.i('Waiting for completerB'); -// await completerB.future; -// } - -// AuthResponse authResponse = await response.completer.future; -// expect(authResponse.result != null, true); - -// expect(counterAPairing, 1); -// expect(counterBPairing, 1); - -// expect(counterA, 1); -// expect(counterB, 1); - -// expect( -// clientA -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 1, -// ); -// expect( -// clientB -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 1, -// ); - -// completerA = Completer(); -// completerB = Completer(); - -// response = await clientA.requestAuth( -// params: defaultRequestParams, -// pairingTopic: pairingTopic, -// ); - -// expect(response.uri == null, true); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } -// if (!completerB.isCompleted) { -// clientA.core.logger.i('Waiting for completerB'); -// await completerB.future; -// } - -// authResponse = await response.completer.future; -// expect(authResponse.result != null, true); - -// // Got the second request and response -// expect(counterA, 2); -// expect(counterB, 2); - -// expect( -// clientA -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 2, -// ); -// expect( -// clientB -// .getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ) -// .length, -// 2, -// ); - -// clientA.onAuthResponse.unsubscribeAll(); -// clientB.onAuthRequest.unsubscribeAll(); -// clientA.core.pairing.onPairingPing.unsubscribeAll(); -// clientB.core.pairing.onPairingPing.unsubscribeAll(); -// }); - -// test('counts pendingAuthRequests properly', () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: defaultRequestParams, -// ); -// final String pairingTopic = response.pairingTopic; - -// await clientB.core.pairing.pair(uri: response.uri!); - -// Completer completerA = Completer(); -// clientB.onAuthRequest.subscribe((AuthRequest? args) async { -// // print('got here'); -// // print(clientB.getPendingAuthRequests().length); -// completerA.complete(); -// }); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } - -// expect(clientB.getPendingAuthRequests().length, 1); - -// completerA = Completer(); - -// response = await clientA.requestAuth( -// params: defaultRequestParams, -// pairingTopic: pairingTopic, -// ); - -// if (!completerA.isCompleted) { -// clientA.core.logger.i('Waiting for completerA'); -// await completerA.future; -// } - -// expect(clientB.getPendingAuthRequests().length, 2); -// }); -// }); - -// group('requestAuth', () { -// test('creates correct URI', () async { -// AuthRequestResponse response = await clientA.requestAuth( -// params: testAuthRequestParamsValid, -// ); - -// expect(response.uri != null, true); -// URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); -// expect(parsed.protocol, 'wc'); -// expect(parsed.version, URIVersion.v2); -// expect(parsed.topic, response.pairingTopic); -// expect(parsed.v2Data!.relay.protocol, 'irn'); -// if (clientA is IWeb3App) { -// expect(parsed.v2Data!.methods.length, 3); -// expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); -// expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); -// expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); -// } else { -// expect(parsed.v2Data!.methods.length, 1); -// expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); -// } - -// response = await clientA.requestAuth( -// params: testAuthRequestParamsValid, -// methods: [], -// ); - -// expect(response.uri != null, true); -// parsed = WalletConnectUtils.parseUri(response.uri!); -// expect(parsed.protocol, 'wc'); -// expect(parsed.version, URIVersion.v2); -// expect(parsed.v2Data!.relay.protocol, 'irn'); -// expect(parsed.v2Data!.methods.length, 0); -// }); - -// test('invalid request params', () async { -// expect( -// () => clientA.requestAuth( -// params: testAuthRequestParamsInvalidAud, -// ), -// throwsA( -// isA().having( -// (e) => e.message, -// 'message', -// 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', -// ), -// ), -// ); -// }); -// }); - -// group('respondAuth', () { -// test('invalid response params', () async { -// expect( -// () => clientB.respondAuthRequest( -// id: -1, -// iss: TEST_ISSUER_EIP191, -// ), -// throwsA( -// isA().having( -// (e) => e.message, -// 'message', -// 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', -// ), -// ), -// ); -// }); -// }); - -// group('formatAuthMessage', () { -// test('works', () { -// final String message = clientA.formatAuthMessage( -// iss: TEST_ISSUER_EIP191, -// cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), -// ); -// expect(message, TEST_FORMATTED_MESSAGE); -// }); -// }); -// }); + TestWidgetsFlutterBinding.ensureInitialized(); + PackageInfo.setMockInitialValues( + appName: 'walletconnect_flutter_v2', + packageName: 'com.walletconnect.flutterdapp', + version: '1.0', + buildNumber: '2', + buildSignature: 'buildSignature', + ); + + final List Function(PairingMetadata)> authAppCreators = + [ + (PairingMetadata metadata) async => + await AuthClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + (PairingMetadata? self) async { + final core = Core( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ); + IAuthEngine e = AuthEngine( + core: core, + metadata: self ?? PairingMetadata.empty(), + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + await core.start(); + await e.init(); + + return e; + }, + (PairingMetadata metadata) async => + await AuthClientTestWrapper.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + ]; + + final List Function(PairingMetadata)> + authWalletCreators = [ + (PairingMetadata metadata) async => await Web3Wallet.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + (PairingMetadata metadata) async { + final core = Core( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ); + IAuthEngine e = AuthEngine( + core: core, + metadata: metadata, + authKeys: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_KEYS, + version: StoreVersions.VERSION_AUTH_KEYS, + fromJson: (dynamic value) { + return AuthPublicKey.fromJson(value); + }, + ), + pairingTopics: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_PAIRING_TOPICS, + version: StoreVersions.VERSION_PAIRING_TOPICS, + fromJson: (dynamic value) { + return value; + }, + ), + authRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingAuthRequest.fromJson(value); + }, + ), + completeRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_COMPLETE_REQUESTS, + version: StoreVersions.VERSION_COMPLETE_REQUESTS, + fromJson: (dynamic value) { + return StoredCacao.fromJson(value); + }, + ), + ); + await core.start(); + await e.init(); + + return e; + }, + (PairingMetadata metadata) async => await Web3Wallet.createInstance( + projectId: TEST_PROJECT_ID, + relayUrl: TEST_RELAY_URL, + metadata: metadata, + memoryStore: true, + logLevel: LogLevel.info, + httpClient: getHttpWrapper(), + ), + ]; + + final List contexts = ['AuthClient', 'AuthEngine', 'Web3App/Wallet']; + + for (int i = 0; i < authAppCreators.length; i++) { + runTests( + context: contexts[i], + engineAppCreator: authAppCreators[i], + engineWalletCreator: authWalletCreators[i], + ); + } +} + +void runTests({ + required String context, + required Future Function(PairingMetadata) engineAppCreator, + required Future Function(PairingMetadata) + engineWalletCreator, +}) { + group(context, () { + late IAuthEngineApp clientA; + late IAuthEngineWallet clientB; + + setUp(() async { + clientA = await engineAppCreator( + TEST_METADATA_REQUESTER, + ); + clientB = await engineWalletCreator( + TEST_METADATA_RESPONDER, + ); + }); + + tearDown(() async { + await clientA.core.relayClient.disconnect(); + await clientB.core.relayClient.disconnect(); + }); + + group('happy path', () { + test('Initializes', () async { + expect(clientA.core.pairing.getPairings().length, 0); + expect(clientB.core.pairing.getPairings().length, 0); + }); + + test( + 'connects and receives request, reconnects and receives another request, and emits proper events', + () async { + AuthRequestResponse response = await clientA.requestAuth( + params: defaultRequestParams, + ); + final String pairingTopic = response.pairingTopic; + + Completer completerAPairing = Completer(); + Completer completerBPairing = Completer(); + Completer completerA = Completer(); + Completer completerB = Completer(); + int counterAPairing = 0; + int counterBPairing = 0; + int counterA = 0; + int counterB = 0; + clientA.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { + expect(pairing != null, true); + expect(pairing!.topic, pairingTopic); + counterAPairing++; + completerAPairing.complete(); + }); + clientB.core.pairing.onPairingPing.subscribe((PairingEvent? pairing) { + expect(pairing != null, true); + expect(pairing!.topic, pairingTopic); + counterBPairing++; + completerBPairing.complete(); + }); + clientA.onAuthResponse.subscribe((AuthResponse? args) { + counterA++; + completerA.complete(); + + expect(args!.result, isNotNull); + }); + clientB.onAuthRequest.subscribe((AuthRequest? args) async { + counterB++; + + int currReqCount = clientB.getPendingAuthRequests().length; + + expect(args != null, true); + + // Create the message to be signed + String message = clientB.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromPayloadParams( + args!.payloadParams, + ), + ); + + String sig = EthSigUtil.signPersonalMessage( + message: Uint8List.fromList(message.codeUnits), + privateKey: TEST_PRIVATE_KEY_EIP191, + ); + + await clientB.respondAuthRequest( + id: args.id, + iss: TEST_ISSUER_EIP191, + signature: CacaoSignature(t: CacaoSignature.EIP191, s: sig), + ); + + expect(clientB.getPendingAuthRequests().length, currReqCount - 1); + + completerB.complete(); + }); + + expect(response.uri != null, true); + + await clientB.core.pairing.pair(uri: response.uri!); + expect(clientA.core.pairing.getPairings().length, 1); + expect(clientB.core.pairing.getPairings().length, 1); + // AuthResponse authResponse = await response.completer.future; + + await clientA.core.pairing.ping(topic: pairingTopic); + await clientB.core.pairing.ping(topic: pairingTopic); + + if (!completerAPairing.isCompleted) { + clientA.core.logger.i('Waiting for completerAPairing'); + await completerAPairing.future; + } + if (!completerBPairing.isCompleted) { + clientA.core.logger.i('Waiting for completerBPairing'); + await completerBPairing.future; + } + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + if (!completerB.isCompleted) { + clientA.core.logger.i('Waiting for completerB'); + await completerB.future; + } + + AuthResponse authResponse = await response.completer.future; + expect(authResponse.result != null, true); + + expect(counterAPairing, 1); + expect(counterBPairing, 1); + + expect(counterA, 1); + expect(counterB, 1); + + expect( + clientA + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 1, + ); + expect( + clientB + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 1, + ); + + completerA = Completer(); + completerB = Completer(); + + response = await clientA.requestAuth( + params: defaultRequestParams, + pairingTopic: pairingTopic, + ); + + expect(response.uri == null, true); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + if (!completerB.isCompleted) { + clientA.core.logger.i('Waiting for completerB'); + await completerB.future; + } + + authResponse = await response.completer.future; + expect(authResponse.result != null, true); + + // Got the second request and response + expect(counterA, 2); + expect(counterB, 2); + + expect( + clientA + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 2, + ); + expect( + clientB + .getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ) + .length, + 2, + ); + + clientA.onAuthResponse.unsubscribeAll(); + clientB.onAuthRequest.unsubscribeAll(); + clientA.core.pairing.onPairingPing.unsubscribeAll(); + clientB.core.pairing.onPairingPing.unsubscribeAll(); + }); + + test('counts pendingAuthRequests properly', () async { + AuthRequestResponse response = await clientA.requestAuth( + params: defaultRequestParams, + ); + final String pairingTopic = response.pairingTopic; + + await clientB.core.pairing.pair(uri: response.uri!); + + Completer completerA = Completer(); + clientB.onAuthRequest.subscribe((AuthRequest? args) async { + // print('got here'); + // print(clientB.getPendingAuthRequests().length); + completerA.complete(); + }); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + + expect(clientB.getPendingAuthRequests().length, 1); + + completerA = Completer(); + + response = await clientA.requestAuth( + params: defaultRequestParams, + pairingTopic: pairingTopic, + ); + + if (!completerA.isCompleted) { + clientA.core.logger.i('Waiting for completerA'); + await completerA.future; + } + + expect(clientB.getPendingAuthRequests().length, 2); + }); + }); + + group('requestAuth', () { + test('creates correct URI', () async { + AuthRequestResponse response = await clientA.requestAuth( + params: testAuthRequestParamsValid, + ); + + expect(response.uri != null, true); + URIParseResult parsed = WalletConnectUtils.parseUri(response.uri!); + expect(parsed.protocol, 'wc'); + expect(parsed.version, URIVersion.v2); + expect(parsed.topic, response.pairingTopic); + expect(parsed.v2Data!.relay.protocol, 'irn'); + if (clientA is IWeb3App) { + expect(parsed.v2Data!.methods.length, 3); + expect(parsed.v2Data!.methods[0], MethodConstants.WC_SESSION_PROPOSE); + expect(parsed.v2Data!.methods[1], MethodConstants.WC_SESSION_REQUEST); + expect(parsed.v2Data!.methods[2], MethodConstants.WC_AUTH_REQUEST); + } else { + expect(parsed.v2Data!.methods.length, 1); + expect(parsed.v2Data!.methods[0], MethodConstants.WC_AUTH_REQUEST); + } + + response = await clientA.requestAuth( + params: testAuthRequestParamsValid, + methods: [], + ); + + expect(response.uri != null, true); + parsed = WalletConnectUtils.parseUri(response.uri!); + expect(parsed.protocol, 'wc'); + expect(parsed.version, URIVersion.v2); + expect(parsed.v2Data!.relay.protocol, 'irn'); + expect(parsed.v2Data!.methods.length, 0); + }); + + test('invalid request params', () async { + expect( + () => clientA.requestAuth( + params: testAuthRequestParamsInvalidAud, + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Missing or invalid. requestAuth() invalid aud: ${testAuthRequestParamsInvalidAud.aud}. Must be a valid url.', + ), + ), + ); + }); + }); + + group('respondAuth', () { + test('invalid response params', () async { + expect( + () => clientB.respondAuthRequest( + id: -1, + iss: TEST_ISSUER_EIP191, + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Missing or invalid. respondAuth() invalid id: -1. No pending request found.', + ), + ), + ); + }); + }); + + group('formatAuthMessage', () { + test('works', () { + final String message = clientA.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromCacaoPayload(testCacaoPayload), + ); + expect(message, TEST_FORMATTED_MESSAGE); + }); + }); + }); } diff --git a/test/auth_api/utils/auth_client_test_wrapper.dart b/test/auth_api/utils/auth_client_test_wrapper.dart index 44766385..d0aa1c3a 100644 --- a/test/auth_api/utils/auth_client_test_wrapper.dart +++ b/test/auth_api/utils/auth_client_test_wrapper.dart @@ -1,158 +1,159 @@ -// import 'package:event/event.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/core.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -// import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; -// import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; -// import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; +import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/core/core.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; +import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; -// class AuthClientTestWrapper implements IAuthEngine { -// bool _initialized = false; +class AuthClientTestWrapper implements IAuthEngine { + bool _initialized = false; -// @override -// Event get onAuthRequest => client.onAuthRequest; -// @override -// Event get onAuthResponse => client.onAuthResponse; + @override + Event get onAuthRequest => client.onAuthRequest; + @override + Event get onAuthResponse => client.onAuthResponse; -// @override -// ICore get core => client.core; -// @override -// PairingMetadata get metadata => client.metadata; -// @override -// IGenericStore get authKeys => client.authKeys; -// @override -// IGenericStore get pairingTopics => client.pairingTopics; -// @override -// IGenericStore get authRequests => client.authRequests; -// @override -// IGenericStore get completeRequests => client.completeRequests; + @override + ICore get core => client.core; + @override + PairingMetadata get metadata => client.metadata; + @override + IGenericStore get authKeys => client.authKeys; + @override + IGenericStore get pairingTopics => client.pairingTopics; + @override + IGenericStore get authRequests => client.authRequests; + @override + IGenericStore get completeRequests => client.completeRequests; -// late IAuthClient client; + late IAuthClient client; -// static Future createInstance({ -// required String projectId, -// String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, -// required PairingMetadata metadata, -// bool memoryStore = false, -// LogLevel logLevel = LogLevel.nothing, -// IHttpClient httpClient = const HttpWrapper(), -// }) async { -// final client = AuthClientTestWrapper( -// core: Core( -// projectId: projectId, -// relayUrl: relayUrl, -// memoryStore: memoryStore, -// logLevel: logLevel, -// httpClient: httpClient, -// ), -// metadata: metadata, -// ); -// await client.init(); + static Future createInstance({ + required String projectId, + String relayUrl = WalletConnectConstants.DEFAULT_RELAY_URL, + required PairingMetadata metadata, + bool memoryStore = false, + LogLevel logLevel = LogLevel.nothing, + IHttpClient httpClient = const HttpWrapper(), + }) async { + final client = AuthClientTestWrapper( + core: Core( + projectId: projectId, + relayUrl: relayUrl, + memoryStore: memoryStore, + logLevel: logLevel, + httpClient: httpClient, + ), + metadata: metadata, + ); + await client.init(); -// return client; -// } + return client; + } -// AuthClientTestWrapper({ -// required ICore core, -// required PairingMetadata metadata, -// }) { -// client = AuthClient( -// core: core, -// metadata: metadata, -// ); -// } + AuthClientTestWrapper({ + required ICore core, + required PairingMetadata metadata, + }) { + client = AuthClient( + core: core, + metadata: metadata, + ); + } -// @override -// Future init() async { -// if (_initialized) { -// return; -// } + @override + Future init() async { + if (_initialized) { + return; + } -// await core.start(); -// await client.init(); + await core.start(); + await client.init(); -// _initialized = true; -// } + _initialized = true; + } -// @override -// Future requestAuth({ -// required AuthRequestParams params, -// String? pairingTopic, -// List>? methods = AuthEngine.DEFAULT_METHODS, -// }) async { -// try { -// return client.request( -// params: params, -// pairingTopic: pairingTopic, -// methods: methods, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Future requestAuth({ + required AuthRequestParams params, + String? pairingTopic, + List>? methods = AuthEngine.DEFAULT_METHODS, + }) async { + try { + return client.request( + params: params, + pairingTopic: pairingTopic, + methods: methods, + ); + } catch (e) { + rethrow; + } + } -// @override -// Future respondAuthRequest({ -// required int id, -// required String iss, -// CacaoSignature? signature, -// WalletConnectError? error, -// }) async { -// try { -// return client.respond( -// id: id, -// iss: iss, -// signature: signature, -// error: error, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Future respondAuthRequest({ + required int id, + required String iss, + CacaoSignature? signature, + WalletConnectError? error, + }) async { + try { + return client.respond( + id: id, + iss: iss, + signature: signature, + error: error, + ); + } catch (e) { + rethrow; + } + } -// @override -// Map getPendingAuthRequests() { -// try { -// return client.getPendingRequests(); -// } catch (e) { -// rethrow; -// } -// } + @override + Map getPendingAuthRequests() { + try { + return client.getPendingRequests(); + } catch (e) { + rethrow; + } + } -// @override -// Map getCompletedRequestsForPairing({ -// required String pairingTopic, -// }) { -// try { -// return client.getCompletedRequestsForPairing( -// pairingTopic: pairingTopic, -// ); -// } catch (e) { -// rethrow; -// } -// } + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return client.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } -// @override -// String formatAuthMessage({ -// required String iss, -// required CacaoRequestPayload cacaoPayload, -// }) { -// try { -// return client.formatMessage( -// iss: iss, -// cacaoPayload: cacaoPayload, -// ); -// } catch (e) { -// rethrow; -// } -// } -// } + @override + String formatAuthMessage({ + required String iss, + required CacaoRequestPayload cacaoPayload, + }) { + try { + return client.formatMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + } catch (e) { + rethrow; + } + } +} diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index f757f548..699a1170 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -1,4 +1,4 @@ -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../../shared/shared_test_values.dart'; From 397b769b0ace952de08e589106659c15077a0c7a Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 11 Jun 2024 19:50:56 +0200 Subject: [PATCH 17/29] minor changes --- lib/apis/auth_api/auth_client.dart | 13 ++- lib/apis/auth_api/auth_engine.dart | 18 ++++- lib/apis/auth_api/i_auth_engine_app.dart | 4 - lib/apis/auth_api/i_auth_engine_common.dart | 4 +- lib/apis/auth_api/i_auth_engine_wallet.dart | 6 +- lib/apis/core/pairing/pairing.dart | 11 ++- lib/apis/sign_api/i_sign_client.dart | 5 +- lib/apis/sign_api/i_sign_engine_app.dart | 4 +- lib/apis/sign_api/i_sign_engine_common.dart | 4 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 2 +- lib/apis/sign_api/sign_engine.dart | 90 ++++++++++----------- 11 files changed, 96 insertions(+), 65 deletions(-) diff --git a/lib/apis/auth_api/auth_client.dart b/lib/apis/auth_api/auth_client.dart index b77d7411..3cbfb4ea 100644 --- a/lib/apis/auth_api/auth_client.dart +++ b/lib/apis/auth_api/auth_client.dart @@ -1,9 +1,20 @@ +import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_client.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/core/core.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/relay_client/websocket/i_http_client.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/log_level.dart'; class AuthClient implements IAuthClient { bool _initialized = false; diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index b4b74b6e..d254b802 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -1,10 +1,26 @@ import 'dart:async'; +import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_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/json_rpc_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.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_api_validators.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_signature.dart'; import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; +import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; +import 'package:walletconnect_flutter_v2/apis/models/json_rpc_request.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/constants.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; +import 'package:walletconnect_flutter_v2/apis/utils/method_constants.dart'; class AuthEngine implements IAuthEngine { static const List> DEFAULT_METHODS = [ diff --git a/lib/apis/auth_api/i_auth_engine_app.dart b/lib/apis/auth_api/i_auth_engine_app.dart index 9d071ad1..c1aae64c 100644 --- a/lib/apis/auth_api/i_auth_engine_app.dart +++ b/lib/apis/auth_api/i_auth_engine_app.dart @@ -6,10 +6,6 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_m abstract class IAuthEngineApp extends IAuthEngineCommon { abstract final Event onAuthResponse; - @Deprecated( - 'AuthEngine/AuthClient is deprecated and will be removed soon. ' - 'Please use authenticate() method from SignEngine/SignClient instead', - ) Future requestAuth({ required AuthRequestParams params, String? pairingTopic, diff --git a/lib/apis/auth_api/i_auth_engine_common.dart b/lib/apis/auth_api/i_auth_engine_common.dart index 406dcd87..016b7b2f 100644 --- a/lib/apis/auth_api/i_auth_engine_common.dart +++ b/lib/apis/auth_api/i_auth_engine_common.dart @@ -1,5 +1,7 @@ +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/core/i_core.dart'; +import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; abstract class IAuthEngineCommon { abstract final ICore core; diff --git a/lib/apis/auth_api/i_auth_engine_wallet.dart b/lib/apis/auth_api/i_auth_engine_wallet.dart index fc25132a..91a2cee2 100644 --- a/lib/apis/auth_api/i_auth_engine_wallet.dart +++ b/lib/apis/auth_api/i_auth_engine_wallet.dart @@ -1,6 +1,10 @@ +import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine_common.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; abstract class IAuthEngineWallet extends IAuthEngineCommon { abstract final Event onAuthRequest; diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index c5b15ded..3926112d 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -240,10 +240,13 @@ class Pairing implements IPairing { required ProtocolType type, }) { if (routerMapRequest.containsKey(method)) { - throw const WalletConnectError( - code: -1, - message: 'Method already exists', - ); + final registered = routerMapRequest[method]; + if (registered!.type == type) { + throw const WalletConnectError( + code: -1, + message: 'Method already exists', + ); + } } routerMapRequest[method] = RegisteredFunction( diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 961ac139..3c9d4c11 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -157,8 +157,7 @@ abstract class ISignClient { required String pairingTopic, }); - // FORMER AUTH ENGINE PROPERTY WALLET - // TODO to be transformed into approveSessionAuthenticate({}) and rejectSessionAuthenticate({}) + // FORMER AUTH ENGINE PROPERTY FOR WALLET Future respondAuthRequest({ required int id, required String iss, @@ -170,7 +169,7 @@ abstract class ISignClient { // query all pending requests Map getPendingAuthRequests(); - // FORMER AUTH ENGINE METHOD DAPP + // FORMER AUTH ENGINE METHOD FOR DAPP Future requestAuth({ required AuthRequestParams params, String? pairingTopic, diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index fd462c48..86178be1 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -49,14 +49,14 @@ abstract class ISignEngineApp extends ISignEngineCommon { required String topic, }); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHOD Future requestAuth({ required AuthRequestParams params, String? pairingTopic, List>? methods, }); - // NEW 1-CA METHOD FOR DAPPS + // NEW 1-CA METHOD Future authenticate({ required OCARequestParams params, String? pairingTopic, diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index 63f7666c..69432ac0 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -40,12 +40,12 @@ abstract class ISignEngineCommon { }); Map getPendingSessionProposals(); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHOD String formatAuthMessage({ required String iss, required CacaoRequestPayload cacaoPayload, }); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHOD Map getCompletedRequestsForPairing({ required String pairingTopic, }); diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index c1ac55ba..ce249deb 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -86,13 +86,13 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // }); // FORMER AUTH ENGINE PROPERTY - // TODO to be transformed into approveSessionAuthenticate({}) and rejectSessionAuthenticate({}) Future respondAuthRequest({ required int id, required String iss, CacaoSignature? signature, WalletConnectError? error, }); + // FORMER AUTH ENGINE PROPERTY // query all pending requests Map getPendingAuthRequests(); diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 0da5e2ee..85739f6d 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -968,16 +968,16 @@ class SignEngine implements ISignEngine { type: ProtocolType.sign, ); // FORMER AUTH ENGINE PROPERTY - // core.pairing.register( - // method: MethodConstants.WC_AUTH_REQUEST, - // function: _onAuthRequest, - // type: ProtocolType.auth, - // ); + core.pairing.register( + method: MethodConstants.WC_AUTH_REQUEST, + function: _onAuthRequest, + type: ProtocolType.sign, + ); // TODO on following PR to be used by Wallet core.pairing.register( method: MethodConstants.WC_SESSION_AUTHENTICATE, function: _onOCARequest, - type: ProtocolType.auth, + type: ProtocolType.sign, ); } @@ -2452,45 +2452,45 @@ class SignEngine implements ISignEngine { } } - // // FORMER AUTH ENGINE PROPERTY - // void _onAuthRequest(String topic, JsonRpcRequest payload) async { - // try { - // final request = WcAuthRequestRequest.fromJson(payload.params); - - // final CacaoRequestPayload cacaoPayload = - // CacaoRequestPayload.fromPayloadParams( - // request.payloadParams, - // ); - - // authRequests.set( - // payload.id.toString(), - // PendingAuthRequest( - // id: payload.id, - // pairingTopic: topic, - // metadata: request.requester, - // cacaoPayload: cacaoPayload, - // ), - // ); - - // onAuthRequest.broadcast( - // AuthRequest( - // id: payload.id, - // topic: topic, - // requester: request.requester, - // payloadParams: request.payloadParams, - // ), - // ); - // } on WalletConnectError catch (err) { - // await core.pairing.sendError( - // payload.id, - // topic, - // payload.method, - // JsonRpcError.invalidParams( - // err.message, - // ), - // ); - // } - // } + // FORMER AUTH ENGINE PROPERTY + void _onAuthRequest(String topic, JsonRpcRequest payload) async { + try { + final request = WcAuthRequestRequest.fromJson(payload.params); + + final CacaoRequestPayload cacaoPayload = + CacaoRequestPayload.fromPayloadParams( + request.payloadParams, + ); + + authRequests.set( + payload.id.toString(), + PendingAuthRequest( + id: payload.id, + pairingTopic: topic, + metadata: request.requester, + cacaoPayload: cacaoPayload, + ), + ); + + onAuthRequest.broadcast( + AuthRequest( + id: payload.id, + topic: topic, + requester: request.requester, + payloadParams: request.payloadParams, + ), + ); + } on WalletConnectError catch (err) { + await core.pairing.sendError( + payload.id, + topic, + payload.method, + JsonRpcError.invalidParams( + err.message, + ), + ); + } + } // TODO void _onOCARequest(String topic, JsonRpcRequest payload) async { From c6084e6146106660167df8a5e643d4f1d4713fc4 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Wed, 12 Jun 2024 11:33:17 +0200 Subject: [PATCH 18/29] minor changes --- example/dapp/lib/pages/connect_page.dart | 5 +- lib/apis/auth_api/auth_engine.dart | 2 - lib/apis/sign_api/sign_engine.dart | 94 ++++++++++++------------ 3 files changed, 49 insertions(+), 52 deletions(-) diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index 1ddb28e7..ef73d7d4 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:developer'; import 'package:fl_toast/fl_toast.dart'; import 'package:flutter/foundation.dart'; @@ -424,7 +425,7 @@ class ConnectPageState extends State { debugPrint('[SampleDapp] Awaiting authentication response'); final response = await authResponse.completer.future; - debugPrint('[SampleDapp] response ${jsonEncode(response.toJson())}'); + log('[SampleDapp] response ${jsonEncode(response.toJson())}'); if (response.result != null) { showPlatformToast( @@ -494,7 +495,7 @@ class ConnectPageState extends State { try { debugPrint('[SampleDapp] Awaiting 1-CA session'); final response = await authResponse.completer.future; - debugPrint('[SampleDapp] response ${jsonEncode(response.toJson())}'); + log('[SampleDapp] response ${jsonEncode(response.toJson())}'); if (response.session != null) { showPlatformToast( diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index d254b802..e389e703 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -344,8 +344,6 @@ class AuthEngine implements IAuthEngine { return completedRequests; } - // kind of a core method to move to sign - // Formats the message that is coming from requestAuth() @override String formatAuthMessage({ required String iss, diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 85739f6d..7eecd4d4 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -172,7 +172,7 @@ class SignEngine implements ISignEngine { final publicKey = await core.crypto.generateKeyPair(); final int id = JsonRpcUtils.payloadId(); - final WcSessionProposeRequest request = WcSessionProposeRequest( + final request = WcSessionProposeRequest( relays: relays ?? [Relay(WalletConnectConstants.RELAYER_DEFAULT_PROTOCOL)], requiredNamespaces: requiredNamespaces ?? {}, @@ -241,7 +241,7 @@ class SignEngine implements ISignEngine { final Map response = await core.pairing.sendRequest( topic, MethodConstants.WC_SESSION_PROPOSE, - request, + request.toJson(), id: requestId, ); final String peerPublicKey = response['responderPublicKey']; @@ -974,11 +974,11 @@ class SignEngine implements ISignEngine { type: ProtocolType.sign, ); // TODO on following PR to be used by Wallet - core.pairing.register( - method: MethodConstants.WC_SESSION_AUTHENTICATE, - function: _onOCARequest, - type: ProtocolType.sign, - ); + // core.pairing.register( + // method: MethodConstants.WC_SESSION_AUTHENTICATE, + // function: _onOCARequest, + // type: ProtocolType.sign, + // ); } Future _onSessionProposeRequest( @@ -1852,7 +1852,6 @@ class SignEngine implements ISignEngine { } // FORMER AUTH ENGINE PROPERTY - // Formats the message that is coming from requestAuth() @override String formatAuthMessage({ required String iss, @@ -2492,44 +2491,43 @@ class SignEngine implements ISignEngine { } } - // TODO - void _onOCARequest(String topic, JsonRpcRequest payload) async { - // TODO to be implemented for Wallet usage on following PR - // try { - // final request = WcOCARequestRequest.fromJson(payload.params); - - // final CacaoRequestPayload cacaoPayload = - // CacaoRequestPayload.fromPayloadParams( - // request.payloadParams, - // ); - - // authRequests.set( - // payload.id.toString(), - // PendingAuthRequest( - // id: payload.id, - // pairingTopic: topic, - // metadata: request.requester, - // cacaoPayload: cacaoPayload, - // ), - // ); - - // onAuthRequest.broadcast( - // AuthRequest( - // id: payload.id, - // topic: topic, - // requester: request.requester, - // payloadParams: request.payloadParams, - // ), - // ); - // } on WalletConnectError catch (err) { - // await core.pairing.sendError( - // payload.id, - // topic, - // payload.method, - // JsonRpcError.invalidParams( - // err.message, - // ), - // ); - // } - } + // // TODO to be implemented for Wallet usage on following PR + // void _onOCARequest(String topic, JsonRpcRequest payload) async { + // try { + // final request = WcOCARequestRequest.fromJson(payload.params); + + // final CacaoRequestPayload cacaoPayload = + // CacaoRequestPayload.fromPayloadParams( + // request.payloadParams, + // ); + + // authRequests.set( + // payload.id.toString(), + // PendingAuthRequest( + // id: payload.id, + // pairingTopic: topic, + // metadata: request.requester, + // cacaoPayload: cacaoPayload, + // ), + // ); + + // onAuthRequest.broadcast( + // AuthRequest( + // id: payload.id, + // topic: topic, + // requester: request.requester, + // payloadParams: request.payloadParams, + // ), + // ); + // } on WalletConnectError catch (err) { + // await core.pairing.sendError( + // payload.id, + // topic, + // payload.method, + // JsonRpcError.invalidParams( + // err.message, + // ), + // ); + // } + // } } From 59620c237f92594de3b1c370bd8743af6bdef8b6 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 24 Jun 2024 15:34:45 +0200 Subject: [PATCH 19/29] wallet side implementation an bug fixes --- example/dapp/lib/main.dart | 43 +- example/dapp/lib/pages/connect_page.dart | 63 +- .../bottom_sheet/i_bottom_sheet_service.dart | 6 + .../lib/dependencies/chains/common.dart | 4 +- .../lib/dependencies/chains/evm_service.dart | 47 +- .../dependencies/chains/kadena_service.dart | 2 +- .../dependencies/key_service/key_service.dart | 31 +- .../lib/dependencies/web3wallet_service.dart | 165 +++- example/wallet/lib/main.dart | 41 +- example/wallet/lib/models/chain_data.dart | 8 - example/wallet/lib/pages/app_detail_page.dart | 59 +- example/wallet/lib/pages/settings_page.dart | 143 ++-- example/wallet/lib/widgets/custom_button.dart | 2 +- example/wallet/lib/widgets/pairing_item.dart | 7 +- .../wc_auth_request_model.dart | 11 - .../wc_connection_request_widget.dart | 100 ++- .../wc_session_request_model.dart | 11 - .../wc_request_widget.dart | 7 +- .../wc_session_auth_request_widget.dart | 61 ++ lib/apis/auth_api/auth_engine.dart | 2 +- lib/apis/core/crypto/crypto.dart | 4 +- lib/apis/core/pairing/i_pairing.dart | 2 + lib/apis/core/pairing/pairing.dart | 14 +- .../core/pairing/utils/pairing_models.dart | 1 + .../pairing/utils/pairing_models.freezed.dart | 37 +- .../core/pairing/utils/pairing_models.g.dart | 3 + lib/apis/sign_api/i_sign_client.dart | 21 +- lib/apis/sign_api/i_sign_engine_app.dart | 6 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 18 + .../models/auth/common_auth_models.dart | 7 +- .../sign_api/models/auth/json_rpc_models.dart | 56 -- .../models/auth/json_rpc_models.freezed.dart | 742 ----------------- .../models/auth/json_rpc_models.g.dart | 70 -- .../models/auth/ocauth_models.freezed.dart | 370 ++++++++- .../sign_api/models/auth/ocauth_models.g.dart | 33 +- ...h_events.dart => session_auth_events.dart} | 38 +- ...h_models.dart => session_auth_models.dart} | 51 +- .../auth/session_auth_models.freezed.dart | 704 +++++++++++++++++ .../models/auth/session_auth_models.g.dart | 78 ++ lib/apis/sign_api/models/json_rpc_models.dart | 53 ++ .../models/json_rpc_models.freezed.dart | 745 ++++++++++++++++++ .../sign_api/models/json_rpc_models.g.dart | 63 ++ .../sign_api/models/sign_client_events.dart | 10 +- .../sign_api/models/sign_client_models.dart | 2 +- lib/apis/sign_api/sign_client.dart | 62 +- lib/apis/sign_api/sign_engine.dart | 399 ++++++++-- .../utils/auth/auth_api_validators.dart | 26 +- .../sign_api/utils/auth/auth_signature.dart | 90 +++ .../sign_api/utils/auth/recaps_utils.dart | 127 +++ lib/apis/utils/method_constants.dart | 10 + lib/apis/web3app/web3app.dart | 17 +- lib/apis/web3wallet/web3wallet.dart | 58 +- lib/walletconnect_flutter_v2.dart | 5 +- test/sign_api/sign_engine_test.dart | 16 + .../utils/sign_client_test_wrapper.dart | 54 +- 55 files changed, 3458 insertions(+), 1347 deletions(-) delete mode 100644 example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart delete mode 100644 example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart create mode 100644 example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart delete mode 100644 lib/apis/sign_api/models/auth/json_rpc_models.dart delete mode 100644 lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart delete mode 100644 lib/apis/sign_api/models/auth/json_rpc_models.g.dart rename lib/apis/sign_api/models/auth/{ocauth_events.dart => session_auth_events.dart} (50%) rename lib/apis/sign_api/models/auth/{ocauth_models.dart => session_auth_models.dart} (61%) create mode 100644 lib/apis/sign_api/models/auth/session_auth_models.freezed.dart create mode 100644 lib/apis/sign_api/models/auth/session_auth_models.g.dart diff --git a/example/dapp/lib/main.dart b/example/dapp/lib/main.dart index bc74973b..802e6827 100644 --- a/example/dapp/lib/main.dart +++ b/example/dapp/lib/main.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:developer'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:walletconnect_flutter_v2_dapp/models/chain_metadata.dart'; @@ -86,17 +87,18 @@ class _MyHomePageState extends State { } // Register event handlers - _web3App!.onSessionPing.subscribe(_onSessionPing); - _web3App!.onSessionEvent.subscribe(_onSessionEvent); - _web3App!.onSessionUpdate.subscribe(_onSessionUpdate); - _web3App!.core.addLogListener(_logListener); _web3App!.core.relayClient.onRelayClientConnect.subscribe(_setState); _web3App!.core.relayClient.onRelayClientDisconnect.subscribe(_setState); - _web3App!.core.relayClient.onRelayClientMessage.subscribe(_onRelayMessage); + _web3App!.core.relayClient.onRelayClientMessage.subscribe( + _onRelayMessage, + ); - _web3App!.signEngine.onSessionEvent.subscribe(_onSessionEvent); - _web3App!.signEngine.onSessionUpdate.subscribe(_onSessionUpdate); + _web3App!.onSessionPing.subscribe(_onSessionPing); + _web3App!.onSessionEvent.subscribe(_onSessionEvent); + _web3App!.onSessionUpdate.subscribe(_onSessionUpdate); + _web3App!.onSessionConnect.subscribe(_onSessionConnect); + _web3App!.onSessionAuthResponse.subscribe(_onSessionAuthResponse); setState(() { _pageDatas = [ @@ -126,28 +128,37 @@ class _MyHomePageState extends State { }); } + void _onSessionConnect(SessionConnect? event) { + log('[SampleDapp] _onSessionConnect $event'); + } + + void _onSessionAuthResponse(SessionAuthResponse? response) { + log('[SampleDapp] _onSessionAuthResponse $response'); + } + void _setState(dynamic args) => setState(() {}); @override void dispose() { // Unregister event handlers - _web3App!.onSessionPing.unsubscribe(_onSessionPing); - _web3App!.onSessionEvent.unsubscribe(_onSessionEvent); - _web3App!.onSessionUpdate.unsubscribe(_onSessionUpdate); - _web3App!.core.removeLogListener(_logListener); _web3App!.core.relayClient.onRelayClientConnect.unsubscribe(_setState); _web3App!.core.relayClient.onRelayClientDisconnect.unsubscribe(_setState); - _web3App!.core.relayClient.onRelayClientMessage - .unsubscribe(_onRelayMessage); + _web3App!.core.relayClient.onRelayClientMessage.unsubscribe( + _onRelayMessage, + ); + + _web3App!.onSessionPing.unsubscribe(_onSessionPing); + _web3App!.onSessionEvent.unsubscribe(_onSessionEvent); + _web3App!.onSessionUpdate.unsubscribe(_onSessionUpdate); + _web3App!.onSessionConnect.subscribe(_onSessionConnect); + _web3App!.onSessionAuthResponse.subscribe(_onSessionAuthResponse); - _web3App!.signEngine.onSessionEvent.unsubscribe(_onSessionEvent); - _web3App!.signEngine.onSessionUpdate.unsubscribe(_onSessionUpdate); super.dispose(); } void _logListener(LogEvent event) { - debugPrint('[SampleDapp] ${event.level.name}: ${event.message}'); + debugPrint('[Logger] ${event.level.name}: ${event.message}'); if (event.level == Level.error) { // TODO send to mixpanel } diff --git a/example/dapp/lib/pages/connect_page.dart b/example/dapp/lib/pages/connect_page.dart index ef73d7d4..dad3c545 100644 --- a/example/dapp/lib/pages/connect_page.dart +++ b/example/dapp/lib/pages/connect_page.dart @@ -1,8 +1,5 @@ -// ignore_for_file: use_build_context_synchronously - import 'dart:async'; import 'dart:convert'; -import 'dart:developer'; import 'package:fl_toast/fl_toast.dart'; import 'package:flutter/foundation.dart'; @@ -179,6 +176,9 @@ class ConnectPageState extends State { Navigator.of(context).pop(); } }, + showToast: (message) { + showPlatformToast(child: Text(message), context: context); + }, ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( @@ -298,6 +298,7 @@ class ConnectPageState extends State { // final uri = 'metamask://wc?uri=$encodedUri'; if (await canLaunchUrlString(uri)) { final openApp = await showDialog( + // ignore: use_build_context_synchronously context: context, builder: (BuildContext context) { return AlertDialog( @@ -377,7 +378,10 @@ class ConnectPageState extends State { ); } - void _requestAuth(SessionConnect? event) async { + void _requestAuth( + SessionConnect? event, { + Function(String message)? showToast, + }) async { final shouldAuth = await showDialog( context: context, barrierDismissible: false, @@ -425,33 +429,25 @@ class ConnectPageState extends State { debugPrint('[SampleDapp] Awaiting authentication response'); final response = await authResponse.completer.future; - log('[SampleDapp] response ${jsonEncode(response.toJson())}'); - if (response.result != null) { - showPlatformToast( - child: const Text(StringConstants.authSucceeded), - context: context, - ); + showToast?.call(StringConstants.authSucceeded); } else { final error = response.error ?? response.jsonRpcError; - showPlatformToast( - child: Text(error.toString()), - context: context, - ); + showToast?.call(error.toString()); } } catch (e) { debugPrint('[SampleDapp] auth $e'); - showPlatformToast( - child: const Text(StringConstants.connectionFailed), - context: context, - ); + showToast?.call(StringConstants.connectionFailed); } } - void _oneClickAuth({VoidCallback? closeModal}) async { + void _oneClickAuth({ + VoidCallback? closeModal, + Function(String message)? showToast, + }) async { final methods = optionalNamespaces['eip155']?.methods ?? []; final authResponse = await widget.web3App.authenticate( - params: OCARequestParams( + params: SessionAuthRequestParams( chains: _selectedChains.map((e) => e.chainId).toList(), domain: Constants.domain, nonce: AuthUtils.generateNonce(), @@ -466,6 +462,7 @@ class ConnectPageState extends State { if (await canLaunchUrlString(uri)) { final openApp = await showDialog( + // ignore: use_build_context_synchronously context: context, builder: (BuildContext context) { return AlertDialog( @@ -495,29 +492,18 @@ class ConnectPageState extends State { try { debugPrint('[SampleDapp] Awaiting 1-CA session'); final response = await authResponse.completer.future; - log('[SampleDapp] response ${jsonEncode(response.toJson())}'); if (response.session != null) { - showPlatformToast( - child: const Text( - '${StringConstants.authSucceeded} and ' - '${StringConstants.connectionEstablished}', - ), - context: context, + showToast?.call( + '${StringConstants.authSucceeded} and ${StringConstants.connectionEstablished}', ); } else { final error = response.error ?? response.jsonRpcError; - showPlatformToast( - child: Text(error.toString()), - context: context, - ); + showToast?.call(error.toString()); } } catch (e) { debugPrint('[SampleDapp] 1-CA $e'); - showPlatformToast( - child: const Text(StringConstants.connectionFailed), - context: context, - ); + showToast?.call(StringConstants.connectionFailed); } closeModal?.call(); } @@ -530,7 +516,12 @@ class ConnectPageState extends State { Navigator.pop(context); } - _requestAuth(event); + _requestAuth( + event, + showToast: (message) { + showPlatformToast(child: Text(message), context: context); + }, + ); } } diff --git a/example/wallet/lib/dependencies/bottom_sheet/i_bottom_sheet_service.dart b/example/wallet/lib/dependencies/bottom_sheet/i_bottom_sheet_service.dart index 5ccca104..48d88c52 100644 --- a/example/wallet/lib/dependencies/bottom_sheet/i_bottom_sheet_service.dart +++ b/example/wallet/lib/dependencies/bottom_sheet/i_bottom_sheet_service.dart @@ -2,6 +2,12 @@ import 'dart:async'; import 'package:flutter/material.dart'; +enum WCBottomSheetResult { + reject, + one, + all, +} + class BottomSheetQueueItem { final Widget widget; final Completer completer; diff --git a/example/wallet/lib/dependencies/chains/common.dart b/example/wallet/lib/dependencies/chains/common.dart index 81d46fb8..368512e4 100644 --- a/example/wallet/lib/dependencies/chains/common.dart +++ b/example/wallet/lib/dependencies/chains/common.dart @@ -30,7 +30,7 @@ class CommonMethods { static Future requestApproval(String text, {String? title}) async { final bottomSheetService = GetIt.I(); - final approved = await bottomSheetService.queueBottomSheet( + final WCBottomSheetResult rs = await bottomSheetService.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionWidget( title: 'Approve Request', @@ -46,6 +46,6 @@ class CommonMethods { ), ); - return approved ?? false; + return rs != WCBottomSheetResult.reject; } } diff --git a/example/wallet/lib/dependencies/chains/evm_service.dart b/example/wallet/lib/dependencies/chains/evm_service.dart index 06c05144..33a4df61 100644 --- a/example/wallet/lib/dependencies/chains/evm_service.dart +++ b/example/wallet/lib/dependencies/chains/evm_service.dart @@ -16,6 +16,35 @@ import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_widget/wc_ import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_widget/wc_connection_widget.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/wc_request_widget.dart/wc_request_widget.dart'; +enum SupportedEVMMethods { + ethSign, + ethSignTransaction, + ethSignTypedData, + ethSignTypedDataV4, + switchChain, + personalSign, + ethSendTransaction; + + String get name { + switch (this) { + case ethSign: + return 'eth_sign'; + case ethSignTransaction: + return 'eth_signTransaction'; + case ethSignTypedData: + return 'eth_signTypedData'; + case ethSignTypedDataV4: + return 'eth_signTypedData_v4'; + case switchChain: + return 'wallet_switchEthereumChain'; + case personalSign: + return 'personal_sign'; + case ethSendTransaction: + return 'eth_sendTransaction'; + } + } +} + class EVMService { final _bottomSheetService = GetIt.I(); final _web3Wallet = GetIt.I().web3wallet; @@ -24,17 +53,17 @@ class EVMService { late final Web3Client ethClient; Map get sessionRequestHandlers => { - 'eth_sign': ethSign, - 'eth_signTransaction': ethSignTransaction, - 'eth_signTypedData': ethSignTypedData, - 'eth_signTypedData_v4': ethSignTypedDataV4, - 'wallet_switchEthereumChain': switchChain, + SupportedEVMMethods.ethSign.name: ethSign, + SupportedEVMMethods.ethSignTransaction.name: ethSignTransaction, + SupportedEVMMethods.ethSignTypedData.name: ethSignTypedData, + SupportedEVMMethods.ethSignTypedDataV4.name: ethSignTypedDataV4, + SupportedEVMMethods.switchChain.name: switchChain, // 'wallet_addEthereumChain': addChain, }; Map get methodRequestHandlers => { - 'personal_sign': personalSign, - 'eth_sendTransaction': ethSendTransaction, + SupportedEVMMethods.personalSign.name: personalSign, + SupportedEVMMethods.ethSendTransaction.name: ethSendTransaction, }; EVMService({required this.chainSupported}) { @@ -451,7 +480,7 @@ class EVMService { final gweiGasPrice = (transaction.gasPrice?.getInWei ?? BigInt.zero) / BigInt.from(1000000000); - final approved = await _bottomSheetService.queueBottomSheet( + final WCBottomSheetResult rs = await _bottomSheetService.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionWidget( title: 'Approve Transaction', @@ -466,7 +495,7 @@ class EVMService { ), ); - if (approved == true) { + if (rs != WCBottomSheetResult.reject) { return transaction; } diff --git a/example/wallet/lib/dependencies/chains/kadena_service.dart b/example/wallet/lib/dependencies/chains/kadena_service.dart index 469c1504..f7fd84fb 100644 --- a/example/wallet/lib/dependencies/chains/kadena_service.dart +++ b/example/wallet/lib/dependencies/chains/kadena_service.dart @@ -112,7 +112,7 @@ class KadenaService { ); try { - final chain = ChainData.allChains.firstWhere( + final chain = ChainData.kadenaChains.firstWhere( (c) => c.chainId == chainSupported.chainId, ); final uri = Uri.parse(chain.rpc.first); diff --git a/example/wallet/lib/dependencies/key_service/key_service.dart b/example/wallet/lib/dependencies/key_service/key_service.dart index a65fbca8..5e0093b9 100644 --- a/example/wallet/lib/dependencies/key_service/key_service.dart +++ b/example/wallet/lib/dependencies/key_service/key_service.dart @@ -9,7 +9,6 @@ import 'package:walletconnect_flutter_v2_wallet/dependencies/bip39/bip39_base.da as bip39; import 'package:walletconnect_flutter_v2_wallet/dependencies/bip32/bip32_base.dart' as bip32; -import 'package:walletconnect_flutter_v2_wallet/models/chain_metadata.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/dart_defines.dart'; class KeyService extends IKeyService { @@ -116,10 +115,7 @@ class KeyService extends IKeyService { final private = EthPrivateKey.fromHex(keyPair.privateKey); final address = private.address.hex; final evmChainKey = ChainKey( - chains: ChainData.allChains - .where((c) => c.type == ChainType.eip155) - .map((e) => e.chainId) - .toList(), + chains: ChainData.eip155Chains.map((e) => e.chainId).toList(), privateKey: keyPair.privateKey, publicKey: keyPair.publicKey, address: address, @@ -148,10 +144,7 @@ class KeyService extends IKeyService { ChainKey _kadenaKeyPair() { return ChainKey( - chains: ChainData.allChains - .where((c) => c.type == ChainType.kadena) - .map((e) => e.chainId) - .toList(), + chains: ChainData.kadenaChains.map((e) => e.chainId).toList(), privateKey: DartDefines.kadenaSecretKey, publicKey: DartDefines.kadenaAddress, address: DartDefines.kadenaAddress, @@ -159,21 +152,8 @@ class KeyService extends IKeyService { } ChainKey _polkadotKeyPair() { - // final keyring = Keyring(); - // final keyPair1 = await KeyPair.sr25519.fromMnemonic( - // DartDefines.polkadotMnemonic1, - // ); - // keyPair1.ss58Format = 1; - // keyring.add(keyPair1); - - // final publicKey = keyPair1.publicKey.bytes; - // final encodedPublicKey = hex.encode(publicKey); - return ChainKey( - chains: ChainData.allChains - .where((c) => c.type == ChainType.polkadot) - .map((e) => e.chainId) - .toList(), + chains: ChainData.polkadotChains.map((e) => e.chainId).toList(), privateKey: DartDefines.polkadotMnemonic, publicKey: '', address: DartDefines.polkadotAddress, @@ -182,10 +162,7 @@ class KeyService extends IKeyService { ChainKey _solanaKeyPair() { return ChainKey( - chains: ChainData.allChains - .where((c) => c.type == ChainType.solana) - .map((e) => e.chainId) - .toList(), + chains: ChainData.solanaChains.map((e) => e.chainId).toList(), privateKey: DartDefines.solanaSecretKey, publicKey: DartDefines.solanaAddress, address: DartDefines.solanaAddress, diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index a82aff86..2690b29a 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -7,17 +7,18 @@ import 'package:flutter/material.dart'; 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/evm_service.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/chain_key.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/i_key_service.dart'; +import 'package:walletconnect_flutter_v2_wallet/models/chain_data.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/dart_defines.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/eth_utils.dart'; -import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_request/wc_auth_request_model.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_request/wc_connection_request_widget.dart'; -import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_request/wc_session_request_model.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/wc_request_widget.dart/wc_request_widget.dart'; +import 'package:walletconnect_flutter_v2_wallet/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart'; class Web3WalletService extends IWeb3WalletService { final _bottomSheetHandler = GetIt.I(); @@ -44,7 +45,6 @@ class Web3WalletService extends IWeb3WalletService { ), ), ); - _web3Wallet!.core.addLogListener(_logListener); // Setup our accounts List chainKeys = await GetIt.I().setKeys(); @@ -74,18 +74,22 @@ class Web3WalletService extends IWeb3WalletService { // Setup our listeners debugPrint('[SampleWallet] create'); + _web3Wallet!.core.addLogListener(_logListener); _web3Wallet!.core.pairing.onPairingInvalid.subscribe(_onPairingInvalid); _web3Wallet!.core.pairing.onPairingCreate.subscribe(_onPairingCreate); - _web3Wallet!.onSessionProposal.subscribe(_onSessionProposal); - _web3Wallet!.onSessionConnect.subscribe(_onSessionConnect); - _web3Wallet!.onSessionProposalError.subscribe(_onSessionProposalError); - _web3Wallet!.onAuthRequest.subscribe(_onAuthRequest); _web3Wallet!.core.relayClient.onRelayClientError.subscribe( _onRelayClientError, ); _web3Wallet!.core.relayClient.onRelayClientMessage.subscribe( _onRelayClientMessage, ); + + _web3Wallet!.onSessionProposal.subscribe(_onSessionProposal); + _web3Wallet!.onSessionProposalError.subscribe(_onSessionProposalError); + _web3Wallet!.onSessionConnect.subscribe(_onSessionConnect); + _web3Wallet!.onSessionAuthRequest.subscribe(_onSessionAuthRequest); + + _web3Wallet!.onAuthRequest.subscribe(_onAuthRequest); } @override @@ -95,7 +99,7 @@ class Web3WalletService extends IWeb3WalletService { } void _logListener(LogEvent event) { - debugPrint('[SampleWallet] ${event.level.name}: ${event.message}'); + debugPrint('[Logger] ${event.level.name}: ${event.message}'); if (event.level == Level.error) { // TODO send to mixpanel } @@ -106,16 +110,19 @@ class Web3WalletService extends IWeb3WalletService { _web3Wallet!.core.removeLogListener(_logListener); _web3Wallet!.core.pairing.onPairingInvalid.unsubscribe(_onPairingInvalid); _web3Wallet!.core.pairing.onPairingCreate.unsubscribe(_onPairingCreate); - _web3Wallet!.onSessionProposal.unsubscribe(_onSessionProposal); - _web3Wallet!.onSessionConnect.unsubscribe(_onSessionConnect); - _web3Wallet!.onSessionProposalError.unsubscribe(_onSessionProposalError); - _web3Wallet!.onAuthRequest.unsubscribe(_onAuthRequest); _web3Wallet!.core.relayClient.onRelayClientError.unsubscribe( _onRelayClientError, ); _web3Wallet!.core.relayClient.onRelayClientMessage.unsubscribe( _onRelayClientMessage, ); + + _web3Wallet!.onSessionProposal.unsubscribe(_onSessionProposal); + _web3Wallet!.onSessionProposalError.unsubscribe(_onSessionProposalError); + _web3Wallet!.onSessionConnect.unsubscribe(_onSessionConnect); + _web3Wallet!.onSessionAuthRequest.unsubscribe(_onSessionAuthRequest); + + _web3Wallet!.onAuthRequest.unsubscribe(_onAuthRequest); } @override @@ -149,19 +156,17 @@ class Web3WalletService extends IWeb3WalletService { void _onSessionProposal(SessionProposalEvent? args) async { if (args != null) { log('[SampleWallet] _onSessionProposal ${jsonEncode(args.params)}'); - final approved = await _bottomSheetHandler.queueBottomSheet( + final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( widget: WCRequestWidget( child: WCConnectionRequestWidget( - wallet: _web3Wallet!, - sessionProposal: WCSessionRequestModel( - request: args.params, - verifyContext: args.verifyContext, - ), + proposalData: args.params, + verifyContext: args.verifyContext, + metadata: args.params.proposer, ), ), ); - if (approved == true) { + if (rs != 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( @@ -235,47 +240,133 @@ class Web3WalletService extends IWeb3WalletService { } void _onRelayClientError(ErrorEvent? args) { - debugPrint( - '[$runtimeType] [SampleWallet] _onRelayClientError ${args?.error}'); + debugPrint('[SampleWallet] _onRelayClientError ${args?.error}'); } void _onPairingInvalid(PairingInvalidEvent? args) { - debugPrint('[$runtimeType] [SampleWallet] _onPairingInvalid $args'); + debugPrint('[SampleWallet] _onPairingInvalid $args'); } void _onPairingCreate(PairingEvent? args) { - debugPrint('[$runtimeType] [SampleWallet] _onPairingCreate $args'); + debugPrint('[SampleWallet] _onPairingCreate $args'); } - Future _onAuthRequest(AuthRequest? args) async { - log('[SampleWallet] _onAuthRequest $args'); + Future _onSessionAuthRequest(SessionAuthRequest? args) async { + log('[SampleWallet] _onSessionAuthRequest ${args?.payloadParams}'); if (args != null) { - final chainKeys = GetIt.I().getKeysForChain('eip155:1'); - // Create the message to be signed - final iss = 'did:pkh:eip155:1:${chainKeys.first.address}'; + final SessionAuthPayloadParams payloadParams = args.payloadParams; + final supportedChains = ChainData.eip155Chains.map((e) => e.chainId); + final supportedMethods = SupportedEVMMethods.values.map((e) => e.name); + final newPayloadParams = AuthSignature.populateAuthPayload( + authPayload: payloadParams, + chains: supportedChains.toList(), + methods: supportedMethods.toList(), + ); + final cacaoRequestPayload = + CacaoRequestPayload.fromSessionAuthPayloadParams( + newPayloadParams, + ); + final List> formattedMessages = []; + for (var chain in newPayloadParams.chains) { + final chainKeys = GetIt.I().getKeysForChain(chain); + final iss = 'did:pkh:$chain:${chainKeys.first.address}'; + final message = _web3Wallet!.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoRequestPayload, + // TODO cacaoPayload should be SessionAuthPayloadParams + ); + formattedMessages.add({iss: message}); + } - final bool? auth = await _bottomSheetHandler.queueBottomSheet( - widget: WCRequestWidget( + final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( + widget: WCSessionAuthRequestWidget( child: WCConnectionRequestWidget( - wallet: _web3Wallet!, - authRequest: WCAuthRequestModel( + sessionAuthPayloadParams: newPayloadParams, + verifyContext: args.verifyContext, + metadata: args.requester, + ), + ), + ); + + if (rs != WCBottomSheetResult.reject) { + const chain = 'eip155:1'; + final chainKeys = GetIt.I().getKeysForChain(chain); + final privateKey = '0x${chainKeys[0].privateKey}'; + final credentials = EthPrivateKey.fromHex(privateKey); + // + final messageToSign = formattedMessages.length; + final count = (rs == WCBottomSheetResult.one) ? 1 : messageToSign; + // + final List cacaos = []; + for (var i = 0; i < count; i++) { + final iss = formattedMessages[i].keys.first; + final message = formattedMessages[i].values.first; + final signature = credentials.signPersonalMessageToUint8List( + Uint8List.fromList(message.codeUnits), + ); + final hexSignature = bytesToHex(signature, include0x: true); + cacaos.add( + AuthSignature.buildAuthObject( + requestPayload: cacaoRequestPayload, + signature: CacaoSignature( + t: CacaoSignature.EIP191, + s: hexSignature, + ), iss: iss, - request: args, ), + ); + } + // + final _ = await _web3Wallet!.approveSessionAuthenticate( + id: args.id, + auths: cacaos, + ); + final scheme = args.requester.metadata.redirect?.native ?? ''; + DeepLinkHandler.goTo(scheme); + } else { + await _web3Wallet!.rejectSessionAuthenticate( + id: args.id, + reason: Errors.getSdkError(Errors.USER_REJECTED_AUTH), + ); + final scheme = args.requester.metadata.redirect?.native ?? ''; + DeepLinkHandler.goTo( + scheme, + modalTitle: 'Error', + modalMessage: 'User rejected', + success: false, + ); + } + } + } + + Future _onAuthRequest(AuthRequest? args) async { + log('[SampleWallet] _onAuthRequest $args'); + if (args != null) { + // + final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionRequestWidget( + authPayloadParams: args.payloadParams, + metadata: args.requester, ), ), ); - if (auth != null && auth) { - final String message = _web3Wallet!.formatAuthMessage( + const chain = 'eip155:1'; + final chainKeys = GetIt.I().getKeysForChain(chain); + final privateKey = '0x${chainKeys[0].privateKey}'; + final credentials = EthPrivateKey.fromHex(privateKey); + final iss = 'did:pkh:$chain:${credentials.address.hex}'; + + if (rs != WCBottomSheetResult.reject) { + // + final message = _web3Wallet!.formatAuthMessage( iss: iss, cacaoPayload: CacaoRequestPayload.fromPayloadParams( args.payloadParams, ), ); - final pk = '0x${chainKeys.first.privateKey}'; - final credentials = EthPrivateKey.fromHex(pk); final signature = credentials.signPersonalMessageToUint8List( Uint8List.fromList(message.codeUnits), ); diff --git a/example/wallet/lib/main.dart b/example/wallet/lib/main.dart index 56f7a03e..39cff46d 100644 --- a/example/wallet/lib/main.dart +++ b/example/wallet/lib/main.dart @@ -14,7 +14,6 @@ import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/i_key_s import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/key_service.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/web3wallet_service.dart'; import 'package:walletconnect_flutter_v2_wallet/models/chain_data.dart'; -import 'package:walletconnect_flutter_v2_wallet/models/chain_metadata.dart'; import 'package:walletconnect_flutter_v2_wallet/models/page_data.dart'; import 'package:walletconnect_flutter_v2_wallet/pages/apps_page.dart'; import 'package:walletconnect_flutter_v2_wallet/pages/settings_page.dart'; @@ -69,9 +68,7 @@ class _MyHomePageState extends State with GetItStateMixin { GetIt.I.registerSingleton(web3WalletService); // Support EVM Chains - final evmChains = - ChainData.allChains.where((c) => c.type == ChainType.eip155).toList(); - for (final chainData in evmChains) { + for (final chainData in ChainData.eip155Chains) { GetIt.I.registerSingleton( EVMService(chainSupported: chainData), instanceName: chainData.chainId, @@ -79,9 +76,7 @@ class _MyHomePageState extends State with GetItStateMixin { } // Support Kadena Chains - final kadenaChains = - ChainData.allChains.where((c) => c.type == ChainType.kadena).toList(); - for (final chainData in kadenaChains) { + for (final chainData in ChainData.kadenaChains) { GetIt.I.registerSingleton( KadenaService(chainSupported: chainData), instanceName: chainData.chainId, @@ -89,9 +84,7 @@ class _MyHomePageState extends State with GetItStateMixin { } // Support Polkadot Chains - final polkadotChains = - ChainData.allChains.where((c) => c.type == ChainType.polkadot).toList(); - for (final chainData in polkadotChains) { + for (final chainData in ChainData.polkadotChains) { GetIt.I.registerSingleton( PolkadotService(chainSupported: chainData), instanceName: chainData.chainId, @@ -99,9 +92,7 @@ class _MyHomePageState extends State with GetItStateMixin { } // Support Solana Chains - final solanaChains = - ChainData.allChains.where((c) => c.type == ChainType.solana).toList(); - for (final chainData in solanaChains) { + for (final chainData in ChainData.solanaChains) { GetIt.I.registerSingleton( SolanaService(chainSupported: chainData), instanceName: chainData.chainId, @@ -109,9 +100,7 @@ class _MyHomePageState extends State with GetItStateMixin { } // Support Cosmos Chains - final cosmosChains = - ChainData.allChains.where((c) => c.type == ChainType.cosmos).toList(); - for (final chainData in cosmosChains) { + for (final chainData in ChainData.cosmosChains) { GetIt.I.registerSingleton( CosmosService(chainSupported: chainData), instanceName: chainData.chainId, @@ -127,16 +116,16 @@ class _MyHomePageState extends State with GetItStateMixin { title: StringConstants.connectPageTitle, icon: Icons.swap_vert_circle_outlined, ), - PageData( - page: const Center( - child: Text( - 'Inbox (Not Implemented)', - style: StyleConstants.bodyText, - ), - ), - title: 'Inbox', - icon: Icons.inbox_rounded, - ), + // PageData( + // page: const Center( + // child: Text( + // 'Inbox (Not Implemented)', + // style: StyleConstants.bodyText, + // ), + // ), + // title: 'Inbox', + // icon: Icons.inbox_rounded, + // ), PageData( page: const SettingsPage(), title: 'Settings', diff --git a/example/wallet/lib/models/chain_data.dart b/example/wallet/lib/models/chain_data.dart index 6440ce7b..f69380ca 100644 --- a/example/wallet/lib/models/chain_data.dart +++ b/example/wallet/lib/models/chain_data.dart @@ -195,12 +195,4 @@ class ChainData { ], ), ]; - - static final List allChains = [ - ...eip155Chains, - ...solanaChains, - ...polkadotChains, - ...kadenaChains, - // ...cosmosChains, - ]; } diff --git a/example/wallet/lib/pages/app_detail_page.dart b/example/wallet/lib/pages/app_detail_page.dart index 632244e8..eaf348b7 100644 --- a/example/wallet/lib/pages/app_detail_page.dart +++ b/example/wallet/lib/pages/app_detail_page.dart @@ -45,6 +45,7 @@ class AppDetailPageState extends State { @override Widget build(BuildContext context) { + final metadata = widget.pairing.peerMetadata; DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(widget.pairing.expiry * 1000); int year = dateTime.year; @@ -104,10 +105,10 @@ class AppDetailPageState extends State { ), ); } - final scheme = widget.pairing.peerMetadata?.redirect?.native ?? ''; + final scheme = metadata?.redirect?.native ?? ''; return Scaffold( appBar: AppBar( - title: Text(widget.pairing.peerMetadata?.name ?? 'Unknown'), + title: Text(metadata?.name ?? 'Unknown'), actions: [ Visibility( visible: scheme.isNotEmpty, @@ -131,33 +132,39 @@ class AppDetailPageState extends State { ), child: Column( children: [ - Row( - children: [ - CircleAvatar( - radius: 40.0, - backgroundImage: (widget - .pairing.peerMetadata!.icons.isNotEmpty - ? NetworkImage(widget.pairing.peerMetadata!.icons[0]) - : const AssetImage('assets/images/default_icon.png')) - as ImageProvider, - ), - const SizedBox(width: 10.0), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(widget.pairing.peerMetadata!.url), - Text('Expires on: $expiryDate'), - ], + Visibility( + visible: metadata != null, + child: Row( + children: [ + CircleAvatar( + radius: 40.0, + backgroundImage: ((metadata?.icons ?? []).isNotEmpty + ? NetworkImage(metadata!.icons[0]) + : const AssetImage( + 'assets/images/default_icon.png')) + as ImageProvider, ), - ), - ], + const SizedBox(width: 10.0), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(metadata?.url ?? ''), + Text('Expires on: $expiryDate'), + ], + ), + ), + ], + ), ), const SizedBox(height: 20.0), - Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: sessionWidgets, + Visibility( + visible: metadata != null, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: sessionWidgets, + ), ), const SizedBox(height: 20.0), Row( diff --git a/example/wallet/lib/pages/settings_page.dart b/example/wallet/lib/pages/settings_page.dart index 3c4f6c47..65a05c4d 100644 --- a/example/wallet/lib/pages/settings_page.dart +++ b/example/wallet/lib/pages/settings_page.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; 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/i_web3wallet_service.dart'; import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/i_key_service.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/custom_button.dart'; @@ -37,6 +38,7 @@ class _SettingsPageState extends State { 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( @@ -45,6 +47,7 @@ class _SettingsPageState extends State { Expanded( child: SingleChildScrollView( child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 8.0, bottom: 8.0), @@ -83,68 +86,92 @@ class _SettingsPageState extends State { ); }, ), - ], - ), - ), - ), - const SizedBox(height: 8.0), - Row( - children: [ - Expanded( - child: Text( - version ?? '', - textAlign: TextAlign.center, - style: const TextStyle(fontSize: 11.0), - ), - ) - ], - ), - const SizedBox(height: 8.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, + 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, + ), ), ), - ), - ), - ], - ), - 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, - ), + FutureBuilder( + future: web3Wallet.core.crypto.getClientId(), + builder: (context, snapshot) { + return _DataContainer( + title: 'Client ID', + data: snapshot.data ?? '', + ); + }, ), - ), + 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, + ), + ), + ), + ), + ], + ), + 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, + ), + ), + ), + ), + ], + ), + const SizedBox(height: 12.0), + Row( + children: [ + Expanded( + child: Text( + version ?? '', + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 11.0), + ), + ) + ], + ), + ], ), - ], + ), ), ], ), diff --git a/example/wallet/lib/widgets/custom_button.dart b/example/wallet/lib/widgets/custom_button.dart index d7c9cf94..f8c79f8f 100644 --- a/example/wallet/lib/widgets/custom_button.dart +++ b/example/wallet/lib/widgets/custom_button.dart @@ -40,7 +40,7 @@ class CustomButton extends StatelessWidget { borderRadius: BorderRadius.circular(16), ), padding: const EdgeInsets.symmetric( - horizontal: 24, + horizontal: 8, vertical: 12, ), child: child, diff --git a/example/wallet/lib/widgets/pairing_item.dart b/example/wallet/lib/widgets/pairing_item.dart index 7195ff3c..95f332d3 100644 --- a/example/wallet/lib/widgets/pairing_item.dart +++ b/example/wallet/lib/widgets/pairing_item.dart @@ -18,9 +18,10 @@ class PairingItem extends StatelessWidget { Widget build(BuildContext context) { PairingMetadata? metadata = pairing.peerMetadata; if (metadata == null) { - return const ListTile( - title: Text('Unknown'), - subtitle: Text('No metadata available'), + return ListTile( + title: const Text('Unknown'), + subtitle: const Text('No metadata available'), + onTap: onTap, ); } final sessions = GetIt.I() diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart b/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart deleted file mode 100644 index cf5efd26..00000000 --- a/example/wallet/lib/widgets/wc_connection_request/wc_auth_request_model.dart +++ /dev/null @@ -1,11 +0,0 @@ -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -class WCAuthRequestModel { - final String iss; - final AuthRequest request; - - WCAuthRequestModel({ - required this.iss, - required this.request, - }); -} diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart index 72a9d967..1e3acc82 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart @@ -1,10 +1,11 @@ import 'package:flutter/material.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'; +import 'package:walletconnect_flutter_v2_wallet/dependencies/key_service/i_key_service.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/constants.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/namespace_model_builder.dart'; import 'package:walletconnect_flutter_v2_wallet/utils/string_constants.dart'; -import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_request/wc_auth_request_model.dart'; -import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_request/wc_session_request_model.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/wc_connection_widget/wc_connection_widget.dart'; import '../wc_connection_widget/wc_connection_model.dart'; @@ -12,21 +13,21 @@ import '../wc_connection_widget/wc_connection_model.dart'; class WCConnectionRequestWidget extends StatelessWidget { const WCConnectionRequestWidget({ Key? key, - required this.wallet, - this.authRequest, - this.sessionProposal, + this.authPayloadParams, + this.sessionAuthPayloadParams, + this.proposalData, + this.metadata, + this.verifyContext, }) : super(key: key); - final Web3Wallet wallet; - final WCAuthRequestModel? authRequest; - final WCSessionRequestModel? sessionProposal; + final AuthPayloadParams? authPayloadParams; + final SessionAuthPayloadParams? sessionAuthPayloadParams; + final ProposalData? proposalData; + final ConnectionMetadata? metadata; + final VerifyContext? verifyContext; @override Widget build(BuildContext context) { - // Get the connection metadata - final proposerMetadata = sessionProposal?.request.proposer; - final metadata = authRequest?.request.requester ?? proposerMetadata; - if (metadata == null) { return const Text('ERROR'); } @@ -34,16 +35,14 @@ class WCConnectionRequestWidget extends StatelessWidget { return Container( decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.circular( - StyleConstants.linear8, - ), + borderRadius: BorderRadius.circular(StyleConstants.linear8), ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( - '${metadata.metadata.name}\n${StringConstants.wouldLikeToConnect}', + '${metadata!.metadata.name}\n${StringConstants.wouldLikeToConnect}', style: StyleConstants.subtitleText.copyWith( fontSize: 18, color: Colors.black, @@ -52,30 +51,73 @@ class WCConnectionRequestWidget extends StatelessWidget { ), const SizedBox(height: StyleConstants.linear8), VerifyContextWidget( - verifyContext: sessionProposal?.verifyContext, + verifyContext: verifyContext, ), const SizedBox(height: StyleConstants.linear8), - authRequest != null + (authPayloadParams != null) ? _buildAuthRequestView() - : _buildSessionProposalView(context), + : (sessionAuthPayloadParams != null) + ? _buildSessionAuthRequestView() + : _buildSessionProposalView(context), ], ), ); } Widget _buildAuthRequestView() { - final model = WCConnectionModel( - text: wallet.formatAuthMessage( - iss: 'did:pkh:eip155:1:${authRequest!.iss}', - cacaoPayload: CacaoRequestPayload.fromPayloadParams( - authRequest!.request.payloadParams, - ), - ), + final web3Wallet = GetIt.I().web3wallet; + // + final cacaoPayload = CacaoRequestPayload.fromPayloadParams( + authPayloadParams!, + ); + const chain = 'eip155:1'; + final chainKeys = GetIt.I().getKeysForChain(chain); + final iss = 'did:pkh:$chain:${chainKeys.first.address}'; + final message = web3Wallet.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + // + final messageModel = WCConnectionModel( + text: message, ); return WCConnectionWidget( - title: StringConstants.message, - info: [model], + title: 'Message', + info: [ + messageModel, + ], + ); + } + + Widget _buildSessionAuthRequestView() { + final web3Wallet = GetIt.I().web3wallet; + // + final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayloadParams( + sessionAuthPayloadParams!, + ); + // + final List messagesModels = []; + for (var chain in sessionAuthPayloadParams!.chains) { + final chainKeys = GetIt.I().getKeysForChain(chain); + final iss = 'did:pkh:$chain:${chainKeys.first.address}'; + final message = web3Wallet.formatAuthMessage( + iss: iss, + cacaoPayload: cacaoPayload, + ); + messagesModels.add( + WCConnectionModel( + title: 'Message ${messagesModels.length + 1}', + elements: [ + message, + ], + ), + ); + } + // + return WCConnectionWidget( + title: 'Messages', + info: messagesModels, ); } @@ -83,7 +125,7 @@ class WCConnectionRequestWidget extends StatelessWidget { // Create the connection models using the required and optional namespaces provided by the proposal data // The key is the title and the list of values is the data final views = ConnectionWidgetBuilder.buildFromRequiredNamespaces( - sessionProposal!.request.generatedNamespaces!, + proposalData!.generatedNamespaces!, ); return Column( diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart b/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart deleted file mode 100644 index fdea6211..00000000 --- a/example/wallet/lib/widgets/wc_connection_request/wc_session_request_model.dart +++ /dev/null @@ -1,11 +0,0 @@ -import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; - -class WCSessionRequestModel { - final ProposalData request; - final VerifyContext? verifyContext; - - WCSessionRequestModel({ - required this.request, - this.verifyContext, - }); -} 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 4e9a91e8..adbdc543 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,4 +1,5 @@ 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'; import 'package:walletconnect_flutter_v2_wallet/utils/string_constants.dart'; import 'package:walletconnect_flutter_v2_wallet/widgets/custom_button.dart'; @@ -29,7 +30,8 @@ class WCRequestWidget extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CustomButton( - onTap: onReject ?? () => Navigator.of(context).pop(false), + onTap: onReject ?? + () => Navigator.of(context).pop(WCBottomSheetResult.reject), type: CustomButtonType.invalid, child: const Text( StringConstants.reject, @@ -41,7 +43,8 @@ class WCRequestWidget extends StatelessWidget { width: StyleConstants.linear16, ), CustomButton( - onTap: onAccept ?? () => Navigator.of(context).pop(true), + onTap: onAccept ?? + () => Navigator.of(context).pop(WCBottomSheetResult.one), type: CustomButtonType.valid, child: const Text( StringConstants.approve, 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 new file mode 100644 index 00000000..6cd4cbf8 --- /dev/null +++ b/example/wallet/lib/widgets/wc_request_widget.dart/wc_session_auth_request_widget.dart @@ -0,0 +1,61 @@ +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'; +import 'package:walletconnect_flutter_v2_wallet/widgets/custom_button.dart'; + +class WCSessionAuthRequestWidget extends StatelessWidget { + const WCSessionAuthRequestWidget({ + super.key, + required this.child, + }); + + final Widget child; + + @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, + ), + ), + 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, + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/apis/auth_api/auth_engine.dart b/lib/apis/auth_api/auth_engine.dart index e389e703..926fb952 100644 --- a/lib/apis/auth_api/auth_engine.dart +++ b/lib/apis/auth_api/auth_engine.dart @@ -5,8 +5,8 @@ import 'package:walletconnect_flutter_v2/apis/auth_api/i_auth_engine.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_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/json_rpc_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/json_rpc_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_api_validators.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/auth_constants.dart'; diff --git a/lib/apis/core/crypto/crypto.dart b/lib/apis/core/crypto/crypto.dart index 34a381d9..ca8c7162 100644 --- a/lib/apis/core/crypto/crypto.dart +++ b/lib/apis/core/crypto/crypto.dart @@ -189,8 +189,8 @@ class Crypto implements ICrypto { final Uint8List seed = await _getClientSeed(); final RelayAuthKeyPair keyPair = await relayAuth.generateKeyPair(seed); - String sub = utils.generateRandomBytes32(); - String jwt = await relayAuth.signJWT( + final String sub = utils.generateRandomBytes32(); + final jwt = await relayAuth.signJWT( sub: sub, aud: aud, ttl: WalletConnectConstants.ONE_DAY, diff --git a/lib/apis/core/pairing/i_pairing.dart b/lib/apis/core/pairing/i_pairing.dart index ea0150a3..c4894624 100644 --- a/lib/apis/core/pairing/i_pairing.dart +++ b/lib/apis/core/pairing/i_pairing.dart @@ -3,6 +3,7 @@ import 'package:walletconnect_flutter_v2/apis/core/crypto/crypto_models.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/i_pairing_store.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/pairing_models.dart'; +import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_request.dart'; @@ -69,6 +70,7 @@ abstract class IPairing { String method, JsonRpcError error, { EncodeOptions? encodeOptions, + RpcOptions? rpcOptions, }); Future isValidPairingTopic({ diff --git a/lib/apis/core/pairing/pairing.dart b/lib/apis/core/pairing/pairing.dart index 3926112d..4ea2e633 100644 --- a/lib/apis/core/pairing/pairing.dart +++ b/lib/apis/core/pairing/pairing.dart @@ -113,6 +113,7 @@ class Pairing implements IPairing { expiry: expiry, relay: relay, active: false, + methods: methods?.expand((e) => e).toList() ?? [], ); final Uri uri = WalletConnectUtils.formatUri( protocol: core.protocol, @@ -168,6 +169,7 @@ class Pairing implements IPairing { expiry: expiry, relay: relay, active: false, + methods: parsedUri.v2Data!.methods, ); try { @@ -499,6 +501,7 @@ class Pairing implements IPairing { String method, JsonRpcError error, { EncodeOptions? encodeOptions, + RpcOptions? rpcOptions, }) async { core.logger.t( 'pairing sendError, id: $id topic: $topic, method: $method, error: $error', @@ -518,10 +521,13 @@ class Pairing implements IPairing { return; } - final RpcOptions opts = MethodConstants.RPC_OPTS.containsKey(method) - ? MethodConstants.RPC_OPTS[method]!['res']! - : MethodConstants - .RPC_OPTS[MethodConstants.UNREGISTERED_METHOD]!['res']!; + final fallbackMethod = MethodConstants.UNREGISTERED_METHOD; + final fallbackRpcOpts = MethodConstants.RPC_OPTS[method] ?? + MethodConstants.RPC_OPTS[fallbackMethod]!; + final fallbackOpts = fallbackRpcOpts['reject'] ?? fallbackRpcOpts['res']!; + + final RpcOptions opts = rpcOptions ?? fallbackOpts; + await core.relayClient.publish( topic: topic, message: message, diff --git a/lib/apis/core/pairing/utils/pairing_models.dart b/lib/apis/core/pairing/utils/pairing_models.dart index f6577412..b4f9499d 100644 --- a/lib/apis/core/pairing/utils/pairing_models.dart +++ b/lib/apis/core/pairing/utils/pairing_models.dart @@ -21,6 +21,7 @@ class PairingInfo with _$PairingInfo { required int expiry, required Relay relay, required bool active, + List? methods, PairingMetadata? peerMetadata, }) = _PairingInfo; diff --git a/lib/apis/core/pairing/utils/pairing_models.freezed.dart b/lib/apis/core/pairing/utils/pairing_models.freezed.dart index 72ccd707..0275658d 100644 --- a/lib/apis/core/pairing/utils/pairing_models.freezed.dart +++ b/lib/apis/core/pairing/utils/pairing_models.freezed.dart @@ -24,6 +24,7 @@ mixin _$PairingInfo { int get expiry => throw _privateConstructorUsedError; Relay get relay => throw _privateConstructorUsedError; bool get active => throw _privateConstructorUsedError; + List? get methods => throw _privateConstructorUsedError; PairingMetadata? get peerMetadata => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @@ -43,6 +44,7 @@ abstract class $PairingInfoCopyWith<$Res> { int expiry, Relay relay, bool active, + List? methods, PairingMetadata? peerMetadata}); $PairingMetadataCopyWith<$Res>? get peerMetadata; @@ -65,6 +67,7 @@ class _$PairingInfoCopyWithImpl<$Res, $Val extends PairingInfo> Object? expiry = null, Object? relay = null, Object? active = null, + Object? methods = freezed, Object? peerMetadata = freezed, }) { return _then(_value.copyWith( @@ -84,6 +87,10 @@ class _$PairingInfoCopyWithImpl<$Res, $Val extends PairingInfo> ? _value.active : active // ignore: cast_nullable_to_non_nullable as bool, + methods: freezed == methods + ? _value.methods + : methods // ignore: cast_nullable_to_non_nullable + as List?, peerMetadata: freezed == peerMetadata ? _value.peerMetadata : peerMetadata // ignore: cast_nullable_to_non_nullable @@ -117,6 +124,7 @@ abstract class _$$PairingInfoImplCopyWith<$Res> int expiry, Relay relay, bool active, + List? methods, PairingMetadata? peerMetadata}); @override @@ -138,6 +146,7 @@ class __$$PairingInfoImplCopyWithImpl<$Res> Object? expiry = null, Object? relay = null, Object? active = null, + Object? methods = freezed, Object? peerMetadata = freezed, }) { return _then(_$PairingInfoImpl( @@ -157,6 +166,10 @@ class __$$PairingInfoImplCopyWithImpl<$Res> ? _value.active : active // ignore: cast_nullable_to_non_nullable as bool, + methods: freezed == methods + ? _value._methods + : methods // ignore: cast_nullable_to_non_nullable + as List?, peerMetadata: freezed == peerMetadata ? _value.peerMetadata : peerMetadata // ignore: cast_nullable_to_non_nullable @@ -174,7 +187,9 @@ class _$PairingInfoImpl implements _PairingInfo { required this.expiry, required this.relay, required this.active, - this.peerMetadata}); + final List? methods, + this.peerMetadata}) + : _methods = methods; factory _$PairingInfoImpl.fromJson(Map json) => _$$PairingInfoImplFromJson(json); @@ -187,12 +202,22 @@ class _$PairingInfoImpl implements _PairingInfo { final Relay relay; @override final bool active; + final List? _methods; + @override + List? get methods { + final value = _methods; + if (value == null) return null; + if (_methods is EqualUnmodifiableListView) return _methods; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + @override final PairingMetadata? peerMetadata; @override String toString() { - return 'PairingInfo(topic: $topic, expiry: $expiry, relay: $relay, active: $active, peerMetadata: $peerMetadata)'; + return 'PairingInfo(topic: $topic, expiry: $expiry, relay: $relay, active: $active, methods: $methods, peerMetadata: $peerMetadata)'; } @override @@ -204,14 +229,15 @@ class _$PairingInfoImpl implements _PairingInfo { (identical(other.expiry, expiry) || other.expiry == expiry) && (identical(other.relay, relay) || other.relay == relay) && (identical(other.active, active) || other.active == active) && + const DeepCollectionEquality().equals(other._methods, _methods) && (identical(other.peerMetadata, peerMetadata) || other.peerMetadata == peerMetadata)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, topic, expiry, relay, active, peerMetadata); + int get hashCode => Object.hash(runtimeType, topic, expiry, relay, active, + const DeepCollectionEquality().hash(_methods), peerMetadata); @JsonKey(ignore: true) @override @@ -233,6 +259,7 @@ abstract class _PairingInfo implements PairingInfo { required final int expiry, required final Relay relay, required final bool active, + final List? methods, final PairingMetadata? peerMetadata}) = _$PairingInfoImpl; factory _PairingInfo.fromJson(Map json) = @@ -247,6 +274,8 @@ abstract class _PairingInfo implements PairingInfo { @override bool get active; @override + List? get methods; + @override PairingMetadata? get peerMetadata; @override @JsonKey(ignore: true) diff --git a/lib/apis/core/pairing/utils/pairing_models.g.dart b/lib/apis/core/pairing/utils/pairing_models.g.dart index 4f064249..78975b35 100644 --- a/lib/apis/core/pairing/utils/pairing_models.g.dart +++ b/lib/apis/core/pairing/utils/pairing_models.g.dart @@ -12,6 +12,8 @@ _$PairingInfoImpl _$$PairingInfoImplFromJson(Map json) => expiry: json['expiry'] as int, relay: Relay.fromJson(json['relay'] as Map), active: json['active'] as bool, + methods: + (json['methods'] as List?)?.map((e) => e as String).toList(), peerMetadata: json['peerMetadata'] == null ? null : PairingMetadata.fromJson( @@ -24,6 +26,7 @@ Map _$$PairingInfoImplToJson(_$PairingInfoImpl instance) => 'expiry': instance.expiry, 'relay': instance.relay.toJson(), 'active': instance.active, + 'methods': instance.methods, 'peerMetadata': instance.peerMetadata?.toJson(), }; diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 3c9d4c11..250d6e75 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -33,6 +33,9 @@ abstract class ISignClient { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthRequest; abstract final IGenericStore authRequests; + // NEW 1-CA METHOD + abstract final Event onSessionAuthRequest; + abstract final IGenericStore sessionAuthRequests; // App abstract final Event onSessionUpdate; @@ -41,7 +44,7 @@ abstract class ISignClient { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; // NEW 1-CA PROPERTY - abstract final Event onOCAuthResponse; + abstract final Event onSessionAuthResponse; Future init(); Future connect({ @@ -177,8 +180,8 @@ abstract class ISignClient { }); // NEW 1-CA METHOD FOR DAPP - Future authenticate({ - required OCARequestParams params, + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods, }); @@ -188,4 +191,16 @@ abstract class ISignClient { required Cacao cacao, required String projectId, }); + + Map getPendingSessionAuthRequests(); + + Future approveSessionAuthenticate({ + required int id, + List? auths, + }); + + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_app.dart b/lib/apis/sign_api/i_sign_engine_app.dart index 86178be1..c7ced660 100644 --- a/lib/apis/sign_api/i_sign_engine_app.dart +++ b/lib/apis/sign_api/i_sign_engine_app.dart @@ -8,7 +8,7 @@ abstract class ISignEngineApp extends ISignEngineCommon { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthResponse; // NEW 1-CA PROPERTY - abstract final Event onOCAuthResponse; + abstract final Event onSessionAuthResponse; Future connect({ Map? requiredNamespaces, @@ -57,8 +57,8 @@ abstract class ISignEngineApp extends ISignEngineCommon { }); // NEW 1-CA METHOD - Future authenticate({ - required OCARequestParams params, + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods, }); diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index ce249deb..0830ef2b 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -13,6 +13,9 @@ import 'package:walletconnect_flutter_v2/apis/core/store/i_generic_store.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_events.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_events.dart'; + abstract class ISignEngineWallet extends ISignEngineCommon { abstract final Event onSessionProposal; abstract final Event onSessionProposalError; @@ -21,6 +24,9 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // FORMER AUTH ENGINE PROPERTY abstract final Event onAuthRequest; abstract final IGenericStore authRequests; + // NEW 1-CA METHOD + abstract final Event onSessionAuthRequest; + abstract final IGenericStore sessionAuthRequests; Future pair({ required Uri uri, @@ -96,4 +102,16 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // FORMER AUTH ENGINE PROPERTY // query all pending requests Map getPendingAuthRequests(); + + Map getPendingSessionAuthRequests(); + + Future approveSessionAuthenticate({ + required int id, + List? auths, + }); + + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }); } diff --git a/lib/apis/sign_api/models/auth/common_auth_models.dart b/lib/apis/sign_api/models/auth/common_auth_models.dart index 99adc23c..a8393afb 100644 --- a/lib/apis/sign_api/models/auth/common_auth_models.dart +++ b/lib/apis/sign_api/models/auth/common_auth_models.dart @@ -1,7 +1,7 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/ocauth_models.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_models.dart'; part 'common_auth_models.g.dart'; part 'common_auth_models.freezed.dart'; @@ -48,7 +48,9 @@ class CacaoRequestPayload with _$CacaoRequestPayload { ); } - factory CacaoRequestPayload.fromOCAPayloadParams(OCAPayloadParams params) { + factory CacaoRequestPayload.fromSessionAuthPayloadParams( + SessionAuthPayloadParams params, + ) { return CacaoRequestPayload( domain: params.domain, aud: params.aud, @@ -125,6 +127,7 @@ class CacaoPayload with _$CacaoPayload { @freezed class CacaoHeader with _$CacaoHeader { static const EIP4361 = 'eip4361'; + static const CAIP122 = 'caip122'; @JsonSerializable(includeIfNull: false) const factory CacaoHeader({ diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.dart b/lib/apis/sign_api/models/auth/json_rpc_models.dart deleted file mode 100644 index 86cc595d..00000000 --- a/lib/apis/sign_api/models/auth/json_rpc_models.dart +++ /dev/null @@ -1,56 +0,0 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; -import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/auth_client_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/ocauth_models.dart'; - -part 'json_rpc_models.g.dart'; -part 'json_rpc_models.freezed.dart'; - -@freezed -class WcAuthRequestRequest with _$WcAuthRequestRequest { - @JsonSerializable() - const factory WcAuthRequestRequest({ - required AuthPayloadParams payloadParams, - required ConnectionMetadata requester, - }) = _WcAuthRequestRequest; - - factory WcAuthRequestRequest.fromJson(Map json) => - _$WcAuthRequestRequestFromJson(json); -} - -@freezed -class WcAuthRequestResult with _$WcAuthRequestResult { - @JsonSerializable() - const factory WcAuthRequestResult({ - required Cacao cacao, - }) = _WcAuthRequestResult; - - factory WcAuthRequestResult.fromJson(Map json) => - _$WcAuthRequestResultFromJson(json); -} - -@freezed -class WcOCARequestParams with _$WcOCARequestParams { - @JsonSerializable() - const factory WcOCARequestParams({ - required OCAPayloadParams authPayload, - required ConnectionMetadata requester, - required int expiryTimestamp, - }) = _WcOCARequestParams; - - factory WcOCARequestParams.fromJson(Map json) => - _$WcOCARequestParamsFromJson(json); -} - -@freezed -class WcOCARequestResult with _$WcOCARequestResult { - @JsonSerializable() - const factory WcOCARequestResult({ - required List cacaos, - required ConnectionMetadata responder, - }) = _WcOCARequestResult; - - factory WcOCARequestResult.fromJson(Map json) => - _$WcOCARequestResultFromJson(json); -} diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart b/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart deleted file mode 100644 index 62eb4727..00000000 --- a/lib/apis/sign_api/models/auth/json_rpc_models.freezed.dart +++ /dev/null @@ -1,742 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'json_rpc_models.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -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'); - -WcAuthRequestRequest _$WcAuthRequestRequestFromJson(Map json) { - return _WcAuthRequestRequest.fromJson(json); -} - -/// @nodoc -mixin _$WcAuthRequestRequest { - AuthPayloadParams get payloadParams => throw _privateConstructorUsedError; - ConnectionMetadata get requester => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $WcAuthRequestRequestCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $WcAuthRequestRequestCopyWith<$Res> { - factory $WcAuthRequestRequestCopyWith(WcAuthRequestRequest value, - $Res Function(WcAuthRequestRequest) then) = - _$WcAuthRequestRequestCopyWithImpl<$Res, WcAuthRequestRequest>; - @useResult - $Res call({AuthPayloadParams payloadParams, ConnectionMetadata requester}); - - $AuthPayloadParamsCopyWith<$Res> get payloadParams; - $ConnectionMetadataCopyWith<$Res> get requester; -} - -/// @nodoc -class _$WcAuthRequestRequestCopyWithImpl<$Res, - $Val extends WcAuthRequestRequest> - implements $WcAuthRequestRequestCopyWith<$Res> { - _$WcAuthRequestRequestCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? payloadParams = null, - Object? requester = null, - }) { - return _then(_value.copyWith( - payloadParams: null == payloadParams - ? _value.payloadParams - : payloadParams // ignore: cast_nullable_to_non_nullable - as AuthPayloadParams, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $AuthPayloadParamsCopyWith<$Res> get payloadParams { - return $AuthPayloadParamsCopyWith<$Res>(_value.payloadParams, (value) { - return _then(_value.copyWith(payloadParams: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $ConnectionMetadataCopyWith<$Res> get requester { - return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { - return _then(_value.copyWith(requester: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$WcAuthRequestRequestImplCopyWith<$Res> - implements $WcAuthRequestRequestCopyWith<$Res> { - factory _$$WcAuthRequestRequestImplCopyWith(_$WcAuthRequestRequestImpl value, - $Res Function(_$WcAuthRequestRequestImpl) then) = - __$$WcAuthRequestRequestImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({AuthPayloadParams payloadParams, ConnectionMetadata requester}); - - @override - $AuthPayloadParamsCopyWith<$Res> get payloadParams; - @override - $ConnectionMetadataCopyWith<$Res> get requester; -} - -/// @nodoc -class __$$WcAuthRequestRequestImplCopyWithImpl<$Res> - extends _$WcAuthRequestRequestCopyWithImpl<$Res, _$WcAuthRequestRequestImpl> - implements _$$WcAuthRequestRequestImplCopyWith<$Res> { - __$$WcAuthRequestRequestImplCopyWithImpl(_$WcAuthRequestRequestImpl _value, - $Res Function(_$WcAuthRequestRequestImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? payloadParams = null, - Object? requester = null, - }) { - return _then(_$WcAuthRequestRequestImpl( - payloadParams: null == payloadParams - ? _value.payloadParams - : payloadParams // ignore: cast_nullable_to_non_nullable - as AuthPayloadParams, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - )); - } -} - -/// @nodoc - -@JsonSerializable() -class _$WcAuthRequestRequestImpl implements _WcAuthRequestRequest { - const _$WcAuthRequestRequestImpl( - {required this.payloadParams, required this.requester}); - - factory _$WcAuthRequestRequestImpl.fromJson(Map json) => - _$$WcAuthRequestRequestImplFromJson(json); - - @override - final AuthPayloadParams payloadParams; - @override - final ConnectionMetadata requester; - - @override - String toString() { - return 'WcAuthRequestRequest(payloadParams: $payloadParams, requester: $requester)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$WcAuthRequestRequestImpl && - (identical(other.payloadParams, payloadParams) || - other.payloadParams == payloadParams) && - (identical(other.requester, requester) || - other.requester == requester)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, payloadParams, requester); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$WcAuthRequestRequestImplCopyWith<_$WcAuthRequestRequestImpl> - get copyWith => - __$$WcAuthRequestRequestImplCopyWithImpl<_$WcAuthRequestRequestImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$WcAuthRequestRequestImplToJson( - this, - ); - } -} - -abstract class _WcAuthRequestRequest implements WcAuthRequestRequest { - const factory _WcAuthRequestRequest( - {required final AuthPayloadParams payloadParams, - required final ConnectionMetadata requester}) = - _$WcAuthRequestRequestImpl; - - factory _WcAuthRequestRequest.fromJson(Map json) = - _$WcAuthRequestRequestImpl.fromJson; - - @override - AuthPayloadParams get payloadParams; - @override - ConnectionMetadata get requester; - @override - @JsonKey(ignore: true) - _$$WcAuthRequestRequestImplCopyWith<_$WcAuthRequestRequestImpl> - get copyWith => throw _privateConstructorUsedError; -} - -WcAuthRequestResult _$WcAuthRequestResultFromJson(Map json) { - return _WcAuthRequestResult.fromJson(json); -} - -/// @nodoc -mixin _$WcAuthRequestResult { - Cacao get cacao => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $WcAuthRequestResultCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $WcAuthRequestResultCopyWith<$Res> { - factory $WcAuthRequestResultCopyWith( - WcAuthRequestResult value, $Res Function(WcAuthRequestResult) then) = - _$WcAuthRequestResultCopyWithImpl<$Res, WcAuthRequestResult>; - @useResult - $Res call({Cacao cacao}); - - $CacaoCopyWith<$Res> get cacao; -} - -/// @nodoc -class _$WcAuthRequestResultCopyWithImpl<$Res, $Val extends WcAuthRequestResult> - implements $WcAuthRequestResultCopyWith<$Res> { - _$WcAuthRequestResultCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? cacao = null, - }) { - return _then(_value.copyWith( - cacao: null == cacao - ? _value.cacao - : cacao // ignore: cast_nullable_to_non_nullable - as Cacao, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoCopyWith<$Res> get cacao { - return $CacaoCopyWith<$Res>(_value.cacao, (value) { - return _then(_value.copyWith(cacao: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$WcAuthRequestResultImplCopyWith<$Res> - implements $WcAuthRequestResultCopyWith<$Res> { - factory _$$WcAuthRequestResultImplCopyWith(_$WcAuthRequestResultImpl value, - $Res Function(_$WcAuthRequestResultImpl) then) = - __$$WcAuthRequestResultImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({Cacao cacao}); - - @override - $CacaoCopyWith<$Res> get cacao; -} - -/// @nodoc -class __$$WcAuthRequestResultImplCopyWithImpl<$Res> - extends _$WcAuthRequestResultCopyWithImpl<$Res, _$WcAuthRequestResultImpl> - implements _$$WcAuthRequestResultImplCopyWith<$Res> { - __$$WcAuthRequestResultImplCopyWithImpl(_$WcAuthRequestResultImpl _value, - $Res Function(_$WcAuthRequestResultImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? cacao = null, - }) { - return _then(_$WcAuthRequestResultImpl( - cacao: null == cacao - ? _value.cacao - : cacao // ignore: cast_nullable_to_non_nullable - as Cacao, - )); - } -} - -/// @nodoc - -@JsonSerializable() -class _$WcAuthRequestResultImpl implements _WcAuthRequestResult { - const _$WcAuthRequestResultImpl({required this.cacao}); - - factory _$WcAuthRequestResultImpl.fromJson(Map json) => - _$$WcAuthRequestResultImplFromJson(json); - - @override - final Cacao cacao; - - @override - String toString() { - return 'WcAuthRequestResult(cacao: $cacao)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$WcAuthRequestResultImpl && - (identical(other.cacao, cacao) || other.cacao == cacao)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, cacao); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$WcAuthRequestResultImplCopyWith<_$WcAuthRequestResultImpl> get copyWith => - __$$WcAuthRequestResultImplCopyWithImpl<_$WcAuthRequestResultImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$WcAuthRequestResultImplToJson( - this, - ); - } -} - -abstract class _WcAuthRequestResult implements WcAuthRequestResult { - const factory _WcAuthRequestResult({required final Cacao cacao}) = - _$WcAuthRequestResultImpl; - - factory _WcAuthRequestResult.fromJson(Map json) = - _$WcAuthRequestResultImpl.fromJson; - - @override - Cacao get cacao; - @override - @JsonKey(ignore: true) - _$$WcAuthRequestResultImplCopyWith<_$WcAuthRequestResultImpl> get copyWith => - throw _privateConstructorUsedError; -} - -WcOCARequestParams _$WcOCARequestParamsFromJson(Map json) { - return _WcOCARequestParams.fromJson(json); -} - -/// @nodoc -mixin _$WcOCARequestParams { - OCAPayloadParams get authPayload => throw _privateConstructorUsedError; - ConnectionMetadata get requester => throw _privateConstructorUsedError; - int get expiryTimestamp => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $WcOCARequestParamsCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $WcOCARequestParamsCopyWith<$Res> { - factory $WcOCARequestParamsCopyWith( - WcOCARequestParams value, $Res Function(WcOCARequestParams) then) = - _$WcOCARequestParamsCopyWithImpl<$Res, WcOCARequestParams>; - @useResult - $Res call( - {OCAPayloadParams authPayload, - ConnectionMetadata requester, - int expiryTimestamp}); - - $OCAPayloadParamsCopyWith<$Res> get authPayload; - $ConnectionMetadataCopyWith<$Res> get requester; -} - -/// @nodoc -class _$WcOCARequestParamsCopyWithImpl<$Res, $Val extends WcOCARequestParams> - implements $WcOCARequestParamsCopyWith<$Res> { - _$WcOCARequestParamsCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? authPayload = null, - Object? requester = null, - Object? expiryTimestamp = null, - }) { - return _then(_value.copyWith( - authPayload: null == authPayload - ? _value.authPayload - : authPayload // ignore: cast_nullable_to_non_nullable - as OCAPayloadParams, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - expiryTimestamp: null == expiryTimestamp - ? _value.expiryTimestamp - : expiryTimestamp // ignore: cast_nullable_to_non_nullable - as int, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $OCAPayloadParamsCopyWith<$Res> get authPayload { - return $OCAPayloadParamsCopyWith<$Res>(_value.authPayload, (value) { - return _then(_value.copyWith(authPayload: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $ConnectionMetadataCopyWith<$Res> get requester { - return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { - return _then(_value.copyWith(requester: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$WcOCARequestParamsImplCopyWith<$Res> - implements $WcOCARequestParamsCopyWith<$Res> { - factory _$$WcOCARequestParamsImplCopyWith(_$WcOCARequestParamsImpl value, - $Res Function(_$WcOCARequestParamsImpl) then) = - __$$WcOCARequestParamsImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {OCAPayloadParams authPayload, - ConnectionMetadata requester, - int expiryTimestamp}); - - @override - $OCAPayloadParamsCopyWith<$Res> get authPayload; - @override - $ConnectionMetadataCopyWith<$Res> get requester; -} - -/// @nodoc -class __$$WcOCARequestParamsImplCopyWithImpl<$Res> - extends _$WcOCARequestParamsCopyWithImpl<$Res, _$WcOCARequestParamsImpl> - implements _$$WcOCARequestParamsImplCopyWith<$Res> { - __$$WcOCARequestParamsImplCopyWithImpl(_$WcOCARequestParamsImpl _value, - $Res Function(_$WcOCARequestParamsImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? authPayload = null, - Object? requester = null, - Object? expiryTimestamp = null, - }) { - return _then(_$WcOCARequestParamsImpl( - authPayload: null == authPayload - ? _value.authPayload - : authPayload // ignore: cast_nullable_to_non_nullable - as OCAPayloadParams, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - expiryTimestamp: null == expiryTimestamp - ? _value.expiryTimestamp - : expiryTimestamp // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// @nodoc - -@JsonSerializable() -class _$WcOCARequestParamsImpl implements _WcOCARequestParams { - const _$WcOCARequestParamsImpl( - {required this.authPayload, - required this.requester, - required this.expiryTimestamp}); - - factory _$WcOCARequestParamsImpl.fromJson(Map json) => - _$$WcOCARequestParamsImplFromJson(json); - - @override - final OCAPayloadParams authPayload; - @override - final ConnectionMetadata requester; - @override - final int expiryTimestamp; - - @override - String toString() { - return 'WcOCARequestParams(authPayload: $authPayload, requester: $requester, expiryTimestamp: $expiryTimestamp)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$WcOCARequestParamsImpl && - (identical(other.authPayload, authPayload) || - other.authPayload == authPayload) && - (identical(other.requester, requester) || - other.requester == requester) && - (identical(other.expiryTimestamp, expiryTimestamp) || - other.expiryTimestamp == expiryTimestamp)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => - Object.hash(runtimeType, authPayload, requester, expiryTimestamp); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$WcOCARequestParamsImplCopyWith<_$WcOCARequestParamsImpl> get copyWith => - __$$WcOCARequestParamsImplCopyWithImpl<_$WcOCARequestParamsImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$WcOCARequestParamsImplToJson( - this, - ); - } -} - -abstract class _WcOCARequestParams implements WcOCARequestParams { - const factory _WcOCARequestParams( - {required final OCAPayloadParams authPayload, - required final ConnectionMetadata requester, - required final int expiryTimestamp}) = _$WcOCARequestParamsImpl; - - factory _WcOCARequestParams.fromJson(Map json) = - _$WcOCARequestParamsImpl.fromJson; - - @override - OCAPayloadParams get authPayload; - @override - ConnectionMetadata get requester; - @override - int get expiryTimestamp; - @override - @JsonKey(ignore: true) - _$$WcOCARequestParamsImplCopyWith<_$WcOCARequestParamsImpl> get copyWith => - throw _privateConstructorUsedError; -} - -WcOCARequestResult _$WcOCARequestResultFromJson(Map json) { - return _WcOCARequestResult.fromJson(json); -} - -/// @nodoc -mixin _$WcOCARequestResult { - List get cacaos => throw _privateConstructorUsedError; - ConnectionMetadata get responder => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $WcOCARequestResultCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $WcOCARequestResultCopyWith<$Res> { - factory $WcOCARequestResultCopyWith( - WcOCARequestResult value, $Res Function(WcOCARequestResult) then) = - _$WcOCARequestResultCopyWithImpl<$Res, WcOCARequestResult>; - @useResult - $Res call({List cacaos, ConnectionMetadata responder}); - - $ConnectionMetadataCopyWith<$Res> get responder; -} - -/// @nodoc -class _$WcOCARequestResultCopyWithImpl<$Res, $Val extends WcOCARequestResult> - implements $WcOCARequestResultCopyWith<$Res> { - _$WcOCARequestResultCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? cacaos = null, - Object? responder = null, - }) { - return _then(_value.copyWith( - cacaos: null == cacaos - ? _value.cacaos - : cacaos // ignore: cast_nullable_to_non_nullable - as List, - responder: null == responder - ? _value.responder - : responder // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $ConnectionMetadataCopyWith<$Res> get responder { - return $ConnectionMetadataCopyWith<$Res>(_value.responder, (value) { - return _then(_value.copyWith(responder: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$WcOCARequestResultImplCopyWith<$Res> - implements $WcOCARequestResultCopyWith<$Res> { - factory _$$WcOCARequestResultImplCopyWith(_$WcOCARequestResultImpl value, - $Res Function(_$WcOCARequestResultImpl) then) = - __$$WcOCARequestResultImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({List cacaos, ConnectionMetadata responder}); - - @override - $ConnectionMetadataCopyWith<$Res> get responder; -} - -/// @nodoc -class __$$WcOCARequestResultImplCopyWithImpl<$Res> - extends _$WcOCARequestResultCopyWithImpl<$Res, _$WcOCARequestResultImpl> - implements _$$WcOCARequestResultImplCopyWith<$Res> { - __$$WcOCARequestResultImplCopyWithImpl(_$WcOCARequestResultImpl _value, - $Res Function(_$WcOCARequestResultImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? cacaos = null, - Object? responder = null, - }) { - return _then(_$WcOCARequestResultImpl( - cacaos: null == cacaos - ? _value._cacaos - : cacaos // ignore: cast_nullable_to_non_nullable - as List, - responder: null == responder - ? _value.responder - : responder // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - )); - } -} - -/// @nodoc - -@JsonSerializable() -class _$WcOCARequestResultImpl implements _WcOCARequestResult { - const _$WcOCARequestResultImpl( - {required final List cacaos, required this.responder}) - : _cacaos = cacaos; - - factory _$WcOCARequestResultImpl.fromJson(Map json) => - _$$WcOCARequestResultImplFromJson(json); - - final List _cacaos; - @override - List get cacaos { - if (_cacaos is EqualUnmodifiableListView) return _cacaos; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_cacaos); - } - - @override - final ConnectionMetadata responder; - - @override - String toString() { - return 'WcOCARequestResult(cacaos: $cacaos, responder: $responder)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$WcOCARequestResultImpl && - const DeepCollectionEquality().equals(other._cacaos, _cacaos) && - (identical(other.responder, responder) || - other.responder == responder)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_cacaos), responder); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$WcOCARequestResultImplCopyWith<_$WcOCARequestResultImpl> get copyWith => - __$$WcOCARequestResultImplCopyWithImpl<_$WcOCARequestResultImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$WcOCARequestResultImplToJson( - this, - ); - } -} - -abstract class _WcOCARequestResult implements WcOCARequestResult { - const factory _WcOCARequestResult( - {required final List cacaos, - required final ConnectionMetadata responder}) = _$WcOCARequestResultImpl; - - factory _WcOCARequestResult.fromJson(Map json) = - _$WcOCARequestResultImpl.fromJson; - - @override - List get cacaos; - @override - ConnectionMetadata get responder; - @override - @JsonKey(ignore: true) - _$$WcOCARequestResultImplCopyWith<_$WcOCARequestResultImpl> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart b/lib/apis/sign_api/models/auth/json_rpc_models.g.dart deleted file mode 100644 index 09e95e45..00000000 --- a/lib/apis/sign_api/models/auth/json_rpc_models.g.dart +++ /dev/null @@ -1,70 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'json_rpc_models.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$WcAuthRequestRequestImpl _$$WcAuthRequestRequestImplFromJson( - Map json) => - _$WcAuthRequestRequestImpl( - payloadParams: AuthPayloadParams.fromJson( - json['payloadParams'] as Map), - requester: ConnectionMetadata.fromJson( - json['requester'] as Map), - ); - -Map _$$WcAuthRequestRequestImplToJson( - _$WcAuthRequestRequestImpl instance) => - { - 'payloadParams': instance.payloadParams.toJson(), - 'requester': instance.requester.toJson(), - }; - -_$WcAuthRequestResultImpl _$$WcAuthRequestResultImplFromJson( - Map json) => - _$WcAuthRequestResultImpl( - cacao: Cacao.fromJson(json['cacao'] as Map), - ); - -Map _$$WcAuthRequestResultImplToJson( - _$WcAuthRequestResultImpl instance) => - { - 'cacao': instance.cacao.toJson(), - }; - -_$WcOCARequestParamsImpl _$$WcOCARequestParamsImplFromJson( - Map json) => - _$WcOCARequestParamsImpl( - authPayload: OCAPayloadParams.fromJson( - json['authPayload'] as Map), - requester: ConnectionMetadata.fromJson( - json['requester'] as Map), - expiryTimestamp: json['expiryTimestamp'] as int, - ); - -Map _$$WcOCARequestParamsImplToJson( - _$WcOCARequestParamsImpl instance) => - { - 'authPayload': instance.authPayload.toJson(), - 'requester': instance.requester.toJson(), - 'expiryTimestamp': instance.expiryTimestamp, - }; - -_$WcOCARequestResultImpl _$$WcOCARequestResultImplFromJson( - Map json) => - _$WcOCARequestResultImpl( - cacaos: (json['cacaos'] as List) - .map((e) => Cacao.fromJson(e as Map)) - .toList(), - responder: ConnectionMetadata.fromJson( - json['responder'] as Map), - ); - -Map _$$WcOCARequestResultImplToJson( - _$WcOCARequestResultImpl instance) => - { - 'cacaos': instance.cacaos.map((e) => e.toJson()).toList(), - 'responder': instance.responder.toJson(), - }; diff --git a/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart b/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart index 42d1b29e..6fab4f7c 100644 --- a/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart +++ b/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart @@ -14,12 +14,13 @@ 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'); -OCAPayloadParams _$OCAPayloadParamsFromJson(Map json) { - return _OCAPayloadParams.fromJson(json); +SessionAuthPayloadParams _$SessionAuthPayloadParamsFromJson( + Map json) { + return _SessionAuthPayloadParams.fromJson(json); } /// @nodoc -mixin _$OCAPayloadParams { +mixin _$SessionAuthPayloadParams { List get chains => throw _privateConstructorUsedError; String get domain => throw _privateConstructorUsedError; String get nonce => throw _privateConstructorUsedError; @@ -35,15 +36,15 @@ mixin _$OCAPayloadParams { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $OCAPayloadParamsCopyWith get copyWith => + $SessionAuthPayloadParamsCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class $OCAPayloadParamsCopyWith<$Res> { - factory $OCAPayloadParamsCopyWith( - OCAPayloadParams value, $Res Function(OCAPayloadParams) then) = - _$OCAPayloadParamsCopyWithImpl<$Res, OCAPayloadParams>; +abstract class $SessionAuthPayloadParamsCopyWith<$Res> { + factory $SessionAuthPayloadParamsCopyWith(SessionAuthPayloadParams value, + $Res Function(SessionAuthPayloadParams) then) = + _$SessionAuthPayloadParamsCopyWithImpl<$Res, SessionAuthPayloadParams>; @useResult $Res call( {List chains, @@ -61,9 +62,10 @@ abstract class $OCAPayloadParamsCopyWith<$Res> { } /// @nodoc -class _$OCAPayloadParamsCopyWithImpl<$Res, $Val extends OCAPayloadParams> - implements $OCAPayloadParamsCopyWith<$Res> { - _$OCAPayloadParamsCopyWithImpl(this._value, this._then); +class _$SessionAuthPayloadParamsCopyWithImpl<$Res, + $Val extends SessionAuthPayloadParams> + implements $SessionAuthPayloadParamsCopyWith<$Res> { + _$SessionAuthPayloadParamsCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; @@ -140,11 +142,12 @@ class _$OCAPayloadParamsCopyWithImpl<$Res, $Val extends OCAPayloadParams> } /// @nodoc -abstract class _$$OCAPayloadParamsImplCopyWith<$Res> - implements $OCAPayloadParamsCopyWith<$Res> { - factory _$$OCAPayloadParamsImplCopyWith(_$OCAPayloadParamsImpl value, - $Res Function(_$OCAPayloadParamsImpl) then) = - __$$OCAPayloadParamsImplCopyWithImpl<$Res>; +abstract class _$$SessionAuthPayloadParamsImplCopyWith<$Res> + implements $SessionAuthPayloadParamsCopyWith<$Res> { + factory _$$SessionAuthPayloadParamsImplCopyWith( + _$SessionAuthPayloadParamsImpl value, + $Res Function(_$SessionAuthPayloadParamsImpl) then) = + __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -163,11 +166,13 @@ abstract class _$$OCAPayloadParamsImplCopyWith<$Res> } /// @nodoc -class __$$OCAPayloadParamsImplCopyWithImpl<$Res> - extends _$OCAPayloadParamsCopyWithImpl<$Res, _$OCAPayloadParamsImpl> - implements _$$OCAPayloadParamsImplCopyWith<$Res> { - __$$OCAPayloadParamsImplCopyWithImpl(_$OCAPayloadParamsImpl _value, - $Res Function(_$OCAPayloadParamsImpl) _then) +class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> + extends _$SessionAuthPayloadParamsCopyWithImpl<$Res, + _$SessionAuthPayloadParamsImpl> + implements _$$SessionAuthPayloadParamsImplCopyWith<$Res> { + __$$SessionAuthPayloadParamsImplCopyWithImpl( + _$SessionAuthPayloadParamsImpl _value, + $Res Function(_$SessionAuthPayloadParamsImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -186,7 +191,7 @@ class __$$OCAPayloadParamsImplCopyWithImpl<$Res> Object? requestId = freezed, Object? resources = freezed, }) { - return _then(_$OCAPayloadParamsImpl( + return _then(_$SessionAuthPayloadParamsImpl( chains: null == chains ? _value._chains : chains // ignore: cast_nullable_to_non_nullable @@ -242,8 +247,8 @@ class __$$OCAPayloadParamsImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable(includeIfNull: false) -class _$OCAPayloadParamsImpl implements _OCAPayloadParams { - const _$OCAPayloadParamsImpl( +class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { + const _$SessionAuthPayloadParamsImpl( {required final List chains, required this.domain, required this.nonce, @@ -259,8 +264,8 @@ class _$OCAPayloadParamsImpl implements _OCAPayloadParams { : _chains = chains, _resources = resources; - factory _$OCAPayloadParamsImpl.fromJson(Map json) => - _$$OCAPayloadParamsImplFromJson(json); + factory _$SessionAuthPayloadParamsImpl.fromJson(Map json) => + _$$SessionAuthPayloadParamsImplFromJson(json); final List _chains; @override @@ -304,14 +309,14 @@ class _$OCAPayloadParamsImpl implements _OCAPayloadParams { @override String toString() { - return 'OCAPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + return 'SessionAuthPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$OCAPayloadParamsImpl && + other is _$SessionAuthPayloadParamsImpl && const DeepCollectionEquality().equals(other._chains, _chains) && (identical(other.domain, domain) || other.domain == domain) && (identical(other.nonce, nonce) || other.nonce == nonce) && @@ -349,20 +354,20 @@ class _$OCAPayloadParamsImpl implements _OCAPayloadParams { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => - __$$OCAPayloadParamsImplCopyWithImpl<_$OCAPayloadParamsImpl>( - this, _$identity); + _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> + get copyWith => __$$SessionAuthPayloadParamsImplCopyWithImpl< + _$SessionAuthPayloadParamsImpl>(this, _$identity); @override Map toJson() { - return _$$OCAPayloadParamsImplToJson( + return _$$SessionAuthPayloadParamsImplToJson( this, ); } } -abstract class _OCAPayloadParams implements OCAPayloadParams { - const factory _OCAPayloadParams( +abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { + const factory _SessionAuthPayloadParams( {required final List chains, required final String domain, required final String nonce, @@ -374,10 +379,10 @@ abstract class _OCAPayloadParams implements OCAPayloadParams { final String? exp, final String? statement, final String? requestId, - final List? resources}) = _$OCAPayloadParamsImpl; + final List? resources}) = _$SessionAuthPayloadParamsImpl; - factory _OCAPayloadParams.fromJson(Map json) = - _$OCAPayloadParamsImpl.fromJson; + factory _SessionAuthPayloadParams.fromJson(Map json) = + _$SessionAuthPayloadParamsImpl.fromJson; @override List get chains; @@ -405,6 +410,295 @@ abstract class _OCAPayloadParams implements OCAPayloadParams { List? get resources; @override @JsonKey(ignore: true) - _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => + _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> + get copyWith => throw _privateConstructorUsedError; +} + +PendingSessionAuthRequest _$PendingSessionAuthRequestFromJson( + Map json) { + return _PendingSessionAuthRequest.fromJson(json); +} + +/// @nodoc +mixin _$PendingSessionAuthRequest { + int get id => throw _privateConstructorUsedError; + String get pairingTopic => throw _privateConstructorUsedError; + ConnectionMetadata get requester => throw _privateConstructorUsedError; + int get expiryTimestamp => throw _privateConstructorUsedError; + CacaoRequestPayload get authPayload => throw _privateConstructorUsedError; + VerifyContext get verifyContext => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $PendingSessionAuthRequestCopyWith get copyWith => throw _privateConstructorUsedError; } + +/// @nodoc +abstract class $PendingSessionAuthRequestCopyWith<$Res> { + factory $PendingSessionAuthRequestCopyWith(PendingSessionAuthRequest value, + $Res Function(PendingSessionAuthRequest) then) = + _$PendingSessionAuthRequestCopyWithImpl<$Res, PendingSessionAuthRequest>; + @useResult + $Res call( + {int id, + String pairingTopic, + ConnectionMetadata requester, + int expiryTimestamp, + CacaoRequestPayload authPayload, + VerifyContext verifyContext}); + + $ConnectionMetadataCopyWith<$Res> get requester; + $CacaoRequestPayloadCopyWith<$Res> get authPayload; + $VerifyContextCopyWith<$Res> get verifyContext; +} + +/// @nodoc +class _$PendingSessionAuthRequestCopyWithImpl<$Res, + $Val extends PendingSessionAuthRequest> + implements $PendingSessionAuthRequestCopyWith<$Res> { + _$PendingSessionAuthRequestCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? requester = null, + Object? expiryTimestamp = null, + Object? authPayload = null, + Object? verifyContext = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as CacaoRequestPayload, + verifyContext: null == verifyContext + ? _value.verifyContext + : verifyContext // ignore: cast_nullable_to_non_nullable + as VerifyContext, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get requester { + return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { + return _then(_value.copyWith(requester: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoRequestPayloadCopyWith<$Res> get authPayload { + return $CacaoRequestPayloadCopyWith<$Res>(_value.authPayload, (value) { + return _then(_value.copyWith(authPayload: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $VerifyContextCopyWith<$Res> get verifyContext { + return $VerifyContextCopyWith<$Res>(_value.verifyContext, (value) { + return _then(_value.copyWith(verifyContext: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$PendingSessionAuthRequestImplCopyWith<$Res> + implements $PendingSessionAuthRequestCopyWith<$Res> { + factory _$$PendingSessionAuthRequestImplCopyWith( + _$PendingSessionAuthRequestImpl value, + $Res Function(_$PendingSessionAuthRequestImpl) then) = + __$$PendingSessionAuthRequestImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String pairingTopic, + ConnectionMetadata requester, + int expiryTimestamp, + CacaoRequestPayload authPayload, + VerifyContext verifyContext}); + + @override + $ConnectionMetadataCopyWith<$Res> get requester; + @override + $CacaoRequestPayloadCopyWith<$Res> get authPayload; + @override + $VerifyContextCopyWith<$Res> get verifyContext; +} + +/// @nodoc +class __$$PendingSessionAuthRequestImplCopyWithImpl<$Res> + extends _$PendingSessionAuthRequestCopyWithImpl<$Res, + _$PendingSessionAuthRequestImpl> + implements _$$PendingSessionAuthRequestImplCopyWith<$Res> { + __$$PendingSessionAuthRequestImplCopyWithImpl( + _$PendingSessionAuthRequestImpl _value, + $Res Function(_$PendingSessionAuthRequestImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? requester = null, + Object? expiryTimestamp = null, + Object? authPayload = null, + Object? verifyContext = null, + }) { + return _then(_$PendingSessionAuthRequestImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as CacaoRequestPayload, + verifyContext: null == verifyContext + ? _value.verifyContext + : verifyContext // ignore: cast_nullable_to_non_nullable + as VerifyContext, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$PendingSessionAuthRequestImpl implements _PendingSessionAuthRequest { + const _$PendingSessionAuthRequestImpl( + {required this.id, + required this.pairingTopic, + required this.requester, + required this.expiryTimestamp, + required this.authPayload, + required this.verifyContext}); + + factory _$PendingSessionAuthRequestImpl.fromJson(Map json) => + _$$PendingSessionAuthRequestImplFromJson(json); + + @override + final int id; + @override + final String pairingTopic; + @override + final ConnectionMetadata requester; + @override + final int expiryTimestamp; + @override + final CacaoRequestPayload authPayload; + @override + final VerifyContext verifyContext; + + @override + String toString() { + return 'PendingSessionAuthRequest(id: $id, pairingTopic: $pairingTopic, requester: $requester, expiryTimestamp: $expiryTimestamp, authPayload: $authPayload, verifyContext: $verifyContext)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PendingSessionAuthRequestImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.pairingTopic, pairingTopic) || + other.pairingTopic == pairingTopic) && + (identical(other.requester, requester) || + other.requester == requester) && + (identical(other.expiryTimestamp, expiryTimestamp) || + other.expiryTimestamp == expiryTimestamp) && + (identical(other.authPayload, authPayload) || + other.authPayload == authPayload) && + (identical(other.verifyContext, verifyContext) || + other.verifyContext == verifyContext)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, pairingTopic, requester, + expiryTimestamp, authPayload, verifyContext); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> + get copyWith => __$$PendingSessionAuthRequestImplCopyWithImpl< + _$PendingSessionAuthRequestImpl>(this, _$identity); + + @override + Map toJson() { + return _$$PendingSessionAuthRequestImplToJson( + this, + ); + } +} + +abstract class _PendingSessionAuthRequest implements PendingSessionAuthRequest { + const factory _PendingSessionAuthRequest( + {required final int id, + required final String pairingTopic, + required final ConnectionMetadata requester, + required final int expiryTimestamp, + required final CacaoRequestPayload authPayload, + required final VerifyContext verifyContext}) = + _$PendingSessionAuthRequestImpl; + + factory _PendingSessionAuthRequest.fromJson(Map json) = + _$PendingSessionAuthRequestImpl.fromJson; + + @override + int get id; + @override + String get pairingTopic; + @override + ConnectionMetadata get requester; + @override + int get expiryTimestamp; + @override + CacaoRequestPayload get authPayload; + @override + VerifyContext get verifyContext; + @override + @JsonKey(ignore: true) + _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/apis/sign_api/models/auth/ocauth_models.g.dart b/lib/apis/sign_api/models/auth/ocauth_models.g.dart index a808b9b6..98b5dae2 100644 --- a/lib/apis/sign_api/models/auth/ocauth_models.g.dart +++ b/lib/apis/sign_api/models/auth/ocauth_models.g.dart @@ -6,9 +6,9 @@ part of 'ocauth_models.dart'; // JsonSerializableGenerator // ************************************************************************** -_$OCAPayloadParamsImpl _$$OCAPayloadParamsImplFromJson( +_$SessionAuthPayloadParamsImpl _$$SessionAuthPayloadParamsImplFromJson( Map json) => - _$OCAPayloadParamsImpl( + _$SessionAuthPayloadParamsImpl( chains: (json['chains'] as List).map((e) => e as String).toList(), domain: json['domain'] as String, @@ -26,8 +26,8 @@ _$OCAPayloadParamsImpl _$$OCAPayloadParamsImplFromJson( .toList(), ); -Map _$$OCAPayloadParamsImplToJson( - _$OCAPayloadParamsImpl instance) { +Map _$$SessionAuthPayloadParamsImplToJson( + _$SessionAuthPayloadParamsImpl instance) { final val = { 'chains': instance.chains, 'domain': instance.domain, @@ -51,3 +51,28 @@ Map _$$OCAPayloadParamsImplToJson( writeNotNull('resources', instance.resources); return val; } + +_$PendingSessionAuthRequestImpl _$$PendingSessionAuthRequestImplFromJson( + Map json) => + _$PendingSessionAuthRequestImpl( + id: json['id'] as int, + pairingTopic: json['pairingTopic'] as String, + requester: ConnectionMetadata.fromJson( + json['requester'] as Map), + expiryTimestamp: json['expiryTimestamp'] as int, + authPayload: CacaoRequestPayload.fromJson( + json['authPayload'] as Map), + verifyContext: + VerifyContext.fromJson(json['verifyContext'] as Map), + ); + +Map _$$PendingSessionAuthRequestImplToJson( + _$PendingSessionAuthRequestImpl instance) => + { + 'id': instance.id, + 'pairingTopic': instance.pairingTopic, + 'requester': instance.requester.toJson(), + 'expiryTimestamp': instance.expiryTimestamp, + 'authPayload': instance.authPayload.toJson(), + 'verifyContext': instance.verifyContext.toJson(), + }; diff --git a/lib/apis/sign_api/models/auth/ocauth_events.dart b/lib/apis/sign_api/models/auth/session_auth_events.dart similarity index 50% rename from lib/apis/sign_api/models/auth/ocauth_events.dart rename to lib/apis/sign_api/models/auth/session_auth_events.dart index adf84971..3f02a784 100644 --- a/lib/apis/sign_api/models/auth/ocauth_events.dart +++ b/lib/apis/sign_api/models/auth/session_auth_events.dart @@ -1,16 +1,44 @@ import 'dart:convert'; import 'package:event/event.dart'; +import 'package:walletconnect_flutter_v2/apis/core/verify/models/verify_context.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; import 'package:walletconnect_flutter_v2/apis/models/json_rpc_error.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/common_auth_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; -class OCAuthRequest extends EventArgs { - // TODO to be implemented for wallet usage +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_models.dart'; + +class SessionAuthRequest extends EventArgs { + final int id; + final String topic; + final SessionAuthPayloadParams payloadParams; + final ConnectionMetadata requester; + final VerifyContext? verifyContext; + + SessionAuthRequest({ + required this.id, + required this.topic, + required this.payloadParams, + required this.requester, + this.verifyContext, + }); + + Map toJson() => { + 'id': id, + 'topic': topic, + 'payloadParams': payloadParams.toJson(), + 'requester': requester.toJson(), + 'verifyContext': verifyContext?.toJson(), + }; + + @override + String toString() { + return 'SessionAuthRequest(${jsonEncode(toJson())})'; + } } -class OCAuthResponse extends EventArgs { +class SessionAuthResponse extends EventArgs { final int id; final String topic; final List? auths; @@ -18,7 +46,7 @@ class OCAuthResponse extends EventArgs { final WalletConnectError? error; final JsonRpcError? jsonRpcError; - OCAuthResponse({ + SessionAuthResponse({ required this.id, required this.topic, this.auths, @@ -38,6 +66,6 @@ class OCAuthResponse extends EventArgs { @override String toString() { - return 'OCAResponse(${jsonEncode(toJson())})'; + return 'SessionAuthResponse(${jsonEncode(toJson())})'; } } diff --git a/lib/apis/sign_api/models/auth/ocauth_models.dart b/lib/apis/sign_api/models/auth/session_auth_models.dart similarity index 61% rename from lib/apis/sign_api/models/auth/ocauth_models.dart rename to lib/apis/sign_api/models/auth/session_auth_models.dart index 23e4e7c6..abbdd7f4 100644 --- a/lib/apis/sign_api/models/auth/ocauth_models.dart +++ b/lib/apis/sign_api/models/auth/session_auth_models.dart @@ -1,21 +1,23 @@ import 'dart:async'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:walletconnect_flutter_v2/apis/core/verify/models/verify_context.dart'; +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/ocauth_events.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_events.dart'; -part 'ocauth_models.g.dart'; -part 'ocauth_models.freezed.dart'; +part 'session_auth_models.g.dart'; +part 'session_auth_models.freezed.dart'; // TODO this should be under sign_client_models.dart probably -class OCARequestResponse { +class SessionAuthRequestResponse { final int id; final String pairingTopic; - final Completer completer; + final Completer completer; final Uri? uri; - OCARequestResponse({ + SessionAuthRequestResponse({ required this.id, required this.pairingTopic, required this.completer, @@ -23,7 +25,7 @@ class OCARequestResponse { }); } -class OCARequestParams { +class SessionAuthRequestParams { final List chains; final String domain; final String nonce; @@ -39,7 +41,7 @@ class OCARequestParams { final List? methods; // - OCARequestParams({ + SessionAuthRequestParams({ required this.chains, required this.domain, required this.nonce, @@ -69,10 +71,11 @@ class OCARequestParams { }; } +// TODO this should be called SessionAuthPayload @freezed -class OCAPayloadParams with _$OCAPayloadParams { +class SessionAuthPayloadParams with _$SessionAuthPayloadParams { @JsonSerializable(includeIfNull: false) - const factory OCAPayloadParams({ + const factory SessionAuthPayloadParams({ required List chains, required String domain, required String nonce, @@ -87,10 +90,12 @@ class OCAPayloadParams with _$OCAPayloadParams { String? statement, String? requestId, List? resources, - }) = _OCAPayloadParams; + }) = _SessionAuthPayloadParams; - factory OCAPayloadParams.fromRequestParams(OCARequestParams params) { - return OCAPayloadParams( + factory SessionAuthPayloadParams.fromRequestParams( + SessionAuthRequestParams params, + ) { + return SessionAuthPayloadParams( chains: params.chains, domain: params.domain, nonce: params.nonce, @@ -107,6 +112,22 @@ class OCAPayloadParams with _$OCAPayloadParams { ); } - factory OCAPayloadParams.fromJson(Map json) => - _$OCAPayloadParamsFromJson(json); + factory SessionAuthPayloadParams.fromJson(Map json) => + _$SessionAuthPayloadParamsFromJson(json); +} + +@freezed +class PendingSessionAuthRequest with _$PendingSessionAuthRequest { + @JsonSerializable(includeIfNull: false) + const factory PendingSessionAuthRequest({ + required int id, + required String pairingTopic, + required ConnectionMetadata requester, + required int expiryTimestamp, + required CacaoRequestPayload authPayload, + required VerifyContext verifyContext, + }) = _PendingSessionAuthRequest; + + factory PendingSessionAuthRequest.fromJson(Map json) => + _$PendingSessionAuthRequestFromJson(json); } 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 new file mode 100644 index 00000000..5152f1d9 --- /dev/null +++ b/lib/apis/sign_api/models/auth/session_auth_models.freezed.dart @@ -0,0 +1,704 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'session_auth_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +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'); + +SessionAuthPayloadParams _$SessionAuthPayloadParamsFromJson( + Map json) { + return _SessionAuthPayloadParams.fromJson(json); +} + +/// @nodoc +mixin _$SessionAuthPayloadParams { + List get chains => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get aud => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; // + String get version => throw _privateConstructorUsedError; + String get iat => throw _privateConstructorUsedError; // + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $SessionAuthPayloadParamsCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SessionAuthPayloadParamsCopyWith<$Res> { + factory $SessionAuthPayloadParamsCopyWith(SessionAuthPayloadParams value, + $Res Function(SessionAuthPayloadParams) then) = + _$SessionAuthPayloadParamsCopyWithImpl<$Res, SessionAuthPayloadParams>; + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class _$SessionAuthPayloadParamsCopyWithImpl<$Res, + $Val extends SessionAuthPayloadParams> + implements $SessionAuthPayloadParamsCopyWith<$Res> { + _$SessionAuthPayloadParamsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_value.copyWith( + chains: null == chains + ? _value.chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$SessionAuthPayloadParamsImplCopyWith<$Res> + implements $SessionAuthPayloadParamsCopyWith<$Res> { + factory _$$SessionAuthPayloadParamsImplCopyWith( + _$SessionAuthPayloadParamsImpl value, + $Res Function(_$SessionAuthPayloadParamsImpl) then) = + __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String aud, + String type, + String version, + String iat, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources}); +} + +/// @nodoc +class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> + extends _$SessionAuthPayloadParamsCopyWithImpl<$Res, + _$SessionAuthPayloadParamsImpl> + implements _$$SessionAuthPayloadParamsImplCopyWith<$Res> { + __$$SessionAuthPayloadParamsImplCopyWithImpl( + _$SessionAuthPayloadParamsImpl _value, + $Res Function(_$SessionAuthPayloadParamsImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? aud = null, + Object? type = null, + Object? version = null, + Object? iat = null, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + }) { + return _then(_$SessionAuthPayloadParamsImpl( + chains: null == chains + ? _value._chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + aud: null == aud + ? _value.aud + : aud // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _value.version + : version // ignore: cast_nullable_to_non_nullable + as String, + iat: null == iat + ? _value.iat + : iat // ignore: cast_nullable_to_non_nullable + as String, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { + const _$SessionAuthPayloadParamsImpl( + {required final List chains, + required this.domain, + required this.nonce, + required this.aud, + required this.type, + required this.version, + required this.iat, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources}) + : _chains = chains, + _resources = resources; + + factory _$SessionAuthPayloadParamsImpl.fromJson(Map json) => + _$$SessionAuthPayloadParamsImplFromJson(json); + + final List _chains; + @override + List get chains { + if (_chains is EqualUnmodifiableListView) return _chains; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_chains); + } + + @override + final String domain; + @override + final String nonce; + @override + final String aud; + @override + final String type; +// + @override + final String version; + @override + final String iat; +// + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'SessionAuthPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SessionAuthPayloadParamsImpl && + const DeepCollectionEquality().equals(other._chains, _chains) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.aud, aud) || other.aud == aud) && + (identical(other.type, type) || other.type == type) && + (identical(other.version, version) || other.version == version) && + (identical(other.iat, iat) || other.iat == iat) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_chains), + domain, + nonce, + aud, + type, + version, + iat, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> + get copyWith => __$$SessionAuthPayloadParamsImplCopyWithImpl< + _$SessionAuthPayloadParamsImpl>(this, _$identity); + + @override + Map toJson() { + return _$$SessionAuthPayloadParamsImplToJson( + this, + ); + } +} + +abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { + const factory _SessionAuthPayloadParams( + {required final List chains, + required final String domain, + required final String nonce, + required final String aud, + required final String type, + required final String version, + required final String iat, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources}) = _$SessionAuthPayloadParamsImpl; + + factory _SessionAuthPayloadParams.fromJson(Map json) = + _$SessionAuthPayloadParamsImpl.fromJson; + + @override + List get chains; + @override + String get domain; + @override + String get nonce; + @override + String get aud; + @override + String get type; + @override // + String get version; + @override + String get iat; + @override // + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + @JsonKey(ignore: true) + _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> + get copyWith => throw _privateConstructorUsedError; +} + +PendingSessionAuthRequest _$PendingSessionAuthRequestFromJson( + Map json) { + return _PendingSessionAuthRequest.fromJson(json); +} + +/// @nodoc +mixin _$PendingSessionAuthRequest { + int get id => throw _privateConstructorUsedError; + String get pairingTopic => throw _privateConstructorUsedError; + ConnectionMetadata get requester => throw _privateConstructorUsedError; + int get expiryTimestamp => throw _privateConstructorUsedError; + CacaoRequestPayload get authPayload => throw _privateConstructorUsedError; + VerifyContext get verifyContext => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $PendingSessionAuthRequestCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PendingSessionAuthRequestCopyWith<$Res> { + factory $PendingSessionAuthRequestCopyWith(PendingSessionAuthRequest value, + $Res Function(PendingSessionAuthRequest) then) = + _$PendingSessionAuthRequestCopyWithImpl<$Res, PendingSessionAuthRequest>; + @useResult + $Res call( + {int id, + String pairingTopic, + ConnectionMetadata requester, + int expiryTimestamp, + CacaoRequestPayload authPayload, + VerifyContext verifyContext}); + + $ConnectionMetadataCopyWith<$Res> get requester; + $CacaoRequestPayloadCopyWith<$Res> get authPayload; + $VerifyContextCopyWith<$Res> get verifyContext; +} + +/// @nodoc +class _$PendingSessionAuthRequestCopyWithImpl<$Res, + $Val extends PendingSessionAuthRequest> + implements $PendingSessionAuthRequestCopyWith<$Res> { + _$PendingSessionAuthRequestCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? requester = null, + Object? expiryTimestamp = null, + Object? authPayload = null, + Object? verifyContext = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as CacaoRequestPayload, + verifyContext: null == verifyContext + ? _value.verifyContext + : verifyContext // ignore: cast_nullable_to_non_nullable + as VerifyContext, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get requester { + return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { + return _then(_value.copyWith(requester: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $CacaoRequestPayloadCopyWith<$Res> get authPayload { + return $CacaoRequestPayloadCopyWith<$Res>(_value.authPayload, (value) { + return _then(_value.copyWith(authPayload: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $VerifyContextCopyWith<$Res> get verifyContext { + return $VerifyContextCopyWith<$Res>(_value.verifyContext, (value) { + return _then(_value.copyWith(verifyContext: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$PendingSessionAuthRequestImplCopyWith<$Res> + implements $PendingSessionAuthRequestCopyWith<$Res> { + factory _$$PendingSessionAuthRequestImplCopyWith( + _$PendingSessionAuthRequestImpl value, + $Res Function(_$PendingSessionAuthRequestImpl) then) = + __$$PendingSessionAuthRequestImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String pairingTopic, + ConnectionMetadata requester, + int expiryTimestamp, + CacaoRequestPayload authPayload, + VerifyContext verifyContext}); + + @override + $ConnectionMetadataCopyWith<$Res> get requester; + @override + $CacaoRequestPayloadCopyWith<$Res> get authPayload; + @override + $VerifyContextCopyWith<$Res> get verifyContext; +} + +/// @nodoc +class __$$PendingSessionAuthRequestImplCopyWithImpl<$Res> + extends _$PendingSessionAuthRequestCopyWithImpl<$Res, + _$PendingSessionAuthRequestImpl> + implements _$$PendingSessionAuthRequestImplCopyWith<$Res> { + __$$PendingSessionAuthRequestImplCopyWithImpl( + _$PendingSessionAuthRequestImpl _value, + $Res Function(_$PendingSessionAuthRequestImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? pairingTopic = null, + Object? requester = null, + Object? expiryTimestamp = null, + Object? authPayload = null, + Object? verifyContext = null, + }) { + return _then(_$PendingSessionAuthRequestImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + pairingTopic: null == pairingTopic + ? _value.pairingTopic + : pairingTopic // ignore: cast_nullable_to_non_nullable + as String, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as CacaoRequestPayload, + verifyContext: null == verifyContext + ? _value.verifyContext + : verifyContext // ignore: cast_nullable_to_non_nullable + as VerifyContext, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$PendingSessionAuthRequestImpl implements _PendingSessionAuthRequest { + const _$PendingSessionAuthRequestImpl( + {required this.id, + required this.pairingTopic, + required this.requester, + required this.expiryTimestamp, + required this.authPayload, + required this.verifyContext}); + + factory _$PendingSessionAuthRequestImpl.fromJson(Map json) => + _$$PendingSessionAuthRequestImplFromJson(json); + + @override + final int id; + @override + final String pairingTopic; + @override + final ConnectionMetadata requester; + @override + final int expiryTimestamp; + @override + final CacaoRequestPayload authPayload; + @override + final VerifyContext verifyContext; + + @override + String toString() { + return 'PendingSessionAuthRequest(id: $id, pairingTopic: $pairingTopic, requester: $requester, expiryTimestamp: $expiryTimestamp, authPayload: $authPayload, verifyContext: $verifyContext)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PendingSessionAuthRequestImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.pairingTopic, pairingTopic) || + other.pairingTopic == pairingTopic) && + (identical(other.requester, requester) || + other.requester == requester) && + (identical(other.expiryTimestamp, expiryTimestamp) || + other.expiryTimestamp == expiryTimestamp) && + (identical(other.authPayload, authPayload) || + other.authPayload == authPayload) && + (identical(other.verifyContext, verifyContext) || + other.verifyContext == verifyContext)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, pairingTopic, requester, + expiryTimestamp, authPayload, verifyContext); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> + get copyWith => __$$PendingSessionAuthRequestImplCopyWithImpl< + _$PendingSessionAuthRequestImpl>(this, _$identity); + + @override + Map toJson() { + return _$$PendingSessionAuthRequestImplToJson( + this, + ); + } +} + +abstract class _PendingSessionAuthRequest implements PendingSessionAuthRequest { + const factory _PendingSessionAuthRequest( + {required final int id, + required final String pairingTopic, + required final ConnectionMetadata requester, + required final int expiryTimestamp, + required final CacaoRequestPayload authPayload, + required final VerifyContext verifyContext}) = + _$PendingSessionAuthRequestImpl; + + factory _PendingSessionAuthRequest.fromJson(Map json) = + _$PendingSessionAuthRequestImpl.fromJson; + + @override + int get id; + @override + String get pairingTopic; + @override + ConnectionMetadata get requester; + @override + int get expiryTimestamp; + @override + CacaoRequestPayload get authPayload; + @override + VerifyContext get verifyContext; + @override + @JsonKey(ignore: true) + _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> + get copyWith => throw _privateConstructorUsedError; +} 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 new file mode 100644 index 00000000..23b70455 --- /dev/null +++ b/lib/apis/sign_api/models/auth/session_auth_models.g.dart @@ -0,0 +1,78 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'session_auth_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$SessionAuthPayloadParamsImpl _$$SessionAuthPayloadParamsImplFromJson( + Map json) => + _$SessionAuthPayloadParamsImpl( + chains: + (json['chains'] as List).map((e) => e as String).toList(), + domain: json['domain'] as String, + nonce: json['nonce'] as String, + aud: json['aud'] as String, + type: json['type'] as String, + version: json['version'] as String, + iat: json['iat'] as String, + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + ); + +Map _$$SessionAuthPayloadParamsImplToJson( + _$SessionAuthPayloadParamsImpl instance) { + final val = { + 'chains': instance.chains, + 'domain': instance.domain, + 'nonce': instance.nonce, + 'aud': instance.aud, + 'type': instance.type, + 'version': instance.version, + 'iat': instance.iat, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + return val; +} + +_$PendingSessionAuthRequestImpl _$$PendingSessionAuthRequestImplFromJson( + Map json) => + _$PendingSessionAuthRequestImpl( + id: json['id'] as int, + pairingTopic: json['pairingTopic'] as String, + requester: ConnectionMetadata.fromJson( + json['requester'] as Map), + expiryTimestamp: json['expiryTimestamp'] as int, + authPayload: CacaoRequestPayload.fromJson( + json['authPayload'] as Map), + verifyContext: + VerifyContext.fromJson(json['verifyContext'] as Map), + ); + +Map _$$PendingSessionAuthRequestImplToJson( + _$PendingSessionAuthRequestImpl instance) => + { + 'id': instance.id, + 'pairingTopic': instance.pairingTopic, + 'requester': instance.requester.toJson(), + 'expiryTimestamp': instance.expiryTimestamp, + 'authPayload': instance.authPayload.toJson(), + 'verifyContext': instance.verifyContext.toJson(), + }; diff --git a/lib/apis/sign_api/models/json_rpc_models.dart b/lib/apis/sign_api/models/json_rpc_models.dart index 35babd28..12728bd9 100644 --- a/lib/apis/sign_api/models/json_rpc_models.dart +++ b/lib/apis/sign_api/models/json_rpc_models.dart @@ -1,6 +1,9 @@ import 'package:freezed_annotation/freezed_annotation.dart'; 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/sign_api/models/auth/auth_client_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/models/proposal_models.dart'; import 'package:walletconnect_flutter_v2/apis/sign_api/models/session_models.dart'; @@ -167,3 +170,53 @@ class SessionEventParams with _$SessionEventParams { factory SessionEventParams.fromJson(Map json) => _$SessionEventParamsFromJson(json); } + +/* AUTHENTICATION MODELS */ + +@freezed +class WcAuthRequestRequest with _$WcAuthRequestRequest { + @JsonSerializable() + const factory WcAuthRequestRequest({ + required AuthPayloadParams payloadParams, + required ConnectionMetadata requester, + }) = _WcAuthRequestRequest; + + factory WcAuthRequestRequest.fromJson(Map json) => + _$WcAuthRequestRequestFromJson(json); +} + +@freezed +class WcAuthRequestResult with _$WcAuthRequestResult { + @JsonSerializable() + const factory WcAuthRequestResult({ + required Cacao cacao, + }) = _WcAuthRequestResult; + + factory WcAuthRequestResult.fromJson(Map json) => + _$WcAuthRequestResultFromJson(json); +} + +@freezed +class WcSessionAuthRequestParams with _$WcSessionAuthRequestParams { + @JsonSerializable() + const factory WcSessionAuthRequestParams({ + required SessionAuthPayloadParams authPayload, + required ConnectionMetadata requester, + required int expiryTimestamp, + }) = _WcSessionAuthRequestParams; + + factory WcSessionAuthRequestParams.fromJson(Map json) => + _$WcSessionAuthRequestParamsFromJson(json); +} + +@freezed +class WcSessionAuthRequestResult with _$WcSessionAuthRequestResult { + @JsonSerializable() + const factory WcSessionAuthRequestResult({ + required List cacaos, + required ConnectionMetadata responder, + }) = _WcSessionAuthRequestResult; + + factory WcSessionAuthRequestResult.fromJson(Map json) => + _$WcSessionAuthRequestResultFromJson(json); +} 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 0c40331e..6f33efae 100644 --- a/lib/apis/sign_api/models/json_rpc_models.freezed.dart +++ b/lib/apis/sign_api/models/json_rpc_models.freezed.dart @@ -2413,3 +2413,748 @@ abstract class _SessionEventParams implements SessionEventParams { _$$SessionEventParamsImplCopyWith<_$SessionEventParamsImpl> get copyWith => throw _privateConstructorUsedError; } + +WcAuthRequestRequest _$WcAuthRequestRequestFromJson(Map json) { + return _WcAuthRequestRequest.fromJson(json); +} + +/// @nodoc +mixin _$WcAuthRequestRequest { + AuthPayloadParams get payloadParams => throw _privateConstructorUsedError; + ConnectionMetadata get requester => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcAuthRequestRequestCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcAuthRequestRequestCopyWith<$Res> { + factory $WcAuthRequestRequestCopyWith(WcAuthRequestRequest value, + $Res Function(WcAuthRequestRequest) then) = + _$WcAuthRequestRequestCopyWithImpl<$Res, WcAuthRequestRequest>; + @useResult + $Res call({AuthPayloadParams payloadParams, ConnectionMetadata requester}); + + $AuthPayloadParamsCopyWith<$Res> get payloadParams; + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class _$WcAuthRequestRequestCopyWithImpl<$Res, + $Val extends WcAuthRequestRequest> + implements $WcAuthRequestRequestCopyWith<$Res> { + _$WcAuthRequestRequestCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? payloadParams = null, + Object? requester = null, + }) { + return _then(_value.copyWith( + payloadParams: null == payloadParams + ? _value.payloadParams + : payloadParams // ignore: cast_nullable_to_non_nullable + as AuthPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $AuthPayloadParamsCopyWith<$Res> get payloadParams { + return $AuthPayloadParamsCopyWith<$Res>(_value.payloadParams, (value) { + return _then(_value.copyWith(payloadParams: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get requester { + return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { + return _then(_value.copyWith(requester: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcAuthRequestRequestImplCopyWith<$Res> + implements $WcAuthRequestRequestCopyWith<$Res> { + factory _$$WcAuthRequestRequestImplCopyWith(_$WcAuthRequestRequestImpl value, + $Res Function(_$WcAuthRequestRequestImpl) then) = + __$$WcAuthRequestRequestImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({AuthPayloadParams payloadParams, ConnectionMetadata requester}); + + @override + $AuthPayloadParamsCopyWith<$Res> get payloadParams; + @override + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class __$$WcAuthRequestRequestImplCopyWithImpl<$Res> + extends _$WcAuthRequestRequestCopyWithImpl<$Res, _$WcAuthRequestRequestImpl> + implements _$$WcAuthRequestRequestImplCopyWith<$Res> { + __$$WcAuthRequestRequestImplCopyWithImpl(_$WcAuthRequestRequestImpl _value, + $Res Function(_$WcAuthRequestRequestImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? payloadParams = null, + Object? requester = null, + }) { + return _then(_$WcAuthRequestRequestImpl( + payloadParams: null == payloadParams + ? _value.payloadParams + : payloadParams // ignore: cast_nullable_to_non_nullable + as AuthPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcAuthRequestRequestImpl implements _WcAuthRequestRequest { + const _$WcAuthRequestRequestImpl( + {required this.payloadParams, required this.requester}); + + factory _$WcAuthRequestRequestImpl.fromJson(Map json) => + _$$WcAuthRequestRequestImplFromJson(json); + + @override + final AuthPayloadParams payloadParams; + @override + final ConnectionMetadata requester; + + @override + String toString() { + return 'WcAuthRequestRequest(payloadParams: $payloadParams, requester: $requester)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcAuthRequestRequestImpl && + (identical(other.payloadParams, payloadParams) || + other.payloadParams == payloadParams) && + (identical(other.requester, requester) || + other.requester == requester)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, payloadParams, requester); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcAuthRequestRequestImplCopyWith<_$WcAuthRequestRequestImpl> + get copyWith => + __$$WcAuthRequestRequestImplCopyWithImpl<_$WcAuthRequestRequestImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$WcAuthRequestRequestImplToJson( + this, + ); + } +} + +abstract class _WcAuthRequestRequest implements WcAuthRequestRequest { + const factory _WcAuthRequestRequest( + {required final AuthPayloadParams payloadParams, + required final ConnectionMetadata requester}) = + _$WcAuthRequestRequestImpl; + + factory _WcAuthRequestRequest.fromJson(Map json) = + _$WcAuthRequestRequestImpl.fromJson; + + @override + AuthPayloadParams get payloadParams; + @override + ConnectionMetadata get requester; + @override + @JsonKey(ignore: true) + _$$WcAuthRequestRequestImplCopyWith<_$WcAuthRequestRequestImpl> + get copyWith => throw _privateConstructorUsedError; +} + +WcAuthRequestResult _$WcAuthRequestResultFromJson(Map json) { + return _WcAuthRequestResult.fromJson(json); +} + +/// @nodoc +mixin _$WcAuthRequestResult { + Cacao get cacao => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcAuthRequestResultCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcAuthRequestResultCopyWith<$Res> { + factory $WcAuthRequestResultCopyWith( + WcAuthRequestResult value, $Res Function(WcAuthRequestResult) then) = + _$WcAuthRequestResultCopyWithImpl<$Res, WcAuthRequestResult>; + @useResult + $Res call({Cacao cacao}); + + $CacaoCopyWith<$Res> get cacao; +} + +/// @nodoc +class _$WcAuthRequestResultCopyWithImpl<$Res, $Val extends WcAuthRequestResult> + implements $WcAuthRequestResultCopyWith<$Res> { + _$WcAuthRequestResultCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacao = null, + }) { + return _then(_value.copyWith( + cacao: null == cacao + ? _value.cacao + : cacao // ignore: cast_nullable_to_non_nullable + as Cacao, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoCopyWith<$Res> get cacao { + return $CacaoCopyWith<$Res>(_value.cacao, (value) { + return _then(_value.copyWith(cacao: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcAuthRequestResultImplCopyWith<$Res> + implements $WcAuthRequestResultCopyWith<$Res> { + factory _$$WcAuthRequestResultImplCopyWith(_$WcAuthRequestResultImpl value, + $Res Function(_$WcAuthRequestResultImpl) then) = + __$$WcAuthRequestResultImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({Cacao cacao}); + + @override + $CacaoCopyWith<$Res> get cacao; +} + +/// @nodoc +class __$$WcAuthRequestResultImplCopyWithImpl<$Res> + extends _$WcAuthRequestResultCopyWithImpl<$Res, _$WcAuthRequestResultImpl> + implements _$$WcAuthRequestResultImplCopyWith<$Res> { + __$$WcAuthRequestResultImplCopyWithImpl(_$WcAuthRequestResultImpl _value, + $Res Function(_$WcAuthRequestResultImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacao = null, + }) { + return _then(_$WcAuthRequestResultImpl( + cacao: null == cacao + ? _value.cacao + : cacao // ignore: cast_nullable_to_non_nullable + as Cacao, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcAuthRequestResultImpl implements _WcAuthRequestResult { + const _$WcAuthRequestResultImpl({required this.cacao}); + + factory _$WcAuthRequestResultImpl.fromJson(Map json) => + _$$WcAuthRequestResultImplFromJson(json); + + @override + final Cacao cacao; + + @override + String toString() { + return 'WcAuthRequestResult(cacao: $cacao)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcAuthRequestResultImpl && + (identical(other.cacao, cacao) || other.cacao == cacao)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, cacao); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcAuthRequestResultImplCopyWith<_$WcAuthRequestResultImpl> get copyWith => + __$$WcAuthRequestResultImplCopyWithImpl<_$WcAuthRequestResultImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$WcAuthRequestResultImplToJson( + this, + ); + } +} + +abstract class _WcAuthRequestResult implements WcAuthRequestResult { + const factory _WcAuthRequestResult({required final Cacao cacao}) = + _$WcAuthRequestResultImpl; + + factory _WcAuthRequestResult.fromJson(Map json) = + _$WcAuthRequestResultImpl.fromJson; + + @override + Cacao get cacao; + @override + @JsonKey(ignore: true) + _$$WcAuthRequestResultImplCopyWith<_$WcAuthRequestResultImpl> get copyWith => + throw _privateConstructorUsedError; +} + +WcSessionAuthRequestParams _$WcSessionAuthRequestParamsFromJson( + Map json) { + return _WcSessionAuthRequestParams.fromJson(json); +} + +/// @nodoc +mixin _$WcSessionAuthRequestParams { + SessionAuthPayloadParams get authPayload => + throw _privateConstructorUsedError; + ConnectionMetadata get requester => throw _privateConstructorUsedError; + int get expiryTimestamp => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcSessionAuthRequestParamsCopyWith + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcSessionAuthRequestParamsCopyWith<$Res> { + factory $WcSessionAuthRequestParamsCopyWith(WcSessionAuthRequestParams value, + $Res Function(WcSessionAuthRequestParams) then) = + _$WcSessionAuthRequestParamsCopyWithImpl<$Res, + WcSessionAuthRequestParams>; + @useResult + $Res call( + {SessionAuthPayloadParams authPayload, + ConnectionMetadata requester, + int expiryTimestamp}); + + $SessionAuthPayloadParamsCopyWith<$Res> get authPayload; + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class _$WcSessionAuthRequestParamsCopyWithImpl<$Res, + $Val extends WcSessionAuthRequestParams> + implements $WcSessionAuthRequestParamsCopyWith<$Res> { + _$WcSessionAuthRequestParamsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authPayload = null, + Object? requester = null, + Object? expiryTimestamp = null, + }) { + return _then(_value.copyWith( + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as SessionAuthPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $SessionAuthPayloadParamsCopyWith<$Res> get authPayload { + return $SessionAuthPayloadParamsCopyWith<$Res>(_value.authPayload, (value) { + return _then(_value.copyWith(authPayload: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get requester { + return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { + return _then(_value.copyWith(requester: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcSessionAuthRequestParamsImplCopyWith<$Res> + implements $WcSessionAuthRequestParamsCopyWith<$Res> { + factory _$$WcSessionAuthRequestParamsImplCopyWith( + _$WcSessionAuthRequestParamsImpl value, + $Res Function(_$WcSessionAuthRequestParamsImpl) then) = + __$$WcSessionAuthRequestParamsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {SessionAuthPayloadParams authPayload, + ConnectionMetadata requester, + int expiryTimestamp}); + + @override + $SessionAuthPayloadParamsCopyWith<$Res> get authPayload; + @override + $ConnectionMetadataCopyWith<$Res> get requester; +} + +/// @nodoc +class __$$WcSessionAuthRequestParamsImplCopyWithImpl<$Res> + extends _$WcSessionAuthRequestParamsCopyWithImpl<$Res, + _$WcSessionAuthRequestParamsImpl> + implements _$$WcSessionAuthRequestParamsImplCopyWith<$Res> { + __$$WcSessionAuthRequestParamsImplCopyWithImpl( + _$WcSessionAuthRequestParamsImpl _value, + $Res Function(_$WcSessionAuthRequestParamsImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authPayload = null, + Object? requester = null, + Object? expiryTimestamp = null, + }) { + return _then(_$WcSessionAuthRequestParamsImpl( + authPayload: null == authPayload + ? _value.authPayload + : authPayload // ignore: cast_nullable_to_non_nullable + as SessionAuthPayloadParams, + requester: null == requester + ? _value.requester + : requester // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + expiryTimestamp: null == expiryTimestamp + ? _value.expiryTimestamp + : expiryTimestamp // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcSessionAuthRequestParamsImpl implements _WcSessionAuthRequestParams { + const _$WcSessionAuthRequestParamsImpl( + {required this.authPayload, + required this.requester, + required this.expiryTimestamp}); + + factory _$WcSessionAuthRequestParamsImpl.fromJson( + Map json) => + _$$WcSessionAuthRequestParamsImplFromJson(json); + + @override + final SessionAuthPayloadParams authPayload; + @override + final ConnectionMetadata requester; + @override + final int expiryTimestamp; + + @override + String toString() { + return 'WcSessionAuthRequestParams(authPayload: $authPayload, requester: $requester, expiryTimestamp: $expiryTimestamp)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcSessionAuthRequestParamsImpl && + (identical(other.authPayload, authPayload) || + other.authPayload == authPayload) && + (identical(other.requester, requester) || + other.requester == requester) && + (identical(other.expiryTimestamp, expiryTimestamp) || + other.expiryTimestamp == expiryTimestamp)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => + Object.hash(runtimeType, authPayload, requester, expiryTimestamp); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcSessionAuthRequestParamsImplCopyWith<_$WcSessionAuthRequestParamsImpl> + get copyWith => __$$WcSessionAuthRequestParamsImplCopyWithImpl< + _$WcSessionAuthRequestParamsImpl>(this, _$identity); + + @override + Map toJson() { + return _$$WcSessionAuthRequestParamsImplToJson( + this, + ); + } +} + +abstract class _WcSessionAuthRequestParams + implements WcSessionAuthRequestParams { + const factory _WcSessionAuthRequestParams( + {required final SessionAuthPayloadParams authPayload, + required final ConnectionMetadata requester, + required final int expiryTimestamp}) = _$WcSessionAuthRequestParamsImpl; + + factory _WcSessionAuthRequestParams.fromJson(Map json) = + _$WcSessionAuthRequestParamsImpl.fromJson; + + @override + SessionAuthPayloadParams get authPayload; + @override + ConnectionMetadata get requester; + @override + int get expiryTimestamp; + @override + @JsonKey(ignore: true) + _$$WcSessionAuthRequestParamsImplCopyWith<_$WcSessionAuthRequestParamsImpl> + get copyWith => throw _privateConstructorUsedError; +} + +WcSessionAuthRequestResult _$WcSessionAuthRequestResultFromJson( + Map json) { + return _WcSessionAuthRequestResult.fromJson(json); +} + +/// @nodoc +mixin _$WcSessionAuthRequestResult { + List get cacaos => throw _privateConstructorUsedError; + ConnectionMetadata get responder => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WcSessionAuthRequestResultCopyWith + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $WcSessionAuthRequestResultCopyWith<$Res> { + factory $WcSessionAuthRequestResultCopyWith(WcSessionAuthRequestResult value, + $Res Function(WcSessionAuthRequestResult) then) = + _$WcSessionAuthRequestResultCopyWithImpl<$Res, + WcSessionAuthRequestResult>; + @useResult + $Res call({List cacaos, ConnectionMetadata responder}); + + $ConnectionMetadataCopyWith<$Res> get responder; +} + +/// @nodoc +class _$WcSessionAuthRequestResultCopyWithImpl<$Res, + $Val extends WcSessionAuthRequestResult> + implements $WcSessionAuthRequestResultCopyWith<$Res> { + _$WcSessionAuthRequestResultCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacaos = null, + Object? responder = null, + }) { + return _then(_value.copyWith( + cacaos: null == cacaos + ? _value.cacaos + : cacaos // ignore: cast_nullable_to_non_nullable + as List, + responder: null == responder + ? _value.responder + : responder // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $ConnectionMetadataCopyWith<$Res> get responder { + return $ConnectionMetadataCopyWith<$Res>(_value.responder, (value) { + return _then(_value.copyWith(responder: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$WcSessionAuthRequestResultImplCopyWith<$Res> + implements $WcSessionAuthRequestResultCopyWith<$Res> { + factory _$$WcSessionAuthRequestResultImplCopyWith( + _$WcSessionAuthRequestResultImpl value, + $Res Function(_$WcSessionAuthRequestResultImpl) then) = + __$$WcSessionAuthRequestResultImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({List cacaos, ConnectionMetadata responder}); + + @override + $ConnectionMetadataCopyWith<$Res> get responder; +} + +/// @nodoc +class __$$WcSessionAuthRequestResultImplCopyWithImpl<$Res> + extends _$WcSessionAuthRequestResultCopyWithImpl<$Res, + _$WcSessionAuthRequestResultImpl> + implements _$$WcSessionAuthRequestResultImplCopyWith<$Res> { + __$$WcSessionAuthRequestResultImplCopyWithImpl( + _$WcSessionAuthRequestResultImpl _value, + $Res Function(_$WcSessionAuthRequestResultImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? cacaos = null, + Object? responder = null, + }) { + return _then(_$WcSessionAuthRequestResultImpl( + cacaos: null == cacaos + ? _value._cacaos + : cacaos // ignore: cast_nullable_to_non_nullable + as List, + responder: null == responder + ? _value.responder + : responder // ignore: cast_nullable_to_non_nullable + as ConnectionMetadata, + )); + } +} + +/// @nodoc + +@JsonSerializable() +class _$WcSessionAuthRequestResultImpl implements _WcSessionAuthRequestResult { + const _$WcSessionAuthRequestResultImpl( + {required final List cacaos, required this.responder}) + : _cacaos = cacaos; + + factory _$WcSessionAuthRequestResultImpl.fromJson( + Map json) => + _$$WcSessionAuthRequestResultImplFromJson(json); + + final List _cacaos; + @override + List get cacaos { + if (_cacaos is EqualUnmodifiableListView) return _cacaos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_cacaos); + } + + @override + final ConnectionMetadata responder; + + @override + String toString() { + return 'WcSessionAuthRequestResult(cacaos: $cacaos, responder: $responder)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$WcSessionAuthRequestResultImpl && + const DeepCollectionEquality().equals(other._cacaos, _cacaos) && + (identical(other.responder, responder) || + other.responder == responder)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_cacaos), responder); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WcSessionAuthRequestResultImplCopyWith<_$WcSessionAuthRequestResultImpl> + get copyWith => __$$WcSessionAuthRequestResultImplCopyWithImpl< + _$WcSessionAuthRequestResultImpl>(this, _$identity); + + @override + Map toJson() { + return _$$WcSessionAuthRequestResultImplToJson( + this, + ); + } +} + +abstract class _WcSessionAuthRequestResult + implements WcSessionAuthRequestResult { + const factory _WcSessionAuthRequestResult( + {required final List cacaos, + required final ConnectionMetadata responder}) = + _$WcSessionAuthRequestResultImpl; + + factory _WcSessionAuthRequestResult.fromJson(Map json) = + _$WcSessionAuthRequestResultImpl.fromJson; + + @override + List get cacaos; + @override + ConnectionMetadata get responder; + @override + @JsonKey(ignore: true) + _$$WcSessionAuthRequestResultImplCopyWith<_$WcSessionAuthRequestResultImpl> + get copyWith => throw _privateConstructorUsedError; +} 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 c86c93c5..908a1f31 100644 --- a/lib/apis/sign_api/models/json_rpc_models.g.dart +++ b/lib/apis/sign_api/models/json_rpc_models.g.dart @@ -275,3 +275,66 @@ Map _$$SessionEventParamsImplToJson( 'name': instance.name, 'data': instance.data, }; + +_$WcAuthRequestRequestImpl _$$WcAuthRequestRequestImplFromJson( + Map json) => + _$WcAuthRequestRequestImpl( + payloadParams: AuthPayloadParams.fromJson( + json['payloadParams'] as Map), + requester: ConnectionMetadata.fromJson( + json['requester'] as Map), + ); + +Map _$$WcAuthRequestRequestImplToJson( + _$WcAuthRequestRequestImpl instance) => + { + 'payloadParams': instance.payloadParams.toJson(), + 'requester': instance.requester.toJson(), + }; + +_$WcAuthRequestResultImpl _$$WcAuthRequestResultImplFromJson( + Map json) => + _$WcAuthRequestResultImpl( + cacao: Cacao.fromJson(json['cacao'] as Map), + ); + +Map _$$WcAuthRequestResultImplToJson( + _$WcAuthRequestResultImpl instance) => + { + 'cacao': instance.cacao.toJson(), + }; + +_$WcSessionAuthRequestParamsImpl _$$WcSessionAuthRequestParamsImplFromJson( + Map json) => + _$WcSessionAuthRequestParamsImpl( + authPayload: SessionAuthPayloadParams.fromJson( + json['authPayload'] as Map), + requester: ConnectionMetadata.fromJson( + json['requester'] as Map), + expiryTimestamp: json['expiryTimestamp'] as int, + ); + +Map _$$WcSessionAuthRequestParamsImplToJson( + _$WcSessionAuthRequestParamsImpl instance) => + { + 'authPayload': instance.authPayload.toJson(), + 'requester': instance.requester.toJson(), + 'expiryTimestamp': instance.expiryTimestamp, + }; + +_$WcSessionAuthRequestResultImpl _$$WcSessionAuthRequestResultImplFromJson( + Map json) => + _$WcSessionAuthRequestResultImpl( + cacaos: (json['cacaos'] as List) + .map((e) => Cacao.fromJson(e as Map)) + .toList(), + responder: ConnectionMetadata.fromJson( + json['responder'] as Map), + ); + +Map _$$WcSessionAuthRequestResultImplToJson( + _$WcSessionAuthRequestResultImpl instance) => + { + 'cacaos': instance.cacaos.map((e) => e.toJson()).toList(), + 'responder': instance.responder.toJson(), + }; diff --git a/lib/apis/sign_api/models/sign_client_events.dart b/lib/apis/sign_api/models/sign_client_events.dart index 5eb125ee..c2e49a97 100644 --- a/lib/apis/sign_api/models/sign_client_events.dart +++ b/lib/apis/sign_api/models/sign_client_events.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:event/event.dart'; import 'package:walletconnect_flutter_v2/apis/core/verify/models/verify_context.dart'; import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart'; @@ -15,9 +17,15 @@ class SessionProposalEvent extends EventArgs { this.verifyContext, ]); + Map toJson() => { + 'id': id, + 'params': params.toJson(), + 'verifyContext': verifyContext?.toJson(), + }; + @override String toString() { - return 'SessionProposalEvent(id: $id, params: $params)'; + return 'SessionProposalEvent(${jsonEncode(toJson())})'; } } diff --git a/lib/apis/sign_api/models/sign_client_models.dart b/lib/apis/sign_api/models/sign_client_models.dart index 3bb4b94e..54828ebc 100644 --- a/lib/apis/sign_api/models/sign_client_models.dart +++ b/lib/apis/sign_api/models/sign_client_models.dart @@ -21,7 +21,7 @@ class ConnectResponse { class ApproveResponse { final String topic; - final SessionData session; + final SessionData? session; ApproveResponse({ required this.topic, diff --git a/lib/apis/sign_api/sign_client.dart b/lib/apis/sign_api/sign_client.dart index 7e02bc9b..6b939421 100644 --- a/lib/apis/sign_api/sign_client.dart +++ b/lib/apis/sign_api/sign_client.dart @@ -134,6 +134,14 @@ class SignClient implements ISignClient { return StoredCacao.fromJson(value); }, ), + sessionAuthRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingSessionAuthRequest.fromJson(value); + }, + ), ); } @@ -498,6 +506,19 @@ class SignClient implements ISignClient { } } + @override + Map getPendingSessionAuthRequests() { + try { + return engine.getPendingSessionAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + IGenericStore get sessionAuthRequests => + engine.sessionAuthRequests; + @override Event get onAuthRequest => engine.onAuthRequest; @@ -506,7 +527,12 @@ class SignClient implements ISignClient { // NEW 1-CLICK AUTH METHOD @override - Event get onOCAuthResponse => engine.onOCAuthResponse; + Event get onSessionAuthResponse => + engine.onSessionAuthResponse; + + @override + Event get onSessionAuthRequest => + engine.onSessionAuthRequest; @override Future requestAuth({ @@ -527,8 +553,8 @@ class SignClient implements ISignClient { // NEW ONE-CLICK AUTH METHOD FOR DAPPS @override - Future authenticate({ - required OCARequestParams params, + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods = const [ [MethodConstants.WC_SESSION_AUTHENTICATE] @@ -564,6 +590,36 @@ class SignClient implements ISignClient { } } + @override + Future approveSessionAuthenticate({ + required int id, + List? auths, + }) { + try { + return engine.approveSessionAuthenticate( + id: id, + auths: auths, + ); + } catch (e) { + rethrow; + } + } + + @override + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }) { + try { + return engine.rejectSessionAuthenticate( + id: id, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + @override IGenericStore get authKeys => engine.authKeys; diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index 7eecd4d4..c0fbe61b 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -85,9 +85,15 @@ class SignEngine implements ISignEngine { // NEW 1-CA METHOD @override - final Event onOCAuthResponse = Event(); + late IGenericStore sessionAuthRequests; + @override + final Event onSessionAuthRequest = + Event(); + @override + final Event onSessionAuthResponse = + Event(); - // FORMER AUTH ENGINE PROPERTY (apparently not used befor and not used now) + // FORMER AUTH ENGINE PROPERTY (apparently not used before and not used now) List pendingAuthRequests = []; SignEngine({ @@ -101,6 +107,8 @@ class SignEngine implements ISignEngine { required this.pairingTopics, required this.authRequests, required this.completeRequests, + // NEW 1-CA PROPERTY + required this.sessionAuthRequests, }); @override @@ -120,6 +128,8 @@ class SignEngine implements ISignEngine { await pairingTopics.init(); await authRequests.init(); await completeRequests.init(); + // NEW 1-CA PROPERTY + await sessionAuthRequests.init(); _registerInternalEvents(); _registerRelayClientFunctions(); @@ -413,13 +423,14 @@ class SignEngine implements ISignEngine { // Attempt to send a response, if the pairing is not active, this will fail // but we don't care try { + final method = MethodConstants.WC_SESSION_PROPOSE; + final rpcOpts = MethodConstants.RPC_OPTS[method]; await core.pairing.sendError( id, proposal.pairingTopic, - MethodConstants.WC_SESSION_PROPOSE, - JsonRpcError.fromJson( - reason.toJson(), - ), + method, + JsonRpcError(code: reason.code, message: reason.message), + rpcOptions: rpcOpts?['reject'], ); } catch (_) { // print('got here'); @@ -973,18 +984,32 @@ class SignEngine implements ISignEngine { function: _onAuthRequest, type: ProtocolType.sign, ); - // TODO on following PR to be used by Wallet - // core.pairing.register( - // method: MethodConstants.WC_SESSION_AUTHENTICATE, - // function: _onOCARequest, - // type: ProtocolType.sign, - // ); + core.pairing.register( + method: MethodConstants.WC_SESSION_AUTHENTICATE, + function: _onSessionAuthRequest, + type: ProtocolType.sign, + ); + } + + bool _shouldIgnoreSessionPropose(String topic) { + final PairingInfo? pairingInfo = core.pairing.getPairing(topic: topic); + final implementSessionAuth = onSessionAuthRequest.subscriberCount > 0; + final method = MethodConstants.WC_SESSION_AUTHENTICATE; + final containsMethod = (pairingInfo?.methods ?? []).contains(method); + + return implementSessionAuth && containsMethod; } Future _onSessionProposeRequest( String topic, JsonRpcRequest payload, ) async { + if (_shouldIgnoreSessionPropose(topic)) { + core.logger.t( + 'Session Propose ignored. Session Authenticate will be used instead', + ); + return; + } try { core.logger.t( '_onSessionProposeRequest, topic: $topic, payload: $payload', @@ -1021,13 +1046,13 @@ class SignEngine implements ISignEngine { core.logger.t( '_onSessionProposeRequest WalletConnectError: $err', ); + final rpcOpts = MethodConstants.RPC_OPTS[payload.method]; await core.pairing.sendError( payload.id, topic, payload.method, - JsonRpcError.fromJson( - err.toJson(), - ), + JsonRpcError(code: err.code, message: err.message), + rpcOptions: rpcOpts?['autoReject'], ); // Broadcast that a session proposal error has occurred @@ -1074,13 +1099,13 @@ class SignEngine implements ISignEngine { ); } on WalletConnectError catch (err) { core.logger.e('_onSessionProposeRequest Error: $err'); + final rpcOpts = MethodConstants.RPC_OPTS[payload.method]; await core.pairing.sendError( payload.id, topic, payload.method, - JsonRpcError.fromJson( - err.toJson(), - ), + JsonRpcError(code: err.code, message: err.message), + rpcOptions: rpcOpts?['autoReject'], ); } } @@ -1860,6 +1885,12 @@ class SignEngine implements ISignEngine { final header = '${cacaoPayload.domain} wants you to sign in with your Ethereum account:'; final walletAddress = AddressUtils.getDidAddress(iss); + + if (cacaoPayload.aud.isEmpty) { + throw WalletConnectError(code: -1, message: 'aud is required'); + } + + String statement = cacaoPayload.statement ?? ''; final uri = 'URI: ${cacaoPayload.aud}'; final version = 'Version: ${cacaoPayload.version}'; final chainId = 'Chain ID: ${AddressUtils.getDidChainId(iss)}'; @@ -1869,12 +1900,22 @@ class SignEngine implements ISignEngine { cacaoPayload.resources!.isNotEmpty ? 'Resources:\n${cacaoPayload.resources!.map((resource) => '- $resource').join('\n')}' : null; + final recap = ReCapsUtils.getRecapFromResources( + resources: cacaoPayload.resources, + ); + if (recap != null) { + final decoded = ReCapsUtils.decodeRecap(recap); + statement = ReCapsUtils.formatStatementFromRecap( + statement: statement, + recap: decoded, + ); + } final message = [ header, walletAddress, '', - cacaoPayload.statement, + statement, '', uri, version, @@ -2072,8 +2113,17 @@ class SignEngine implements ISignEngine { // NEW ONE-CLICK AUTH METHOD FOR DAPPS @override - Future authenticate({ - required OCARequestParams params, + Map getPendingSessionAuthRequests() { + Map pendingRequests = {}; + sessionAuthRequests.getAll().forEach((key) { + pendingRequests[key.id] = key; + }); + return pendingRequests; + } + + @override + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods = const [ [MethodConstants.WC_SESSION_AUTHENTICATE] @@ -2143,8 +2193,8 @@ class SignEngine implements ISignEngine { Duration(seconds: authRequestExpiry), ); - final request = WcOCARequestParams( - authPayload: OCAPayloadParams.fromRequestParams(params).copyWith( + final request = WcSessionAuthRequestParams( + authPayload: SessionAuthPayloadParams.fromRequestParams(params).copyWith( resources: resources, ), requester: ConnectionMetadata( @@ -2161,7 +2211,7 @@ class SignEngine implements ISignEngine { expiry: authRequestExpiry, ); - Completer completer = Completer(); + Completer completer = Completer(); // ----- build fallback session proposal request ----- // @@ -2212,7 +2262,7 @@ class SignEngine implements ISignEngine { // ------------------------------------------------------- // // Send One-Click Auth request - _ocAuthResponseHandler( + _sessionAuthResponseHandler( id: id, publicKey: publicKey, pairingTopic: pTopic, @@ -2229,7 +2279,7 @@ class SignEngine implements ISignEngine { proposalData.id, ); - return OCARequestResponse( + return SessionAuthRequestResponse( id: id, pairingTopic: pTopic, completer: completer, @@ -2237,17 +2287,17 @@ class SignEngine implements ISignEngine { ); } - Future _ocAuthResponseHandler({ + Future _sessionAuthResponseHandler({ required int id, required String publicKey, required String pairingTopic, required String responseTopic, required int expiry, - required WcOCARequestParams request, - required Completer completer, + required WcSessionAuthRequestParams request, + required Completer completer, }) async { // - late WcOCARequestResult result; + late WcSessionAuthRequestResult result; try { final Map response = await core.pairing.sendRequest( pairingTopic, @@ -2256,9 +2306,9 @@ class SignEngine implements ISignEngine { id: id, ttl: expiry, ); - result = WcOCARequestResult.fromJson(response); + result = WcSessionAuthRequestResult.fromJson(response); } catch (error) { - final response = OCAuthResponse( + final response = SessionAuthResponse( id: id, topic: responseTopic, jsonRpcError: (error is JsonRpcError) ? error : null, @@ -2269,7 +2319,7 @@ class SignEngine implements ISignEngine { ) : null, ); - onOCAuthResponse.broadcast(response); + onSessionAuthResponse.broadcast(response); completer.complete(response); return; } @@ -2325,7 +2375,7 @@ class SignEngine implements ISignEngine { } } } on WalletConnectError catch (e) { - final resp = OCAuthResponse( + final resp = SessionAuthResponse( id: id, topic: responseTopic, error: WalletConnectError( @@ -2333,7 +2383,7 @@ class SignEngine implements ISignEngine { message: e.message, ), ); - onOCAuthResponse.broadcast(resp); + onSessionAuthResponse.broadcast(resp); completer.complete(resp); return; } @@ -2343,7 +2393,7 @@ class SignEngine implements ISignEngine { responder.publicKey, ); - late SessionData? session; + SessionData? session; if (approvedMethods.isNotEmpty) { session = SessionData( topic: sessionTopic, @@ -2368,16 +2418,21 @@ class SignEngine implements ISignEngine { await core.relayClient.subscribe(topic: sessionTopic); await sessions.set(sessionTopic, session); + await core.pairing.updateMetadata( + topic: pairingTopic, + metadata: responder.metadata, + ); + session = sessions.get(sessionTopic); } - final resp = OCAuthResponse( + final resp = SessionAuthResponse( id: id, topic: responseTopic, auths: cacaos, session: session, ); - onOCAuthResponse.broadcast(resp); + onSessionAuthResponse.broadcast(resp); completer.complete(resp); } @@ -2451,6 +2506,179 @@ class SignEngine implements ISignEngine { } } + @override + Future approveSessionAuthenticate({ + required int id, + List? auths, + }) async { + _checkInitialized(); + + final pendingRequests = getPendingSessionAuthRequests(); + + AuthApiValidators.isValidRespondAuthenticate( + id: id, + pendingRequests: pendingRequests, + auths: auths, + ); + + final PendingSessionAuthRequest pendingRequest = pendingRequests[id]!; + final receiverPublicKey = pendingRequest.requester.publicKey; + final senderPublicKey = await core.crypto.generateKeyPair(); + final responseTopic = core.crypto.getUtils().hashKey(receiverPublicKey); + + final encodeOpts = EncodeOptions( + type: EncodeOptions.TYPE_1, + receiverPublicKey: receiverPublicKey, + senderPublicKey: senderPublicKey, + ); + + final approvedMethods = {}; + final approvedAccounts = {}; + for (final Cacao cacao in auths!) { + final isValid = await validateSignedCacao( + cacao: cacao, + projectId: core.projectId, + ); + if (!isValid) { + final error = Errors.getSdkError( + Errors.SIGNATURE_VERIFICATION_FAILED, + context: 'Signature verification failed', + ); + await core.pairing.sendError( + id, + responseTopic, + MethodConstants.WC_SESSION_AUTHENTICATE, + JsonRpcError(code: error.code, message: error.message), + encodeOptions: encodeOpts, + ); + throw error; + } + + final CacaoPayload payload = cacao.p; + final chainId = AddressUtils.getDidChainId(payload.iss); + final approvedChains = ['eip155:$chainId']; + + final recap = ReCapsUtils.getRecapFromResources( + resources: payload.resources, + ); + if (recap != null) { + final methodsfromRecap = ReCapsUtils.getMethodsFromRecap(recap); + final chainsFromRecap = ReCapsUtils.getChainsFromRecap(recap); + approvedMethods.addAll(methodsfromRecap); + approvedChains.addAll(chainsFromRecap); + } + + final parsedAddress = AddressUtils.getDidAddress(payload.iss); + for (var chain in approvedChains.toSet()) { + approvedAccounts.add('$chain:$parsedAddress'); + } + } + + final sessionTopic = await core.crypto.generateSharedKey( + senderPublicKey, + receiverPublicKey, + ); + + SessionData? session; + if (approvedMethods.isNotEmpty) { + session = SessionData( + topic: sessionTopic, + acknowledged: true, + self: ConnectionMetadata( + publicKey: senderPublicKey, + metadata: metadata, + ), + peer: pendingRequest.requester, + controller: receiverPublicKey, + expiry: WalletConnectUtils.calculateExpiry( + WalletConnectConstants.SEVEN_DAYS, + ), + relay: Relay(WalletConnectConstants.RELAYER_DEFAULT_PROTOCOL), + pairingTopic: pendingRequest.pairingTopic, + namespaces: NamespaceUtils.buildNamespacesFromAuth( + accounts: approvedAccounts, + methods: approvedMethods, + ), + ); + + await core.relayClient.subscribe(topic: sessionTopic); + await sessions.set(sessionTopic, session); + + session = sessions.get(sessionTopic); + } + + final result = WcSessionAuthRequestResult( + cacaos: auths, + responder: ConnectionMetadata( + publicKey: senderPublicKey, + metadata: metadata, + ), + ); + await core.pairing.sendResult( + id, + responseTopic, + MethodConstants.WC_SESSION_AUTHENTICATE, + result.toJson(), + encodeOptions: encodeOpts, + ); + + await sessionAuthRequests.delete(id.toString()); + await core.pairing.activate(topic: pendingRequest.pairingTopic); + await core.pairing.updateMetadata( + topic: pendingRequest.pairingTopic, + metadata: pendingRequest.requester.metadata, + ); + + // return session; ? TODO check if should return session + return ApproveResponse( + topic: sessionTopic, + session: session, + ); + } + + @override + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }) async { + _checkInitialized(); + + final pendingRequests = getPendingSessionAuthRequests(); + + if (!pendingRequests.containsKey(id)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'rejectSessionAuthenticate() Could not find pending auth request with id $id', + ); + } + + final PendingSessionAuthRequest pendingRequest = pendingRequests[id]!; + final receiverPublicKey = pendingRequest.requester.publicKey; + final senderPublicKey = await core.crypto.generateKeyPair(); + final responseTopic = core.crypto.getUtils().hashKey(receiverPublicKey); + + final encodeOpts = EncodeOptions( + type: EncodeOptions.TYPE_1, + receiverPublicKey: receiverPublicKey, + senderPublicKey: senderPublicKey, + ); + + final method = MethodConstants.WC_SESSION_AUTHENTICATE; + final rpcOpts = MethodConstants.RPC_OPTS[method]; + await core.pairing.sendError( + id, + responseTopic, + method, + JsonRpcError(code: reason.code, message: reason.message), + encodeOptions: encodeOpts, + rpcOptions: rpcOpts?['reject'], + ); + + await sessionAuthRequests.delete(id.toString()); + await _deleteProposal(id); + } + // FORMER AUTH ENGINE PROPERTY void _onAuthRequest(String topic, JsonRpcRequest payload) async { try { @@ -2491,43 +2719,60 @@ class SignEngine implements ISignEngine { } } - // // TODO to be implemented for Wallet usage on following PR - // void _onOCARequest(String topic, JsonRpcRequest payload) async { - // try { - // final request = WcOCARequestRequest.fromJson(payload.params); - - // final CacaoRequestPayload cacaoPayload = - // CacaoRequestPayload.fromPayloadParams( - // request.payloadParams, - // ); - - // authRequests.set( - // payload.id.toString(), - // PendingAuthRequest( - // id: payload.id, - // pairingTopic: topic, - // metadata: request.requester, - // cacaoPayload: cacaoPayload, - // ), - // ); - - // onAuthRequest.broadcast( - // AuthRequest( - // id: payload.id, - // topic: topic, - // requester: request.requester, - // payloadParams: request.payloadParams, - // ), - // ); - // } on WalletConnectError catch (err) { - // await core.pairing.sendError( - // payload.id, - // topic, - // payload.method, - // JsonRpcError.invalidParams( - // err.message, - // ), - // ); - // } - // } + void _onSessionAuthRequest(String topic, JsonRpcRequest payload) async { + core.logger.t('_onSessionAuthRequest, topic: $topic, payload: $payload'); + + final sessionAuthRequest = WcSessionAuthRequestParams.fromJson( + payload.params, + ); + try { + // AuthApiValidators.isValidAuthenticate(params); // TODO + + final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayloadParams( + sessionAuthRequest.authPayload, + ); + + final verifyContext = await _getVerifyContext(payload, metadata); + + sessionAuthRequests.set( + payload.id.toString(), + PendingSessionAuthRequest( + id: payload.id, + pairingTopic: topic, + requester: sessionAuthRequest.requester, + authPayload: cacaoPayload, + expiryTimestamp: sessionAuthRequest.expiryTimestamp, + verifyContext: verifyContext, + ), + ); + + onSessionAuthRequest.broadcast( + SessionAuthRequest( + id: payload.id, + topic: topic, + requester: sessionAuthRequest.requester, // TODO is this needed? + payloadParams: sessionAuthRequest.authPayload, + verifyContext: verifyContext, + ), + ); + } on WalletConnectError catch (err) { + final receiverPublicKey = sessionAuthRequest.requester.publicKey; + final senderPublicKey = await core.crypto.generateKeyPair(); + + final encodeOpts = EncodeOptions( + type: EncodeOptions.TYPE_1, + receiverPublicKey: receiverPublicKey, + senderPublicKey: senderPublicKey, + ); + final rpcOpts = MethodConstants.RPC_OPTS[payload.method]; + await core.pairing.sendError( + payload.id, + topic, + payload.method, + JsonRpcError.invalidParams(err.message), + encodeOptions: encodeOpts, + rpcOptions: rpcOpts?['autoReject'], + ); + } + } } diff --git a/lib/apis/sign_api/utils/auth/auth_api_validators.dart b/lib/apis/sign_api/utils/auth/auth_api_validators.dart index 0c1bda59..7d5a39e7 100644 --- a/lib/apis/sign_api/utils/auth/auth_api_validators.dart +++ b/lib/apis/sign_api/utils/auth/auth_api_validators.dart @@ -76,7 +76,7 @@ class AuthApiValidators { return true; } - static bool isValidAuthenticate(OCARequestParams params) { + static bool isValidAuthenticate(SessionAuthRequestParams params) { if (params.chains.isEmpty) { throw Errors.getInternalError( Errors.MISSING_OR_INVALID, @@ -136,4 +136,28 @@ class AuthApiValidators { return true; } + + static bool isValidRespondAuthenticate({ + required int id, + required Map pendingRequests, + List? auths, + }) { + if (!pendingRequests.containsKey(id)) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'approveSessionAuthenticate() Could not find pending auth request with id $id', + ); + } + + if (auths == null || auths.isEmpty) { + throw Errors.getInternalError( + Errors.MISSING_OR_INVALID, + context: + 'approveSessionAuthenticate() invalid response. Must contain Cacao signatures.', + ); + } + + return true; + } } diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index de642765..90ba3095 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -5,8 +5,11 @@ import 'package:http/http.dart' as http; import 'package:pointycastle/digests/keccak.dart'; import 'package:walletconnect_flutter_v2/apis/core/pairing/utils/json_rpc_utils.dart'; +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/auth_constants.dart'; +import 'package:walletconnect_flutter_v2/apis/sign_api/utils/auth/recaps_utils.dart'; import 'package:web3dart/crypto.dart' as crypto; class AuthSignature { @@ -187,4 +190,91 @@ class AuthSignature { ); } } + + static Cacao buildAuthObject({ + required CacaoRequestPayload requestPayload, + required CacaoSignature signature, + required String iss, + }) { + if (!iss.contains('did:pkh:')) { + iss = 'did:pkh:$iss'; + } + return Cacao( + h: const CacaoHeader(t: CacaoHeader.CAIP122), + p: CacaoPayload.fromRequestPayload( + issuer: iss, + payload: requestPayload, + ), + s: signature, + ); + } + + static SessionAuthPayloadParams populateAuthPayload({ + required SessionAuthPayloadParams authPayload, + required List chains, + required List methods, + }) { + final statement = authPayload.statement ?? ''; + + if (chains.isEmpty) return authPayload; + + final requested = authPayload.chains; + final supported = chains; + + final approvedChains = + supported.where((value) => requested.contains(value)).toList(); + if (approvedChains.isEmpty) { + throw WalletConnectError(code: -1, message: 'No supported chains'); + } + + final requestedRecaps = ReCapsUtils.getDecodedRecapFromResources( + resources: authPayload.resources, + ); + if (requestedRecaps == null) return authPayload; + + ReCapsUtils.isValidRecap(requestedRecaps); + + final resource = ReCapsUtils.getRecapResource( + recap: requestedRecaps, + resource: 'eip155', + ); + List updatedResources = authPayload.resources ?? []; + + if (resource.isNotEmpty) { + final actions = ReCapsUtils.getReCapActions(abilities: resource); + final approvedActions = + actions.where((value) => methods.contains(value)).toList(); + if (approvedActions.isEmpty) { + throw WalletConnectError( + code: -1, + message: 'Supported methods don\'t satisfy the requested: $actions, ' + 'supported: $methods', + ); + } + final formattedActions = ReCapsUtils.assignAbilityToActions( + 'request', + approvedActions, + limits: {'chains': approvedChains}, + ); + final updatedRecap = ReCapsUtils.addResourceToRecap( + recap: requestedRecaps, + resource: 'eip155', + actions: formattedActions, + ); + // remove recap from resources as we will add the updated one + updatedResources = List.from((authPayload.resources ?? [])) + ..removeLast(); + updatedResources.add(ReCapsUtils.encodeRecap(updatedRecap)); + } + // + return SessionAuthPayloadParams.fromJson(authPayload.toJson()).copyWith( + statement: ReCapsUtils.buildRecapStatement( + statement, + ReCapsUtils.getRecapFromResources(resources: updatedResources), + ), + chains: approvedChains, + resources: authPayload.resources ?? + (updatedResources.isNotEmpty ? updatedResources : null), + ); + } } diff --git a/lib/apis/sign_api/utils/auth/recaps_utils.dart b/lib/apis/sign_api/utils/auth/recaps_utils.dart index bafc96d2..f217872f 100644 --- a/lib/apis/sign_api/utils/auth/recaps_utils.dart +++ b/lib/apis/sign_api/utils/auth/recaps_utils.dart @@ -1,8 +1,10 @@ import 'dart:convert'; +import 'package:flutter/foundation.dart'; import 'package:walletconnect_flutter_v2/apis/utils/errors.dart'; class ReCapsUtils { + // static String? getRecapFromResources({List? resources}) { final resourcesList = resources ?? []; if (resourcesList.isEmpty) return null; @@ -218,4 +220,129 @@ class ReCapsUtils { return mergedRecap; } + + static Map? getDecodedRecapFromResources({ + List? resources, + }) { + final resource = getRecapFromResources(resources: resources); + if (resource == null) return null; + if (!isRecap(resource)) return null; + return decodeRecap(resource); + } + + static String formatStatementFromRecap({ + String statement = '', + Map recap = const {}, + }) { + isValidRecap(recap); + // + final baseStatement = + 'I further authorize the stated URI to perform the following actions on my behalf: '; + if (statement.contains(baseStatement)) return statement; + // + final List statementForRecap = []; + int currentCounter = 0; + final att = recap['att'] as Map; + final resources = att.keys; + for (var resource in resources) { + final abilities = att[resource]; + final resourceAbilities = (abilities as Map).keys; + final actions = resourceAbilities.map((ability) { + return { + 'ability': ability.split('/')[0], + 'action': ability.split('/')[1], + }; + }).toList(); + actions.sort((a, b) => a['action']!.compareTo(b['action']!)); + // + final uniqueAbilities = {}; + for (var actionMap in actions) { + final ability = actionMap['ability']!; + final action = actionMap['action']!; + if (uniqueAbilities[ability] == null) { + uniqueAbilities[ability] = []; + } + uniqueAbilities[ability].add(action); + } + // + final abilitiesStatements = uniqueAbilities.keys.map((ability) { + currentCounter++; + final abilities = (uniqueAbilities[ability] as List).join('\', \''); + return '($currentCounter) \'$ability\': \'$abilities\' for \'$resource\'.'; + }).toList(); + + statementForRecap.add( + abilitiesStatements.join(', ').replaceAll('.,', '.'), + ); + } + // + final recapStatemet = statementForRecap.join(' '); + final recapStatement = '$baseStatement$recapStatemet'; + // add a space if there is a statement + return '${statement.isNotEmpty ? "$statement " : ""}$recapStatement'; + } + + static List getRecapResource({ + required Map recap, + required String resource, + }) { + try { + final att = recap['att'] as Map?; + final abilities = att?[resource] as Map?; + if (abilities != null) { + return abilities.keys.toList(); + } + } catch (e) { + debugPrint(e.toString()); + } + return []; + } + + static List getReCapActions({required List abilities}) { + try { + return abilities.map((ability) => ability.split('/')[1]).toList(); + } catch (e) { + debugPrint(e.toString()); + } + return []; + } + + static Map assignAbilityToActions( + String ability, + List actions, { + Map limits = const {}, + }) { + final sortedActions = List.from(actions) + ..sort((a, b) => a.compareTo(b)); + + Map abilities = {}; + for (var method in sortedActions) { + abilities['$ability/$method'] = [ + ...(abilities['$ability/$method'] ?? []), + limits, + ]; + } + + return Map.fromEntries(abilities.entries); + } + + static Map addResourceToRecap({ + required Map recap, + required String resource, + required Map actions, + }) { + // + final sortedRecap = Map.from(recap); + sortedRecap['att']![resource] = actions; + sortedRecap.keys.toList().sort((a, b) => a.compareTo(b)); + isValidRecap(sortedRecap); + return sortedRecap; + } + + static String buildRecapStatement(String statement, String? recap) { + if ((recap ?? '').isEmpty) return statement; + final decoded = decodeRecap(recap!); + isValidRecap(decoded); + return formatStatementFromRecap(statement: statement, recap: decoded); + } } diff --git a/lib/apis/utils/method_constants.dart b/lib/apis/utils/method_constants.dart index 71dfc851..82592401 100644 --- a/lib/apis/utils/method_constants.dart +++ b/lib/apis/utils/method_constants.dart @@ -67,6 +67,16 @@ class MethodConstants { prompt: false, tag: 1101, ), + 'reject': RpcOptions( + ttl: WalletConnectConstants.FIVE_MINUTES, + prompt: false, + tag: 1120, + ), + 'autoReject': RpcOptions( + ttl: WalletConnectConstants.FIVE_MINUTES, + prompt: false, + tag: 1121, + ), }, WC_SESSION_SETTLE: { 'req': RpcOptions( diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index c51b842b..cadcfe3e 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -117,6 +117,14 @@ class Web3App implements IWeb3App { return StoredCacao.fromJson(value); }, ), + sessionAuthRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingSessionAuthRequest.fromJson(value); + }, + ), ); authEngine = AuthEngine( @@ -341,7 +349,8 @@ class Web3App implements IWeb3App { @override Event get onAuthResponse => authEngine.onAuthResponse; @override - Event get onOCAuthResponse => signEngine.onOCAuthResponse; + Event get onSessionAuthResponse => + signEngine.onSessionAuthResponse; @override IGenericStore get authKeys => authEngine.authKeys; @@ -377,8 +386,8 @@ class Web3App implements IWeb3App { // NEW ONE-CLICK AUTH METHOD FOR DAPPS @override - Future authenticate({ - required OCARequestParams params, + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods = const [ [MethodConstants.WC_SESSION_AUTHENTICATE] @@ -429,7 +438,7 @@ class Web3App implements IWeb3App { required CacaoRequestPayload cacaoPayload, }) { try { - return authEngine.formatAuthMessage( + return signEngine.formatAuthMessage( iss: iss, cacaoPayload: cacaoPayload, ); diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index 08719d91..a53946c5 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -110,6 +110,14 @@ class Web3Wallet implements IWeb3Wallet { return StoredCacao.fromJson(value); }, ), + sessionAuthRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingSessionAuthRequest.fromJson(value); + }, + ), ); authEngine = AuthEngine( @@ -403,6 +411,13 @@ class Web3Wallet implements IWeb3Wallet { IGenericStore get completeRequests => authEngine.completeRequests; + @override + IGenericStore get sessionAuthRequests => + signEngine.sessionAuthRequests; + @override + Event get onSessionAuthRequest => + signEngine.onSessionAuthRequest; + @Deprecated( 'AuthEngine/AuthClient is deprecated and will be removed soon.\n' 'Please use authentication methods from SignEngine/SignClient instead', @@ -416,7 +431,7 @@ class Web3Wallet implements IWeb3Wallet { required String iss, CacaoSignature? signature, WalletConnectError? error, - }) async { + }) { try { return authEngine.respondAuthRequest( id: id, @@ -429,6 +444,36 @@ class Web3Wallet implements IWeb3Wallet { } } + @override + Future approveSessionAuthenticate({ + required int id, + List? auths, + }) { + try { + return signEngine.approveSessionAuthenticate( + id: id, + auths: auths, + ); + } catch (e) { + rethrow; + } + } + + @override + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }) { + try { + return signEngine.rejectSessionAuthenticate( + id: id, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + @override Map getPendingAuthRequests() { try { @@ -438,6 +483,15 @@ class Web3Wallet implements IWeb3Wallet { } } + @override + Map getPendingSessionAuthRequests() { + try { + return signEngine.getPendingSessionAuthRequests(); + } catch (e) { + rethrow; + } + } + @override Map getCompletedRequestsForPairing({ required String pairingTopic, @@ -457,7 +511,7 @@ class Web3Wallet implements IWeb3Wallet { required CacaoRequestPayload cacaoPayload, }) { try { - return authEngine.formatAuthMessage( + return signEngine.formatAuthMessage( iss: iss, cacaoPayload: cacaoPayload, ); diff --git a/lib/walletconnect_flutter_v2.dart b/lib/walletconnect_flutter_v2.dart index ed86fded..9d04f292 100644 --- a/lib/walletconnect_flutter_v2.dart +++ b/lib/walletconnect_flutter_v2.dart @@ -37,9 +37,8 @@ export 'apis/sign_api/models/sign_client_events.dart'; export 'apis/sign_api/models/auth/auth_client_models.dart'; export 'apis/sign_api/models/auth/auth_client_events.dart'; export 'apis/sign_api/models/auth/common_auth_models.dart'; -export 'apis/sign_api/models/auth/json_rpc_models.dart'; -export 'apis/sign_api/models/auth/ocauth_events.dart'; -export 'apis/sign_api/models/auth/ocauth_models.dart'; +export 'apis/sign_api/models/auth/session_auth_events.dart'; +export 'apis/sign_api/models/auth/session_auth_models.dart'; export 'apis/sign_api/utils/auth/auth_utils.dart'; export 'apis/sign_api/utils/auth/address_utils.dart'; export 'apis/sign_api/utils/auth/auth_signature.dart'; diff --git a/test/sign_api/sign_engine_test.dart b/test/sign_api/sign_engine_test.dart index 874dca8d..d6b4b433 100644 --- a/test/sign_api/sign_engine_test.dart +++ b/test/sign_api/sign_engine_test.dart @@ -87,6 +87,14 @@ void main() { return StoredCacao.fromJson(value); }, ), + sessionAuthRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingSessionAuthRequest.fromJson(value); + }, + ), ); await core.start(); await e.init(); @@ -160,6 +168,14 @@ void main() { return StoredCacao.fromJson(value); }, ), + sessionAuthRequests: GenericStore( + storage: core.storage, + context: StoreVersions.CONTEXT_AUTH_REQUESTS, + version: StoreVersions.VERSION_AUTH_REQUESTS, + fromJson: (dynamic value) { + return PendingSessionAuthRequest.fromJson(value); + }, + ), ); await core.start(); await e.init(); diff --git a/test/sign_api/utils/sign_client_test_wrapper.dart b/test/sign_api/utils/sign_client_test_wrapper.dart index e3d2a93d..11f74f0c 100644 --- a/test/sign_api/utils/sign_client_test_wrapper.dart +++ b/test/sign_api/utils/sign_client_test_wrapper.dart @@ -498,11 +498,20 @@ class SignClientTestWrapper implements ISignEngine { Event get onAuthResponse => client.onAuthResponse; @override - Event get onOCAuthResponse => client.onOCAuthResponse; + Event get onSessionAuthResponse => + client.onSessionAuthResponse; @override IGenericStore get pairingTopics => client.pairingTopics; + @override + IGenericStore get sessionAuthRequests => + client.sessionAuthRequests; + + @override + Event get onSessionAuthRequest => + client.onSessionAuthRequest; + @override Future requestAuth({ required AuthRequestParams params, @@ -522,8 +531,8 @@ class SignClientTestWrapper implements ISignEngine { // NEW ONE-CLICK AUTH METHOD FOR DAPPS @override - Future authenticate({ - required OCARequestParams params, + Future authenticate({ + required SessionAuthRequestParams params, String? pairingTopic, List>? methods, }) async { @@ -556,4 +565,43 @@ class SignClientTestWrapper implements ISignEngine { rethrow; } } + + @override + Future approveSessionAuthenticate({ + required int id, + List? auths, + }) async { + try { + return await client.approveSessionAuthenticate( + id: id, + auths: auths, + ); + } catch (e) { + rethrow; + } + } + + @override + Future rejectSessionAuthenticate({ + required int id, + required WalletConnectError reason, + }) async { + try { + return await client.rejectSessionAuthenticate( + id: id, + reason: reason, + ); + } catch (e) { + rethrow; + } + } + + @override + Map getPendingSessionAuthRequests() { + try { + return client.getPendingSessionAuthRequests(); + } catch (e) { + rethrow; + } + } } From 78d98dbbc02c0d077f5cf2b2f7028ec4275ed0b2 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 24 Jun 2024 16:12:27 +0200 Subject: [PATCH 20/29] minor changes --- .../lib/dependencies/web3wallet_service.dart | 9 +- .../wc_connection_request_widget.dart | 12 +-- .../models/auth/common_auth_models.dart | 4 +- .../models/auth/session_auth_events.dart | 6 +- .../models/auth/session_auth_models.dart | 15 ++-- .../auth/session_auth_models.freezed.dart | 83 +++++++++---------- .../models/auth/session_auth_models.g.dart | 8 +- lib/apis/sign_api/models/json_rpc_models.dart | 2 +- .../models/json_rpc_models.freezed.dart | 25 +++--- .../sign_api/models/json_rpc_models.g.dart | 2 +- lib/apis/sign_api/sign_engine.dart | 11 +-- .../sign_api/utils/auth/auth_signature.dart | 6 +- 12 files changed, 86 insertions(+), 97 deletions(-) diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 2690b29a..2da25a65 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -252,9 +252,9 @@ class Web3WalletService extends IWeb3WalletService { } Future _onSessionAuthRequest(SessionAuthRequest? args) async { - log('[SampleWallet] _onSessionAuthRequest ${args?.payloadParams}'); + log('[SampleWallet] _onSessionAuthRequest ${args?.authPayload}'); if (args != null) { - final SessionAuthPayloadParams payloadParams = args.payloadParams; + final SessionAuthPayload payloadParams = args.authPayload; final supportedChains = ChainData.eip155Chains.map((e) => e.chainId); final supportedMethods = SupportedEVMMethods.values.map((e) => e.name); final newPayloadParams = AuthSignature.populateAuthPayload( @@ -262,8 +262,7 @@ class Web3WalletService extends IWeb3WalletService { chains: supportedChains.toList(), methods: supportedMethods.toList(), ); - final cacaoRequestPayload = - CacaoRequestPayload.fromSessionAuthPayloadParams( + final cacaoRequestPayload = CacaoRequestPayload.fromSessionAuthPayload( newPayloadParams, ); final List> formattedMessages = []; @@ -281,7 +280,7 @@ class Web3WalletService extends IWeb3WalletService { final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( widget: WCSessionAuthRequestWidget( child: WCConnectionRequestWidget( - sessionAuthPayloadParams: newPayloadParams, + sessionAuthPayload: newPayloadParams, verifyContext: args.verifyContext, metadata: args.requester, ), diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart index 1e3acc82..89f78f5f 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart @@ -14,14 +14,14 @@ class WCConnectionRequestWidget extends StatelessWidget { const WCConnectionRequestWidget({ Key? key, this.authPayloadParams, - this.sessionAuthPayloadParams, + this.sessionAuthPayload, this.proposalData, this.metadata, this.verifyContext, }) : super(key: key); final AuthPayloadParams? authPayloadParams; - final SessionAuthPayloadParams? sessionAuthPayloadParams; + final SessionAuthPayload? sessionAuthPayload; final ProposalData? proposalData; final ConnectionMetadata? metadata; final VerifyContext? verifyContext; @@ -56,7 +56,7 @@ class WCConnectionRequestWidget extends StatelessWidget { const SizedBox(height: StyleConstants.linear8), (authPayloadParams != null) ? _buildAuthRequestView() - : (sessionAuthPayloadParams != null) + : (sessionAuthPayload != null) ? _buildSessionAuthRequestView() : _buildSessionProposalView(context), ], @@ -93,12 +93,12 @@ class WCConnectionRequestWidget extends StatelessWidget { Widget _buildSessionAuthRequestView() { final web3Wallet = GetIt.I().web3wallet; // - final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayloadParams( - sessionAuthPayloadParams!, + final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayload( + sessionAuthPayload!, ); // final List messagesModels = []; - for (var chain in sessionAuthPayloadParams!.chains) { + for (var chain in sessionAuthPayload!.chains) { final chainKeys = GetIt.I().getKeysForChain(chain); final iss = 'did:pkh:$chain:${chainKeys.first.address}'; final message = web3Wallet.formatAuthMessage( diff --git a/lib/apis/sign_api/models/auth/common_auth_models.dart b/lib/apis/sign_api/models/auth/common_auth_models.dart index a8393afb..973760fc 100644 --- a/lib/apis/sign_api/models/auth/common_auth_models.dart +++ b/lib/apis/sign_api/models/auth/common_auth_models.dart @@ -48,8 +48,8 @@ class CacaoRequestPayload with _$CacaoRequestPayload { ); } - factory CacaoRequestPayload.fromSessionAuthPayloadParams( - SessionAuthPayloadParams params, + factory CacaoRequestPayload.fromSessionAuthPayload( + SessionAuthPayload params, ) { return CacaoRequestPayload( domain: params.domain, diff --git a/lib/apis/sign_api/models/auth/session_auth_events.dart b/lib/apis/sign_api/models/auth/session_auth_events.dart index 3f02a784..3c7cce32 100644 --- a/lib/apis/sign_api/models/auth/session_auth_events.dart +++ b/lib/apis/sign_api/models/auth/session_auth_events.dart @@ -12,14 +12,14 @@ import 'package:walletconnect_flutter_v2/apis/sign_api/models/auth/session_auth_ class SessionAuthRequest extends EventArgs { final int id; final String topic; - final SessionAuthPayloadParams payloadParams; + final SessionAuthPayload authPayload; final ConnectionMetadata requester; final VerifyContext? verifyContext; SessionAuthRequest({ required this.id, required this.topic, - required this.payloadParams, + required this.authPayload, required this.requester, this.verifyContext, }); @@ -27,7 +27,7 @@ class SessionAuthRequest extends EventArgs { Map toJson() => { 'id': id, 'topic': topic, - 'payloadParams': payloadParams.toJson(), + 'authPayload': authPayload.toJson(), 'requester': requester.toJson(), 'verifyContext': verifyContext?.toJson(), }; diff --git a/lib/apis/sign_api/models/auth/session_auth_models.dart b/lib/apis/sign_api/models/auth/session_auth_models.dart index abbdd7f4..bbf95c45 100644 --- a/lib/apis/sign_api/models/auth/session_auth_models.dart +++ b/lib/apis/sign_api/models/auth/session_auth_models.dart @@ -71,11 +71,10 @@ class SessionAuthRequestParams { }; } -// TODO this should be called SessionAuthPayload @freezed -class SessionAuthPayloadParams with _$SessionAuthPayloadParams { +class SessionAuthPayload with _$SessionAuthPayload { @JsonSerializable(includeIfNull: false) - const factory SessionAuthPayloadParams({ + const factory SessionAuthPayload({ required List chains, required String domain, required String nonce, @@ -90,12 +89,12 @@ class SessionAuthPayloadParams with _$SessionAuthPayloadParams { String? statement, String? requestId, List? resources, - }) = _SessionAuthPayloadParams; + }) = _SessionAuthPayload; - factory SessionAuthPayloadParams.fromRequestParams( + factory SessionAuthPayload.fromRequestParams( SessionAuthRequestParams params, ) { - return SessionAuthPayloadParams( + return SessionAuthPayload( chains: params.chains, domain: params.domain, nonce: params.nonce, @@ -112,8 +111,8 @@ class SessionAuthPayloadParams with _$SessionAuthPayloadParams { ); } - factory SessionAuthPayloadParams.fromJson(Map json) => - _$SessionAuthPayloadParamsFromJson(json); + factory SessionAuthPayload.fromJson(Map json) => + _$SessionAuthPayloadFromJson(json); } @freezed 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 5152f1d9..70510d49 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 @@ -14,13 +14,12 @@ 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'); -SessionAuthPayloadParams _$SessionAuthPayloadParamsFromJson( - Map json) { - return _SessionAuthPayloadParams.fromJson(json); +SessionAuthPayload _$SessionAuthPayloadFromJson(Map json) { + return _SessionAuthPayload.fromJson(json); } /// @nodoc -mixin _$SessionAuthPayloadParams { +mixin _$SessionAuthPayload { List get chains => throw _privateConstructorUsedError; String get domain => throw _privateConstructorUsedError; String get nonce => throw _privateConstructorUsedError; @@ -36,15 +35,15 @@ mixin _$SessionAuthPayloadParams { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $SessionAuthPayloadParamsCopyWith get copyWith => + $SessionAuthPayloadCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class $SessionAuthPayloadParamsCopyWith<$Res> { - factory $SessionAuthPayloadParamsCopyWith(SessionAuthPayloadParams value, - $Res Function(SessionAuthPayloadParams) then) = - _$SessionAuthPayloadParamsCopyWithImpl<$Res, SessionAuthPayloadParams>; +abstract class $SessionAuthPayloadCopyWith<$Res> { + factory $SessionAuthPayloadCopyWith( + SessionAuthPayload value, $Res Function(SessionAuthPayload) then) = + _$SessionAuthPayloadCopyWithImpl<$Res, SessionAuthPayload>; @useResult $Res call( {List chains, @@ -62,10 +61,9 @@ abstract class $SessionAuthPayloadParamsCopyWith<$Res> { } /// @nodoc -class _$SessionAuthPayloadParamsCopyWithImpl<$Res, - $Val extends SessionAuthPayloadParams> - implements $SessionAuthPayloadParamsCopyWith<$Res> { - _$SessionAuthPayloadParamsCopyWithImpl(this._value, this._then); +class _$SessionAuthPayloadCopyWithImpl<$Res, $Val extends SessionAuthPayload> + implements $SessionAuthPayloadCopyWith<$Res> { + _$SessionAuthPayloadCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; @@ -142,12 +140,11 @@ class _$SessionAuthPayloadParamsCopyWithImpl<$Res, } /// @nodoc -abstract class _$$SessionAuthPayloadParamsImplCopyWith<$Res> - implements $SessionAuthPayloadParamsCopyWith<$Res> { - factory _$$SessionAuthPayloadParamsImplCopyWith( - _$SessionAuthPayloadParamsImpl value, - $Res Function(_$SessionAuthPayloadParamsImpl) then) = - __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res>; +abstract class _$$SessionAuthPayloadImplCopyWith<$Res> + implements $SessionAuthPayloadCopyWith<$Res> { + factory _$$SessionAuthPayloadImplCopyWith(_$SessionAuthPayloadImpl value, + $Res Function(_$SessionAuthPayloadImpl) then) = + __$$SessionAuthPayloadImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -166,13 +163,11 @@ abstract class _$$SessionAuthPayloadParamsImplCopyWith<$Res> } /// @nodoc -class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> - extends _$SessionAuthPayloadParamsCopyWithImpl<$Res, - _$SessionAuthPayloadParamsImpl> - implements _$$SessionAuthPayloadParamsImplCopyWith<$Res> { - __$$SessionAuthPayloadParamsImplCopyWithImpl( - _$SessionAuthPayloadParamsImpl _value, - $Res Function(_$SessionAuthPayloadParamsImpl) _then) +class __$$SessionAuthPayloadImplCopyWithImpl<$Res> + extends _$SessionAuthPayloadCopyWithImpl<$Res, _$SessionAuthPayloadImpl> + implements _$$SessionAuthPayloadImplCopyWith<$Res> { + __$$SessionAuthPayloadImplCopyWithImpl(_$SessionAuthPayloadImpl _value, + $Res Function(_$SessionAuthPayloadImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -191,7 +186,7 @@ class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> Object? requestId = freezed, Object? resources = freezed, }) { - return _then(_$SessionAuthPayloadParamsImpl( + return _then(_$SessionAuthPayloadImpl( chains: null == chains ? _value._chains : chains // ignore: cast_nullable_to_non_nullable @@ -247,8 +242,8 @@ class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable(includeIfNull: false) -class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { - const _$SessionAuthPayloadParamsImpl( +class _$SessionAuthPayloadImpl implements _SessionAuthPayload { + const _$SessionAuthPayloadImpl( {required final List chains, required this.domain, required this.nonce, @@ -264,8 +259,8 @@ class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { : _chains = chains, _resources = resources; - factory _$SessionAuthPayloadParamsImpl.fromJson(Map json) => - _$$SessionAuthPayloadParamsImplFromJson(json); + factory _$SessionAuthPayloadImpl.fromJson(Map json) => + _$$SessionAuthPayloadImplFromJson(json); final List _chains; @override @@ -309,14 +304,14 @@ class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { @override String toString() { - return 'SessionAuthPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; + return 'SessionAuthPayload(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$SessionAuthPayloadParamsImpl && + other is _$SessionAuthPayloadImpl && const DeepCollectionEquality().equals(other._chains, _chains) && (identical(other.domain, domain) || other.domain == domain) && (identical(other.nonce, nonce) || other.nonce == nonce) && @@ -354,20 +349,20 @@ class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> - get copyWith => __$$SessionAuthPayloadParamsImplCopyWithImpl< - _$SessionAuthPayloadParamsImpl>(this, _$identity); + _$$SessionAuthPayloadImplCopyWith<_$SessionAuthPayloadImpl> get copyWith => + __$$SessionAuthPayloadImplCopyWithImpl<_$SessionAuthPayloadImpl>( + this, _$identity); @override Map toJson() { - return _$$SessionAuthPayloadParamsImplToJson( + return _$$SessionAuthPayloadImplToJson( this, ); } } -abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { - const factory _SessionAuthPayloadParams( +abstract class _SessionAuthPayload implements SessionAuthPayload { + const factory _SessionAuthPayload( {required final List chains, required final String domain, required final String nonce, @@ -379,10 +374,10 @@ abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { final String? exp, final String? statement, final String? requestId, - final List? resources}) = _$SessionAuthPayloadParamsImpl; + final List? resources}) = _$SessionAuthPayloadImpl; - factory _SessionAuthPayloadParams.fromJson(Map json) = - _$SessionAuthPayloadParamsImpl.fromJson; + factory _SessionAuthPayload.fromJson(Map json) = + _$SessionAuthPayloadImpl.fromJson; @override List get chains; @@ -410,8 +405,8 @@ abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { List? get resources; @override @JsonKey(ignore: true) - _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> - get copyWith => throw _privateConstructorUsedError; + _$$SessionAuthPayloadImplCopyWith<_$SessionAuthPayloadImpl> get copyWith => + throw _privateConstructorUsedError; } PendingSessionAuthRequest _$PendingSessionAuthRequestFromJson( 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 23b70455..d0b00eca 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 @@ -6,9 +6,9 @@ part of 'session_auth_models.dart'; // JsonSerializableGenerator // ************************************************************************** -_$SessionAuthPayloadParamsImpl _$$SessionAuthPayloadParamsImplFromJson( +_$SessionAuthPayloadImpl _$$SessionAuthPayloadImplFromJson( Map json) => - _$SessionAuthPayloadParamsImpl( + _$SessionAuthPayloadImpl( chains: (json['chains'] as List).map((e) => e as String).toList(), domain: json['domain'] as String, @@ -26,8 +26,8 @@ _$SessionAuthPayloadParamsImpl _$$SessionAuthPayloadParamsImplFromJson( .toList(), ); -Map _$$SessionAuthPayloadParamsImplToJson( - _$SessionAuthPayloadParamsImpl instance) { +Map _$$SessionAuthPayloadImplToJson( + _$SessionAuthPayloadImpl instance) { final val = { 'chains': instance.chains, 'domain': instance.domain, diff --git a/lib/apis/sign_api/models/json_rpc_models.dart b/lib/apis/sign_api/models/json_rpc_models.dart index 12728bd9..bc88c75f 100644 --- a/lib/apis/sign_api/models/json_rpc_models.dart +++ b/lib/apis/sign_api/models/json_rpc_models.dart @@ -200,7 +200,7 @@ class WcAuthRequestResult with _$WcAuthRequestResult { class WcSessionAuthRequestParams with _$WcSessionAuthRequestParams { @JsonSerializable() const factory WcSessionAuthRequestParams({ - required SessionAuthPayloadParams authPayload, + required SessionAuthPayload authPayload, required ConnectionMetadata requester, required int expiryTimestamp, }) = _WcSessionAuthRequestParams; 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 6f33efae..f72335a4 100644 --- a/lib/apis/sign_api/models/json_rpc_models.freezed.dart +++ b/lib/apis/sign_api/models/json_rpc_models.freezed.dart @@ -2759,8 +2759,7 @@ WcSessionAuthRequestParams _$WcSessionAuthRequestParamsFromJson( /// @nodoc mixin _$WcSessionAuthRequestParams { - SessionAuthPayloadParams get authPayload => - throw _privateConstructorUsedError; + SessionAuthPayload get authPayload => throw _privateConstructorUsedError; ConnectionMetadata get requester => throw _privateConstructorUsedError; int get expiryTimestamp => throw _privateConstructorUsedError; @@ -2778,11 +2777,11 @@ abstract class $WcSessionAuthRequestParamsCopyWith<$Res> { WcSessionAuthRequestParams>; @useResult $Res call( - {SessionAuthPayloadParams authPayload, + {SessionAuthPayload authPayload, ConnectionMetadata requester, int expiryTimestamp}); - $SessionAuthPayloadParamsCopyWith<$Res> get authPayload; + $SessionAuthPayloadCopyWith<$Res> get authPayload; $ConnectionMetadataCopyWith<$Res> get requester; } @@ -2808,7 +2807,7 @@ class _$WcSessionAuthRequestParamsCopyWithImpl<$Res, authPayload: null == authPayload ? _value.authPayload : authPayload // ignore: cast_nullable_to_non_nullable - as SessionAuthPayloadParams, + as SessionAuthPayload, requester: null == requester ? _value.requester : requester // ignore: cast_nullable_to_non_nullable @@ -2822,8 +2821,8 @@ class _$WcSessionAuthRequestParamsCopyWithImpl<$Res, @override @pragma('vm:prefer-inline') - $SessionAuthPayloadParamsCopyWith<$Res> get authPayload { - return $SessionAuthPayloadParamsCopyWith<$Res>(_value.authPayload, (value) { + $SessionAuthPayloadCopyWith<$Res> get authPayload { + return $SessionAuthPayloadCopyWith<$Res>(_value.authPayload, (value) { return _then(_value.copyWith(authPayload: value) as $Val); }); } @@ -2847,12 +2846,12 @@ abstract class _$$WcSessionAuthRequestParamsImplCopyWith<$Res> @override @useResult $Res call( - {SessionAuthPayloadParams authPayload, + {SessionAuthPayload authPayload, ConnectionMetadata requester, int expiryTimestamp}); @override - $SessionAuthPayloadParamsCopyWith<$Res> get authPayload; + $SessionAuthPayloadCopyWith<$Res> get authPayload; @override $ConnectionMetadataCopyWith<$Res> get requester; } @@ -2878,7 +2877,7 @@ class __$$WcSessionAuthRequestParamsImplCopyWithImpl<$Res> authPayload: null == authPayload ? _value.authPayload : authPayload // ignore: cast_nullable_to_non_nullable - as SessionAuthPayloadParams, + as SessionAuthPayload, requester: null == requester ? _value.requester : requester // ignore: cast_nullable_to_non_nullable @@ -2905,7 +2904,7 @@ class _$WcSessionAuthRequestParamsImpl implements _WcSessionAuthRequestParams { _$$WcSessionAuthRequestParamsImplFromJson(json); @override - final SessionAuthPayloadParams authPayload; + final SessionAuthPayload authPayload; @override final ConnectionMetadata requester; @override @@ -2952,7 +2951,7 @@ class _$WcSessionAuthRequestParamsImpl implements _WcSessionAuthRequestParams { abstract class _WcSessionAuthRequestParams implements WcSessionAuthRequestParams { const factory _WcSessionAuthRequestParams( - {required final SessionAuthPayloadParams authPayload, + {required final SessionAuthPayload authPayload, required final ConnectionMetadata requester, required final int expiryTimestamp}) = _$WcSessionAuthRequestParamsImpl; @@ -2960,7 +2959,7 @@ abstract class _WcSessionAuthRequestParams _$WcSessionAuthRequestParamsImpl.fromJson; @override - SessionAuthPayloadParams get authPayload; + SessionAuthPayload get authPayload; @override ConnectionMetadata get requester; @override 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 908a1f31..8008131a 100644 --- a/lib/apis/sign_api/models/json_rpc_models.g.dart +++ b/lib/apis/sign_api/models/json_rpc_models.g.dart @@ -307,7 +307,7 @@ Map _$$WcAuthRequestResultImplToJson( _$WcSessionAuthRequestParamsImpl _$$WcSessionAuthRequestParamsImplFromJson( Map json) => _$WcSessionAuthRequestParamsImpl( - authPayload: SessionAuthPayloadParams.fromJson( + authPayload: SessionAuthPayload.fromJson( json['authPayload'] as Map), requester: ConnectionMetadata.fromJson( json['requester'] as Map), diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index c0fbe61b..cdcd2f4a 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -2194,7 +2194,7 @@ class SignEngine implements ISignEngine { ); final request = WcSessionAuthRequestParams( - authPayload: SessionAuthPayloadParams.fromRequestParams(params).copyWith( + authPayload: SessionAuthPayload.fromRequestParams(params).copyWith( resources: resources, ), requester: ConnectionMetadata( @@ -2629,7 +2629,6 @@ class SignEngine implements ISignEngine { metadata: pendingRequest.requester.metadata, ); - // return session; ? TODO check if should return session return ApproveResponse( topic: sessionTopic, session: session, @@ -2726,9 +2725,7 @@ class SignEngine implements ISignEngine { payload.params, ); try { - // AuthApiValidators.isValidAuthenticate(params); // TODO - - final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayloadParams( + final cacaoPayload = CacaoRequestPayload.fromSessionAuthPayload( sessionAuthRequest.authPayload, ); @@ -2750,8 +2747,8 @@ class SignEngine implements ISignEngine { SessionAuthRequest( id: payload.id, topic: topic, - requester: sessionAuthRequest.requester, // TODO is this needed? - payloadParams: sessionAuthRequest.authPayload, + requester: sessionAuthRequest.requester, + authPayload: sessionAuthRequest.authPayload, verifyContext: verifyContext, ), ); diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index 90ba3095..32e31c94 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -209,8 +209,8 @@ class AuthSignature { ); } - static SessionAuthPayloadParams populateAuthPayload({ - required SessionAuthPayloadParams authPayload, + static SessionAuthPayload populateAuthPayload({ + required SessionAuthPayload authPayload, required List chains, required List methods, }) { @@ -267,7 +267,7 @@ class AuthSignature { updatedResources.add(ReCapsUtils.encodeRecap(updatedRecap)); } // - return SessionAuthPayloadParams.fromJson(authPayload.toJson()).copyWith( + return SessionAuthPayload.fromJson(authPayload.toJson()).copyWith( statement: ReCapsUtils.buildRecapStatement( statement, ReCapsUtils.getRecapFromResources(resources: updatedResources), From 55478f6cb3b50fb09cec82e8d6ad951bbed17d2c Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 24 Jun 2024 16:54:09 +0200 Subject: [PATCH 21/29] Delete unused generated files --- .../auth/auth_common_models.freezed.dart | 1633 ----------------- .../models/auth/auth_common_models.g.dart | 164 -- .../models/auth/cacao_models.freezed.dart | 1494 --------------- .../sign_api/models/auth/cacao_models.g.dart | 154 -- .../models/auth/ocauth_models.freezed.dart | 704 ------- .../sign_api/models/auth/ocauth_models.g.dart | 78 - .../auth/one_click_auth_models.freezed.dart | 410 ----- .../models/auth/one_click_auth_models.g.dart | 53 - test/auth_api/auth_client_test.dart | 2 +- 9 files changed, 1 insertion(+), 4691 deletions(-) delete mode 100644 lib/apis/sign_api/models/auth/auth_common_models.freezed.dart delete mode 100644 lib/apis/sign_api/models/auth/auth_common_models.g.dart delete mode 100644 lib/apis/sign_api/models/auth/cacao_models.freezed.dart delete mode 100644 lib/apis/sign_api/models/auth/cacao_models.g.dart delete mode 100644 lib/apis/sign_api/models/auth/ocauth_models.freezed.dart delete mode 100644 lib/apis/sign_api/models/auth/ocauth_models.g.dart delete mode 100644 lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart delete mode 100644 lib/apis/sign_api/models/auth/one_click_auth_models.g.dart diff --git a/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart b/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart deleted file mode 100644 index ce14e4ff..00000000 --- a/lib/apis/sign_api/models/auth/auth_common_models.freezed.dart +++ /dev/null @@ -1,1633 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'auth_common_models.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -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'); - -AuthPublicKey _$AuthPublicKeyFromJson(Map json) { - return _AuthPublicKey.fromJson(json); -} - -/// @nodoc -mixin _$AuthPublicKey { - String get publicKey => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $AuthPublicKeyCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $AuthPublicKeyCopyWith<$Res> { - factory $AuthPublicKeyCopyWith( - AuthPublicKey value, $Res Function(AuthPublicKey) then) = - _$AuthPublicKeyCopyWithImpl<$Res, AuthPublicKey>; - @useResult - $Res call({String publicKey}); -} - -/// @nodoc -class _$AuthPublicKeyCopyWithImpl<$Res, $Val extends AuthPublicKey> - implements $AuthPublicKeyCopyWith<$Res> { - _$AuthPublicKeyCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? publicKey = null, - }) { - return _then(_value.copyWith( - publicKey: null == publicKey - ? _value.publicKey - : publicKey // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$AuthPublicKeyImplCopyWith<$Res> - implements $AuthPublicKeyCopyWith<$Res> { - factory _$$AuthPublicKeyImplCopyWith( - _$AuthPublicKeyImpl value, $Res Function(_$AuthPublicKeyImpl) then) = - __$$AuthPublicKeyImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String publicKey}); -} - -/// @nodoc -class __$$AuthPublicKeyImplCopyWithImpl<$Res> - extends _$AuthPublicKeyCopyWithImpl<$Res, _$AuthPublicKeyImpl> - implements _$$AuthPublicKeyImplCopyWith<$Res> { - __$$AuthPublicKeyImplCopyWithImpl( - _$AuthPublicKeyImpl _value, $Res Function(_$AuthPublicKeyImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? publicKey = null, - }) { - return _then(_$AuthPublicKeyImpl( - publicKey: null == publicKey - ? _value.publicKey - : publicKey // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$AuthPublicKeyImpl implements _AuthPublicKey { - const _$AuthPublicKeyImpl({required this.publicKey}); - - factory _$AuthPublicKeyImpl.fromJson(Map json) => - _$$AuthPublicKeyImplFromJson(json); - - @override - final String publicKey; - - @override - String toString() { - return 'AuthPublicKey(publicKey: $publicKey)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$AuthPublicKeyImpl && - (identical(other.publicKey, publicKey) || - other.publicKey == publicKey)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, publicKey); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => - __$$AuthPublicKeyImplCopyWithImpl<_$AuthPublicKeyImpl>(this, _$identity); - - @override - Map toJson() { - return _$$AuthPublicKeyImplToJson( - this, - ); - } -} - -abstract class _AuthPublicKey implements AuthPublicKey { - const factory _AuthPublicKey({required final String publicKey}) = - _$AuthPublicKeyImpl; - - factory _AuthPublicKey.fromJson(Map json) = - _$AuthPublicKeyImpl.fromJson; - - @override - String get publicKey; - @override - @JsonKey(ignore: true) - _$$AuthPublicKeyImplCopyWith<_$AuthPublicKeyImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { - return _CacaoRequestPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoRequestPayload { - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoRequestPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoRequestPayloadCopyWith<$Res> { - factory $CacaoRequestPayloadCopyWith( - CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = - _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> - implements $CacaoRequestPayloadCopyWith<$Res> { - _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> - implements $CacaoRequestPayloadCopyWith<$Res> { - factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, - $Res Function(_$CacaoRequestPayloadImpl) then) = - __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> - extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> - implements _$$CacaoRequestPayloadImplCopyWith<$Res> { - __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, - $Res Function(_$CacaoRequestPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoRequestPayloadImpl( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { - const _$CacaoRequestPayloadImpl( - {required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoRequestPayloadImpl.fromJson(Map json) => - _$$CacaoRequestPayloadImplFromJson(json); - - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoRequestPayloadImpl && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoRequestPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoRequestPayload implements CacaoRequestPayload { - const factory _CacaoRequestPayload( - {required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoRequestPayloadImpl; - - factory _CacaoRequestPayload.fromJson(Map json) = - _$CacaoRequestPayloadImpl.fromJson; - - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoPayload _$CacaoPayloadFromJson(Map json) { - return _CacaoPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoPayload { - String get iss => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoPayloadCopyWith<$Res> { - factory $CacaoPayloadCopyWith( - CacaoPayload value, $Res Function(CacaoPayload) then) = - _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> - implements $CacaoPayloadCopyWith<$Res> { - _$CacaoPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoPayloadImplCopyWith<$Res> - implements $CacaoPayloadCopyWith<$Res> { - factory _$$CacaoPayloadImplCopyWith( - _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = - __$$CacaoPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoPayloadImplCopyWithImpl<$Res> - extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> - implements _$$CacaoPayloadImplCopyWith<$Res> { - __$$CacaoPayloadImplCopyWithImpl( - _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoPayloadImpl( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoPayloadImpl implements _CacaoPayload { - const _$CacaoPayloadImpl( - {required this.iss, - required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoPayloadImpl.fromJson(Map json) => - _$$CacaoPayloadImplFromJson(json); - - @override - final String iss; - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoPayloadImpl && - (identical(other.iss, iss) || other.iss == iss) && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - iss, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoPayload implements CacaoPayload { - const factory _CacaoPayload( - {required final String iss, - required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoPayloadImpl; - - factory _CacaoPayload.fromJson(Map json) = - _$CacaoPayloadImpl.fromJson; - - @override - String get iss; - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoHeader _$CacaoHeaderFromJson(Map json) { - return _CacaoHeader.fromJson(json); -} - -/// @nodoc -mixin _$CacaoHeader { - String get t => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoHeaderCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoHeaderCopyWith<$Res> { - factory $CacaoHeaderCopyWith( - CacaoHeader value, $Res Function(CacaoHeader) then) = - _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; - @useResult - $Res call({String t}); -} - -/// @nodoc -class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> - implements $CacaoHeaderCopyWith<$Res> { - _$CacaoHeaderCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoHeaderImplCopyWith<$Res> - implements $CacaoHeaderCopyWith<$Res> { - factory _$$CacaoHeaderImplCopyWith( - _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = - __$$CacaoHeaderImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t}); -} - -/// @nodoc -class __$$CacaoHeaderImplCopyWithImpl<$Res> - extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> - implements _$$CacaoHeaderImplCopyWith<$Res> { - __$$CacaoHeaderImplCopyWithImpl( - _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_$CacaoHeaderImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoHeaderImpl implements _CacaoHeader { - const _$CacaoHeaderImpl({this.t = 'eip4361'}); - - factory _$CacaoHeaderImpl.fromJson(Map json) => - _$$CacaoHeaderImplFromJson(json); - - @override - @JsonKey() - final String t; - - @override - String toString() { - return 'CacaoHeader(t: $t)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoHeaderImpl && - (identical(other.t, t) || other.t == t)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoHeaderImplToJson( - this, - ); - } -} - -abstract class _CacaoHeader implements CacaoHeader { - const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; - - factory _CacaoHeader.fromJson(Map json) = - _$CacaoHeaderImpl.fromJson; - - @override - String get t; - @override - @JsonKey(ignore: true) - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoSignature _$CacaoSignatureFromJson(Map json) { - return _CacaoSignature.fromJson(json); -} - -/// @nodoc -mixin _$CacaoSignature { - String get t => throw _privateConstructorUsedError; - String get s => throw _privateConstructorUsedError; - String? get m => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoSignatureCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoSignatureCopyWith<$Res> { - factory $CacaoSignatureCopyWith( - CacaoSignature value, $Res Function(CacaoSignature) then) = - _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> - implements $CacaoSignatureCopyWith<$Res> { - _$CacaoSignatureCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoSignatureImplCopyWith<$Res> - implements $CacaoSignatureCopyWith<$Res> { - factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, - $Res Function(_$CacaoSignatureImpl) then) = - __$$CacaoSignatureImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class __$$CacaoSignatureImplCopyWithImpl<$Res> - extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> - implements _$$CacaoSignatureImplCopyWith<$Res> { - __$$CacaoSignatureImplCopyWithImpl( - _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_$CacaoSignatureImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoSignatureImpl implements _CacaoSignature { - const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); - - factory _$CacaoSignatureImpl.fromJson(Map json) => - _$$CacaoSignatureImplFromJson(json); - - @override - final String t; - @override - final String s; - @override - final String? m; - - @override - String toString() { - return 'CacaoSignature(t: $t, s: $s, m: $m)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoSignatureImpl && - (identical(other.t, t) || other.t == t) && - (identical(other.s, s) || other.s == s) && - (identical(other.m, m) || other.m == m)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t, s, m); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoSignatureImplToJson( - this, - ); - } -} - -abstract class _CacaoSignature implements CacaoSignature { - const factory _CacaoSignature( - {required final String t, - required final String s, - final String? m}) = _$CacaoSignatureImpl; - - factory _CacaoSignature.fromJson(Map json) = - _$CacaoSignatureImpl.fromJson; - - @override - String get t; - @override - String get s; - @override - String? get m; - @override - @JsonKey(ignore: true) - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - throw _privateConstructorUsedError; -} - -Cacao _$CacaoFromJson(Map json) { - return _Cacao.fromJson(json); -} - -/// @nodoc -mixin _$Cacao { - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoCopyWith<$Res> { - factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = - _$CacaoCopyWithImpl<$Res, Cacao>; - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> - implements $CacaoCopyWith<$Res> { - _$CacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { - factory _$$CacaoImplCopyWith( - _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = - __$$CacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$CacaoImplCopyWithImpl<$Res> - extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> - implements _$$CacaoImplCopyWith<$Res> { - __$$CacaoImplCopyWithImpl( - _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$CacaoImpl( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoImpl implements _Cacao { - const _$CacaoImpl({required this.h, required this.p, required this.s}); - - factory _$CacaoImpl.fromJson(Map json) => - _$$CacaoImplFromJson(json); - - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'Cacao(h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoImpl && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoImplToJson( - this, - ); - } -} - -abstract class _Cacao implements Cacao { - const factory _Cacao( - {required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$CacaoImpl; - - factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; - - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} - -StoredCacao _$StoredCacaoFromJson(Map json) { - return _StoredCacao.fromJson(json); -} - -/// @nodoc -mixin _$StoredCacao { - int get id => throw _privateConstructorUsedError; - String get pairingTopic => throw _privateConstructorUsedError; - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $StoredCacaoCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $StoredCacaoCopyWith<$Res> { - factory $StoredCacaoCopyWith( - StoredCacao value, $Res Function(StoredCacao) then) = - _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> - implements $StoredCacaoCopyWith<$Res> { - _$StoredCacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$StoredCacaoImplCopyWith<$Res> - implements $StoredCacaoCopyWith<$Res> { - factory _$$StoredCacaoImplCopyWith( - _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = - __$$StoredCacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$StoredCacaoImplCopyWithImpl<$Res> - extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> - implements _$$StoredCacaoImplCopyWith<$Res> { - __$$StoredCacaoImplCopyWithImpl( - _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$StoredCacaoImpl( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$StoredCacaoImpl implements _StoredCacao { - const _$StoredCacaoImpl( - {required this.id, - required this.pairingTopic, - required this.h, - required this.p, - required this.s}); - - factory _$StoredCacaoImpl.fromJson(Map json) => - _$$StoredCacaoImplFromJson(json); - - @override - final int id; - @override - final String pairingTopic; - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$StoredCacaoImpl && - (identical(other.id, id) || other.id == id) && - (identical(other.pairingTopic, pairingTopic) || - other.pairingTopic == pairingTopic) && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$StoredCacaoImplToJson( - this, - ); - } -} - -abstract class _StoredCacao implements StoredCacao { - const factory _StoredCacao( - {required final int id, - required final String pairingTopic, - required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$StoredCacaoImpl; - - factory _StoredCacao.fromJson(Map json) = - _$StoredCacaoImpl.fromJson; - - @override - int get id; - @override - String get pairingTopic; - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/apis/sign_api/models/auth/auth_common_models.g.dart b/lib/apis/sign_api/models/auth/auth_common_models.g.dart deleted file mode 100644 index cc175fa9..00000000 --- a/lib/apis/sign_api/models/auth/auth_common_models.g.dart +++ /dev/null @@ -1,164 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'auth_common_models.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$AuthPublicKeyImpl _$$AuthPublicKeyImplFromJson(Map json) => - _$AuthPublicKeyImpl( - publicKey: json['publicKey'] as String, - ); - -Map _$$AuthPublicKeyImplToJson(_$AuthPublicKeyImpl instance) => - { - 'publicKey': instance.publicKey, - }; - -_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( - Map json) => - _$CacaoRequestPayloadImpl( - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoRequestPayloadImplToJson( - _$CacaoRequestPayloadImpl instance) { - final val = { - 'domain': instance.domain, - 'aud': instance.aud, - 'version': instance.version, - 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => - _$CacaoPayloadImpl( - iss: json['iss'] as String, - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { - final val = { - 'iss': instance.iss, - 'domain': instance.domain, - 'aud': instance.aud, - 'version': instance.version, - 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => - _$CacaoHeaderImpl( - t: json['t'] as String? ?? 'eip4361', - ); - -Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => - { - 't': instance.t, - }; - -_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => - _$CacaoSignatureImpl( - t: json['t'] as String, - s: json['s'] as String, - m: json['m'] as String?, - ); - -Map _$$CacaoSignatureImplToJson( - _$CacaoSignatureImpl instance) { - final val = { - 't': instance.t, - 's': instance.s, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('m', instance.m); - return val; -} - -_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$CacaoImplToJson(_$CacaoImpl instance) => - { - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; - -_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => - _$StoredCacaoImpl( - id: json['id'] as int, - pairingTopic: json['pairingTopic'] as String, - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => - { - 'id': instance.id, - 'pairingTopic': instance.pairingTopic, - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; diff --git a/lib/apis/sign_api/models/auth/cacao_models.freezed.dart b/lib/apis/sign_api/models/auth/cacao_models.freezed.dart deleted file mode 100644 index 998b2364..00000000 --- a/lib/apis/sign_api/models/auth/cacao_models.freezed.dart +++ /dev/null @@ -1,1494 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'cacao_models.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -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'); - -CacaoRequestPayload _$CacaoRequestPayloadFromJson(Map json) { - return _CacaoRequestPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoRequestPayload { - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoRequestPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoRequestPayloadCopyWith<$Res> { - factory $CacaoRequestPayloadCopyWith( - CacaoRequestPayload value, $Res Function(CacaoRequestPayload) then) = - _$CacaoRequestPayloadCopyWithImpl<$Res, CacaoRequestPayload>; - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoRequestPayloadCopyWithImpl<$Res, $Val extends CacaoRequestPayload> - implements $CacaoRequestPayloadCopyWith<$Res> { - _$CacaoRequestPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoRequestPayloadImplCopyWith<$Res> - implements $CacaoRequestPayloadCopyWith<$Res> { - factory _$$CacaoRequestPayloadImplCopyWith(_$CacaoRequestPayloadImpl value, - $Res Function(_$CacaoRequestPayloadImpl) then) = - __$$CacaoRequestPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoRequestPayloadImplCopyWithImpl<$Res> - extends _$CacaoRequestPayloadCopyWithImpl<$Res, _$CacaoRequestPayloadImpl> - implements _$$CacaoRequestPayloadImplCopyWith<$Res> { - __$$CacaoRequestPayloadImplCopyWithImpl(_$CacaoRequestPayloadImpl _value, - $Res Function(_$CacaoRequestPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoRequestPayloadImpl( - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoRequestPayloadImpl implements _CacaoRequestPayload { - const _$CacaoRequestPayloadImpl( - {required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoRequestPayloadImpl.fromJson(Map json) => - _$$CacaoRequestPayloadImplFromJson(json); - - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoRequestPayload(domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoRequestPayloadImpl && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - __$$CacaoRequestPayloadImplCopyWithImpl<_$CacaoRequestPayloadImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoRequestPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoRequestPayload implements CacaoRequestPayload { - const factory _CacaoRequestPayload( - {required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoRequestPayloadImpl; - - factory _CacaoRequestPayload.fromJson(Map json) = - _$CacaoRequestPayloadImpl.fromJson; - - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoRequestPayloadImplCopyWith<_$CacaoRequestPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoPayload _$CacaoPayloadFromJson(Map json) { - return _CacaoPayload.fromJson(json); -} - -/// @nodoc -mixin _$CacaoPayload { - String get iss => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get version => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoPayloadCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoPayloadCopyWith<$Res> { - factory $CacaoPayloadCopyWith( - CacaoPayload value, $Res Function(CacaoPayload) then) = - _$CacaoPayloadCopyWithImpl<$Res, CacaoPayload>; - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$CacaoPayloadCopyWithImpl<$Res, $Val extends CacaoPayload> - implements $CacaoPayloadCopyWith<$Res> { - _$CacaoPayloadCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoPayloadImplCopyWith<$Res> - implements $CacaoPayloadCopyWith<$Res> { - factory _$$CacaoPayloadImplCopyWith( - _$CacaoPayloadImpl value, $Res Function(_$CacaoPayloadImpl) then) = - __$$CacaoPayloadImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {String iss, - String domain, - String aud, - String version, - String nonce, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$CacaoPayloadImplCopyWithImpl<$Res> - extends _$CacaoPayloadCopyWithImpl<$Res, _$CacaoPayloadImpl> - implements _$$CacaoPayloadImplCopyWith<$Res> { - __$$CacaoPayloadImplCopyWithImpl( - _$CacaoPayloadImpl _value, $Res Function(_$CacaoPayloadImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? iss = null, - Object? domain = null, - Object? aud = null, - Object? version = null, - Object? nonce = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$CacaoPayloadImpl( - iss: null == iss - ? _value.iss - : iss // ignore: cast_nullable_to_non_nullable - as String, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoPayloadImpl implements _CacaoPayload { - const _$CacaoPayloadImpl( - {required this.iss, - required this.domain, - required this.aud, - required this.version, - required this.nonce, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _resources = resources; - - factory _$CacaoPayloadImpl.fromJson(Map json) => - _$$CacaoPayloadImplFromJson(json); - - @override - final String iss; - @override - final String domain; - @override - final String aud; - @override - final String version; - @override - final String nonce; - @override - final String iat; - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'CacaoPayload(iss: $iss, domain: $domain, aud: $aud, version: $version, nonce: $nonce, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoPayloadImpl && - (identical(other.iss, iss) || other.iss == iss) && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.version, version) || other.version == version) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - iss, - domain, - aud, - version, - nonce, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - __$$CacaoPayloadImplCopyWithImpl<_$CacaoPayloadImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoPayloadImplToJson( - this, - ); - } -} - -abstract class _CacaoPayload implements CacaoPayload { - const factory _CacaoPayload( - {required final String iss, - required final String domain, - required final String aud, - required final String version, - required final String nonce, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$CacaoPayloadImpl; - - factory _CacaoPayload.fromJson(Map json) = - _$CacaoPayloadImpl.fromJson; - - @override - String get iss; - @override - String get domain; - @override - String get aud; - @override - String get version; - @override - String get nonce; - @override - String get iat; - @override - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$CacaoPayloadImplCopyWith<_$CacaoPayloadImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoHeader _$CacaoHeaderFromJson(Map json) { - return _CacaoHeader.fromJson(json); -} - -/// @nodoc -mixin _$CacaoHeader { - String get t => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoHeaderCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoHeaderCopyWith<$Res> { - factory $CacaoHeaderCopyWith( - CacaoHeader value, $Res Function(CacaoHeader) then) = - _$CacaoHeaderCopyWithImpl<$Res, CacaoHeader>; - @useResult - $Res call({String t}); -} - -/// @nodoc -class _$CacaoHeaderCopyWithImpl<$Res, $Val extends CacaoHeader> - implements $CacaoHeaderCopyWith<$Res> { - _$CacaoHeaderCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoHeaderImplCopyWith<$Res> - implements $CacaoHeaderCopyWith<$Res> { - factory _$$CacaoHeaderImplCopyWith( - _$CacaoHeaderImpl value, $Res Function(_$CacaoHeaderImpl) then) = - __$$CacaoHeaderImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t}); -} - -/// @nodoc -class __$$CacaoHeaderImplCopyWithImpl<$Res> - extends _$CacaoHeaderCopyWithImpl<$Res, _$CacaoHeaderImpl> - implements _$$CacaoHeaderImplCopyWith<$Res> { - __$$CacaoHeaderImplCopyWithImpl( - _$CacaoHeaderImpl _value, $Res Function(_$CacaoHeaderImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - }) { - return _then(_$CacaoHeaderImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoHeaderImpl implements _CacaoHeader { - const _$CacaoHeaderImpl({this.t = 'eip4361'}); - - factory _$CacaoHeaderImpl.fromJson(Map json) => - _$$CacaoHeaderImplFromJson(json); - - @override - @JsonKey() - final String t; - - @override - String toString() { - return 'CacaoHeader(t: $t)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoHeaderImpl && - (identical(other.t, t) || other.t == t)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - __$$CacaoHeaderImplCopyWithImpl<_$CacaoHeaderImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoHeaderImplToJson( - this, - ); - } -} - -abstract class _CacaoHeader implements CacaoHeader { - const factory _CacaoHeader({final String t}) = _$CacaoHeaderImpl; - - factory _CacaoHeader.fromJson(Map json) = - _$CacaoHeaderImpl.fromJson; - - @override - String get t; - @override - @JsonKey(ignore: true) - _$$CacaoHeaderImplCopyWith<_$CacaoHeaderImpl> get copyWith => - throw _privateConstructorUsedError; -} - -CacaoSignature _$CacaoSignatureFromJson(Map json) { - return _CacaoSignature.fromJson(json); -} - -/// @nodoc -mixin _$CacaoSignature { - String get t => throw _privateConstructorUsedError; - String get s => throw _privateConstructorUsedError; - String? get m => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoSignatureCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoSignatureCopyWith<$Res> { - factory $CacaoSignatureCopyWith( - CacaoSignature value, $Res Function(CacaoSignature) then) = - _$CacaoSignatureCopyWithImpl<$Res, CacaoSignature>; - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class _$CacaoSignatureCopyWithImpl<$Res, $Val extends CacaoSignature> - implements $CacaoSignatureCopyWith<$Res> { - _$CacaoSignatureCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_value.copyWith( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$CacaoSignatureImplCopyWith<$Res> - implements $CacaoSignatureCopyWith<$Res> { - factory _$$CacaoSignatureImplCopyWith(_$CacaoSignatureImpl value, - $Res Function(_$CacaoSignatureImpl) then) = - __$$CacaoSignatureImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({String t, String s, String? m}); -} - -/// @nodoc -class __$$CacaoSignatureImplCopyWithImpl<$Res> - extends _$CacaoSignatureCopyWithImpl<$Res, _$CacaoSignatureImpl> - implements _$$CacaoSignatureImplCopyWith<$Res> { - __$$CacaoSignatureImplCopyWithImpl( - _$CacaoSignatureImpl _value, $Res Function(_$CacaoSignatureImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? t = null, - Object? s = null, - Object? m = freezed, - }) { - return _then(_$CacaoSignatureImpl( - t: null == t - ? _value.t - : t // ignore: cast_nullable_to_non_nullable - as String, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as String, - m: freezed == m - ? _value.m - : m // ignore: cast_nullable_to_non_nullable - as String?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoSignatureImpl implements _CacaoSignature { - const _$CacaoSignatureImpl({required this.t, required this.s, this.m}); - - factory _$CacaoSignatureImpl.fromJson(Map json) => - _$$CacaoSignatureImplFromJson(json); - - @override - final String t; - @override - final String s; - @override - final String? m; - - @override - String toString() { - return 'CacaoSignature(t: $t, s: $s, m: $m)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoSignatureImpl && - (identical(other.t, t) || other.t == t) && - (identical(other.s, s) || other.s == s) && - (identical(other.m, m) || other.m == m)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, t, s, m); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - __$$CacaoSignatureImplCopyWithImpl<_$CacaoSignatureImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$CacaoSignatureImplToJson( - this, - ); - } -} - -abstract class _CacaoSignature implements CacaoSignature { - const factory _CacaoSignature( - {required final String t, - required final String s, - final String? m}) = _$CacaoSignatureImpl; - - factory _CacaoSignature.fromJson(Map json) = - _$CacaoSignatureImpl.fromJson; - - @override - String get t; - @override - String get s; - @override - String? get m; - @override - @JsonKey(ignore: true) - _$$CacaoSignatureImplCopyWith<_$CacaoSignatureImpl> get copyWith => - throw _privateConstructorUsedError; -} - -Cacao _$CacaoFromJson(Map json) { - return _Cacao.fromJson(json); -} - -/// @nodoc -mixin _$Cacao { - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CacaoCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CacaoCopyWith<$Res> { - factory $CacaoCopyWith(Cacao value, $Res Function(Cacao) then) = - _$CacaoCopyWithImpl<$Res, Cacao>; - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$CacaoCopyWithImpl<$Res, $Val extends Cacao> - implements $CacaoCopyWith<$Res> { - _$CacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$CacaoImplCopyWith<$Res> implements $CacaoCopyWith<$Res> { - factory _$$CacaoImplCopyWith( - _$CacaoImpl value, $Res Function(_$CacaoImpl) then) = - __$$CacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({CacaoHeader h, CacaoPayload p, CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$CacaoImplCopyWithImpl<$Res> - extends _$CacaoCopyWithImpl<$Res, _$CacaoImpl> - implements _$$CacaoImplCopyWith<$Res> { - __$$CacaoImplCopyWithImpl( - _$CacaoImpl _value, $Res Function(_$CacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$CacaoImpl( - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$CacaoImpl implements _Cacao { - const _$CacaoImpl({required this.h, required this.p, required this.s}); - - factory _$CacaoImpl.fromJson(Map json) => - _$$CacaoImplFromJson(json); - - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'Cacao(h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$CacaoImpl && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - __$$CacaoImplCopyWithImpl<_$CacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$CacaoImplToJson( - this, - ); - } -} - -abstract class _Cacao implements Cacao { - const factory _Cacao( - {required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$CacaoImpl; - - factory _Cacao.fromJson(Map json) = _$CacaoImpl.fromJson; - - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$CacaoImplCopyWith<_$CacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} - -StoredCacao _$StoredCacaoFromJson(Map json) { - return _StoredCacao.fromJson(json); -} - -/// @nodoc -mixin _$StoredCacao { - int get id => throw _privateConstructorUsedError; - String get pairingTopic => throw _privateConstructorUsedError; - CacaoHeader get h => throw _privateConstructorUsedError; - CacaoPayload get p => throw _privateConstructorUsedError; - CacaoSignature get s => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $StoredCacaoCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $StoredCacaoCopyWith<$Res> { - factory $StoredCacaoCopyWith( - StoredCacao value, $Res Function(StoredCacao) then) = - _$StoredCacaoCopyWithImpl<$Res, StoredCacao>; - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - $CacaoHeaderCopyWith<$Res> get h; - $CacaoPayloadCopyWith<$Res> get p; - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class _$StoredCacaoCopyWithImpl<$Res, $Val extends StoredCacao> - implements $StoredCacaoCopyWith<$Res> { - _$StoredCacaoCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_value.copyWith( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $CacaoHeaderCopyWith<$Res> get h { - return $CacaoHeaderCopyWith<$Res>(_value.h, (value) { - return _then(_value.copyWith(h: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoPayloadCopyWith<$Res> get p { - return $CacaoPayloadCopyWith<$Res>(_value.p, (value) { - return _then(_value.copyWith(p: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoSignatureCopyWith<$Res> get s { - return $CacaoSignatureCopyWith<$Res>(_value.s, (value) { - return _then(_value.copyWith(s: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$StoredCacaoImplCopyWith<$Res> - implements $StoredCacaoCopyWith<$Res> { - factory _$$StoredCacaoImplCopyWith( - _$StoredCacaoImpl value, $Res Function(_$StoredCacaoImpl) then) = - __$$StoredCacaoImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {int id, - String pairingTopic, - CacaoHeader h, - CacaoPayload p, - CacaoSignature s}); - - @override - $CacaoHeaderCopyWith<$Res> get h; - @override - $CacaoPayloadCopyWith<$Res> get p; - @override - $CacaoSignatureCopyWith<$Res> get s; -} - -/// @nodoc -class __$$StoredCacaoImplCopyWithImpl<$Res> - extends _$StoredCacaoCopyWithImpl<$Res, _$StoredCacaoImpl> - implements _$$StoredCacaoImplCopyWith<$Res> { - __$$StoredCacaoImplCopyWithImpl( - _$StoredCacaoImpl _value, $Res Function(_$StoredCacaoImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? h = null, - Object? p = null, - Object? s = null, - }) { - return _then(_$StoredCacaoImpl( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - h: null == h - ? _value.h - : h // ignore: cast_nullable_to_non_nullable - as CacaoHeader, - p: null == p - ? _value.p - : p // ignore: cast_nullable_to_non_nullable - as CacaoPayload, - s: null == s - ? _value.s - : s // ignore: cast_nullable_to_non_nullable - as CacaoSignature, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$StoredCacaoImpl implements _StoredCacao { - const _$StoredCacaoImpl( - {required this.id, - required this.pairingTopic, - required this.h, - required this.p, - required this.s}); - - factory _$StoredCacaoImpl.fromJson(Map json) => - _$$StoredCacaoImplFromJson(json); - - @override - final int id; - @override - final String pairingTopic; - @override - final CacaoHeader h; - @override - final CacaoPayload p; - @override - final CacaoSignature s; - - @override - String toString() { - return 'StoredCacao(id: $id, pairingTopic: $pairingTopic, h: $h, p: $p, s: $s)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$StoredCacaoImpl && - (identical(other.id, id) || other.id == id) && - (identical(other.pairingTopic, pairingTopic) || - other.pairingTopic == pairingTopic) && - (identical(other.h, h) || other.h == h) && - (identical(other.p, p) || other.p == p) && - (identical(other.s, s) || other.s == s)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, id, pairingTopic, h, p, s); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - __$$StoredCacaoImplCopyWithImpl<_$StoredCacaoImpl>(this, _$identity); - - @override - Map toJson() { - return _$$StoredCacaoImplToJson( - this, - ); - } -} - -abstract class _StoredCacao implements StoredCacao { - const factory _StoredCacao( - {required final int id, - required final String pairingTopic, - required final CacaoHeader h, - required final CacaoPayload p, - required final CacaoSignature s}) = _$StoredCacaoImpl; - - factory _StoredCacao.fromJson(Map json) = - _$StoredCacaoImpl.fromJson; - - @override - int get id; - @override - String get pairingTopic; - @override - CacaoHeader get h; - @override - CacaoPayload get p; - @override - CacaoSignature get s; - @override - @JsonKey(ignore: true) - _$$StoredCacaoImplCopyWith<_$StoredCacaoImpl> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/apis/sign_api/models/auth/cacao_models.g.dart b/lib/apis/sign_api/models/auth/cacao_models.g.dart deleted file mode 100644 index 0dc187d8..00000000 --- a/lib/apis/sign_api/models/auth/cacao_models.g.dart +++ /dev/null @@ -1,154 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'cacao_models.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$CacaoRequestPayloadImpl _$$CacaoRequestPayloadImplFromJson( - Map json) => - _$CacaoRequestPayloadImpl( - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoRequestPayloadImplToJson( - _$CacaoRequestPayloadImpl instance) { - final val = { - 'domain': instance.domain, - 'aud': instance.aud, - 'version': instance.version, - 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoPayloadImpl _$$CacaoPayloadImplFromJson(Map json) => - _$CacaoPayloadImpl( - iss: json['iss'] as String, - domain: json['domain'] as String, - aud: json['aud'] as String, - version: json['version'] as String, - nonce: json['nonce'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$CacaoPayloadImplToJson(_$CacaoPayloadImpl instance) { - final val = { - 'iss': instance.iss, - 'domain': instance.domain, - 'aud': instance.aud, - 'version': instance.version, - 'nonce': instance.nonce, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$CacaoHeaderImpl _$$CacaoHeaderImplFromJson(Map json) => - _$CacaoHeaderImpl( - t: json['t'] as String? ?? 'eip4361', - ); - -Map _$$CacaoHeaderImplToJson(_$CacaoHeaderImpl instance) => - { - 't': instance.t, - }; - -_$CacaoSignatureImpl _$$CacaoSignatureImplFromJson(Map json) => - _$CacaoSignatureImpl( - t: json['t'] as String, - s: json['s'] as String, - m: json['m'] as String?, - ); - -Map _$$CacaoSignatureImplToJson( - _$CacaoSignatureImpl instance) { - final val = { - 't': instance.t, - 's': instance.s, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('m', instance.m); - return val; -} - -_$CacaoImpl _$$CacaoImplFromJson(Map json) => _$CacaoImpl( - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$CacaoImplToJson(_$CacaoImpl instance) => - { - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; - -_$StoredCacaoImpl _$$StoredCacaoImplFromJson(Map json) => - _$StoredCacaoImpl( - id: json['id'] as int, - pairingTopic: json['pairingTopic'] as String, - h: CacaoHeader.fromJson(json['h'] as Map), - p: CacaoPayload.fromJson(json['p'] as Map), - s: CacaoSignature.fromJson(json['s'] as Map), - ); - -Map _$$StoredCacaoImplToJson(_$StoredCacaoImpl instance) => - { - 'id': instance.id, - 'pairingTopic': instance.pairingTopic, - 'h': instance.h.toJson(), - 'p': instance.p.toJson(), - 's': instance.s.toJson(), - }; diff --git a/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart b/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart deleted file mode 100644 index 6fab4f7c..00000000 --- a/lib/apis/sign_api/models/auth/ocauth_models.freezed.dart +++ /dev/null @@ -1,704 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'ocauth_models.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -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'); - -SessionAuthPayloadParams _$SessionAuthPayloadParamsFromJson( - Map json) { - return _SessionAuthPayloadParams.fromJson(json); -} - -/// @nodoc -mixin _$SessionAuthPayloadParams { - List get chains => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get type => throw _privateConstructorUsedError; // - String get version => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; // - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $SessionAuthPayloadParamsCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $SessionAuthPayloadParamsCopyWith<$Res> { - factory $SessionAuthPayloadParamsCopyWith(SessionAuthPayloadParams value, - $Res Function(SessionAuthPayloadParams) then) = - _$SessionAuthPayloadParamsCopyWithImpl<$Res, SessionAuthPayloadParams>; - @useResult - $Res call( - {List chains, - String domain, - String nonce, - String aud, - String type, - String version, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$SessionAuthPayloadParamsCopyWithImpl<$Res, - $Val extends SessionAuthPayloadParams> - implements $SessionAuthPayloadParamsCopyWith<$Res> { - _$SessionAuthPayloadParamsCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? chains = null, - Object? domain = null, - Object? nonce = null, - Object? aud = null, - Object? type = null, - Object? version = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - chains: null == chains - ? _value.chains - : chains // ignore: cast_nullable_to_non_nullable - as List, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$SessionAuthPayloadParamsImplCopyWith<$Res> - implements $SessionAuthPayloadParamsCopyWith<$Res> { - factory _$$SessionAuthPayloadParamsImplCopyWith( - _$SessionAuthPayloadParamsImpl value, - $Res Function(_$SessionAuthPayloadParamsImpl) then) = - __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {List chains, - String domain, - String nonce, - String aud, - String type, - String version, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$SessionAuthPayloadParamsImplCopyWithImpl<$Res> - extends _$SessionAuthPayloadParamsCopyWithImpl<$Res, - _$SessionAuthPayloadParamsImpl> - implements _$$SessionAuthPayloadParamsImplCopyWith<$Res> { - __$$SessionAuthPayloadParamsImplCopyWithImpl( - _$SessionAuthPayloadParamsImpl _value, - $Res Function(_$SessionAuthPayloadParamsImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? chains = null, - Object? domain = null, - Object? nonce = null, - Object? aud = null, - Object? type = null, - Object? version = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$SessionAuthPayloadParamsImpl( - chains: null == chains - ? _value._chains - : chains // ignore: cast_nullable_to_non_nullable - as List, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$SessionAuthPayloadParamsImpl implements _SessionAuthPayloadParams { - const _$SessionAuthPayloadParamsImpl( - {required final List chains, - required this.domain, - required this.nonce, - required this.aud, - required this.type, - required this.version, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _chains = chains, - _resources = resources; - - factory _$SessionAuthPayloadParamsImpl.fromJson(Map json) => - _$$SessionAuthPayloadParamsImplFromJson(json); - - final List _chains; - @override - List get chains { - if (_chains is EqualUnmodifiableListView) return _chains; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_chains); - } - - @override - final String domain; - @override - final String nonce; - @override - final String aud; - @override - final String type; -// - @override - final String version; - @override - final String iat; -// - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'SessionAuthPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$SessionAuthPayloadParamsImpl && - const DeepCollectionEquality().equals(other._chains, _chains) && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.type, type) || other.type == type) && - (identical(other.version, version) || other.version == version) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(_chains), - domain, - nonce, - aud, - type, - version, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> - get copyWith => __$$SessionAuthPayloadParamsImplCopyWithImpl< - _$SessionAuthPayloadParamsImpl>(this, _$identity); - - @override - Map toJson() { - return _$$SessionAuthPayloadParamsImplToJson( - this, - ); - } -} - -abstract class _SessionAuthPayloadParams implements SessionAuthPayloadParams { - const factory _SessionAuthPayloadParams( - {required final List chains, - required final String domain, - required final String nonce, - required final String aud, - required final String type, - required final String version, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$SessionAuthPayloadParamsImpl; - - factory _SessionAuthPayloadParams.fromJson(Map json) = - _$SessionAuthPayloadParamsImpl.fromJson; - - @override - List get chains; - @override - String get domain; - @override - String get nonce; - @override - String get aud; - @override - String get type; - @override // - String get version; - @override - String get iat; - @override // - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$SessionAuthPayloadParamsImplCopyWith<_$SessionAuthPayloadParamsImpl> - get copyWith => throw _privateConstructorUsedError; -} - -PendingSessionAuthRequest _$PendingSessionAuthRequestFromJson( - Map json) { - return _PendingSessionAuthRequest.fromJson(json); -} - -/// @nodoc -mixin _$PendingSessionAuthRequest { - int get id => throw _privateConstructorUsedError; - String get pairingTopic => throw _privateConstructorUsedError; - ConnectionMetadata get requester => throw _privateConstructorUsedError; - int get expiryTimestamp => throw _privateConstructorUsedError; - CacaoRequestPayload get authPayload => throw _privateConstructorUsedError; - VerifyContext get verifyContext => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $PendingSessionAuthRequestCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $PendingSessionAuthRequestCopyWith<$Res> { - factory $PendingSessionAuthRequestCopyWith(PendingSessionAuthRequest value, - $Res Function(PendingSessionAuthRequest) then) = - _$PendingSessionAuthRequestCopyWithImpl<$Res, PendingSessionAuthRequest>; - @useResult - $Res call( - {int id, - String pairingTopic, - ConnectionMetadata requester, - int expiryTimestamp, - CacaoRequestPayload authPayload, - VerifyContext verifyContext}); - - $ConnectionMetadataCopyWith<$Res> get requester; - $CacaoRequestPayloadCopyWith<$Res> get authPayload; - $VerifyContextCopyWith<$Res> get verifyContext; -} - -/// @nodoc -class _$PendingSessionAuthRequestCopyWithImpl<$Res, - $Val extends PendingSessionAuthRequest> - implements $PendingSessionAuthRequestCopyWith<$Res> { - _$PendingSessionAuthRequestCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? requester = null, - Object? expiryTimestamp = null, - Object? authPayload = null, - Object? verifyContext = null, - }) { - return _then(_value.copyWith( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - expiryTimestamp: null == expiryTimestamp - ? _value.expiryTimestamp - : expiryTimestamp // ignore: cast_nullable_to_non_nullable - as int, - authPayload: null == authPayload - ? _value.authPayload - : authPayload // ignore: cast_nullable_to_non_nullable - as CacaoRequestPayload, - verifyContext: null == verifyContext - ? _value.verifyContext - : verifyContext // ignore: cast_nullable_to_non_nullable - as VerifyContext, - ) as $Val); - } - - @override - @pragma('vm:prefer-inline') - $ConnectionMetadataCopyWith<$Res> get requester { - return $ConnectionMetadataCopyWith<$Res>(_value.requester, (value) { - return _then(_value.copyWith(requester: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $CacaoRequestPayloadCopyWith<$Res> get authPayload { - return $CacaoRequestPayloadCopyWith<$Res>(_value.authPayload, (value) { - return _then(_value.copyWith(authPayload: value) as $Val); - }); - } - - @override - @pragma('vm:prefer-inline') - $VerifyContextCopyWith<$Res> get verifyContext { - return $VerifyContextCopyWith<$Res>(_value.verifyContext, (value) { - return _then(_value.copyWith(verifyContext: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$PendingSessionAuthRequestImplCopyWith<$Res> - implements $PendingSessionAuthRequestCopyWith<$Res> { - factory _$$PendingSessionAuthRequestImplCopyWith( - _$PendingSessionAuthRequestImpl value, - $Res Function(_$PendingSessionAuthRequestImpl) then) = - __$$PendingSessionAuthRequestImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {int id, - String pairingTopic, - ConnectionMetadata requester, - int expiryTimestamp, - CacaoRequestPayload authPayload, - VerifyContext verifyContext}); - - @override - $ConnectionMetadataCopyWith<$Res> get requester; - @override - $CacaoRequestPayloadCopyWith<$Res> get authPayload; - @override - $VerifyContextCopyWith<$Res> get verifyContext; -} - -/// @nodoc -class __$$PendingSessionAuthRequestImplCopyWithImpl<$Res> - extends _$PendingSessionAuthRequestCopyWithImpl<$Res, - _$PendingSessionAuthRequestImpl> - implements _$$PendingSessionAuthRequestImplCopyWith<$Res> { - __$$PendingSessionAuthRequestImplCopyWithImpl( - _$PendingSessionAuthRequestImpl _value, - $Res Function(_$PendingSessionAuthRequestImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? pairingTopic = null, - Object? requester = null, - Object? expiryTimestamp = null, - Object? authPayload = null, - Object? verifyContext = null, - }) { - return _then(_$PendingSessionAuthRequestImpl( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - pairingTopic: null == pairingTopic - ? _value.pairingTopic - : pairingTopic // ignore: cast_nullable_to_non_nullable - as String, - requester: null == requester - ? _value.requester - : requester // ignore: cast_nullable_to_non_nullable - as ConnectionMetadata, - expiryTimestamp: null == expiryTimestamp - ? _value.expiryTimestamp - : expiryTimestamp // ignore: cast_nullable_to_non_nullable - as int, - authPayload: null == authPayload - ? _value.authPayload - : authPayload // ignore: cast_nullable_to_non_nullable - as CacaoRequestPayload, - verifyContext: null == verifyContext - ? _value.verifyContext - : verifyContext // ignore: cast_nullable_to_non_nullable - as VerifyContext, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$PendingSessionAuthRequestImpl implements _PendingSessionAuthRequest { - const _$PendingSessionAuthRequestImpl( - {required this.id, - required this.pairingTopic, - required this.requester, - required this.expiryTimestamp, - required this.authPayload, - required this.verifyContext}); - - factory _$PendingSessionAuthRequestImpl.fromJson(Map json) => - _$$PendingSessionAuthRequestImplFromJson(json); - - @override - final int id; - @override - final String pairingTopic; - @override - final ConnectionMetadata requester; - @override - final int expiryTimestamp; - @override - final CacaoRequestPayload authPayload; - @override - final VerifyContext verifyContext; - - @override - String toString() { - return 'PendingSessionAuthRequest(id: $id, pairingTopic: $pairingTopic, requester: $requester, expiryTimestamp: $expiryTimestamp, authPayload: $authPayload, verifyContext: $verifyContext)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$PendingSessionAuthRequestImpl && - (identical(other.id, id) || other.id == id) && - (identical(other.pairingTopic, pairingTopic) || - other.pairingTopic == pairingTopic) && - (identical(other.requester, requester) || - other.requester == requester) && - (identical(other.expiryTimestamp, expiryTimestamp) || - other.expiryTimestamp == expiryTimestamp) && - (identical(other.authPayload, authPayload) || - other.authPayload == authPayload) && - (identical(other.verifyContext, verifyContext) || - other.verifyContext == verifyContext)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash(runtimeType, id, pairingTopic, requester, - expiryTimestamp, authPayload, verifyContext); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> - get copyWith => __$$PendingSessionAuthRequestImplCopyWithImpl< - _$PendingSessionAuthRequestImpl>(this, _$identity); - - @override - Map toJson() { - return _$$PendingSessionAuthRequestImplToJson( - this, - ); - } -} - -abstract class _PendingSessionAuthRequest implements PendingSessionAuthRequest { - const factory _PendingSessionAuthRequest( - {required final int id, - required final String pairingTopic, - required final ConnectionMetadata requester, - required final int expiryTimestamp, - required final CacaoRequestPayload authPayload, - required final VerifyContext verifyContext}) = - _$PendingSessionAuthRequestImpl; - - factory _PendingSessionAuthRequest.fromJson(Map json) = - _$PendingSessionAuthRequestImpl.fromJson; - - @override - int get id; - @override - String get pairingTopic; - @override - ConnectionMetadata get requester; - @override - int get expiryTimestamp; - @override - CacaoRequestPayload get authPayload; - @override - VerifyContext get verifyContext; - @override - @JsonKey(ignore: true) - _$$PendingSessionAuthRequestImplCopyWith<_$PendingSessionAuthRequestImpl> - get copyWith => throw _privateConstructorUsedError; -} diff --git a/lib/apis/sign_api/models/auth/ocauth_models.g.dart b/lib/apis/sign_api/models/auth/ocauth_models.g.dart deleted file mode 100644 index 98b5dae2..00000000 --- a/lib/apis/sign_api/models/auth/ocauth_models.g.dart +++ /dev/null @@ -1,78 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'ocauth_models.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$SessionAuthPayloadParamsImpl _$$SessionAuthPayloadParamsImplFromJson( - Map json) => - _$SessionAuthPayloadParamsImpl( - chains: - (json['chains'] as List).map((e) => e as String).toList(), - domain: json['domain'] as String, - nonce: json['nonce'] as String, - aud: json['aud'] as String, - type: json['type'] as String, - version: json['version'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$SessionAuthPayloadParamsImplToJson( - _$SessionAuthPayloadParamsImpl instance) { - final val = { - 'chains': instance.chains, - 'domain': instance.domain, - 'nonce': instance.nonce, - 'aud': instance.aud, - 'type': instance.type, - 'version': instance.version, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} - -_$PendingSessionAuthRequestImpl _$$PendingSessionAuthRequestImplFromJson( - Map json) => - _$PendingSessionAuthRequestImpl( - id: json['id'] as int, - pairingTopic: json['pairingTopic'] as String, - requester: ConnectionMetadata.fromJson( - json['requester'] as Map), - expiryTimestamp: json['expiryTimestamp'] as int, - authPayload: CacaoRequestPayload.fromJson( - json['authPayload'] as Map), - verifyContext: - VerifyContext.fromJson(json['verifyContext'] as Map), - ); - -Map _$$PendingSessionAuthRequestImplToJson( - _$PendingSessionAuthRequestImpl instance) => - { - 'id': instance.id, - 'pairingTopic': instance.pairingTopic, - 'requester': instance.requester.toJson(), - 'expiryTimestamp': instance.expiryTimestamp, - 'authPayload': instance.authPayload.toJson(), - 'verifyContext': instance.verifyContext.toJson(), - }; diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart deleted file mode 100644 index 93f62b1f..00000000 --- a/lib/apis/sign_api/models/auth/one_click_auth_models.freezed.dart +++ /dev/null @@ -1,410 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'one_click_auth_models.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -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'); - -OCAPayloadParams _$OCAPayloadParamsFromJson(Map json) { - return _OCAPayloadParams.fromJson(json); -} - -/// @nodoc -mixin _$OCAPayloadParams { - List get chains => throw _privateConstructorUsedError; - String get domain => throw _privateConstructorUsedError; - String get nonce => throw _privateConstructorUsedError; - String get aud => throw _privateConstructorUsedError; - String get type => throw _privateConstructorUsedError; // - String get version => throw _privateConstructorUsedError; - String get iat => throw _privateConstructorUsedError; // - String? get nbf => throw _privateConstructorUsedError; - String? get exp => throw _privateConstructorUsedError; - String? get statement => throw _privateConstructorUsedError; - String? get requestId => throw _privateConstructorUsedError; - List? get resources => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $OCAPayloadParamsCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $OCAPayloadParamsCopyWith<$Res> { - factory $OCAPayloadParamsCopyWith( - OCAPayloadParams value, $Res Function(OCAPayloadParams) then) = - _$OCAPayloadParamsCopyWithImpl<$Res, OCAPayloadParams>; - @useResult - $Res call( - {List chains, - String domain, - String nonce, - String aud, - String type, - String version, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class _$OCAPayloadParamsCopyWithImpl<$Res, $Val extends OCAPayloadParams> - implements $OCAPayloadParamsCopyWith<$Res> { - _$OCAPayloadParamsCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? chains = null, - Object? domain = null, - Object? nonce = null, - Object? aud = null, - Object? type = null, - Object? version = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_value.copyWith( - chains: null == chains - ? _value.chains - : chains // ignore: cast_nullable_to_non_nullable - as List, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value.resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$OCAPayloadParamsImplCopyWith<$Res> - implements $OCAPayloadParamsCopyWith<$Res> { - factory _$$OCAPayloadParamsImplCopyWith(_$OCAPayloadParamsImpl value, - $Res Function(_$OCAPayloadParamsImpl) then) = - __$$OCAPayloadParamsImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {List chains, - String domain, - String nonce, - String aud, - String type, - String version, - String iat, - String? nbf, - String? exp, - String? statement, - String? requestId, - List? resources}); -} - -/// @nodoc -class __$$OCAPayloadParamsImplCopyWithImpl<$Res> - extends _$OCAPayloadParamsCopyWithImpl<$Res, _$OCAPayloadParamsImpl> - implements _$$OCAPayloadParamsImplCopyWith<$Res> { - __$$OCAPayloadParamsImplCopyWithImpl(_$OCAPayloadParamsImpl _value, - $Res Function(_$OCAPayloadParamsImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? chains = null, - Object? domain = null, - Object? nonce = null, - Object? aud = null, - Object? type = null, - Object? version = null, - Object? iat = null, - Object? nbf = freezed, - Object? exp = freezed, - Object? statement = freezed, - Object? requestId = freezed, - Object? resources = freezed, - }) { - return _then(_$OCAPayloadParamsImpl( - chains: null == chains - ? _value._chains - : chains // ignore: cast_nullable_to_non_nullable - as List, - domain: null == domain - ? _value.domain - : domain // ignore: cast_nullable_to_non_nullable - as String, - nonce: null == nonce - ? _value.nonce - : nonce // ignore: cast_nullable_to_non_nullable - as String, - aud: null == aud - ? _value.aud - : aud // ignore: cast_nullable_to_non_nullable - as String, - type: null == type - ? _value.type - : type // ignore: cast_nullable_to_non_nullable - as String, - version: null == version - ? _value.version - : version // ignore: cast_nullable_to_non_nullable - as String, - iat: null == iat - ? _value.iat - : iat // ignore: cast_nullable_to_non_nullable - as String, - nbf: freezed == nbf - ? _value.nbf - : nbf // ignore: cast_nullable_to_non_nullable - as String?, - exp: freezed == exp - ? _value.exp - : exp // ignore: cast_nullable_to_non_nullable - as String?, - statement: freezed == statement - ? _value.statement - : statement // ignore: cast_nullable_to_non_nullable - as String?, - requestId: freezed == requestId - ? _value.requestId - : requestId // ignore: cast_nullable_to_non_nullable - as String?, - resources: freezed == resources - ? _value._resources - : resources // ignore: cast_nullable_to_non_nullable - as List?, - )); - } -} - -/// @nodoc - -@JsonSerializable(includeIfNull: false) -class _$OCAPayloadParamsImpl implements _OCAPayloadParams { - const _$OCAPayloadParamsImpl( - {required final List chains, - required this.domain, - required this.nonce, - required this.aud, - required this.type, - required this.version, - required this.iat, - this.nbf, - this.exp, - this.statement, - this.requestId, - final List? resources}) - : _chains = chains, - _resources = resources; - - factory _$OCAPayloadParamsImpl.fromJson(Map json) => - _$$OCAPayloadParamsImplFromJson(json); - - final List _chains; - @override - List get chains { - if (_chains is EqualUnmodifiableListView) return _chains; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_chains); - } - - @override - final String domain; - @override - final String nonce; - @override - final String aud; - @override - final String type; -// - @override - final String version; - @override - final String iat; -// - @override - final String? nbf; - @override - final String? exp; - @override - final String? statement; - @override - final String? requestId; - final List? _resources; - @override - List? get resources { - final value = _resources; - if (value == null) return null; - if (_resources is EqualUnmodifiableListView) return _resources; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); - } - - @override - String toString() { - return 'OCAPayloadParams(chains: $chains, domain: $domain, nonce: $nonce, aud: $aud, type: $type, version: $version, iat: $iat, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$OCAPayloadParamsImpl && - const DeepCollectionEquality().equals(other._chains, _chains) && - (identical(other.domain, domain) || other.domain == domain) && - (identical(other.nonce, nonce) || other.nonce == nonce) && - (identical(other.aud, aud) || other.aud == aud) && - (identical(other.type, type) || other.type == type) && - (identical(other.version, version) || other.version == version) && - (identical(other.iat, iat) || other.iat == iat) && - (identical(other.nbf, nbf) || other.nbf == nbf) && - (identical(other.exp, exp) || other.exp == exp) && - (identical(other.statement, statement) || - other.statement == statement) && - (identical(other.requestId, requestId) || - other.requestId == requestId) && - const DeepCollectionEquality() - .equals(other._resources, _resources)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(_chains), - domain, - nonce, - aud, - type, - version, - iat, - nbf, - exp, - statement, - requestId, - const DeepCollectionEquality().hash(_resources)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => - __$$OCAPayloadParamsImplCopyWithImpl<_$OCAPayloadParamsImpl>( - this, _$identity); - - @override - Map toJson() { - return _$$OCAPayloadParamsImplToJson( - this, - ); - } -} - -abstract class _OCAPayloadParams implements OCAPayloadParams { - const factory _OCAPayloadParams( - {required final List chains, - required final String domain, - required final String nonce, - required final String aud, - required final String type, - required final String version, - required final String iat, - final String? nbf, - final String? exp, - final String? statement, - final String? requestId, - final List? resources}) = _$OCAPayloadParamsImpl; - - factory _OCAPayloadParams.fromJson(Map json) = - _$OCAPayloadParamsImpl.fromJson; - - @override - List get chains; - @override - String get domain; - @override - String get nonce; - @override - String get aud; - @override - String get type; - @override // - String get version; - @override - String get iat; - @override // - String? get nbf; - @override - String? get exp; - @override - String? get statement; - @override - String? get requestId; - @override - List? get resources; - @override - @JsonKey(ignore: true) - _$$OCAPayloadParamsImplCopyWith<_$OCAPayloadParamsImpl> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart b/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart deleted file mode 100644 index b3b76a9e..00000000 --- a/lib/apis/sign_api/models/auth/one_click_auth_models.g.dart +++ /dev/null @@ -1,53 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'one_click_auth_models.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$OCAPayloadParamsImpl _$$OCAPayloadParamsImplFromJson( - Map json) => - _$OCAPayloadParamsImpl( - chains: - (json['chains'] as List).map((e) => e as String).toList(), - domain: json['domain'] as String, - nonce: json['nonce'] as String, - aud: json['aud'] as String, - type: json['type'] as String, - version: json['version'] as String, - iat: json['iat'] as String, - nbf: json['nbf'] as String?, - exp: json['exp'] as String?, - statement: json['statement'] as String?, - requestId: json['requestId'] as String?, - resources: (json['resources'] as List?) - ?.map((e) => e as String) - .toList(), - ); - -Map _$$OCAPayloadParamsImplToJson( - _$OCAPayloadParamsImpl instance) { - final val = { - 'chains': instance.chains, - 'domain': instance.domain, - 'nonce': instance.nonce, - 'aud': instance.aud, - 'type': instance.type, - 'version': instance.version, - 'iat': instance.iat, - }; - - void writeNotNull(String key, dynamic value) { - if (value != null) { - val[key] = value; - } - } - - writeNotNull('nbf', instance.nbf); - writeNotNull('exp', instance.exp); - writeNotNull('statement', instance.statement); - writeNotNull('requestId', instance.requestId); - writeNotNull('resources', instance.resources); - return val; -} diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index 2333782d..ef6c9e77 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -239,7 +239,7 @@ void runTests({ counterA++; completerA.complete(); - expect(args!.result, isNotNull); + expect(args!.result != null, true); }); clientB.onAuthRequest.subscribe((AuthRequest? args) async { counterB++; From f0d001318c1eb33f9694ad7144fdad0bc6913f9f Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 24 Jun 2024 17:15:52 +0200 Subject: [PATCH 22/29] minor changes --- lib/apis/sign_api/i_sign_client.dart | 52 +++++++++-------- lib/apis/sign_api/i_sign_engine_common.dart | 2 +- lib/apis/sign_api/i_sign_engine_wallet.dart | 9 +-- lib/apis/web3app/web3app.dart | 39 +++++++------ lib/apis/web3wallet/web3wallet.dart | 63 +++++++++++---------- 5 files changed, 87 insertions(+), 78 deletions(-) diff --git a/lib/apis/sign_api/i_sign_client.dart b/lib/apis/sign_api/i_sign_client.dart index 250d6e75..b8482cd9 100644 --- a/lib/apis/sign_api/i_sign_client.dart +++ b/lib/apis/sign_api/i_sign_client.dart @@ -21,7 +21,7 @@ abstract class ISignClient { abstract final ISessions sessions; abstract final IGenericStore pendingRequests; - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE PROPERTIES abstract final IGenericStore authKeys; abstract final IGenericStore pairingTopics; abstract final IGenericStore completeRequests; @@ -30,10 +30,10 @@ abstract class ISignClient { abstract final Event onSessionProposal; abstract final Event onSessionProposalError; abstract final Event onSessionRequest; - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHODS abstract final Event onAuthRequest; abstract final IGenericStore authRequests; - // NEW 1-CA METHOD + // NEW 1-CA METHODS abstract final Event onSessionAuthRequest; abstract final IGenericStore sessionAuthRequests; @@ -41,9 +41,9 @@ abstract class ISignClient { abstract final Event onSessionUpdate; abstract final Event onSessionExtend; abstract final Event onSessionEvent; - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHOD abstract final Event onAuthResponse; - // NEW 1-CA PROPERTY + // NEW 1-CA METHOD abstract final Event onSessionAuthResponse; Future init(); @@ -149,8 +149,8 @@ abstract class ISignClient { required String accountAddress, }); - // FORMER AUTH ENGINE PROPERTY COMMON - /// format payload to message string + // FORMER AUTH ENGINE COMMON METHODS + String formatAuthMessage({ required String iss, required CacaoRequestPayload cacaoPayload, @@ -160,7 +160,8 @@ abstract class ISignClient { required String pairingTopic, }); - // FORMER AUTH ENGINE PROPERTY FOR WALLET + // FORMER AUTH ENGINE WALLET METHODS + Future respondAuthRequest({ required int id, required String iss, @@ -168,31 +169,17 @@ abstract class ISignClient { WalletConnectError? error, }); - // FORMER AUTH ENGINE METHOD WALLET - // query all pending requests Map getPendingAuthRequests(); - // FORMER AUTH ENGINE METHOD FOR DAPP + // FORMER AUTH ENGINE DAPP METHODS + Future requestAuth({ required AuthRequestParams params, String? pairingTopic, List>? methods, }); - // NEW 1-CA METHOD FOR DAPP - Future authenticate({ - required SessionAuthRequestParams params, - String? pairingTopic, - List>? methods, - }); - - // NEW 1-CA METHOD FOR DAPP - Future validateSignedCacao({ - required Cacao cacao, - required String projectId, - }); - - Map getPendingSessionAuthRequests(); + // NEW 1-CA WALLET METHODS Future approveSessionAuthenticate({ required int id, @@ -203,4 +190,19 @@ abstract class ISignClient { required int id, required WalletConnectError reason, }); + + Map getPendingSessionAuthRequests(); + + // NEW 1-CA DAPP METHODS + + Future authenticate({ + required SessionAuthRequestParams params, + String? pairingTopic, + List>? methods, + }); + + Future validateSignedCacao({ + required Cacao cacao, + required String projectId, + }); } diff --git a/lib/apis/sign_api/i_sign_engine_common.dart b/lib/apis/sign_api/i_sign_engine_common.dart index 69432ac0..0acd8f0d 100644 --- a/lib/apis/sign_api/i_sign_engine_common.dart +++ b/lib/apis/sign_api/i_sign_engine_common.dart @@ -45,10 +45,10 @@ abstract class ISignEngineCommon { required String iss, required CacaoRequestPayload cacaoPayload, }); - // FORMER AUTH ENGINE METHOD Map getCompletedRequestsForPairing({ required String pairingTopic, }); + // NEW 1-CA METHOD Future validateSignedCacao({ required Cacao cacao, diff --git a/lib/apis/sign_api/i_sign_engine_wallet.dart b/lib/apis/sign_api/i_sign_engine_wallet.dart index 0830ef2b..c2f125d6 100644 --- a/lib/apis/sign_api/i_sign_engine_wallet.dart +++ b/lib/apis/sign_api/i_sign_engine_wallet.dart @@ -91,7 +91,8 @@ abstract class ISignEngineWallet extends ISignEngineCommon { // Map? optionalNamespaces, // }); - // FORMER AUTH ENGINE PROPERTY + // FORMER AUTH ENGINE METHODS + Future respondAuthRequest({ required int id, required String iss, @@ -99,11 +100,9 @@ abstract class ISignEngineWallet extends ISignEngineCommon { WalletConnectError? error, }); - // FORMER AUTH ENGINE PROPERTY - // query all pending requests Map getPendingAuthRequests(); - Map getPendingSessionAuthRequests(); + // NEW 1-CA METHODS Future approveSessionAuthenticate({ required int id, @@ -114,4 +113,6 @@ abstract class ISignEngineWallet extends ISignEngineCommon { required int id, required WalletConnectError reason, }); + + Map getPendingSessionAuthRequests(); } diff --git a/lib/apis/web3app/web3app.dart b/lib/apis/web3app/web3app.dart index cadcfe3e..28be6cb8 100644 --- a/lib/apis/web3app/web3app.dart +++ b/lib/apis/web3app/web3app.dart @@ -345,12 +345,10 @@ class Web3App implements IWeb3App { @override IPairingStore get pairings => core.pairing.getStore(); - ///---------- AUTH ENGINE ----------/// + ///---------- (DEPRECATED) AUTH ENGINE ----------/// + @override Event get onAuthResponse => authEngine.onAuthResponse; - @override - Event get onSessionAuthResponse => - signEngine.onSessionAuthResponse; @override IGenericStore get authKeys => authEngine.authKeys; @@ -384,7 +382,25 @@ class Web3App implements IWeb3App { } } - // NEW ONE-CLICK AUTH METHOD FOR DAPPS + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return authEngine.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + ///---------- ONE-CLICK AUTH SIGN ENGINE ----------/// + + @override + Event get onSessionAuthResponse => + signEngine.onSessionAuthResponse; + @override Future authenticate({ required SessionAuthRequestParams params, @@ -404,19 +420,6 @@ class Web3App implements IWeb3App { } } - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return authEngine.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - @override Future validateSignedCacao({ required Cacao cacao, diff --git a/lib/apis/web3wallet/web3wallet.dart b/lib/apis/web3wallet/web3wallet.dart index a53946c5..75c95cce 100644 --- a/lib/apis/web3wallet/web3wallet.dart +++ b/lib/apis/web3wallet/web3wallet.dart @@ -397,7 +397,8 @@ class Web3Wallet implements IWeb3Wallet { @override IPairingStore get pairings => core.pairing.getStore(); - ///---------- AUTH ENGINE ----------/// + ///---------- (DEPRECATED) AUTH ENGINE ----------/// + @override Event get onAuthRequest => authEngine.onAuthRequest; @@ -411,13 +412,6 @@ class Web3Wallet implements IWeb3Wallet { IGenericStore get completeRequests => authEngine.completeRequests; - @override - IGenericStore get sessionAuthRequests => - signEngine.sessionAuthRequests; - @override - Event get onSessionAuthRequest => - signEngine.onSessionAuthRequest; - @Deprecated( 'AuthEngine/AuthClient is deprecated and will be removed soon.\n' 'Please use authentication methods from SignEngine/SignClient instead', @@ -444,6 +438,37 @@ class Web3Wallet implements IWeb3Wallet { } } + @override + Map getPendingAuthRequests() { + try { + return authEngine.getPendingAuthRequests(); + } catch (e) { + rethrow; + } + } + + @override + Map getCompletedRequestsForPairing({ + required String pairingTopic, + }) { + try { + return authEngine.getCompletedRequestsForPairing( + pairingTopic: pairingTopic, + ); + } catch (e) { + rethrow; + } + } + + ///---------- ONE-CLICK AUTH SIGN ENGINE ----------/// + + @override + IGenericStore get sessionAuthRequests => + signEngine.sessionAuthRequests; + @override + Event get onSessionAuthRequest => + signEngine.onSessionAuthRequest; + @override Future approveSessionAuthenticate({ required int id, @@ -474,15 +499,6 @@ class Web3Wallet implements IWeb3Wallet { } } - @override - Map getPendingAuthRequests() { - try { - return authEngine.getPendingAuthRequests(); - } catch (e) { - rethrow; - } - } - @override Map getPendingSessionAuthRequests() { try { @@ -492,19 +508,6 @@ class Web3Wallet implements IWeb3Wallet { } } - @override - Map getCompletedRequestsForPairing({ - required String pairingTopic, - }) { - try { - return authEngine.getCompletedRequestsForPairing( - pairingTopic: pairingTopic, - ); - } catch (e) { - rethrow; - } - } - @override String formatAuthMessage({ required String iss, From 08d89979f1fd9a29e824d066a315d844273e3b29 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Mon, 24 Jun 2024 18:14:52 +0200 Subject: [PATCH 23/29] minor changes and fixed tests --- lib/apis/sign_api/sign_engine.dart | 1 + test/auth_api/auth_client_test.dart | 31 +++++++++++++++++++------ test/web3wallet/web3wallet_helpers.dart | 2 +- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/lib/apis/sign_api/sign_engine.dart b/lib/apis/sign_api/sign_engine.dart index cdcd2f4a..5266da74 100644 --- a/lib/apis/sign_api/sign_engine.dart +++ b/lib/apis/sign_api/sign_engine.dart @@ -1849,6 +1849,7 @@ class SignEngine implements ISignEngine { } // NEW 1-CA METHOD (Should this be private?) + @override Future validateSignedCacao({ required Cacao cacao, diff --git a/test/auth_api/auth_client_test.dart b/test/auth_api/auth_client_test.dart index ef6c9e77..9a795561 100644 --- a/test/auth_api/auth_client_test.dart +++ b/test/auth_api/auth_client_test.dart @@ -239,7 +239,7 @@ void runTests({ counterA++; completerA.complete(); - expect(args!.result != null, true); + expect(args!.result, isNotNull); }); clientB.onAuthRequest.subscribe((AuthRequest? args) async { counterB++; @@ -249,12 +249,29 @@ void runTests({ expect(args != null, true); // Create the message to be signed - String message = clientB.formatAuthMessage( - iss: TEST_ISSUER_EIP191, - cacaoPayload: CacaoRequestPayload.fromPayloadParams( - args!.payloadParams, - ), - ); + late String message; + if (clientB is Web3Wallet) { + message = (clientB as Web3Wallet).authEngine.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromPayloadParams( + args!.payloadParams, + ), + ); + } else if (clientB is Web3Wallet) { + message = (clientB as Web3App).authEngine.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromPayloadParams( + args!.payloadParams, + ), + ); + } else { + message = clientB.formatAuthMessage( + iss: TEST_ISSUER_EIP191, + cacaoPayload: CacaoRequestPayload.fromPayloadParams( + args!.payloadParams, + ), + ); + } String sig = EthSigUtil.signPersonalMessage( message: Uint8List.fromList(message.codeUnits), diff --git a/test/web3wallet/web3wallet_helpers.dart b/test/web3wallet/web3wallet_helpers.dart index 4977545e..0d1aee82 100644 --- a/test/web3wallet/web3wallet_helpers.dart +++ b/test/web3wallet/web3wallet_helpers.dart @@ -77,7 +77,7 @@ class Web3WalletHelpers { expect(b.getPendingAuthRequests().length, 1); // Create the message to be signed - String message = b.formatAuthMessage( + String message = b.authEngine.formatAuthMessage( iss: TEST_ISSUER_EIP191, cacaoPayload: CacaoRequestPayload.fromPayloadParams( args!.payloadParams, From b36e4e598bda4e052c3a8bd8fa67618a6ed3d834 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 25 Jun 2024 10:23:25 +0200 Subject: [PATCH 24/29] minor change --- example/wallet/lib/dependencies/web3wallet_service.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 2da25a65..34768d59 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -252,7 +252,7 @@ class Web3WalletService extends IWeb3WalletService { } Future _onSessionAuthRequest(SessionAuthRequest? args) async { - log('[SampleWallet] _onSessionAuthRequest ${args?.authPayload}'); + log('[SampleWallet] _onSessionAuthRequest ${jsonEncode(args?.authPayload.toJson())}'); if (args != null) { final SessionAuthPayload payloadParams = args.authPayload; final supportedChains = ChainData.eip155Chains.map((e) => e.chainId); From 1addc091502711d4dbe27f1514b9f5d3177430ce Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 25 Jun 2024 11:45:31 +0200 Subject: [PATCH 25/29] bug fix on recap population --- CHANGELOG.md | 4 +- README.md | 4 -- .../lib/dependencies/chains/common.dart | 27 ++++---- .../lib/dependencies/chains/evm_service.dart | 27 ++++---- .../lib/dependencies/web3wallet_service.dart | 69 ++++++++++--------- .../wc_connection_request_widget.dart | 2 +- .../sign_api/utils/auth/auth_signature.dart | 3 +- .../sign_api/utils/auth/recaps_utils.dart | 2 +- lib/src/version.dart | 2 +- pubspec.yaml | 2 +- 10 files changed, 72 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0edc3513..f6fa9244 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ -## 2.3.0-alpha01 +## 2.3.0-beta01 -- One-Click Auth support (dApp side) +- One-Click Auth support ## 2.2.3 diff --git a/README.md b/README.md index 665e5535..9f406f08 100644 --- a/README.md +++ b/README.md @@ -8,10 +8,6 @@ WalletConnect Dart v2 library for Flutter, heavily inspired by the WalletConnect ### dApp Flow ```dart -// To create both an Auth and Sign API, you can use the Web3App -// If you just need one of the other, replace Web3App with SignClient or AuthClient -// SignClient wcClient = await SignClient.createInstance( -// AuthClient wcClient = await AuthClient.createInstance( Web3App wcClient = await Web3App.createInstance( relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default projectId: '123', diff --git a/example/wallet/lib/dependencies/chains/common.dart b/example/wallet/lib/dependencies/chains/common.dart index 368512e4..1b5be74c 100644 --- a/example/wallet/lib/dependencies/chains/common.dart +++ b/example/wallet/lib/dependencies/chains/common.dart @@ -30,21 +30,22 @@ class CommonMethods { static Future requestApproval(String text, {String? title}) async { final bottomSheetService = GetIt.I(); - final WCBottomSheetResult rs = await bottomSheetService.queueBottomSheet( - widget: WCRequestWidget( - child: WCConnectionWidget( - title: 'Approve Request', - info: [ - WCConnectionModel( - title: title, - elements: [ - text, + final WCBottomSheetResult rs = (await bottomSheetService.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionWidget( + title: 'Approve Request', + info: [ + WCConnectionModel( + title: title, + elements: [ + text, + ], + ), ], ), - ], - ), - ), - ); + ), + )) ?? + WCBottomSheetResult.reject; return rs != WCBottomSheetResult.reject; } diff --git a/example/wallet/lib/dependencies/chains/evm_service.dart b/example/wallet/lib/dependencies/chains/evm_service.dart index 33a4df61..38ecad84 100644 --- a/example/wallet/lib/dependencies/chains/evm_service.dart +++ b/example/wallet/lib/dependencies/chains/evm_service.dart @@ -480,20 +480,21 @@ class EVMService { final gweiGasPrice = (transaction.gasPrice?.getInWei ?? BigInt.zero) / BigInt.from(1000000000); - final WCBottomSheetResult rs = await _bottomSheetService.queueBottomSheet( - widget: WCRequestWidget( - child: WCConnectionWidget( - title: 'Approve Transaction', - info: [ - WCConnectionModel(elements: [jsonEncode(tJson)]), - WCConnectionModel( - title: 'Gas price', - elements: ['${gweiGasPrice.toStringAsFixed(2)} GWEI'], + final WCBottomSheetResult rs = (await _bottomSheetService.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionWidget( + title: 'Approve Transaction', + info: [ + WCConnectionModel(elements: [jsonEncode(tJson)]), + WCConnectionModel( + title: 'Gas price', + elements: ['${gweiGasPrice.toStringAsFixed(2)} GWEI'], + ), + ], ), - ], - ), - ), - ); + ), + )) ?? + WCBottomSheetResult.reject; if (rs != WCBottomSheetResult.reject) { return transaction; diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index 34768d59..ea1728b5 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -156,15 +156,17 @@ 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, - ), - ), - ); + final WCBottomSheetResult rs = + (await _bottomSheetHandler.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionRequestWidget( + proposalData: args.params, + verifyContext: args.verifyContext, + metadata: args.params.proposer, + ), + ), + )) ?? + WCBottomSheetResult.reject; if (rs != WCBottomSheetResult.reject) { // generatedNamespaces is constructed based on registered methods handlers @@ -254,38 +256,39 @@ class Web3WalletService extends IWeb3WalletService { Future _onSessionAuthRequest(SessionAuthRequest? args) async { log('[SampleWallet] _onSessionAuthRequest ${jsonEncode(args?.authPayload.toJson())}'); if (args != null) { - final SessionAuthPayload payloadParams = args.authPayload; + final SessionAuthPayload authPayload = args.authPayload; final supportedChains = ChainData.eip155Chains.map((e) => e.chainId); final supportedMethods = SupportedEVMMethods.values.map((e) => e.name); - final newPayloadParams = AuthSignature.populateAuthPayload( - authPayload: payloadParams, + final newAuthPayload = AuthSignature.populateAuthPayload( + authPayload: authPayload, chains: supportedChains.toList(), methods: supportedMethods.toList(), ); final cacaoRequestPayload = CacaoRequestPayload.fromSessionAuthPayload( - newPayloadParams, + newAuthPayload, ); final List> formattedMessages = []; - for (var chain in newPayloadParams.chains) { + for (var chain in newAuthPayload.chains) { final chainKeys = GetIt.I().getKeysForChain(chain); final iss = 'did:pkh:$chain:${chainKeys.first.address}'; final message = _web3Wallet!.formatAuthMessage( iss: iss, cacaoPayload: cacaoRequestPayload, - // TODO cacaoPayload should be SessionAuthPayloadParams ); formattedMessages.add({iss: message}); } - final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( - widget: WCSessionAuthRequestWidget( - child: WCConnectionRequestWidget( - sessionAuthPayload: newPayloadParams, - verifyContext: args.verifyContext, - metadata: args.requester, - ), - ), - ); + final WCBottomSheetResult rs = + (await _bottomSheetHandler.queueBottomSheet( + widget: WCSessionAuthRequestWidget( + child: WCConnectionRequestWidget( + sessionAuthPayload: newAuthPayload, + verifyContext: args.verifyContext, + metadata: args.requester, + ), + ), + )) ?? + WCBottomSheetResult.reject; if (rs != WCBottomSheetResult.reject) { const chain = 'eip155:1'; @@ -342,14 +345,16 @@ class Web3WalletService extends IWeb3WalletService { log('[SampleWallet] _onAuthRequest $args'); if (args != null) { // - final WCBottomSheetResult rs = await _bottomSheetHandler.queueBottomSheet( - widget: WCRequestWidget( - child: WCConnectionRequestWidget( - authPayloadParams: args.payloadParams, - metadata: args.requester, - ), - ), - ); + final WCBottomSheetResult rs = + (await _bottomSheetHandler.queueBottomSheet( + widget: WCRequestWidget( + child: WCConnectionRequestWidget( + authPayloadParams: args.payloadParams, + metadata: args.requester, + ), + ), + )) ?? + WCBottomSheetResult.reject; const chain = 'eip155:1'; final chainKeys = GetIt.I().getKeysForChain(chain); diff --git a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart index 89f78f5f..3155bb42 100644 --- a/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart +++ b/example/wallet/lib/widgets/wc_connection_request/wc_connection_request_widget.dart @@ -116,7 +116,7 @@ class WCConnectionRequestWidget extends StatelessWidget { } // return WCConnectionWidget( - title: 'Messages', + title: '${messagesModels.length} Messages', info: messagesModels, ); } diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index 32e31c94..76be3fe8 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -273,8 +273,7 @@ class AuthSignature { ReCapsUtils.getRecapFromResources(resources: updatedResources), ), chains: approvedChains, - resources: authPayload.resources ?? - (updatedResources.isNotEmpty ? updatedResources : null), + resources: updatedResources.isNotEmpty ? updatedResources : null, ); } } diff --git a/lib/apis/sign_api/utils/auth/recaps_utils.dart b/lib/apis/sign_api/utils/auth/recaps_utils.dart index f217872f..0c8a20fa 100644 --- a/lib/apis/sign_api/utils/auth/recaps_utils.dart +++ b/lib/apis/sign_api/utils/auth/recaps_utils.dart @@ -150,7 +150,7 @@ class ReCapsUtils { final jsonRecap = jsonEncode(recap); final bytes = utf8.encode(jsonRecap).toList(); // remove the padding from the base64 string as per recap spec - return 'urn:recap:${base64.encode(bytes).replaceAll('/=/g', '')}'; + return 'urn:recap:${base64.encode(bytes).replaceAll('=', '')}'; } static Map createRecap( diff --git a/lib/src/version.dart b/lib/src/version.dart index a8bfab2f..65b3d782 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-alpha01'; +const packageVersion = '2.3.0-beta01'; diff --git a/pubspec.yaml b/pubspec.yaml index 7288fd7c..8a5b26a7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: walletconnect_flutter_v2 description: This repository contains oficial implementation of WalletConnect v2 protocols for Flutter applications. The communications protocol for web3. -version: 2.3.0-alpha01 +version: 2.3.0-beta01 repository: https://github.com/WalletConnect/WalletConnectFlutterV2 environment: From 849bb14df43e43abd2aa2f752bcc1bf0410741a4 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 25 Jun 2024 12:43:55 +0200 Subject: [PATCH 26/29] update readme --- README.md | 173 +++++++++++++----- .../lib/dependencies/web3wallet_service.dart | 8 +- 2 files changed, 135 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 9f406f08..28d53bf5 100644 --- a/README.md +++ b/README.md @@ -8,38 +8,47 @@ WalletConnect Dart v2 library for Flutter, heavily inspired by the WalletConnect ### dApp Flow ```dart +// To create both an Auth and Sign API, you can use the Web3App +// If you just need one of the other, replace Web3App with SignClient or AuthClient +// SignClient wcClient = await SignClient.createInstance( +// AuthClient wcClient = await AuthClient.createInstance( +// BE MINDFUL THAT AuthClient is currently deprecated and will be removed soon. Authentication methods, including One-Click Auth, are now withing SignClient Web3App wcClient = await Web3App.createInstance( - relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default projectId: '123', + relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default metadata: PairingMetadata( - name: 'dApp (Requester)', + name: 'Your dApp Name (Requester)', description: 'A dapp that can request that transactions be signed', url: 'https://walletconnect.com', icons: ['https://avatars.githubusercontent.com/u/37784886'], + redirect: Redirect( // Specially important object if you the Wallet to navigate back to your dapp + native: 'mydapp://', + universal: 'https://mydapp.com/app', + ), ), ); // For a dApp, you would connect with specific parameters, then display // the returned URI. ConnectResponse resp = await wcClient.connect( - requiredNamespaces: { - 'eip155': RequiredNamespace( - chains: ['eip155:1'], // Ethereum chain - methods: ['personal_sign'], // Requestable Methods, see MethodsConstants for reference - events: ['chainChanged'], // Requestable Events, see EventsConstants for reference - ), - }, optionalNamespaces: { 'eip155': RequiredNamespace( - chains: ['eip155:1', 'eip155:5'], // Any other optional Ethereum chain - methods: ['eth_signTransaction'], // Optional requestable Methods, see MethodsConstants for reference - events: ['accountsChanged'], // Optional requestable events, see EventsConstants for reference + // Any Ethereum chain you want to connect with + chains: ['eip155:1', 'eip155:5'], + // Requestable Methods, see MethodsConstants class for reference + methods: ['personal_sign', 'eth_sendTransaction'], + // Optional requestable events, see EventsConstants for reference + events: ['accountsChanged'], ), }, ); +// display connection uri withih a QR code or use it to launch a wallet Uri? uri = resp.uri; +// Example: +// final encodedUri = Uri.encodeComponent(uri.toString()); +// launchUrlString('metamask://wc?uri=$encodedUri', mode: LaunchMode.externalApplication); -// Once you've display the URI, you can wait for the future, and hide the QR code once you've received session data +// Once you've displayed the URI, you can wait for the future, and hide the QR code once you've received session data final SessionData session = await resp.session.future; // Now that you have a session, you can request signatures @@ -55,6 +64,7 @@ final dynamic signResponse = await wcClient.request( // Structure is dependant upon the JSON RPC call you made. +// [DEPRECATED] // You can also request authentication final AuthRequestResponse authReq = await wcClient.requestAuth( params: AuthRequestParams( @@ -67,7 +77,7 @@ final AuthRequestResponse authReq = await wcClient.requestAuth( ); // Await the auth response using the provided completer -final AuthResponse authResponse = await authResponse.completer.future; +final AuthResponse authResponse = await authReq.completer.future; if (authResponse.result != null) { // Having a result means you have the signature and it is verified. @@ -81,6 +91,39 @@ else { final JsonRpcError? error = authResponse.jsonRpcError; } +// Instead of connect() and then requestAuth() you can leverage One-Click Auth +// Which is connection (session proposal) and authentication (SIWE) in just 1 step +final SessionAuthRequestResponse authReq = await wcClient.authenticate( + params: SessionAuthRequestParams( + chains: ['eip155:1', 'eip155:5'], + domain: 'yourdomain.com', + uri: 'https://yourdomain.com/login', + nonce: AuthUtils.generateNonce(), + statement: 'Welcome to my example dApp.', + methods: ['personal_sign', 'eth_sendTransaction'], + ), +); +// display authentication uri withih a QR code or use it to launch a wallet +Uri? uri = authReq.uri; +// Example: +// final encodedUri = Uri.encodeComponent(uri.toString()); +// launchUrlString('metamask://wc?uri=$encodedUri', mode: LaunchMode.externalApplication); +// IMPORTANT: Not every wallet supports One-Click Auth yet but don't worry, if wallet does not support it, +// it will fallback to regular session proposal automatically + +// Once you've displayed the URI, you can wait for the future, and hide the QR code once you've received session data +final SessionAuthResponse authResponse = await authReq.completer.future; +if (authResponse.session != null) { + // Having a result means you have succesfully authenticated and created a session +} +else { + // Otherwise, you might have gotten a WalletConnectError if there was un issue verifying the signature. + final WalletConnectError? error = authResponse.error; + // Of a JsonRpcError if something went wrong when signing with the wallet. + final JsonRpcError? error = authResponse.jsonRpcError; +} + + // You can also respond to events from the wallet, like session events wcClient.registerEventHandler( @@ -95,13 +138,17 @@ wcClient.onSessionEvent.subscribe((SessionEvent? session) { ### Wallet Flow ```dart Web3Wallet wcClient = await Web3Wallet.createInstance( - relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default projectId: '123', + relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default metadata: PairingMetadata( - name: 'Wallet (Responder)', + name: 'Your Wallet Name (Responder)', description: 'A wallet that can be requested to sign transactions', url: 'https://walletconnect.com', icons: ['https://avatars.githubusercontent.com/u/37784886'], + redirect: Redirect( // Specially important object if you want dApps to be able to open you wallet + native: 'mywallet://', + universal: 'https://mywallet.com/app', + ), ), ); @@ -118,6 +165,72 @@ wcClient.onSessionProposal.subscribe((SessionProposal? args) async { final isInvalidApp = args.verifyContext?.validation.invalid; final isValidApp = args.verifyContext?.validation.valid; final unknown = args.verifyContext?.validation.unknown; + // + // Present the UI to the user, and allow them to reject or approve the proposal + await wcClient.approveSession( + id: args.id, + namespaces: args.params.generatedNamespaces!, + sessionProperties: args.params.sessionProperties, + ); + // Or to reject... + // Error codes and reasons can be found here: https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes + await wcClient.rejectSession( + id: id, + reason: Errors.getSdkError(Errors.USER_REJECTED), + ); + } +}); + +// If you are planning to support One-Click Auth then you would have to subscribe to onSessionAuthRequest events +wcClient.onSessionAuthRequest.subscribe((SessionAuthRequest? args) async { + // Handle UI updates using the args.params + // Keep track of the args.id for the approval response + if (args != null) { + id = args!.id; + // To check VerifyAPI validation in regards of the dApp is trying to connnect you can check verifyContext + // More info about VerifyAPI https://docs.walletconnect.com/web3wallet/verify + final isScamApp = args.verifyContext?.validation.scam; + final isInvalidApp = args.verifyContext?.validation.invalid; + final isValidApp = args.verifyContext?.validation.valid; + final unknown = args.verifyContext?.validation.unknown; + // + // Process Authentication request + final SessionAuthPayload requestPayload = args.authPayload; + final responsePayload = AuthSignature.populateAuthPayload( + authPayload: requestPayload, + chains: ['eip155:1', 'eip155:5'], // Your supported EVM chains + methods: ['personal_sign', 'etg_sendTransaction'], // Your supported methods + ); + // For every chain you support you decide to sign a the message + final message = _web3Wallet!.formatAuthMessage( + iss: 'did:pkh:eip155:1:0xADDRESS.....', + cacaoPayload: CacaoRequestPayload.fromSessionAuthPayload( + responsePayload, + ), + ); + // final hexSignature = * signMessage(message) * + // And creates a Cacao object with it + final cacao = AuthSignature.buildAuthObject( + requestPayload: CacaoRequestPayload.fromSessionAuthPayload( + responsePayload, + ), + signature: CacaoSignature( + t: CacaoSignature.EIP191, + s: hexSignature, + ), + iss: 'did:pkh:eip155:1:0xADDRESS.....', + ); + // + // To respond with the signed messages and create a session for the dapp you use approveSessionAuthenticate + await _web3Wallet!.approveSessionAuthenticate( + id: args.id, + auths: [cacao], // You would have here as many cacaos as messages your wallet signed + ); + // To reject to session authenticate request you use rejectSessionAuthenticate + await _web3Wallet!.rejectSessionAuthenticate( + id: args.id, + reason: Errors.getSdkError(Errors.USER_REJECTED_AUTH), + ); } }); @@ -169,6 +282,7 @@ final signRequestHandler = (String topic, dynamic parameters) async { throw Errors.getSdkError(Errors.USER_REJECTED_SIGN); } } + wcClient.registerRequestHandler( chainId: 'eip155:1', method: 'eth_sendTransaction', @@ -192,6 +306,7 @@ wcClient.onSessionProposalError.subscribe((SessionProposalError? args) { // Handle the error }); +/* [DEPRECATED] */ // Setup the auth handling clientB.onAuthRequest.subscribe((AuthRequest? args) async { @@ -208,31 +323,6 @@ clientB.onAuthRequest.subscribe((AuthRequest? args) async { ); }); -// Then, scan the QR code and parse the URI, and pair with the dApp -// On the first pairing, you will immediately receive onSessionProposal and onAuthRequest events. -Uri uri = Uri.parse(scannedUriString); -final PairingInfo pairing = await wcClient.pair(uri: uri); - -// Present the UI to the user, and allow them to reject or approve the proposal -final walletNamespaces = { - 'eip155': Namespace( - accounts: ['eip155:1:abc'], - methods: ['eth_signTransaction'], - events: ['accountsChanged'], - ), -} -await wcClient.approveSession( - id: id, - namespaces: walletNamespaces // This will have the accounts requested in params - // If you registered correctly events emitters, methods handlers and accounts for your supported chains you can just us `args.params.generatedNamespaces!` value from SessionProposalEvent -); -// Or to reject... -// Error codes and reasons can be found here: https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes -await wcClient.rejectSession( - id: id, - reason: Errors.getSdkError(Errors.USER_REJECTED), -); - // For auth, you can do the same thing: Present the UI to them, and have them approve the signature. // Then respond with that signature. In this example I use EthSigUtil, but you can use any library that can perform // a personal eth sign. @@ -252,6 +342,7 @@ await wcClient.respondAuthRequest( iss: 'did:pkh:eip155:1:ETH_ADDRESS', error: Errors.getSdkError(Errors.USER_REJECTED_AUTH), ); +// // You can also emit events for the dApp await wcClient.emitSessionEvent( diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index ea1728b5..aef76f93 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -27,11 +27,9 @@ class Web3WalletService extends IWeb3WalletService { @override Future create() async { // Create the web3wallet - _web3Wallet = Web3Wallet( - core: Core( - projectId: DartDefines.projectId, - logLevel: LogLevel.error, - ), + _web3Wallet = await Web3Wallet.createInstance( + projectId: DartDefines.projectId, + logLevel: LogLevel.error, metadata: const PairingMetadata( name: 'Sample Wallet Flutter', description: 'WalletConnect\'s sample wallet with Flutter', From f784712fc6258f278b7d415e2c482654daf90bfc Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 25 Jun 2024 12:45:18 +0200 Subject: [PATCH 27/29] update readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 28d53bf5..a332a9a6 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ WalletConnect Dart v2 library for Flutter, heavily inspired by the WalletConnect // If you just need one of the other, replace Web3App with SignClient or AuthClient // SignClient wcClient = await SignClient.createInstance( // AuthClient wcClient = await AuthClient.createInstance( -// BE MINDFUL THAT AuthClient is currently deprecated and will be removed soon. Authentication methods, including One-Click Auth, are now withing SignClient +// BE MINDFUL THAT AuthClient is currently deprecated and will be removed soon. +// Authentication methods, including One-Click Auth, are now withing SignClient Web3App wcClient = await Web3App.createInstance( projectId: '123', relayUrl: 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default From 453ae094b1eededdf56049c3f6f735d466fda400 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Tue, 25 Jun 2024 16:17:40 +0200 Subject: [PATCH 28/29] minor change --- example/wallet/lib/dependencies/web3wallet_service.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/wallet/lib/dependencies/web3wallet_service.dart b/example/wallet/lib/dependencies/web3wallet_service.dart index aef76f93..210ee07e 100644 --- a/example/wallet/lib/dependencies/web3wallet_service.dart +++ b/example/wallet/lib/dependencies/web3wallet_service.dart @@ -251,7 +251,7 @@ class Web3WalletService extends IWeb3WalletService { debugPrint('[SampleWallet] _onPairingCreate $args'); } - Future _onSessionAuthRequest(SessionAuthRequest? args) async { + void _onSessionAuthRequest(SessionAuthRequest? args) async { log('[SampleWallet] _onSessionAuthRequest ${jsonEncode(args?.authPayload.toJson())}'); if (args != null) { final SessionAuthPayload authPayload = args.authPayload; From 6ab65ec06426e4805dee1f5b357b9523b9b674d6 Mon Sep 17 00:00:00 2001 From: Alfreedom <00tango.bromine@icloud.com> Date: Fri, 28 Jun 2024 11:46:12 +0200 Subject: [PATCH 29/29] minor changes --- .../models/auth/auth_client_models.dart | 11 +- .../models/auth/session_auth_models.dart | 75 ++- .../auth/session_auth_models.freezed.dart | 426 ++++++++++++++++++ .../models/auth/session_auth_models.g.dart | 51 +++ .../sign_api/utils/auth/auth_signature.dart | 24 + test/auth_api/signature_test.dart | 35 ++ test/auth_api/utils/signature_constants.dart | 12 + 7 files changed, 588 insertions(+), 46 deletions(-) diff --git a/lib/apis/sign_api/models/auth/auth_client_models.dart b/lib/apis/sign_api/models/auth/auth_client_models.dart index dcff6757..272cf1b3 100644 --- a/lib/apis/sign_api/models/auth/auth_client_models.dart +++ b/lib/apis/sign_api/models/auth/auth_client_models.dart @@ -95,6 +95,7 @@ class AuthPayloadParams with _$AuthPayloadParams { }) = _AuthPayloadParams; factory AuthPayloadParams.fromRequestParams(AuthRequestParams params) { + final now = DateTime.now(); return AuthPayloadParams( type: params.type ?? CacaoHeader.EIP4361, chainId: params.chainId, @@ -102,7 +103,15 @@ class AuthPayloadParams with _$AuthPayloadParams { aud: params.aud, version: '1', nonce: params.nonce, - iat: DateTime.now().toIso8601String(), + iat: DateTime.utc( + now.year, + now.month, + now.day, + now.hour, + now.minute, + now.second, + now.millisecond, + ).toIso8601String(), nbf: params.nbf, exp: params.exp, statement: params.statement, diff --git a/lib/apis/sign_api/models/auth/session_auth_models.dart b/lib/apis/sign_api/models/auth/session_auth_models.dart index bbf95c45..4bd920c0 100644 --- a/lib/apis/sign_api/models/auth/session_auth_models.dart +++ b/lib/apis/sign_api/models/auth/session_auth_models.dart @@ -25,50 +25,27 @@ class SessionAuthRequestResponse { }); } -class SessionAuthRequestParams { - final List chains; - final String domain; - final String nonce; - final String uri; - // - final CacaoHeader? type; - final String? nbf; - final String? exp; - final String? statement; - final String? requestId; - final List? resources; - final int? expiry; - final List? methods; +@freezed +class SessionAuthRequestParams with _$SessionAuthRequestParams { + @JsonSerializable(includeIfNull: false) + const factory SessionAuthRequestParams({ + required List chains, + required String domain, + required String nonce, + required String uri, + // + CacaoHeader? type, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + int? expiry, + @Default([]) List? methods, + }) = _SessionAuthRequestParams; // - - SessionAuthRequestParams({ - required this.chains, - required this.domain, - required this.nonce, - required this.uri, - this.type, - this.nbf, - this.exp, - this.statement, - this.requestId, - this.resources, - this.expiry, - this.methods = const [], - }); - - Map toJson() => { - 'chains': chains, - 'domain': domain, - 'nonce': nonce, - 'uri': uri, - if (type != null) 'type': type, - if (nbf != null) 'nbf': nbf, - if (exp != null) 'exp': exp, - if (statement != null) 'statement': statement, - if (requestId != null) 'requestId': requestId, - if (resources != null) 'resources': resources, - if (expiry != null) 'expiry': expiry, - }; + factory SessionAuthRequestParams.fromJson(Map json) => + _$SessionAuthRequestParamsFromJson(json); } @freezed @@ -94,6 +71,7 @@ class SessionAuthPayload with _$SessionAuthPayload { factory SessionAuthPayload.fromRequestParams( SessionAuthRequestParams params, ) { + final now = DateTime.now(); return SessionAuthPayload( chains: params.chains, domain: params.domain, @@ -101,8 +79,15 @@ class SessionAuthPayload with _$SessionAuthPayload { aud: params.uri, type: params.type?.t ?? 'eip4361', version: '1', - iat: DateTime.now().toIso8601String(), - // + iat: DateTime.utc( + now.year, + now.month, + now.day, + now.hour, + now.minute, + now.second, + now.millisecond, + ).toIso8601String(), nbf: params.nbf, exp: params.exp, statement: params.statement, 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 70510d49..c8ab6514 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 @@ -14,6 +14,432 @@ 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'); +SessionAuthRequestParams _$SessionAuthRequestParamsFromJson( + Map json) { + return _SessionAuthRequestParams.fromJson(json); +} + +/// @nodoc +mixin _$SessionAuthRequestParams { + List get chains => throw _privateConstructorUsedError; + String get domain => throw _privateConstructorUsedError; + String get nonce => throw _privateConstructorUsedError; + String get uri => throw _privateConstructorUsedError; // + CacaoHeader? get type => throw _privateConstructorUsedError; + String? get nbf => throw _privateConstructorUsedError; + String? get exp => throw _privateConstructorUsedError; + String? get statement => throw _privateConstructorUsedError; + String? get requestId => throw _privateConstructorUsedError; + List? get resources => throw _privateConstructorUsedError; + int? get expiry => throw _privateConstructorUsedError; + List? get methods => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $SessionAuthRequestParamsCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SessionAuthRequestParamsCopyWith<$Res> { + factory $SessionAuthRequestParamsCopyWith(SessionAuthRequestParams value, + $Res Function(SessionAuthRequestParams) then) = + _$SessionAuthRequestParamsCopyWithImpl<$Res, SessionAuthRequestParams>; + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String uri, + CacaoHeader? type, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + int? expiry, + List? methods}); + + $CacaoHeaderCopyWith<$Res>? get type; +} + +/// @nodoc +class _$SessionAuthRequestParamsCopyWithImpl<$Res, + $Val extends SessionAuthRequestParams> + implements $SessionAuthRequestParamsCopyWith<$Res> { + _$SessionAuthRequestParamsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? uri = null, + Object? type = freezed, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + Object? expiry = freezed, + Object? methods = freezed, + }) { + return _then(_value.copyWith( + chains: null == chains + ? _value.chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + uri: null == uri + ? _value.uri + : uri // ignore: cast_nullable_to_non_nullable + as String, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as CacaoHeader?, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value.resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + expiry: freezed == expiry + ? _value.expiry + : expiry // ignore: cast_nullable_to_non_nullable + as int?, + methods: freezed == methods + ? _value.methods + : methods // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $CacaoHeaderCopyWith<$Res>? get type { + if (_value.type == null) { + return null; + } + + return $CacaoHeaderCopyWith<$Res>(_value.type!, (value) { + return _then(_value.copyWith(type: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$SessionAuthRequestParamsImplCopyWith<$Res> + implements $SessionAuthRequestParamsCopyWith<$Res> { + factory _$$SessionAuthRequestParamsImplCopyWith( + _$SessionAuthRequestParamsImpl value, + $Res Function(_$SessionAuthRequestParamsImpl) then) = + __$$SessionAuthRequestParamsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {List chains, + String domain, + String nonce, + String uri, + CacaoHeader? type, + String? nbf, + String? exp, + String? statement, + String? requestId, + List? resources, + int? expiry, + List? methods}); + + @override + $CacaoHeaderCopyWith<$Res>? get type; +} + +/// @nodoc +class __$$SessionAuthRequestParamsImplCopyWithImpl<$Res> + extends _$SessionAuthRequestParamsCopyWithImpl<$Res, + _$SessionAuthRequestParamsImpl> + implements _$$SessionAuthRequestParamsImplCopyWith<$Res> { + __$$SessionAuthRequestParamsImplCopyWithImpl( + _$SessionAuthRequestParamsImpl _value, + $Res Function(_$SessionAuthRequestParamsImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? chains = null, + Object? domain = null, + Object? nonce = null, + Object? uri = null, + Object? type = freezed, + Object? nbf = freezed, + Object? exp = freezed, + Object? statement = freezed, + Object? requestId = freezed, + Object? resources = freezed, + Object? expiry = freezed, + Object? methods = freezed, + }) { + return _then(_$SessionAuthRequestParamsImpl( + chains: null == chains + ? _value._chains + : chains // ignore: cast_nullable_to_non_nullable + as List, + domain: null == domain + ? _value.domain + : domain // ignore: cast_nullable_to_non_nullable + as String, + nonce: null == nonce + ? _value.nonce + : nonce // ignore: cast_nullable_to_non_nullable + as String, + uri: null == uri + ? _value.uri + : uri // ignore: cast_nullable_to_non_nullable + as String, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as CacaoHeader?, + nbf: freezed == nbf + ? _value.nbf + : nbf // ignore: cast_nullable_to_non_nullable + as String?, + exp: freezed == exp + ? _value.exp + : exp // ignore: cast_nullable_to_non_nullable + as String?, + statement: freezed == statement + ? _value.statement + : statement // ignore: cast_nullable_to_non_nullable + as String?, + requestId: freezed == requestId + ? _value.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + resources: freezed == resources + ? _value._resources + : resources // ignore: cast_nullable_to_non_nullable + as List?, + expiry: freezed == expiry + ? _value.expiry + : expiry // ignore: cast_nullable_to_non_nullable + as int?, + methods: freezed == methods + ? _value._methods + : methods // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc + +@JsonSerializable(includeIfNull: false) +class _$SessionAuthRequestParamsImpl implements _SessionAuthRequestParams { + const _$SessionAuthRequestParamsImpl( + {required final List chains, + required this.domain, + required this.nonce, + required this.uri, + this.type, + this.nbf, + this.exp, + this.statement, + this.requestId, + final List? resources, + this.expiry, + final List? methods = const []}) + : _chains = chains, + _resources = resources, + _methods = methods; + + factory _$SessionAuthRequestParamsImpl.fromJson(Map json) => + _$$SessionAuthRequestParamsImplFromJson(json); + + final List _chains; + @override + List get chains { + if (_chains is EqualUnmodifiableListView) return _chains; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_chains); + } + + @override + final String domain; + @override + final String nonce; + @override + final String uri; +// + @override + final CacaoHeader? type; + @override + final String? nbf; + @override + final String? exp; + @override + final String? statement; + @override + final String? requestId; + final List? _resources; + @override + List? get resources { + final value = _resources; + if (value == null) return null; + if (_resources is EqualUnmodifiableListView) return _resources; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + final int? expiry; + final List? _methods; + @override + @JsonKey() + List? get methods { + final value = _methods; + if (value == null) return null; + if (_methods is EqualUnmodifiableListView) return _methods; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'SessionAuthRequestParams(chains: $chains, domain: $domain, nonce: $nonce, uri: $uri, type: $type, nbf: $nbf, exp: $exp, statement: $statement, requestId: $requestId, resources: $resources, expiry: $expiry, methods: $methods)'; + } + + @override + bool operator ==(dynamic other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SessionAuthRequestParamsImpl && + const DeepCollectionEquality().equals(other._chains, _chains) && + (identical(other.domain, domain) || other.domain == domain) && + (identical(other.nonce, nonce) || other.nonce == nonce) && + (identical(other.uri, uri) || other.uri == uri) && + (identical(other.type, type) || other.type == type) && + (identical(other.nbf, nbf) || other.nbf == nbf) && + (identical(other.exp, exp) || other.exp == exp) && + (identical(other.statement, statement) || + other.statement == statement) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + const DeepCollectionEquality() + .equals(other._resources, _resources) && + (identical(other.expiry, expiry) || other.expiry == expiry) && + const DeepCollectionEquality().equals(other._methods, _methods)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_chains), + domain, + nonce, + uri, + type, + nbf, + exp, + statement, + requestId, + const DeepCollectionEquality().hash(_resources), + expiry, + const DeepCollectionEquality().hash(_methods)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$SessionAuthRequestParamsImplCopyWith<_$SessionAuthRequestParamsImpl> + get copyWith => __$$SessionAuthRequestParamsImplCopyWithImpl< + _$SessionAuthRequestParamsImpl>(this, _$identity); + + @override + Map toJson() { + return _$$SessionAuthRequestParamsImplToJson( + this, + ); + } +} + +abstract class _SessionAuthRequestParams implements SessionAuthRequestParams { + const factory _SessionAuthRequestParams( + {required final List chains, + required final String domain, + required final String nonce, + required final String uri, + final CacaoHeader? type, + final String? nbf, + final String? exp, + final String? statement, + final String? requestId, + final List? resources, + final int? expiry, + final List? methods}) = _$SessionAuthRequestParamsImpl; + + factory _SessionAuthRequestParams.fromJson(Map json) = + _$SessionAuthRequestParamsImpl.fromJson; + + @override + List get chains; + @override + String get domain; + @override + String get nonce; + @override + String get uri; + @override // + CacaoHeader? get type; + @override + String? get nbf; + @override + String? get exp; + @override + String? get statement; + @override + String? get requestId; + @override + List? get resources; + @override + int? get expiry; + @override + List? get methods; + @override + @JsonKey(ignore: true) + _$$SessionAuthRequestParamsImplCopyWith<_$SessionAuthRequestParamsImpl> + get copyWith => throw _privateConstructorUsedError; +} + SessionAuthPayload _$SessionAuthPayloadFromJson(Map json) { return _SessionAuthPayload.fromJson(json); } 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 d0b00eca..b0193a8b 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 @@ -6,6 +6,57 @@ part of 'session_auth_models.dart'; // JsonSerializableGenerator // ************************************************************************** +_$SessionAuthRequestParamsImpl _$$SessionAuthRequestParamsImplFromJson( + Map json) => + _$SessionAuthRequestParamsImpl( + chains: + (json['chains'] as List).map((e) => e as String).toList(), + domain: json['domain'] as String, + nonce: json['nonce'] as String, + uri: json['uri'] as String, + type: json['type'] == null + ? null + : CacaoHeader.fromJson(json['type'] as Map), + nbf: json['nbf'] as String?, + exp: json['exp'] as String?, + statement: json['statement'] as String?, + requestId: json['requestId'] as String?, + resources: (json['resources'] as List?) + ?.map((e) => e as String) + .toList(), + expiry: json['expiry'] as int?, + methods: (json['methods'] as List?) + ?.map((e) => e as String) + .toList() ?? + const [], + ); + +Map _$$SessionAuthRequestParamsImplToJson( + _$SessionAuthRequestParamsImpl instance) { + final val = { + 'chains': instance.chains, + 'domain': instance.domain, + 'nonce': instance.nonce, + 'uri': instance.uri, + }; + + void writeNotNull(String key, dynamic value) { + if (value != null) { + val[key] = value; + } + } + + writeNotNull('type', instance.type?.toJson()); + writeNotNull('nbf', instance.nbf); + writeNotNull('exp', instance.exp); + writeNotNull('statement', instance.statement); + writeNotNull('requestId', instance.requestId); + writeNotNull('resources', instance.resources); + writeNotNull('expiry', instance.expiry); + writeNotNull('methods', instance.methods); + return val; +} + _$SessionAuthPayloadImpl _$$SessionAuthPayloadImplFromJson( Map json) => _$SessionAuthPayloadImpl( diff --git a/lib/apis/sign_api/utils/auth/auth_signature.dart b/lib/apis/sign_api/utils/auth/auth_signature.dart index 76be3fe8..bdd7ea50 100644 --- a/lib/apis/sign_api/utils/auth/auth_signature.dart +++ b/lib/apis/sign_api/utils/auth/auth_signature.dart @@ -276,4 +276,28 @@ class AuthSignature { resources: updatedResources.isNotEmpty ? updatedResources : null, ); } + + static String getAddressFromMessage(String message) { + try { + final regexp = RegExp('0x[a-fA-F0-9]{40}'); + final matches = regexp.allMatches(message); + for (final Match m in matches) { + return m[0]!; + } + return ''; + } catch (_) {} + return ''; + } + + static String getChainIdFromMessage(String message) { + try { + final pattern = 'Chain ID: '; + final regexp = RegExp('$pattern(?\\d+)'); + final matches = regexp.allMatches(message); + for (final Match m in matches) { + return m[0]!.toString().replaceAll(pattern, ''); + } + } catch (_) {} + return ''; + } } diff --git a/test/auth_api/signature_test.dart b/test/auth_api/signature_test.dart index 884a504d..112c9abd 100644 --- a/test/auth_api/signature_test.dart +++ b/test/auth_api/signature_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import '../shared/shared_test_values.dart'; +import 'utils/engine_constants.dart'; import 'utils/signature_constants.dart'; void main() { @@ -71,6 +72,40 @@ void main() { expect(bool2, false); }); + test('getAddressFromMessage', () { + final address = AuthSignature.getAddressFromMessage( + TEST_MESSAGE_EIP1271, + ); + expect(address, TEST_ADDRESS_EIP1271); + + final address2 = AuthSignature.getAddressFromMessage( + TEST_FORMATTED_MESSAGE, + ); + expect(address2, '0x06C6A22feB5f8CcEDA0db0D593e6F26A3611d5fa'); + + final address3 = AuthSignature.getAddressFromMessage( + TEST_MESSAGE_EIP1271_2, + ); + expect(address3, '0x59e2f66C0E96803206B6486cDb39029abAE834c0'); + }); + + test('getChainIdFromMessage', () { + final chainId = AuthSignature.getChainIdFromMessage( + TEST_MESSAGE_EIP1271, + ); + expect(chainId, '1'); + + final chainId2 = AuthSignature.getChainIdFromMessage( + TEST_FORMATTED_MESSAGE, + ); + expect(chainId2, '1'); + + final chainId3 = AuthSignature.getChainIdFromMessage( + TEST_MESSAGE_EIP1271_2, + ); + expect(chainId3, '465321'); + }); + // TODO: Fix this test, can't call http requests from within the test // test('isValidEip1271Signature', () async { // final cacaoSig = CacaoSignature( diff --git a/test/auth_api/utils/signature_constants.dart b/test/auth_api/utils/signature_constants.dart index 699a1170..b15be0ad 100644 --- a/test/auth_api/utils/signature_constants.dart +++ b/test/auth_api/utils/signature_constants.dart @@ -15,6 +15,18 @@ Nonce: 1665443015700 Issued At: 2022-10-10T23:03:35.700Z Expiration Time: 2022-10-11T23:03:35.700Z'''; +const TEST_MESSAGE_EIP1271_2 = + '''walletconnect.com wants you to sign in with your Ethereum account: +0x59e2f66C0E96803206B6486cDb39029abAE834c0 + +Welcome to AppKit for Flutter. + +URI: https://walletconnect.com/login +Version: 1 +Chain ID: 465321 +Nonce: 1719392409504 +Issued At: 2024-06-26T11:00:41.043Z'''; + const TEST_SIG_EIP191 = '0x560a65deed4aaf332d9dbab82af897245c93139773b483072d5e59afdc5788d76e1dcbefaef36b11a52755bfd152241b4ea03d2cc08638818c5105cba9beb83d1c'; const TEST_PRIVATE_KEY_EIP191 =