From 84586197ca41d35a1ef58dd0c76f0a55fe3ee3bd Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Wed, 28 Jun 2023 19:17:11 +0545 Subject: [PATCH 01/13] walletconnect v2 pairing --- lib/app/shared/constants/parameters.dart | 7 + lib/app/shared/enum/type/blockchain_type.dart | 25 + .../helper_functions/helper_functions.dart | 11 + lib/app/view/app.dart | 1 + .../model/ethereum_sign_message.dart | 19 + .../model/ethereum_transaction.dart | 40 ++ lib/connection_bridge/model/model.dart | 2 + .../cubit/wallet_connect_cubit.dart | 504 ++++++++++++++++-- .../cubit/wallet_connect_state.dart | 50 +- .../cubit/confirm_connection_cubit.dart | 106 ++-- .../view/confirm_connection_page.dart | 87 ++- pubspec.lock | 68 ++- pubspec.yaml | 1 + 13 files changed, 799 insertions(+), 122 deletions(-) create mode 100644 lib/connection_bridge/model/ethereum_sign_message.dart create mode 100644 lib/connection_bridge/model/ethereum_transaction.dart diff --git a/lib/app/shared/constants/parameters.dart b/lib/app/shared/constants/parameters.dart index b090275ce..7a59eb9e0 100644 --- a/lib/app/shared/constants/parameters.dart +++ b/lib/app/shared/constants/parameters.dart @@ -37,4 +37,11 @@ class Parameters { static const MUMBAI_ID_STATE_CONTRACT_ADDR = '0x134B1BE34911E39A8397ec6289782989729807a4'; static const MUMBAI_PUSH_URL = 'https://push-staging.polygonid.com/api/v1'; + + static const NAMESPACE = 'eip155'; + static const PERSONAL_SIGN = 'personal_sign'; + static const ETH_SIGN = 'eth_sign'; + static const ETH_SIGN_TRANSACTION = 'eth_signTransaction'; + static const ETH_SIGN_TYPE_DATA = 'eth_signTypedData'; + static const ETH_SEND_TRANSACTION = 'eth_sendTransaction'; } diff --git a/lib/app/shared/enum/type/blockchain_type.dart b/lib/app/shared/enum/type/blockchain_type.dart index 60ed4095e..d62921d05 100644 --- a/lib/app/shared/enum/type/blockchain_type.dart +++ b/lib/app/shared/enum/type/blockchain_type.dart @@ -62,6 +62,31 @@ extension BlockchainTypeX on BlockchainType { } } + String get chain { + String name = ''; + switch (this) { + case BlockchainType.tezos: + throw Exception(); + + case BlockchainType.ethereum: + name = '1'; + break; + case BlockchainType.fantom: + name = '250'; + break; + + case BlockchainType.polygon: + name = '137'; + break; + + case BlockchainType.binance: + name = '56'; + break; + } + + return '${Parameters.NAMESPACE}:$name'; + } + int get chainId { switch (this) { case BlockchainType.tezos: diff --git a/lib/app/shared/helper_functions/helper_functions.dart b/lib/app/shared/helper_functions/helper_functions.dart index 67bbbe9e3..094af3a53 100644 --- a/lib/app/shared/helper_functions/helper_functions.dart +++ b/lib/app/shared/helper_functions/helper_functions.dart @@ -417,3 +417,14 @@ List generateUriList(String url) { return uriList ?? []; } + +String getUtf8Message(String maybeHex) { + if (maybeHex.startsWith('0x')) { + final List decoded = hex.decode( + maybeHex.substring(2), + ); + return utf8.decode(decoded); + } + + return maybeHex; +} diff --git a/lib/app/view/app.dart b/lib/app/view/app.dart index 934f25b03..3697f1568 100644 --- a/lib/app/view/app.dart +++ b/lib/app/view/app.dart @@ -56,6 +56,7 @@ class App extends StatelessWidget { ), BlocProvider( create: (context) => WalletConnectCubit( + secureStorageProvider: secure_storage.getSecureStorage, connectedDappRepository: ConnectedDappRepository(secure_storage.getSecureStorage), ), diff --git a/lib/connection_bridge/model/ethereum_sign_message.dart b/lib/connection_bridge/model/ethereum_sign_message.dart new file mode 100644 index 000000000..cacbb8e9f --- /dev/null +++ b/lib/connection_bridge/model/ethereum_sign_message.dart @@ -0,0 +1,19 @@ +enum WCV2SignType { + message, + personalMessage, + typedMessageV2, + typedMessageV3, + typedMessageV4, +} + +class EthereumSignMessage { + const EthereumSignMessage({ + required this.data, + required this.address, + required this.type, + }); + + final String data; + final String address; + final WCV2SignType type; +} diff --git a/lib/connection_bridge/model/ethereum_transaction.dart b/lib/connection_bridge/model/ethereum_transaction.dart new file mode 100644 index 000000000..9b3e27bfd --- /dev/null +++ b/lib/connection_bridge/model/ethereum_transaction.dart @@ -0,0 +1,40 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'ethereum_transaction.g.dart'; + +@JsonSerializable(includeIfNull: false) +class EthereumTransaction { + final String from; + final String to; + final String value; + final String? nonce; + final String? gasPrice; + final String? maxFeePerGas; + final String? maxPriorityFeePerGas; + final String? gas; + final String? gasLimit; + final String? data; + + EthereumTransaction({ + required this.from, + required this.to, + required this.value, + this.nonce, + this.gasPrice, + this.maxFeePerGas, + this.maxPriorityFeePerGas, + this.gas, + this.gasLimit, + this.data, + }); + + factory EthereumTransaction.fromJson(Map json) => + _$EthereumTransactionFromJson(json); + + Map toJson() => _$EthereumTransactionToJson(this); + + @override + String toString() { + return 'WCEthereumTransaction(from: $from, to: $to, nonce: $nonce, gasPrice: $gasPrice, maxFeePerGas: $maxFeePerGas, maxPriorityFeePerGas: $maxPriorityFeePerGas, gas: $gas, gasLimit: $gasLimit, value: $value, data: $data)'; + } +} diff --git a/lib/connection_bridge/model/model.dart b/lib/connection_bridge/model/model.dart index 4ed3be351..b4cb0f5fc 100644 --- a/lib/connection_bridge/model/model.dart +++ b/lib/connection_bridge/model/model.dart @@ -1 +1,3 @@ +export 'ethereum_sign_message.dart'; +export 'ethereum_transaction.dart'; export 'saved_dapp_data.dart'; diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 4270637e5..8b7ac3f3c 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -1,11 +1,21 @@ import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; import 'package:altme/app/app.dart'; import 'package:altme/connection_bridge/connection_bridge.dart'; +import 'package:altme/wallet/wallet.dart'; import 'package:bloc/bloc.dart'; +import 'package:convert/convert.dart'; import 'package:equatable/equatable.dart'; +import 'package:eth_sig_util/eth_sig_util.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart'; import 'package:json_annotation/json_annotation.dart'; +import 'package:secure_storage/secure_storage.dart'; import 'package:wallet_connect/wallet_connect.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:web3dart/web3dart.dart'; part 'wallet_connect_cubit.g.dart'; part 'wallet_connect_state.dart'; @@ -13,40 +23,148 @@ part 'wallet_connect_state.dart'; class WalletConnectCubit extends Cubit { WalletConnectCubit({ required this.connectedDappRepository, + required this.secureStorageProvider, }) : super(WalletConnectState()) { initialise(); } final ConnectedDappRepository connectedDappRepository; + final SecureStorageProvider secureStorageProvider; final log = getLogger('WalletConnectCubit'); + Web3Wallet? _web3Wallet; + + Web3Wallet? get web3Wallet => _web3Wallet; + Future initialise() async { try { - log.i('initialise'); - final List savedDapps = - await connectedDappRepository.findAll(); + //log.i('initialise'); + // final List savedDapps = + // await connectedDappRepository.findAll(); - final connectedDapps = List.of(savedDapps).where( - (element) => element.blockchainType != BlockchainType.tezos, - ); + // final connectedDapps = List.of(savedDapps).where( + // (element) => element.blockchainType != BlockchainType.tezos, + // ); - final List wcClients = List.empty(growable: true); - for (final element in connectedDapps) { - final sessionStore = element.wcSessionStore; + // Await the initialization of the web3wallet - final WCClient? wcClient = createWCClient(element.wcSessionStore); + // final List wcClients = List.empty(growable: true); + // for (final element in connectedDapps) { + // final sessionStore = element.wcSessionStore; - await wcClient!.connectFromSessionStore(sessionStore!); - log.i('sessionStore: ${wcClient.sessionStore.toJson()}'); - wcClients.add(wcClient); - } - emit( - state.copyWith( - status: WalletConnectStatus.idle, - wcClients: wcClients, + // final WCClient? wcClient = createWCClient(element.wcSessionStore); + + // await wcClient!.connectFromSessionStore(sessionStore!); + // log.i('sessionStore: ${wcClient.sessionStore.toJson()}'); + // wcClients.add(wcClient); + //} + + // emit( + // state.copyWith( + // status: WalletConnectStatus.idle, + // // wcClients: wcClients, + // ), + // ); + + final String? savedCryptoAccount = + await secureStorageProvider.get(SecureStorageKeys.cryptoAccount); + + log.i('Create the web3wallet'); + await dotenv.load(); + final projectId = dotenv.get('WALLET_CONNECT_PROJECT_ID'); + _web3Wallet = await Web3Wallet.createInstance( + relayUrl: + 'wss://relay.walletconnect.com', // The relay websocket URL, leave blank to use the default + projectId: projectId, + metadata: const PairingMetadata( + name: 'Wallet (Altme)', + description: 'Altme Wallet', + url: 'https://altme.io', + icons: [], ), ); + + log.i('Setup our accounts'); + + if (savedCryptoAccount != null && savedCryptoAccount.isNotEmpty) { + //load all the content of walletAddress + final cryptoAccountJson = + jsonDecode(savedCryptoAccount) as Map; + final CryptoAccount cryptoAccount = + CryptoAccount.fromJson(cryptoAccountJson); + + final eVMAccounts = cryptoAccount.data + .where((e) => e.blockchainType != BlockchainType.tezos) + .toList(); + + final events = ['chainChanged', 'accountsChanged']; + + for (final accounts in eVMAccounts) { + log.i(accounts.blockchainType); + log.i('registerAccount'); + _web3Wallet!.registerAccount( + chainId: accounts.blockchainType.chain, + accountAddress: accounts.walletAddress, + ); + + log.i('registerEventEmitter'); + for (final String event in events) { + _web3Wallet!.registerEventEmitter( + chainId: accounts.blockchainType.chain, + event: event, + ); + } + + log.i('registerRequestHandler'); + _web3Wallet!.registerRequestHandler( + chainId: accounts.blockchainType.chain, + method: Parameters.PERSONAL_SIGN, + handler: personalSign, + ); + _web3Wallet!.registerRequestHandler( + chainId: accounts.blockchainType.chain, + method: Parameters.ETH_SIGN, + handler: ethSign, + ); + _web3Wallet!.registerRequestHandler( + chainId: accounts.blockchainType.chain, + method: Parameters.ETH_SIGN_TRANSACTION, + handler: ethSignTransaction, + ); + _web3Wallet!.registerRequestHandler( + chainId: accounts.blockchainType.chain, + method: Parameters.ETH_SIGN_TYPE_DATA, + handler: ethSignTransaction, + ); + _web3Wallet!.registerRequestHandler( + chainId: accounts.blockchainType.chain, + method: Parameters.ETH_SEND_TRANSACTION, + handler: ethSignTypedData, + ); + } + } + + log.i('Setup our listeners'); + _web3Wallet!.core.pairing.onPairingInvalid.subscribe(_onPairingInvalid); + _web3Wallet!.core.pairing.onPairingCreate.subscribe(_onPairingCreate); + _web3Wallet!.pairings.onSync.subscribe(_onPairingsSync); + _web3Wallet!.onSessionProposal.subscribe(_onSessionProposal); + _web3Wallet!.onSessionProposalError.subscribe(_onSessionProposalError); + _web3Wallet!.onSessionConnect.subscribe(_onSessionConnect); + _web3Wallet!.onAuthRequest.subscribe(_onAuthRequest); + + log.i('web3wallet init'); + await _web3Wallet!.init(); + log.i('metadata'); + log.i(_web3Wallet!.metadata); + + log.i('pairings'); + log.i(_web3Wallet!.pairings.getAll()); + log.i('sessions'); + log.i(_web3Wallet!.sessions.getAll()); + log.i('completeRequests'); + log.i(_web3Wallet!.completeRequests.getAll()); } catch (e) { log.e(e); } @@ -54,31 +172,35 @@ class WalletConnectCubit extends Cubit { Future connect(String walletConnectUri) async { log.i('walletConnectUri - $walletConnectUri'); - final WCSession session = WCSession.from(walletConnectUri); - final WCPeerMeta walletPeerMeta = WCPeerMeta( - name: 'Altme', - url: 'https://altme.io', - description: 'Altme Wallet', - icons: [], - ); - log.i('walletPeerMeta: $walletPeerMeta'); + // final WCSession session = WCSession.from(walletConnectUri); + // final WCPeerMeta walletPeerMeta = WCPeerMeta( + // name: 'Altme', + // url: 'https://altme.io', + // description: 'Altme Wallet', + // icons: [], + // ); - final WCClient? wcClient = createWCClient(null); - log.i('wcClient: $wcClient'); - if (wcClient == null) return; + // final WCClient? wcClient = createWCClient(null); + // log.i('wcClient: $wcClient'); + // if (wcClient == null) return; - await wcClient.connectNewSession( - session: session, - peerMeta: walletPeerMeta, - ); + // await wcClient.connectNewSession( + // session: session, + // peerMeta: walletPeerMeta, + // ); - final wcClients = List.of(state.wcClients)..add(wcClient); - emit( - state.copyWith( - status: WalletConnectStatus.idle, - wcClients: wcClients, - ), + // final wcClients = List.of(state.wcClients)..add(wcClient); + // emit( + // state.copyWith( + // status: WalletConnectStatus.idle, + // wcClients: wcClients, + // ), + // ); + final Uri uriData = Uri.parse(walletConnectUri); + final PairingInfo pairingInfo = await _web3Wallet!.pair( + uri: uriData, ); + log.i(pairingInfo); } WCClient? createWCClient(WCSessionStore? sessionStore) { @@ -168,4 +290,308 @@ class WalletConnectCubit extends Cubit { }, ); } + + void _onPairingInvalid(PairingInvalidEvent? args) { + print('Pairing Invalid Event: $args'); + } + + void _onPairingsSync(StoreSyncEvent? args) { + if (args != null) { + //pairings.value = _web3Wallet!.pairings.getAll(); + log.i('onPairingsSync'); + print(_web3Wallet!.pairings.getAll()); + } + } + + void _onSessionProposal(SessionProposalEvent? args) { + log.i('onSessionProposal'); + if (args != null) { + log.i('sessionProposalEvent - $args'); + emit( + state.copyWith( + status: WalletConnectStatus.permission, + sessionProposalEvent: args, + ), + ); + } + } + + void _onSessionProposalError(SessionProposalErrorEvent? args) { + log.i('onSessionProposalError'); + print(args); + } + + void _onSessionConnect(SessionConnect? args) { + if (args != null) { + print(args); + print(args.session); + //sessions.value.add(args.session); + } + } + + void _onPairingCreate(PairingEvent? args) { + print('Pairing Create Event: $args'); + } + + Future _onAuthRequest(AuthRequest? args) async { + if (args != null) { + print(args); + // List chainKeys = GetIt.I().getKeysForChain( + // 'eip155:1', + // ); + // Create the message to be signed + //final String iss = 'did:pkh:eip155:1:${chainKeys.first.publicKey}'; + + // print(args); + // final Widget w = WCRequestWidget( + // child: WCConnectionRequestWidget( + // wallet: _web3Wallet!, + // authRequest: WCAuthRequestModel( + // iss: iss, + // request: args, + // ), + // ), + // ); + // final bool? auth = await _bottomSheetHandler.queueBottomSheet( + // widget: w, + // ); + + // if (auth != null && auth) { + // final String message = _web3Wallet!.formatAuthMessage( + // iss: iss, + // cacaoPayload: CacaoRequestPayload.fromPayloadParams( + // args.payloadParams, + // ), + // ); + + // // EthPrivateKey credentials = + // // EthPrivateKey.fromHex(chainKeys.first.privateKey); + // // final String sig = utf8.decode( + // // credentials.signPersonalMessageToUint8List( + // // Uint8List.fromList(message.codeUnits), + // // ), + // // ); + + // final String sig = EthSigUtil.signPersonalMessage( + // message: Uint8List.fromList(message.codeUnits), + // privateKey: chainKeys.first.privateKey, + // ); + + // await _web3Wallet!.respondAuthRequest( + // id: args.id, + // iss: iss, + // signature: CacaoSignature( + // t: CacaoSignature.EIP191, + // s: sig, + // ), + // ); + // } else { + // await _web3Wallet!.respondAuthRequest( + // id: args.id, + // iss: iss, + // error: Errors.getSdkError( + // Errors.USER_REJECTED_AUTH, + // ), + // ); + // } + // } + } + } + + // Future requestAuthorization(String text) async { + // final bool? approved = await _bottomSheetService.queueBottomSheet( + // widget: WCRequestWidget( + // child: WCConnectionWidget( + // title: 'Sign Transaction', + // info: [ + // WCConnectionModel( + // text: text, + // ), + // ], + // ), + // ), + // ); + + // if (approved != null && approved == false) { + // return 'User rejected signature'; + // } + + // return null; + // } + + Future personalSign(String topic, dynamic parameters) async { + print('received personal sign request: $parameters'); + + final String message = getUtf8Message(parameters[0].toString()); + + // final String? authAcquired = await requestAuthorization(message); + // if (authAcquired != null) { + // return authAcquired; + // } + + try { + // Load the private key + + final Credentials credentials = + EthPrivateKey.fromHex('keys[0].privateKey'); + + final String signature = hex.encode( + credentials.signPersonalMessageToUint8List( + Uint8List.fromList( + utf8.encode(message), + ), + ), + ); + + return '0x$signature'; + } catch (e) { + print(e); + return 'Failed'; + } + } + + Future ethSign(String topic, dynamic parameters) async { + print('received eth sign request: $parameters'); + + final String message = getUtf8Message(parameters[1].toString()); + + // final String? authAcquired = await requestAuthorization(message); + // if (authAcquired != null) { + // return authAcquired; + // } + + try { + // Load the private key + + final EthPrivateKey credentials = EthPrivateKey.fromHex( + 'keys[0].privateKey', + ); + final String signature = hex.encode( + credentials.signPersonalMessageToUint8List( + Uint8List.fromList( + utf8.encode(message), + ), + ), + ); + print(signature); + + return '0x$signature'; + } catch (e) { + print('error:'); + print(e); + return 'Failed'; + } + } + + Future ethSignTransaction(String topic, dynamic parameters) async { + print('received eth sign transaction request: $parameters'); + // final String? authAcquired = await requestAuthorization( + // jsonEncode( + // parameters[0], + // ), + // ); + // if (authAcquired != null) { + // return authAcquired; + // } + + // Load the private key + + final Credentials credentials = EthPrivateKey.fromHex( + '0xkeys[0].privateKey', + ); + + final EthereumTransaction ethTransaction = EthereumTransaction.fromJson( + parameters[0] as Map, + ); + + // Construct a transaction from the EthereumTransaction object + final transaction = Transaction( + from: EthereumAddress.fromHex(ethTransaction.from), + to: EthereumAddress.fromHex(ethTransaction.to), + value: EtherAmount.fromUnitAndValue( + EtherUnit.wei, + BigInt.tryParse(ethTransaction.value) ?? BigInt.zero, + ), + gasPrice: ethTransaction.gasPrice != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.gasPrice!) ?? BigInt.zero, + ) + : null, + maxFeePerGas: ethTransaction.maxFeePerGas != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxFeePerGas!) ?? BigInt.zero, + ) + : null, + maxPriorityFeePerGas: ethTransaction.maxPriorityFeePerGas != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxPriorityFeePerGas!) ?? + BigInt.zero, + ) + : null, + maxGas: int.tryParse(ethTransaction.gasLimit ?? ''), + nonce: int.tryParse(ethTransaction.nonce ?? ''), + data: (ethTransaction.data != null && ethTransaction.data != '0x') + ? Uint8List.fromList(hex.decode(ethTransaction.data!)) + : null, + ); + + try { + await dotenv.load(); + final infuraApiKey = dotenv.get('INFURA_API_KEY'); + final ethRpcUrl = Urls.infuraBaseUrl + infuraApiKey; + final httpClient = Client(); + + final Web3Client ethClient = Web3Client(ethRpcUrl, httpClient); + + final Uint8List sig = await ethClient.signTransaction( + credentials, + transaction, + ); + + // Sign the transaction + final String signedTx = hex.encode(sig); + + // Return the signed transaction as a hexadecimal string + return '0x$signedTx'; + } catch (e) { + print(e); + return 'Failed'; + } + } + + Future ethSignTypedData(String topic, dynamic parameters) async { + print('received eth sign typed data request: $parameters'); + final String data = parameters[1] as String; + // final String? authAcquired = await requestAuthorization(data); + // if (authAcquired != null) { + // return authAcquired; + // } + + // final List keys = GetIt.I().getKeysForChain( + // getChainId(), + // ); + + // EthPrivateKey credentials = EthPrivateKey.fromHex(keys[0].privateKey); + // credentials. + + return EthSigUtil.signTypedData( + privateKey: 'keys[0].privateKey', + jsonData: data, + version: TypedDataVersion.V4, + ); + } + + Future dispose() async { + log.i('web3wallet dispose'); + _web3Wallet!.core.pairing.onPairingInvalid.unsubscribe(_onPairingInvalid); + _web3Wallet!.pairings.onSync.unsubscribe(_onPairingsSync); + _web3Wallet!.onSessionProposal.unsubscribe(_onSessionProposal); + _web3Wallet!.onSessionProposalError.unsubscribe(_onSessionProposalError); + _web3Wallet!.onSessionConnect.unsubscribe(_onSessionConnect); + // _web3Wallet!.onSessionRequest.unsubscribe(_onSessionRequest); + _web3Wallet!.onAuthRequest.unsubscribe(_onAuthRequest); + } } diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index e183689a1..2166a9162 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -4,8 +4,10 @@ part of 'wallet_connect_cubit.dart'; class WalletConnectState extends Equatable { WalletConnectState({ this.status = WalletConnectStatus.init, - this.isWalletConnectStarted = false, this.message, + + /// v1 + this.isWalletConnectStarted = false, this.sessionId, List? wcClients, this.currentDappPeerId, @@ -14,6 +16,9 @@ class WalletConnectState extends Equatable { this.signMessage, this.transactionId, this.transaction, + + /// v2 + this.sessionProposalEvent, }) : wcClients = wcClients ?? []; factory WalletConnectState.fromJson(Map json) => @@ -21,6 +26,8 @@ class WalletConnectState extends Equatable { final WalletConnectStatus? status; final StateMessage? message; + + /// v1 final bool isWalletConnectStarted; final int? sessionId; final String? currentDappPeerId; @@ -34,44 +41,26 @@ class WalletConnectState extends Equatable { @JsonKey(includeFromJson: false, includeToJson: false) final WCEthereumTransaction? transaction; + /// v2 + @JsonKey(includeFromJson: false, includeToJson: false) + final SessionProposalEvent? sessionProposalEvent; + Map toJson() => _$WalletConnectStateToJson(this); WalletConnectState loading() { - return WalletConnectState( - status: WalletConnectStatus.loading, - isWalletConnectStarted: isWalletConnectStarted, - sessionId: sessionId, - wcClients: wcClients, - currentDappPeerId: currentDappPeerId, - currentDAppPeerMeta: currentDAppPeerMeta, - signId: signId, - signMessage: signMessage, - transactionId: transactionId, - transaction: transaction, - ); + return copyWith(status: WalletConnectStatus.loading); } - WalletConnectState error({ - required MessageHandler messageHandler, - }) { - return WalletConnectState( + WalletConnectState error({required MessageHandler messageHandler}) { + return copyWith( status: WalletConnectStatus.error, message: StateMessage.error(messageHandler: messageHandler), - isWalletConnectStarted: isWalletConnectStarted, - currentDappPeerId: currentDappPeerId, - currentDAppPeerMeta: currentDAppPeerMeta, - sessionId: sessionId, - wcClients: wcClients, - signId: signId, - signMessage: signMessage, - transactionId: transactionId, - transaction: transaction, ); } WalletConnectState copyWith({ WalletConnectStatus status = WalletConnectStatus.idle, - MessageHandler? messageHandler, + StateMessage? message, bool? isWalletConnectStarted, int? sessionId, String? currentDappPeerId, @@ -81,12 +70,11 @@ class WalletConnectState extends Equatable { WCEthereumSignMessage? signMessage, int? transactionId, WCEthereumTransaction? transaction, + SessionProposalEvent? sessionProposalEvent, }) { return WalletConnectState( status: status, - message: messageHandler == null - ? null - : StateMessage.success(messageHandler: messageHandler), + message: message, isWalletConnectStarted: isWalletConnectStarted ?? this.isWalletConnectStarted, currentDAppPeerMeta: currentDAppPeerMeta ?? this.currentDAppPeerMeta, @@ -97,6 +85,7 @@ class WalletConnectState extends Equatable { signMessage: signMessage ?? this.signMessage, transactionId: transactionId ?? this.transactionId, transaction: transaction ?? this.transaction, + sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, ); } @@ -113,5 +102,6 @@ class WalletConnectState extends Equatable { signMessage, transactionId, transaction, + sessionProposalEvent, ]; } diff --git a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart index 4884a3106..866a64a7a 100644 --- a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart +++ b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart @@ -9,6 +9,7 @@ import 'package:dartez/dartez.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wallet_connect/wallet_connect.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; part 'confirm_connection_cubit.g.dart'; part 'confirm_connection_state.dart'; @@ -80,43 +81,53 @@ class ConfirmConnectionCubit extends Cubit { } break; case ConnectionBridgeType.walletconnect: - final List walletAddresses = [currentAccount.walletAddress]; + // final List walletAddresses = [currentAccount.walletAddress]; final walletConnectState = walletConnectCubit.state; - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - if (wcClient == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - wcClient.approveSession( - accounts: walletAddresses, - chainId: currentAccount.blockchainType.chainId, + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + // if (wcClient == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // wcClient.approveSession( + // accounts: walletAddresses, + // chainId: currentAccount.blockchainType.chainId, + // ); + + // log.i('Connected to walletconnect'); + + // final savedDappData = SavedDappData( + // walletAddress: currentAccount.walletAddress, + // blockchainType: currentAccount.blockchainType, + // wcSessionStore: WCSessionStore( + // session: wcClient.session!, + // peerMeta: wcClient.peerMeta!, + // peerId: wcClient.peerId!, + // remotePeerId: wcClient.remotePeerId!, + // remotePeerMeta: wcClient.remotePeerMeta!, + // chainId: currentAccount.blockchainType.chainId, + // ), + // ); + + // log.i(savedDappData.toJson()); + // await connectedDappRepository.insert(savedDappData); + + /// v2 + final SessionProposalEvent? sessionProposalEvent = + walletConnectState.sessionProposalEvent; + + await walletConnectCubit.web3Wallet!.approveSession( + id: sessionProposalEvent!.id, + namespaces: sessionProposalEvent.params.generatedNamespaces!, ); - log.i('Connected to walletconnect'); - - final savedDappData = SavedDappData( - walletAddress: currentAccount.walletAddress, - blockchainType: currentAccount.blockchainType, - wcSessionStore: WCSessionStore( - session: wcClient.session!, - peerMeta: wcClient.peerMeta!, - peerId: wcClient.peerId!, - remotePeerId: wcClient.remotePeerId!, - remotePeerMeta: wcClient.remotePeerMeta!, - chainId: currentAccount.blockchainType.chainId, - ), - ); - - log.i(savedDappData.toJson()); - await connectedDappRepository.insert(savedDappData); break; } emit( @@ -127,7 +138,7 @@ class ConfirmConnectionCubit extends Cubit { ), ), ); - } catch (e,s) { + } catch (e, s) { log.e('error connecting to $connectionBridgeType , e: $e , s: $s'); if (e is MessageHandler) { emit(state.error(messageHandler: e)); @@ -161,15 +172,26 @@ class ConfirmConnectionCubit extends Cubit { log.i('walletconnect connection rejected'); final walletConnectState = walletConnectCubit.state; - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + + // if (wcClient != null) { + // wcClient.rejectRequest(id: walletConnectState.sessionId!); + // } - if (wcClient != null) { - wcClient.rejectRequest(id: walletConnectState.sessionId!); - } + /// v2 + final SessionProposalEvent? sessionProposalEvent = + walletConnectState.sessionProposalEvent; + + walletConnectCubit.web3Wallet!.rejectSession( + id: sessionProposalEvent!.id, + reason: Errors.getSdkError( + Errors.USER_REJECTED, + ), + ); break; } emit(state.copyWith(appStatus: AppStatus.goBack)); diff --git a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart index d5833b376..d0cadc50b 100644 --- a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart +++ b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart @@ -8,6 +8,7 @@ import 'package:beacon_flutter/beacon_flutter.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:secure_storage/secure_storage.dart' as secure_storage; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; class ConfirmConnectionPage extends StatelessWidget { const ConfirmConnectionPage({ @@ -55,6 +56,9 @@ class ConfirmConnectionView extends StatelessWidget { @override Widget build(BuildContext context) { final l10n = context.l10n; + + final walletConnectCubit = context.read(); + return BlocListener( listener: (context, state) { if (state.status == AppStatus.loading) { @@ -115,21 +119,86 @@ class ConfirmConnectionView extends StatelessWidget { .request! .appMetadata! .name! - : context - .read() - .state - .currentDAppPeerMeta! - .name, + // : context + // .read() + // .state + // .currentDAppPeerMeta! + // .name, + : walletConnectCubit.state.sessionProposalEvent! + .params.proposer.metadata.name, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: Sizes.spaceXLarge), const Permissions(), const SizedBox(height: Sizes.spaceXLarge), - SelectAccount(connectionBridgeType: connectionBridgeType), - const SizedBox( - height: Sizes.spaceNormal, - ), + if (connectionBridgeType == + ConnectionBridgeType.walletconnect) ...[ + Text( + walletConnectCubit.state.sessionProposalEvent!.params + .proposer.metadata.url, + textAlign: TextAlign.center, + ), + const SizedBox(height: Sizes.spaceLarge), + ListView.builder( + itemCount: walletConnectCubit + .state + .sessionProposalEvent! + .params + .requiredNamespaces + .length, + shrinkWrap: true, + physics: const ScrollPhysics(), + itemBuilder: (context, i) { + final key = walletConnectCubit + .state + .sessionProposalEvent! + .params + .requiredNamespaces + .keys + .elementAt(i); + + final RequiredNamespace ns = walletConnectCubit + .state + .sessionProposalEvent! + .params + .requiredNamespaces[key]!; + + return Column( + children: [ + Text('$key : '), + if (ns.chains != null) ...[ + Column( + children: [ + const Text('Chains'), + Text(ns.chains!.toString()), + ], + ), + ], + Column( + children: [ + const Text('Methods'), + Text(ns.methods.toString()), + ], + ), + Column( + children: [ + const Text('Events'), + Text(ns.events.toString()), + ], + ), + const SizedBox(height: Sizes.spaceNormal), + ], + ); + }, + ) + ], + if (connectionBridgeType != + ConnectionBridgeType.walletconnect) ...[ + const SizedBox(height: Sizes.spaceXLarge), + SelectAccount(connectionBridgeType: connectionBridgeType), + ], + const SizedBox(height: Sizes.spaceNormal), ], ), ), diff --git a/pubspec.lock b/pubspec.lock index 4b52cbe63..ee3f93c17 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -105,6 +105,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" + base_x: + dependency: transitive + description: + name: base_x + sha256: "3f1043679659f1759c651f900da6f24f0a8062c28daa6f9625e8d580002e187b" + url: "https://pub.dev" + source: hosted + version: "2.0.0" beacon_flutter: dependency: "direct main" description: @@ -170,6 +178,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.1" + bs58: + dependency: transitive + description: + name: bs58 + sha256: "3ed24dadf386ca749ff50af678be1131ef569a3583a6f37b87b90c032270c767" + url: "https://pub.dev" + source: hosted + version: "1.0.2" bs58check: dependency: transitive description: @@ -178,6 +194,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.2" + buffer: + dependency: transitive + description: + name: buffer + sha256: "8962c12174f53e2e848a6acd7ac7fd63d8a1a6a316c20c458a832d87eba5422a" + url: "https://pub.dev" + source: hosted + version: "1.2.0" build: dependency: transitive description: @@ -702,6 +726,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.5" + eth_sig_util: + dependency: "direct main" + description: + name: eth_sig_util + sha256: "20fdc5ce3864e70e5ade1c1cd03cce4ef01018db00adab107303f9055d26b01a" + url: "https://pub.dev" + source: hosted + version: "0.0.9" + event: + dependency: transitive + description: + name: event + sha256: eb4814de94cbf6a10da9c4f652bc654087d7066e33566b5036822e6c0b24befb + url: "https://pub.dev" + source: hosted + version: "2.1.2" fake_async: dependency: transitive description: @@ -1364,10 +1404,10 @@ packages: dependency: "direct main" description: name: logger - sha256: db2ff852ed77090ba9f62d3611e4208a3d11dfa35991a81ae724c113fcb3e3f7 + sha256: "7ad7215c15420a102ec687bb320a7312afd449bac63bfb1c60d9787c27b9767f" url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.4.0" logging: dependency: transitive description: @@ -2301,6 +2341,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: "1722b2dcc462b4b2f3ee7d188dad008b6eb4c40bbd03a3de451d82c78bba9aad" + url: "https://pub.dev" + source: hosted + version: "2.2.2" unorm_dart: dependency: transitive description: @@ -2454,6 +2502,14 @@ packages: url: "https://github.com/bibash28/wallet-connect-dart.git" source: git version: "1.0.4" + walletconnect_flutter_v2: + dependency: "direct main" + description: + name: walletconnect_flutter_v2 + sha256: "6b9ef246acdbc3684167d1519c73d7bb79fef68ae2c6fc822e350b4b5d3e8fd8" + url: "https://pub.dev" + source: hosted + version: "2.0.10" watcher: dependency: transitive description: @@ -2542,6 +2598,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + x25519: + dependency: transitive + description: + name: x25519 + sha256: cec3c125f0d934dccba6c4cab48f3fbf866dc78895dcc5a1584d35b0a845005b + url: "https://pub.dev" + source: hosted + version: "0.1.1" x509: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index a6da0d46c..249f580e1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -42,6 +42,7 @@ dependencies: path: packages/ebsi ed25519_hd_key: ^2.2.0 equatable: ^2.0.5 + eth_sig_util: ^0.0.9 file_picker: ^5.3.1 file_saver: ^0.2.4 flutter: From ce2a82a9f13c211aabb6b6ddb1e01b2df8c85b7c Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Thu, 29 Jun 2023 12:49:57 +0545 Subject: [PATCH 02/13] personal sign done --- .../cubit/wallet_connect_cubit.dart | 50 ++-- .../cubit/wallet_connect_state.dart | 5 + .../view/confirm_connection_page.dart | 8 +- .../cubit/sign_payload_cubit.dart | 259 ++++++++++-------- .../sign_payload/view/sign_payload_page.dart | 9 +- 5 files changed, 184 insertions(+), 147 deletions(-) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 8b7ac3f3c..f0a3192b0 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -299,7 +299,7 @@ class WalletConnectCubit extends Cubit { if (args != null) { //pairings.value = _web3Wallet!.pairings.getAll(); log.i('onPairingsSync'); - print(_web3Wallet!.pairings.getAll()); + log.i(_web3Wallet!.pairings.getAll()); } } @@ -318,19 +318,19 @@ class WalletConnectCubit extends Cubit { void _onSessionProposalError(SessionProposalErrorEvent? args) { log.i('onSessionProposalError'); - print(args); + log.i(args); } void _onSessionConnect(SessionConnect? args) { if (args != null) { - print(args); - print(args.session); + log.i(args); + log.i(args.session); //sessions.value.add(args.session); } } void _onPairingCreate(PairingEvent? args) { - print('Pairing Create Event: $args'); + log.i('Pairing Create Event: $args'); } Future _onAuthRequest(AuthRequest? args) async { @@ -419,35 +419,25 @@ class WalletConnectCubit extends Cubit { // return null; // } - Future personalSign(String topic, dynamic parameters) async { - print('received personal sign request: $parameters'); - - final String message = getUtf8Message(parameters[0].toString()); + Completer? completer; - // final String? authAcquired = await requestAuthorization(message); - // if (authAcquired != null) { - // return authAcquired; - // } - - try { - // Load the private key + Future personalSign(String topic, dynamic parameters) async { + log.i('received personal sign request: $parameters'); - final Credentials credentials = - EthPrivateKey.fromHex('keys[0].privateKey'); + completer = Completer(); - final String signature = hex.encode( - credentials.signPersonalMessageToUint8List( - Uint8List.fromList( - utf8.encode(message), - ), - ), - ); + log.i('completer'); + emit( + state.copyWith( + status: WalletConnectStatus.signPayload, + parameters: parameters, + ), + ); - return '0x$signature'; - } catch (e) { - print(e); - return 'Failed'; - } + final String result = await completer!.future; + log.i('complete - $result'); + completer = null; + return result; } Future ethSign(String topic, dynamic parameters) async { diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index 2166a9162..6ba6ac49d 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -19,6 +19,7 @@ class WalletConnectState extends Equatable { /// v2 this.sessionProposalEvent, + this.parameters, }) : wcClients = wcClients ?? []; factory WalletConnectState.fromJson(Map json) => @@ -40,6 +41,7 @@ class WalletConnectState extends Equatable { final int? transactionId; @JsonKey(includeFromJson: false, includeToJson: false) final WCEthereumTransaction? transaction; + final dynamic parameters; /// v2 @JsonKey(includeFromJson: false, includeToJson: false) @@ -71,6 +73,7 @@ class WalletConnectState extends Equatable { int? transactionId, WCEthereumTransaction? transaction, SessionProposalEvent? sessionProposalEvent, + dynamic parameters, }) { return WalletConnectState( status: status, @@ -86,6 +89,7 @@ class WalletConnectState extends Equatable { transactionId: transactionId ?? this.transactionId, transaction: transaction ?? this.transaction, sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, + parameters: parameters ?? this.parameters, ); } @@ -103,5 +107,6 @@ class WalletConnectState extends Equatable { transactionId, transaction, sessionProposalEvent, + parameters, ]; } diff --git a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart index d0cadc50b..c51c2e559 100644 --- a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart +++ b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart @@ -165,29 +165,35 @@ class ConfirmConnectionView extends StatelessWidget { .requiredNamespaces[key]!; return Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('$key : '), if (ns.chains != null) ...[ Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Chains'), Text(ns.chains!.toString()), ], ), + const SizedBox(height: Sizes.spaceSmall), ], Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Methods'), Text(ns.methods.toString()), ], ), + const SizedBox(height: Sizes.spaceSmall), Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Events'), Text(ns.events.toString()), ], ), - const SizedBox(height: Sizes.spaceNormal), + const SizedBox(height: Sizes.spaceSmall), ], ); }, diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index 6b7aab269..0fb0fdbf3 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -8,6 +8,7 @@ import 'package:altme/dashboard/dashboard.dart'; import 'package:altme/wallet/wallet.dart'; import 'package:beacon_flutter/beacon_flutter.dart'; import 'package:bloc/bloc.dart'; +import 'package:convert/convert.dart'; import 'package:dartez/dartez.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; @@ -49,6 +50,8 @@ class SignPayloadCubit extends Cubit { final log = getLogger('SignPayloadCubit'); + String payloadMessage = ''; + switch (connectionBridgeType) { case ConnectionBridgeType.beacon: log.i('decoding payload'); @@ -66,16 +69,24 @@ class SignPayloadCubit extends Cubit { encodedPayload = stringToHexPrefixedWith05(payload: payload); signingType = SigningType.raw; } + final bytes = hexToBytes(encodedPayload); + payloadMessage = utf8.decode(bytes, allowMalformed: true); break; case ConnectionBridgeType.walletconnect: - encodedPayload = walletConnectCubit.state.signMessage!.data!; + // encodedPayload = walletConnectCubit.state.signMessage!.data!; + // signingType = SigningType.raw; + // final bytes = hexToBytes(encodedPayload); + // payloadMessage = utf8.decode(bytes, allowMalformed: true); + + // v2 + payloadMessage = getUtf8Message( + walletConnectCubit.state.parameters[0] as String, + ); signingType = SigningType.raw; break; } - final bytes = hexToBytes(encodedPayload); - final String payloadMessage = utf8.decode(bytes, allowMalformed: true); log.i('payloadMessage - $payloadMessage'); emit( @@ -151,105 +162,124 @@ class SignPayloadCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: final walletConnectState = walletConnectCubit.state; - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - - log.i('wcClient -$wcClient'); - if (wcClient == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - final List savedDapps = - await connectedDappRepository.findAll(); - - final SavedDappData? dappData = savedDapps.firstWhereOrNull( - (element) { - return element.wcSessionStore != null && - element.wcSessionStore!.session.key == - wcClient.sessionStore.session.key; - }, - ); - - log.i('dappData -$dappData'); - if (dappData == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - final CryptoAccountData? currentAccount = - walletCubit.state.cryptoAccount.data.firstWhereOrNull( - (element) => - element.walletAddress == dappData.walletAddress && - element.blockchainType == dappData.blockchainType, + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + + // log.i('wcClient -$wcClient'); + // if (wcClient == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // final List savedDapps = + // await connectedDappRepository.findAll(); + + // final SavedDappData? dappData = savedDapps.firstWhereOrNull( + // (element) { + // return element.wcSessionStore != null && + // element.wcSessionStore!.session.key == + // wcClient.sessionStore.session.key; + // }, + // ); + + // log.i('dappData -$dappData'); + // if (dappData == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // final CryptoAccountData? currentAccount = + // walletCubit.state.cryptoAccount.data.firstWhereOrNull( + // (element) => + // element.walletAddress == dappData.walletAddress && + // element.blockchainType == dappData.blockchainType, + // ); + + // log.i('currentAccount -$currentAccount'); + // // ignore: invariant_booleans + // if (currentAccount == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // log.i('type -${walletConnectCubit.state.signMessage!.type}}'); + + // switch (walletConnectCubit.state.signMessage!.type) { + // /// rejected in wallet_connect_cubit + // case WCSignType.MESSAGE: + // break; + + // /// rejected in wallet_connect_cubit + // case WCSignType.TYPED_MESSAGE: + // break; + + // case WCSignType.PERSONAL_MESSAGE: + // const messagePrefix = '\u0019Ethereum Signed Message:\n'; + + // final payloadBytes = hexToBytes(encodedPayload); + + // final prefix = messagePrefix + payloadBytes.length.toString(); + // final prefixBytes = ascii.encode(prefix); + + // final concatPayload = + // Uint8List.fromList(prefixBytes + payloadBytes); + + // final Credentials credentials = + // EthPrivateKey.fromHex(currentAccount.secretKey); + + // final MsgSignature signature = + // credentials.signToEcSignature(concatPayload); + + // final String r = signature.r.toRadixString(16); + // log.i('r -$r'); + // final String s = signature.s.toRadixString(16); + // log.i('s -$s'); + // final String v = signature.v.toRadixString(16); + // log.i('v -$v'); + + // final signedDataAsHex = '0x$r$s$v'; + // log.i('signedDataAsHex -$signedDataAsHex'); + + // wcClient.approveRequest( + // id: walletConnectState.signId!, + // result: signedDataAsHex, + // ); + // success = true; + // break; + // } + + //v2 + + final CryptoAccountData currentAccount = + walletCubit.state.currentAccount!; + + final String message = + getUtf8Message(walletConnectState.parameters[0].toString()); + + log.i('message - $message'); + // Load the private key + + final Credentials credentials = + EthPrivateKey.fromHex(currentAccount.secretKey); + + final String signature = hex.encode( + credentials.signPersonalMessageToUint8List( + Uint8List.fromList( + utf8.encode(message), + ), + ), ); - - log.i('currentAccount -$currentAccount'); - // ignore: invariant_booleans - if (currentAccount == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - log.i('type -${walletConnectCubit.state.signMessage!.type}}'); - - switch (walletConnectCubit.state.signMessage!.type) { - /// rejected in wallet_connect_cubit - case WCSignType.MESSAGE: - break; - - /// rejected in wallet_connect_cubit - case WCSignType.TYPED_MESSAGE: - break; - - case WCSignType.PERSONAL_MESSAGE: - const messagePrefix = '\u0019Ethereum Signed Message:\n'; - - final payloadBytes = hexToBytes(encodedPayload); - - final prefix = messagePrefix + payloadBytes.length.toString(); - final prefixBytes = ascii.encode(prefix); - - final concatPayload = - Uint8List.fromList(prefixBytes + payloadBytes); - - final Credentials credentials = - EthPrivateKey.fromHex(currentAccount.secretKey); - - final MsgSignature signature = - credentials.signToEcSignature(concatPayload); - - final r = signature.r; - final s = signature.s; - final v = signature.v; - - final rHex = r.toRadixString(16).padLeft(64, '0'); - final sHex = s.toRadixString(16).padLeft(64, '0'); - final vHex = v.toRadixString(16); - - log.i('rHex -$rHex'); - log.i('sHex -$sHex'); - log.i('vHex -$vHex'); - - final signedDataHex = '0x$rHex$sHex$vHex'; - log.i('signedDataAsHex -$signedDataHex'); - - wcClient.approveRequest( - id: walletConnectState.signId!, - result: signedDataHex, - ); - success = true; - break; - } + walletConnectCubit.completer!.complete('0x$signature'); + success = true; break; } @@ -296,6 +326,10 @@ class SignPayloadCubit extends Cubit { ), ); } + + if (connectionBridgeType == ConnectionBridgeType.walletconnect) { + walletConnectCubit.completer!.complete('Failed'); + } } } @@ -313,17 +347,18 @@ class SignPayloadCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: log.i('walletconnect Signing rejected'); - final walletConnectState = walletConnectCubit.state; - - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - - if (wcClient != null) { - wcClient.rejectRequest(id: walletConnectState.signId!); - } + // final walletConnectState = walletConnectCubit.state; + + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + + // if (wcClient != null) { + // wcClient.rejectRequest(id: walletConnectState.signId!); + // } + walletConnectCubit.completer!.complete('Failed'); break; } emit(state.copyWith(appStatus: AppStatus.goBack)); diff --git a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart index a7cfc6c31..175cb670f 100644 --- a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart +++ b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart @@ -132,10 +132,11 @@ class _SignPayloadViewState extends State { ConnectionBridgeType.beacon ? beaconRequest!.request!.appMetadata!.name! : context - .read() - .state - .currentDAppPeerMeta! - .name, + .read() + .state + .currentDAppPeerMeta + ?.name ?? + '', textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), From 4275488bff21f6490b24fc86f64af3fc445e18f0 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Thu, 29 Jun 2023 16:42:29 +0545 Subject: [PATCH 03/13] feat: Added wallet connect v2 person_sign, eth_sign_standard and eth_signTypedData --- .../cubit/wallet_connect_cubit.dart | 86 +++++++--------- .../cubit/wallet_connect_state.dart | 5 + .../cubit/sign_payload_cubit.dart | 99 +++++++++++++++---- 3 files changed, 121 insertions(+), 69 deletions(-) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index f0a3192b0..07734b3ff 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -8,7 +8,6 @@ import 'package:altme/wallet/wallet.dart'; import 'package:bloc/bloc.dart'; import 'package:convert/convert.dart'; import 'package:equatable/equatable.dart'; -import 'package:eth_sig_util/eth_sig_util.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart'; import 'package:json_annotation/json_annotation.dart'; @@ -135,7 +134,7 @@ class WalletConnectCubit extends Cubit { _web3Wallet!.registerRequestHandler( chainId: accounts.blockchainType.chain, method: Parameters.ETH_SIGN_TYPE_DATA, - handler: ethSignTransaction, + handler: ethSignTypedData, ); _web3Wallet!.registerRequestHandler( chainId: accounts.blockchainType.chain, @@ -419,58 +418,47 @@ class WalletConnectCubit extends Cubit { // return null; // } - Completer? completer; + List?> completer = ?>[]; Future personalSign(String topic, dynamic parameters) async { log.i('received personal sign request: $parameters'); + log.i('topic: $topic'); - completer = Completer(); + log.i('completer initialise'); + completer.add(Completer()); - log.i('completer'); emit( state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, + signType: Parameters.PERSONAL_SIGN, ), ); - final String result = await completer!.future; + final String result = await completer[completer.length - 1]!.future; log.i('complete - $result'); - completer = null; + completer.removeLast(); return result; } Future ethSign(String topic, dynamic parameters) async { - print('received eth sign request: $parameters'); - - final String message = getUtf8Message(parameters[1].toString()); - - // final String? authAcquired = await requestAuthorization(message); - // if (authAcquired != null) { - // return authAcquired; - // } + log.i('received eth sign request: $parameters'); - try { - // Load the private key + log.i('completer initialise'); + completer.add(Completer()); - final EthPrivateKey credentials = EthPrivateKey.fromHex( - 'keys[0].privateKey', - ); - final String signature = hex.encode( - credentials.signPersonalMessageToUint8List( - Uint8List.fromList( - utf8.encode(message), - ), - ), - ); - print(signature); + emit( + state.copyWith( + status: WalletConnectStatus.signPayload, + parameters: parameters, + signType: Parameters.ETH_SIGN, + ), + ); - return '0x$signature'; - } catch (e) { - print('error:'); - print(e); - return 'Failed'; - } + final String result = await completer[completer.length - 1]!.future; + log.i('complete - $result'); + completer.removeLast(); + return result; } Future ethSignTransaction(String topic, dynamic parameters) async { @@ -553,25 +541,23 @@ class WalletConnectCubit extends Cubit { } Future ethSignTypedData(String topic, dynamic parameters) async { - print('received eth sign typed data request: $parameters'); - final String data = parameters[1] as String; - // final String? authAcquired = await requestAuthorization(data); - // if (authAcquired != null) { - // return authAcquired; - // } - - // final List keys = GetIt.I().getKeysForChain( - // getChainId(), - // ); + log.i('received eth sign typed data request: $parameters'); - // EthPrivateKey credentials = EthPrivateKey.fromHex(keys[0].privateKey); - // credentials. + log.i('completer initialise'); + completer.add(Completer()); - return EthSigUtil.signTypedData( - privateKey: 'keys[0].privateKey', - jsonData: data, - version: TypedDataVersion.V4, + emit( + state.copyWith( + status: WalletConnectStatus.signPayload, + parameters: parameters, + signType: Parameters.ETH_SIGN_TYPE_DATA, + ), ); + + final String result = await completer[completer.length - 1]!.future; + log.i('complete - $result'); + completer.removeLast(); + return result; } Future dispose() async { diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index 6ba6ac49d..97e1300cb 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -20,6 +20,7 @@ class WalletConnectState extends Equatable { /// v2 this.sessionProposalEvent, this.parameters, + this.signType, }) : wcClients = wcClients ?? []; factory WalletConnectState.fromJson(Map json) => @@ -42,6 +43,7 @@ class WalletConnectState extends Equatable { @JsonKey(includeFromJson: false, includeToJson: false) final WCEthereumTransaction? transaction; final dynamic parameters; + final String? signType; /// v2 @JsonKey(includeFromJson: false, includeToJson: false) @@ -74,6 +76,7 @@ class WalletConnectState extends Equatable { WCEthereumTransaction? transaction, SessionProposalEvent? sessionProposalEvent, dynamic parameters, + String? signType, }) { return WalletConnectState( status: status, @@ -90,6 +93,7 @@ class WalletConnectState extends Equatable { transaction: transaction ?? this.transaction, sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, parameters: parameters ?? this.parameters, + signType: signType ?? this.signType, ); } @@ -108,5 +112,6 @@ class WalletConnectState extends Equatable { transaction, sessionProposalEvent, parameters, + signType, ]; } diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index 0fb0fdbf3..c5db99f68 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -11,6 +11,7 @@ import 'package:bloc/bloc.dart'; import 'package:convert/convert.dart'; import 'package:dartez/dartez.dart'; import 'package:equatable/equatable.dart'; +import 'package:eth_sig_util/eth_sig_util.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wallet_connect/wallet_connect.dart'; import 'package:web3dart/crypto.dart'; @@ -80,9 +81,24 @@ class SignPayloadCubit extends Cubit { // payloadMessage = utf8.decode(bytes, allowMalformed: true); // v2 - payloadMessage = getUtf8Message( - walletConnectCubit.state.parameters[0] as String, - ); + + if (walletConnectCubit.state.signType == Parameters.PERSONAL_SIGN) { + payloadMessage = getUtf8Message( + walletConnectCubit.state.parameters[0] as String, + ); + } else if (walletConnectCubit.state.signType == Parameters.ETH_SIGN) { + payloadMessage = getUtf8Message( + walletConnectCubit.state.parameters[1] as String, + ); + } else if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TYPE_DATA) { + payloadMessage = walletConnectCubit.state.parameters[1] as String; + } else { + throw ResponseMessage( + ResponseString + .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + ); + } signingType = SigningType.raw; break; } @@ -259,27 +275,70 @@ class SignPayloadCubit extends Cubit { //v2 - final CryptoAccountData currentAccount = - walletCubit.state.currentAccount!; + final String publicKey; - final String message = - getUtf8Message(walletConnectState.parameters[0].toString()); + /// Extracting secret key + if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TYPE_DATA || + walletConnectCubit.state.signType == Parameters.ETH_SIGN) { + publicKey = walletConnectState.parameters[0].toString(); + } else if (walletConnectCubit.state.signType == + Parameters.PERSONAL_SIGN) { + publicKey = walletConnectState.parameters[1].toString(); + } else { + throw ResponseMessage( + ResponseString + .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + ); + } + + final CryptoAccountData? currentAccount = + walletCubit.state.cryptoAccount.data.firstWhereOrNull( + (element) => element.walletAddress == publicKey); - log.i('message - $message'); - // Load the private key + log.i('currentAccount -$currentAccount'); + if (currentAccount == null) { + throw ResponseMessage( + ResponseString + .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + ); + } final Credentials credentials = EthPrivateKey.fromHex(currentAccount.secretKey); - final String signature = hex.encode( - credentials.signPersonalMessageToUint8List( - Uint8List.fromList( - utf8.encode(message), + /// sign + if (walletConnectCubit.state.signType == Parameters.PERSONAL_SIGN || + walletConnectCubit.state.signType == Parameters.ETH_SIGN) { + final String signature = hex.encode( + credentials.signPersonalMessageToUint8List( + Uint8List.fromList( + utf8.encode(state.payloadMessage!), + ), ), - ), - ); - walletConnectCubit.completer!.complete('0x$signature'); - success = true; + ); + walletConnectCubit + .completer[walletConnectCubit.completer.length - 1]! + .complete('0x$signature'); + success = true; + } else if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TYPE_DATA) { + final signTypedData = EthSigUtil.signTypedData( + privateKey: currentAccount.secretKey, + jsonData: state.payloadMessage!, + version: TypedDataVersion.V4, + ); + walletConnectCubit + .completer[walletConnectCubit.completer.length - 1]! + .complete(signTypedData); + success = true; + } else { + throw ResponseMessage( + ResponseString + .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + ); + } + break; } @@ -328,7 +387,8 @@ class SignPayloadCubit extends Cubit { } if (connectionBridgeType == ConnectionBridgeType.walletconnect) { - walletConnectCubit.completer!.complete('Failed'); + walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! + .complete('Failed'); } } } @@ -358,7 +418,8 @@ class SignPayloadCubit extends Cubit { // if (wcClient != null) { // wcClient.rejectRequest(id: walletConnectState.signId!); // } - walletConnectCubit.completer!.complete('Failed'); + walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! + .complete('Failed'); break; } emit(state.copyWith(appStatus: AppStatus.goBack)); From cc5523abd75fc7bd29e4cc0725c336fe426157f1 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Thu, 29 Jun 2023 16:50:50 +0545 Subject: [PATCH 04/13] fix: Readded wallet connected v2 package --- pubspec.lock | 16 ---------------- pubspec.yaml | 1 + 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index ee3f93c17..7ea4ef6d3 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -811,22 +811,6 @@ packages: description: flutter source: sdk version: "0.0.0" - flutter_appauth: - dependency: "direct main" - description: - name: flutter_appauth - sha256: a047019b525ab0e260776d1b0da1000b7416b45b9e8dd02d124c9da571fc1918 - url: "https://pub.dev" - source: hosted - version: "6.0.0" - flutter_appauth_platform_interface: - dependency: transitive - description: - name: flutter_appauth_platform_interface - sha256: "44feaa7058191b5d3cd7c9ff195262725773643121bcada172d49c2ddcff71cb" - url: "https://pub.dev" - source: hosted - version: "6.0.0" flutter_bloc: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 249f580e1..23733c9e6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -111,6 +111,7 @@ dependencies: git: url: https://github.com/bibash28/wallet-connect-dart.git ref: 5d3003d51ee5afb9911d04d15b6b2aa2f12989c8 + walletconnect_flutter_v2: ^2.0.10 webview_flutter: ^4.2.1 webview_flutter_android: ^3.7.1 webview_flutter_wkwebview: ^3.4.4 From f618e3c314d1cc594b42a27dc7ecd128eae309d8 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Fri, 30 Jun 2023 12:27:41 +0545 Subject: [PATCH 05/13] feat: Ability to eth_signTransaction --- .../cubit/wallet_connect_cubit.dart | 110 +++--------------- .../cubit/sign_payload_cubit.dart | 72 +++++++++++- .../confirm_token_transaction_cubit.dart | 6 +- 3 files changed, 88 insertions(+), 100 deletions(-) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 07734b3ff..6686a7f75 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -1,20 +1,16 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:typed_data'; import 'package:altme/app/app.dart'; import 'package:altme/connection_bridge/connection_bridge.dart'; import 'package:altme/wallet/wallet.dart'; import 'package:bloc/bloc.dart'; -import 'package:convert/convert.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:http/http.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:secure_storage/secure_storage.dart'; import 'package:wallet_connect/wallet_connect.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; -import 'package:web3dart/web3dart.dart'; part 'wallet_connect_cubit.g.dart'; part 'wallet_connect_state.dart'; @@ -291,7 +287,7 @@ class WalletConnectCubit extends Cubit { } void _onPairingInvalid(PairingInvalidEvent? args) { - print('Pairing Invalid Event: $args'); + log.i('Pairing Invalid Event: $args'); } void _onPairingsSync(StoreSyncEvent? args) { @@ -397,27 +393,6 @@ class WalletConnectCubit extends Cubit { } } - // Future requestAuthorization(String text) async { - // final bool? approved = await _bottomSheetService.queueBottomSheet( - // widget: WCRequestWidget( - // child: WCConnectionWidget( - // title: 'Sign Transaction', - // info: [ - // WCConnectionModel( - // text: text, - // ), - // ], - // ), - // ), - // ); - - // if (approved != null && approved == false) { - // return 'User rejected signature'; - // } - - // return null; - // } - List?> completer = ?>[]; Future personalSign(String topic, dynamic parameters) async { @@ -462,82 +437,23 @@ class WalletConnectCubit extends Cubit { } Future ethSignTransaction(String topic, dynamic parameters) async { - print('received eth sign transaction request: $parameters'); - // final String? authAcquired = await requestAuthorization( - // jsonEncode( - // parameters[0], - // ), - // ); - // if (authAcquired != null) { - // return authAcquired; - // } - - // Load the private key + log.i('received eth sign transaction request: $parameters'); - final Credentials credentials = EthPrivateKey.fromHex( - '0xkeys[0].privateKey', - ); - - final EthereumTransaction ethTransaction = EthereumTransaction.fromJson( - parameters[0] as Map, - ); + log.i('completer initialise'); + completer.add(Completer()); - // Construct a transaction from the EthereumTransaction object - final transaction = Transaction( - from: EthereumAddress.fromHex(ethTransaction.from), - to: EthereumAddress.fromHex(ethTransaction.to), - value: EtherAmount.fromUnitAndValue( - EtherUnit.wei, - BigInt.tryParse(ethTransaction.value) ?? BigInt.zero, + emit( + state.copyWith( + status: WalletConnectStatus.signPayload, + parameters: parameters, + signType: Parameters.ETH_SIGN_TRANSACTION, ), - gasPrice: ethTransaction.gasPrice != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.gasPrice!) ?? BigInt.zero, - ) - : null, - maxFeePerGas: ethTransaction.maxFeePerGas != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.maxFeePerGas!) ?? BigInt.zero, - ) - : null, - maxPriorityFeePerGas: ethTransaction.maxPriorityFeePerGas != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.maxPriorityFeePerGas!) ?? - BigInt.zero, - ) - : null, - maxGas: int.tryParse(ethTransaction.gasLimit ?? ''), - nonce: int.tryParse(ethTransaction.nonce ?? ''), - data: (ethTransaction.data != null && ethTransaction.data != '0x') - ? Uint8List.fromList(hex.decode(ethTransaction.data!)) - : null, ); - try { - await dotenv.load(); - final infuraApiKey = dotenv.get('INFURA_API_KEY'); - final ethRpcUrl = Urls.infuraBaseUrl + infuraApiKey; - final httpClient = Client(); - - final Web3Client ethClient = Web3Client(ethRpcUrl, httpClient); - - final Uint8List sig = await ethClient.signTransaction( - credentials, - transaction, - ); - - // Sign the transaction - final String signedTx = hex.encode(sig); - - // Return the signed transaction as a hexadecimal string - return '0x$signedTx'; - } catch (e) { - print(e); - return 'Failed'; - } + final String result = await completer[completer.length - 1]!.future; + log.i('complete - $result'); + completer.removeLast(); + return result; } Future ethSignTypedData(String topic, dynamic parameters) async { diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index c5db99f68..5560c8831 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -12,8 +12,9 @@ import 'package:convert/convert.dart'; import 'package:dartez/dartez.dart'; import 'package:equatable/equatable.dart'; import 'package:eth_sig_util/eth_sig_util.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart'; import 'package:json_annotation/json_annotation.dart'; -import 'package:wallet_connect/wallet_connect.dart'; import 'package:web3dart/crypto.dart'; import 'package:web3dart/web3dart.dart'; @@ -93,6 +94,9 @@ class SignPayloadCubit extends Cubit { } else if (walletConnectCubit.state.signType == Parameters.ETH_SIGN_TYPE_DATA) { payloadMessage = walletConnectCubit.state.parameters[1] as String; + } else if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TRANSACTION) { + payloadMessage = jsonEncode(walletConnectCubit.state.parameters[0]); } else { throw ResponseMessage( ResponseString @@ -285,6 +289,9 @@ class SignPayloadCubit extends Cubit { } else if (walletConnectCubit.state.signType == Parameters.PERSONAL_SIGN) { publicKey = walletConnectState.parameters[1].toString(); + } else if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TRANSACTION) { + publicKey = walletConnectState.parameters[0]['from'].toString(); } else { throw ResponseMessage( ResponseString @@ -332,6 +339,69 @@ class SignPayloadCubit extends Cubit { .completer[walletConnectCubit.completer.length - 1]! .complete(signTypedData); success = true; + } else if (walletConnectCubit.state.signType == + Parameters.ETH_SIGN_TRANSACTION) { + final EthereumTransaction ethTransaction = + EthereumTransaction.fromJson( + walletConnectCubit.state.parameters[0] as Map, + ); + + // Construct a transaction from the EthereumTransaction object + final transaction = Transaction( + from: EthereumAddress.fromHex(ethTransaction.from), + to: EthereumAddress.fromHex(ethTransaction.to), + value: EtherAmount.fromUnitAndValue( + EtherUnit.wei, + BigInt.tryParse(ethTransaction.value) ?? BigInt.zero, + ), + gasPrice: ethTransaction.gasPrice != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.gasPrice!) ?? BigInt.zero, + ) + : null, + maxFeePerGas: ethTransaction.maxFeePerGas != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxFeePerGas!) ?? + BigInt.zero, + ) + : null, + maxPriorityFeePerGas: ethTransaction.maxPriorityFeePerGas != null + ? EtherAmount.fromUnitAndValue( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxPriorityFeePerGas!) ?? + BigInt.zero, + ) + : null, + maxGas: int.tryParse(ethTransaction.gasLimit ?? ''), + nonce: int.tryParse(ethTransaction.nonce ?? ''), + data: (ethTransaction.data != null && ethTransaction.data != '0x') + ? Uint8List.fromList(hex.decode(ethTransaction.data!)) + : null, + ); + + await dotenv.load(); + final infuraApiKey = dotenv.get('INFURA_API_KEY'); + final ethRpcUrl = Urls.infuraBaseUrl + infuraApiKey; + final httpClient = Client(); + + final Web3Client ethClient = Web3Client(ethRpcUrl, httpClient); + + final Uint8List sig = await ethClient.signTransaction( + credentials, + transaction, + ); + + // Sign the transaction + final String signedTx = hex.encode(sig); + + // Return the signed transaction as a hexadecimal string + + walletConnectCubit + .completer[walletConnectCubit.completer.length - 1]! + .complete('0x$signedTx'); + success = true; } else { throw ResponseMessage( ResponseString diff --git a/lib/dashboard/home/tab_bar/tokens/confirm_token_transaction/cubit/confirm_token_transaction_cubit.dart b/lib/dashboard/home/tab_bar/tokens/confirm_token_transaction/cubit/confirm_token_transaction_cubit.dart index ce4230f99..928741dd3 100644 --- a/lib/dashboard/home/tab_bar/tokens/confirm_token_transaction/cubit/confirm_token_transaction_cubit.dart +++ b/lib/dashboard/home/tab_bar/tokens/confirm_token_transaction/cubit/confirm_token_transaction_cubit.dart @@ -30,7 +30,6 @@ class ConfirmTokenTransactionCubit extends Cubit { final logger = getLogger('ConfirmWithdrawal'); Future getXtzUSDPrice() async { - await dotenv.load(); final apiKey = dotenv.get('COIN_GECKO_API_KEY'); @@ -222,7 +221,10 @@ class ConfirmTokenTransactionCubit extends Cubit { } Future prepareTezosOperation( - Keystore keystore, TezartClient client, int transactionAmount) async { + Keystore keystore, + TezartClient client, + int transactionAmount, + ) async { final operationList = OperationsList( source: keystore, publicKey: keystore.publicKey, From 5e4d413c4a8df276ed7f92d0da6a355ee5467e2b Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Fri, 30 Jun 2023 17:07:19 +0545 Subject: [PATCH 06/13] feat: Transaction via walletconnect --- .../cubit/wallet_connect_cubit.dart | 79 ++++- .../cubit/wallet_connect_state.dart | 20 +- .../operation/cubit/operation_cubit.dart | 284 ++++++++++++------ .../operation/view/operation_page.dart | 11 +- .../cubit/sign_payload_cubit.dart | 45 +-- 5 files changed, 286 insertions(+), 153 deletions(-) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 6686a7f75..91f8235c0 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -1,16 +1,19 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:typed_data'; import 'package:altme/app/app.dart'; import 'package:altme/connection_bridge/connection_bridge.dart'; import 'package:altme/wallet/wallet.dart'; import 'package:bloc/bloc.dart'; +import 'package:convert/convert.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:secure_storage/secure_storage.dart'; import 'package:wallet_connect/wallet_connect.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; +import 'package:web3dart/web3dart.dart'; part 'wallet_connect_cubit.g.dart'; part 'wallet_connect_state.dart'; @@ -135,7 +138,7 @@ class WalletConnectCubit extends Cubit { _web3Wallet!.registerRequestHandler( chainId: accounts.blockchainType.chain, method: Parameters.ETH_SEND_TRANSACTION, - handler: ethSignTypedData, + handler: ethSendTransaction, ); } } @@ -261,10 +264,10 @@ class WalletConnectCubit extends Cubit { break; } }, - onEthSendTransaction: (int id, WCEthereumTransaction transaction) { + onEthSendTransaction: (int id, WCEthereumTransaction wcTransaction) { log.i('onEthSendTransaction'); log.i('id: $id'); - log.i('tx: $transaction'); + log.i('tx: $wcTransaction'); log.i('dAppPeerId: $currentPeerId'); log.i('currentDAppPeerMeta: $currentPeerMeta'); emit( @@ -272,7 +275,7 @@ class WalletConnectCubit extends Cubit { signId: id, status: WalletConnectStatus.operation, transactionId: id, - transaction: transaction, + wcTransaction: wcTransaction, currentDappPeerId: currentPeerId, currentDAppPeerMeta: currentPeerMeta, ), @@ -442,11 +445,14 @@ class WalletConnectCubit extends Cubit { log.i('completer initialise'); completer.add(Completer()); + final transaction = getTransaction(parameters); + emit( state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, signType: Parameters.ETH_SIGN_TRANSACTION, + transaction: transaction, ), ); @@ -456,6 +462,71 @@ class WalletConnectCubit extends Cubit { return result; } + Future ethSendTransaction(String topic, dynamic parameters) async { + log.i('received eth send transaction request: $parameters'); + + log.i('completer initialise'); + completer.add(Completer()); + + final transaction = getTransaction(parameters); + + emit( + state.copyWith( + status: WalletConnectStatus.operation, + parameters: parameters, + signType: Parameters.ETH_SIGN_TRANSACTION, + transaction: transaction, + ), + ); + + final String result = await completer[completer.length - 1]!.future; + log.i('complete - $result'); + completer.removeLast(); + return result; + } + + Transaction getTransaction(dynamic parameters) { + final EthereumTransaction ethTransaction = EthereumTransaction.fromJson( + parameters[0] as Map, + ); + + // Construct a transaction from the EthereumTransaction object + final transaction = Transaction( + from: EthereumAddress.fromHex(ethTransaction.from), + to: EthereumAddress.fromHex(ethTransaction.to), + value: EtherAmount.fromBigInt( + EtherUnit.wei, + BigInt.tryParse(ethTransaction.value) ?? BigInt.zero, + ), + gasPrice: ethTransaction.gasPrice != null + ? EtherAmount.fromBigInt( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.gasPrice!) ?? BigInt.zero, + ) + : null, + maxFeePerGas: ethTransaction.maxFeePerGas != null + ? EtherAmount.fromBigInt( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxFeePerGas!) ?? BigInt.zero, + ) + : null, + maxPriorityFeePerGas: ethTransaction.maxPriorityFeePerGas != null + ? EtherAmount.fromBigInt( + EtherUnit.gwei, + BigInt.tryParse(ethTransaction.maxPriorityFeePerGas!) ?? + BigInt.zero, + ) + : null, + maxGas: int.tryParse(ethTransaction.gasLimit ?? ''), + nonce: int.tryParse(ethTransaction.nonce ?? ''), + data: (ethTransaction.data != null && ethTransaction.data != '0x') + ? Uint8List.fromList(hex.decode(ethTransaction.data!)) + : null, + ); + + return transaction; + } + Future ethSignTypedData(String topic, dynamic parameters) async { log.i('received eth sign typed data request: $parameters'); diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index 97e1300cb..02f0ce38e 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -15,12 +15,13 @@ class WalletConnectState extends Equatable { this.signId, this.signMessage, this.transactionId, - this.transaction, + this.wcTransaction, /// v2 this.sessionProposalEvent, this.parameters, this.signType, + this.transaction, }) : wcClients = wcClients ?? []; factory WalletConnectState.fromJson(Map json) => @@ -41,13 +42,15 @@ class WalletConnectState extends Equatable { final WCEthereumSignMessage? signMessage; final int? transactionId; @JsonKey(includeFromJson: false, includeToJson: false) - final WCEthereumTransaction? transaction; - final dynamic parameters; - final String? signType; + final WCEthereumTransaction? wcTransaction; /// v2 @JsonKey(includeFromJson: false, includeToJson: false) final SessionProposalEvent? sessionProposalEvent; + final dynamic parameters; + final String? signType; + @JsonKey(includeFromJson: false, includeToJson: false) + final Transaction? transaction; Map toJson() => _$WalletConnectStateToJson(this); @@ -73,10 +76,11 @@ class WalletConnectState extends Equatable { int? signId, WCEthereumSignMessage? signMessage, int? transactionId, - WCEthereumTransaction? transaction, + WCEthereumTransaction? wcTransaction, SessionProposalEvent? sessionProposalEvent, dynamic parameters, String? signType, + Transaction? transaction, }) { return WalletConnectState( status: status, @@ -90,10 +94,11 @@ class WalletConnectState extends Equatable { signId: signId ?? this.signId, signMessage: signMessage ?? this.signMessage, transactionId: transactionId ?? this.transactionId, - transaction: transaction ?? this.transaction, + wcTransaction: wcTransaction ?? this.wcTransaction, sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, parameters: parameters ?? this.parameters, signType: signType ?? this.signType, + transaction: transaction ?? this.transaction, ); } @@ -109,9 +114,10 @@ class WalletConnectState extends Equatable { signId, signMessage, transactionId, - transaction, + wcTransaction, sessionProposalEvent, parameters, signType, + transaction, ]; } diff --git a/lib/dashboard/connection/operation/cubit/operation_cubit.dart b/lib/dashboard/connection/operation/cubit/operation_cubit.dart index ca42e4ec1..db2cb4f82 100644 --- a/lib/dashboard/connection/operation/cubit/operation_cubit.dart +++ b/lib/dashboard/connection/operation/cubit/operation_cubit.dart @@ -12,7 +12,7 @@ import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:key_generator/key_generator.dart'; import 'package:tezart/tezart.dart'; -import 'package:wallet_connect/wallet_connect.dart'; +//import 'package:wallet_connect/wallet_connect.dart'; import 'package:web3dart/web3dart.dart'; part 'operation_cubit.g.dart'; @@ -43,7 +43,7 @@ class OperationCubit extends Cubit { final log = getLogger('OperationCubit'); - late WCClient? wcClient; + //late WCClient? wcClient; Future initialise(ConnectionBridgeType connectionBridgeType) async { if (isClosed) return; @@ -56,63 +56,83 @@ class OperationCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: final walletConnectState = walletConnectCubit.state; - wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - - log.i('wcClient -$wcClient'); - if (wcClient == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - final List savedDapps = - await connectedDappRepository.findAll(); - - final SavedDappData? dappData = savedDapps.firstWhereOrNull( - (element) { - return element.wcSessionStore != null && - element.wcSessionStore!.session.key == - wcClient!.sessionStore.session.key; - }, - ); - - log.i('dappData -$dappData'); - if (dappData == null) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - if (walletConnectState.transaction!.from != dappData.walletAddress) { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - - final CryptoAccountData? cryptoAccountData = + // wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + + // log.i('wcClient -$wcClient'); + // if (wcClient == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // final List savedDapps = + // await connectedDappRepository.findAll(); + + // final SavedDappData? dappData = savedDapps.firstWhereOrNull( + // (element) { + // return element.wcSessionStore != null && + // element.wcSessionStore!.session.key == + // wcClient!.sessionStore.session.key; + // }, + // ); + + // log.i('dappData -$dappData'); + // if (dappData == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // if (walletConnectState.transaction!.from != dappData.walletAddress) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + + // final CryptoAccountData? cryptoAccountData = + // walletCubit.state.cryptoAccount.data.firstWhereOrNull( + // (element) => + // element.walletAddress == dappData.walletAddress && + // element.blockchainType == dappData.blockchainType, + // ); + + // log.i('cryptoAccountData -$cryptoAccountData'); + // if (cryptoAccountData == null) { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } else { + // emit(state.copyWith(cryptoAccountData: cryptoAccountData)); + // await getUsdPrice(connectionBridgeType); + // } + + final publicKey = walletConnectState.parameters[0]['from'].toString(); + + final CryptoAccountData? currentAccount = walletCubit.state.cryptoAccount.data.firstWhereOrNull( - (element) => - element.walletAddress == dappData.walletAddress && - element.blockchainType == dappData.blockchainType, + (element) => element.walletAddress == publicKey, ); - log.i('cryptoAccountData -$cryptoAccountData'); - if (cryptoAccountData == null) { + log.i('currentAccount -$currentAccount'); + if (currentAccount == null) { throw ResponseMessage( ResponseString .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, ); } else { - emit(state.copyWith(cryptoAccountData: cryptoAccountData)); + emit(state.copyWith(cryptoAccountData: currentAccount)); + await getUsdPrice(connectionBridgeType); } + break; } } catch (e) { @@ -222,31 +242,50 @@ class OperationCubit extends Cubit { 1e6; break; case ConnectionBridgeType.walletconnect: - final WCEthereumTransaction transaction = - walletConnectCubit.state.transaction!; - - late EtherAmount ethAmount; - - if (transaction.value != null) { - ethAmount = EtherAmount.fromBase10String( - EtherUnit.wei, - transaction.value!, - ); - } else { - ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); - } - + // final WCEthereumTransaction transaction = + // walletConnectCubit.state.wcTransaction!; + + // late EtherAmount ethAmount; + + // if (transaction.value != null) { + // ethAmount = EtherAmount.fromBase10String( + // EtherUnit.wei, + // transaction.value!, + // ); + // } else { + // ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); + // } + + // amount = MWeb3Client.formatEthAmount(amount: ethAmount.getInWei); + + // final String web3RpcURL = await web3RpcMainnetInfuraURL(); + + // final feeData = await MWeb3Client.estimateEthereumFee( + // web3RpcURL: web3RpcURL, + // sender: EthereumAddress.fromHex(transaction.from), + // reciever: EthereumAddress.fromHex(transaction.to!), + // amount: ethAmount, + // data: transaction.data, + // ); + // fee = MWeb3Client.formatEthAmount(amount: feeData); + + final EtherAmount ethAmount = + walletConnectCubit.state.transaction!.value!; amount = MWeb3Client.formatEthAmount(amount: ethAmount.getInWei); final String web3RpcURL = await web3RpcMainnetInfuraURL(); + log.i('web3RpcURL - $web3RpcURL'); final feeData = await MWeb3Client.estimateEthereumFee( web3RpcURL: web3RpcURL, - sender: EthereumAddress.fromHex(transaction.from), - reciever: EthereumAddress.fromHex(transaction.to!), + sender: walletConnectCubit.state.transaction!.from!, + reciever: walletConnectCubit.state.transaction!.to!, amount: ethAmount, - data: transaction.data, + data: walletConnectCubit.state.transaction?.data == null + ? null + : utf8.decode(walletConnectCubit.state.transaction!.data!), ); + fee = MWeb3Client.formatEthAmount(amount: feeData); break; } @@ -370,22 +409,65 @@ class OperationCubit extends Cubit { success = json.decode(response['success'].toString()) as bool; break; case ConnectionBridgeType.walletconnect: + // final CryptoAccountData transactionAccountData = + // state.cryptoAccountData!; + + // final WCEthereumTransaction transaction = + // walletConnectCubit.state.wcTransaction!; + + // late EtherAmount ethAmount; + + // if (transaction.value != null) { + // ethAmount = EtherAmount.fromBase10String( + // EtherUnit.wei, + // transaction.value!, + // ); + // } else { + // ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); + // } + + // late String rpcUrl; + + // switch (transactionAccountData.blockchainType) { + // case BlockchainType.tezos: + // throw Exception(); + // case BlockchainType.ethereum: + // rpcUrl = await web3RpcMainnetInfuraURL(); + // break; + // case BlockchainType.fantom: + // rpcUrl = FantomNetwork.mainNet().rpcNodeUrl; + // break; + // case BlockchainType.polygon: + // rpcUrl = PolygonNetwork.mainNet().rpcNodeUrl; + // break; + // case BlockchainType.binance: + // rpcUrl = BinanceNetwork.mainNet().rpcNodeUrl; + // break; + // } + + // log.i('rpcUrl - $rpcUrl'); + + // final String transactionHash = + // await MWeb3Client.sendEthereumTransaction( + // chainId: transactionAccountData.blockchainType.chainId, + // web3RpcURL: rpcUrl, + // privateKey: transactionAccountData.secretKey, + // sender: EthereumAddress.fromHex(transaction.from), + // reciever: EthereumAddress.fromHex(transaction.to!), + // amount: ethAmount, + // data: transaction.data, + // ); + + // wcClient!.approveRequest( + // id: walletConnectCubit.state.transactionId!, + // result: transactionHash, + // ); + final CryptoAccountData transactionAccountData = state.cryptoAccountData!; - final WCEthereumTransaction transaction = - walletConnectCubit.state.transaction!; - - late EtherAmount ethAmount; - - if (transaction.value != null) { - ethAmount = EtherAmount.fromBase10String( - EtherUnit.wei, - transaction.value!, - ); - } else { - ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); - } + final EtherAmount ethAmount = + walletConnectCubit.state.transaction!.value!; late String rpcUrl; @@ -413,16 +495,17 @@ class OperationCubit extends Cubit { chainId: transactionAccountData.blockchainType.chainId, web3RpcURL: rpcUrl, privateKey: transactionAccountData.secretKey, - sender: EthereumAddress.fromHex(transaction.from), - reciever: EthereumAddress.fromHex(transaction.to!), + sender: walletConnectCubit.state.transaction!.from!, + reciever: walletConnectCubit.state.transaction!.to!, amount: ethAmount, - data: transaction.data, + data: walletConnectCubit.state.transaction?.data == null + ? null + : utf8.decode(walletConnectCubit.state.transaction!.data!), ); - wcClient!.approveRequest( - id: walletConnectCubit.state.transactionId!, - result: transactionHash, - ); + walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! + .complete(transactionHash); + success = true; success = true; break; @@ -479,6 +562,11 @@ class OperationCubit extends Cubit { ), ); } + + if (connectionBridgeType == ConnectionBridgeType.walletconnect) { + walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! + .complete('Failed'); + } } } @@ -494,17 +582,19 @@ class OperationCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: log.i('walletconnect connection rejected'); - final walletConnectState = walletConnectCubit.state; - - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - - if (wcClient != null) { - wcClient.rejectRequest(id: walletConnectState.transactionId!); - } + // final walletConnectState = walletConnectCubit.state; + + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + + // if (wcClient != null) { + // wcClient.rejectRequest(id: walletConnectState.transactionId!); + // } + walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! + .complete('Failed'); break; } diff --git a/lib/dashboard/connection/operation/view/operation_page.dart b/lib/dashboard/connection/operation/view/operation_page.dart index 670dc6e2d..06115b6d4 100644 --- a/lib/dashboard/connection/operation/view/operation_page.dart +++ b/lib/dashboard/connection/operation/view/operation_page.dart @@ -125,10 +125,15 @@ class _OperationViewState extends State { break; case ConnectionBridgeType.walletconnect: - dAppName = walletConnectState.currentDAppPeerMeta!.name; + // dAppName = walletConnectState.currentDAppPeerMeta?.name ?? ''; + // symbol = state.cryptoAccountData?.blockchainType.symbol; + // sender = walletConnectState.wcTransaction!.from; + // reciever = walletConnectState.wcTransaction!.to ?? ''; + + dAppName = walletConnectState.currentDAppPeerMeta?.name ?? '--'; symbol = state.cryptoAccountData?.blockchainType.symbol; - sender = walletConnectState.transaction!.from; - reciever = walletConnectState.transaction!.to ?? ''; + sender = walletConnectState.transaction!.from!.toString(); + reciever = walletConnectState.transaction!.to!.toString(); break; } diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index 5560c8831..5f869de1c 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -301,7 +301,8 @@ class SignPayloadCubit extends Cubit { final CryptoAccountData? currentAccount = walletCubit.state.cryptoAccount.data.firstWhereOrNull( - (element) => element.walletAddress == publicKey); + (element) => element.walletAddress == publicKey, + ); log.i('currentAccount -$currentAccount'); if (currentAccount == null) { @@ -341,46 +342,6 @@ class SignPayloadCubit extends Cubit { success = true; } else if (walletConnectCubit.state.signType == Parameters.ETH_SIGN_TRANSACTION) { - final EthereumTransaction ethTransaction = - EthereumTransaction.fromJson( - walletConnectCubit.state.parameters[0] as Map, - ); - - // Construct a transaction from the EthereumTransaction object - final transaction = Transaction( - from: EthereumAddress.fromHex(ethTransaction.from), - to: EthereumAddress.fromHex(ethTransaction.to), - value: EtherAmount.fromUnitAndValue( - EtherUnit.wei, - BigInt.tryParse(ethTransaction.value) ?? BigInt.zero, - ), - gasPrice: ethTransaction.gasPrice != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.gasPrice!) ?? BigInt.zero, - ) - : null, - maxFeePerGas: ethTransaction.maxFeePerGas != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.maxFeePerGas!) ?? - BigInt.zero, - ) - : null, - maxPriorityFeePerGas: ethTransaction.maxPriorityFeePerGas != null - ? EtherAmount.fromUnitAndValue( - EtherUnit.gwei, - BigInt.tryParse(ethTransaction.maxPriorityFeePerGas!) ?? - BigInt.zero, - ) - : null, - maxGas: int.tryParse(ethTransaction.gasLimit ?? ''), - nonce: int.tryParse(ethTransaction.nonce ?? ''), - data: (ethTransaction.data != null && ethTransaction.data != '0x') - ? Uint8List.fromList(hex.decode(ethTransaction.data!)) - : null, - ); - await dotenv.load(); final infuraApiKey = dotenv.get('INFURA_API_KEY'); final ethRpcUrl = Urls.infuraBaseUrl + infuraApiKey; @@ -390,7 +351,7 @@ class SignPayloadCubit extends Cubit { final Uint8List sig = await ethClient.signTransaction( credentials, - transaction, + walletConnectCubit.state.transaction!, ); // Sign the transaction From 7e9925deaae235329c300513a77027e4b3e5edf7 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Mon, 3 Jul 2023 16:58:56 +0545 Subject: [PATCH 07/13] feat: Adding account to connect to walletconnect instantly --- .../enum/status/credentials_status.dart | 1 + lib/app/view/app.dart | 1 + .../cubit/wallet_connect_cubit.dart | 16 +++++++---- lib/credentials/cubit/credentials_cubit.dart | 3 +- .../cubit/create_account_cubit.dart | 1 + .../view/confirm_connection_page.dart | 22 ++++++++------- .../operation/cubit/operation_cubit.dart | 1 - lib/splash/bloclisteners/blocklisteners.dart | 4 +++ lib/wallet/cubit/wallet_cubit.dart | 28 ++++++++++++++++--- 9 files changed, 56 insertions(+), 21 deletions(-) diff --git a/lib/app/shared/enum/status/credentials_status.dart b/lib/app/shared/enum/status/credentials_status.dart index 40f4cd28c..24223593e 100644 --- a/lib/app/shared/enum/status/credentials_status.dart +++ b/lib/app/shared/enum/status/credentials_status.dart @@ -1,5 +1,6 @@ enum CredentialsStatus { init, + idle, populate, loading, insert, diff --git a/lib/app/view/app.dart b/lib/app/view/app.dart index 3697f1568..0148c7dba 100644 --- a/lib/app/view/app.dart +++ b/lib/app/view/app.dart @@ -126,6 +126,7 @@ class App extends StatelessWidget { homeCubit: context.read(), keyGenerator: KeyGenerator(), credentialsCubit: context.read(), + walletConnectCubit: context.read(), ), ), BlocProvider( diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 91f8235c0..d2a83c9d6 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -37,6 +37,7 @@ class WalletConnectCubit extends Cubit { Future initialise() async { try { + _web3Wallet = null; //log.i('initialise'); // final List savedDapps = // await connectedDappRepository.findAll(); @@ -100,11 +101,6 @@ class WalletConnectCubit extends Cubit { for (final accounts in eVMAccounts) { log.i(accounts.blockchainType); - log.i('registerAccount'); - _web3Wallet!.registerAccount( - chainId: accounts.blockchainType.chain, - accountAddress: accounts.walletAddress, - ); log.i('registerEventEmitter'); for (final String event in events) { @@ -114,6 +110,8 @@ class WalletConnectCubit extends Cubit { ); } + registerAccount(accounts); + log.i('registerRequestHandler'); _web3Wallet!.registerRequestHandler( chainId: accounts.blockchainType.chain, @@ -168,6 +166,14 @@ class WalletConnectCubit extends Cubit { } } + void registerAccount(CryptoAccountData cryptoAccountData) { + log.i('registerAccount - $cryptoAccountData'); + _web3Wallet!.registerAccount( + chainId: cryptoAccountData.blockchainType.chain, + accountAddress: cryptoAccountData.walletAddress, + ); + } + Future connect(String walletConnectUri) async { log.i('walletConnectUri - $walletConnectUri'); // final WCSession session = WCSession.from(walletConnectUri); diff --git a/lib/credentials/cubit/credentials_cubit.dart b/lib/credentials/cubit/credentials_cubit.dart index 3162bb96d..b73cab9a8 100644 --- a/lib/credentials/cubit/credentials_cubit.dart +++ b/lib/credentials/cubit/credentials_cubit.dart @@ -167,6 +167,7 @@ class CredentialsCubit extends Cubit { Future insertCredential({ required CredentialModel credential, bool showMessage = true, + bool showStatus = true, }) async { late final List credentials; @@ -197,7 +198,7 @@ class CredentialsCubit extends Cubit { emit( state.copyWith( - status: CredentialsStatus.insert, + status: showStatus ? CredentialsStatus.insert : CredentialsStatus.idle, credentials: credentials, dummyCredentials: dummies, messageHandler: showMessage diff --git a/lib/dashboard/add_account/create_account/cubit/create_account_cubit.dart b/lib/dashboard/add_account/create_account/cubit/create_account_cubit.dart index e3fa46c16..3662ff2d3 100644 --- a/lib/dashboard/add_account/create_account/cubit/create_account_cubit.dart +++ b/lib/dashboard/add_account/create_account/cubit/create_account_cubit.dart @@ -30,6 +30,7 @@ class CreateAccountCubit extends Cubit { mnemonicOrKey: ssiMnemonic!, blockchainType: blockChaintype, isFromOnboarding: false, + showStatus: false, onComplete: ({ required CryptoAccount cryptoAccount, required MessageHandler messageHandler, diff --git a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart index c51c2e559..e6e115d2d 100644 --- a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart +++ b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart @@ -222,20 +222,22 @@ class ConfirmConnectionView extends StatelessWidget { children: [ BlocBuilder( builder: (context, walletState) { + if (connectionBridgeType == ConnectionBridgeType.beacon && + walletState.currentAccount!.blockchainType + .connectionBridge != + connectionBridgeType) { + return Container(); + } + return MyGradientButton( verticalSpacing: 15, borderRadius: Sizes.normalRadius, text: l10n.connect, - onPressed: walletState.currentAccount!.blockchainType - .connectionBridge != - connectionBridgeType - ? null - : () { - context.read().connect( - connectionBridgeType: - connectionBridgeType, - ); - }, + onPressed: () { + context.read().connect( + connectionBridgeType: connectionBridgeType, + ); + }, ); }, ), diff --git a/lib/dashboard/connection/operation/cubit/operation_cubit.dart b/lib/dashboard/connection/operation/cubit/operation_cubit.dart index db2cb4f82..940febaf7 100644 --- a/lib/dashboard/connection/operation/cubit/operation_cubit.dart +++ b/lib/dashboard/connection/operation/cubit/operation_cubit.dart @@ -507,7 +507,6 @@ class OperationCubit extends Cubit { .complete(transactionHash); success = true; - success = true; break; } diff --git a/lib/splash/bloclisteners/blocklisteners.dart b/lib/splash/bloclisteners/blocklisteners.dart index f0b9f0339..e2b627277 100644 --- a/lib/splash/bloclisteners/blocklisteners.dart +++ b/lib/splash/bloclisteners/blocklisteners.dart @@ -66,6 +66,10 @@ final walletBlocListener = BlocListener( final credentialsBlocListener = BlocListener( listener: (BuildContext context, CredentialsState state) async { + if (state.status == CredentialsStatus.idle) { + return; + } + if (state.status == CredentialsStatus.loading) { LoadingView().show(context: context); } else { diff --git a/lib/wallet/cubit/wallet_cubit.dart b/lib/wallet/cubit/wallet_cubit.dart index 17a2f82f7..719d833bf 100644 --- a/lib/wallet/cubit/wallet_cubit.dart +++ b/lib/wallet/cubit/wallet_cubit.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import 'package:altme/app/app.dart'; +import 'package:altme/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart'; import 'package:altme/credentials/credentials.dart'; import 'package:altme/dashboard/dashboard.dart'; import 'package:altme/wallet/wallet.dart'; @@ -22,12 +23,14 @@ class WalletCubit extends Cubit { required this.homeCubit, required this.keyGenerator, required this.credentialsCubit, + required this.walletConnectCubit, }) : super(const WalletState()); final SecureStorageProvider secureStorageProvider; final HomeCubit homeCubit; final KeyGenerator keyGenerator; final CredentialsCubit credentialsCubit; + WalletConnectCubit walletConnectCubit; final log = getLogger('WalletCubit'); @@ -51,11 +54,11 @@ class WalletCubit extends Cubit { required bool isImported, required bool isFromOnboarding, BlockchainType? blockchainType, + bool showStatus = true, void Function({ required CryptoAccount cryptoAccount, required MessageHandler messageHandler, - })? - onComplete, + })? onComplete, }) async { if (isFromOnboarding) { final String? ssiKey = @@ -113,6 +116,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: blockchainType, totalAccountsYet: accountsCount, + showStatus: showStatus, ), ); } else { @@ -135,6 +139,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.tezos, totalAccountsYet: accountsCount, + showStatus: showStatus, ), ); } else { @@ -147,6 +152,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.fantom, totalAccountsYet: accountsCount, + showStatus: showStatus, ), ); cryptoAccountDataList.add( @@ -157,6 +163,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.polygon, totalAccountsYet: accountsCount + 1, + showStatus: showStatus, ), ); cryptoAccountDataList.add( @@ -167,6 +174,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.binance, totalAccountsYet: accountsCount + 2, + showStatus: showStatus, ), ); cryptoAccountDataList.add( @@ -177,6 +185,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.ethereum, totalAccountsYet: accountsCount + 3, + showStatus: showStatus, ), ); } @@ -190,6 +199,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.polygon, totalAccountsYet: accountsCount, + showStatus: showStatus, ), ); @@ -202,6 +212,7 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.binance, totalAccountsYet: accountsCount + 1, + showStatus: showStatus, ), ); @@ -214,15 +225,19 @@ class WalletCubit extends Cubit { isSecretKey: isSecretKey, blockchainType: BlockchainType.tezos, totalAccountsYet: accountsCount + 2, + showStatus: showStatus, ), ); } } + final updatedCryptoAccount = CryptoAccount(data: cryptoAccountDataList); await _saveCryptoAccountDataInStorage(updatedCryptoAccount); - /// set new account as current - await setCurrentWalletAccount(cryptoAccountDataList.length - 1); + if (blockchainType != BlockchainType.tezos) { + await Future.delayed(const Duration(milliseconds: 500)); + await walletConnectCubit.initialise(); + } emitCryptoAccount(updatedCryptoAccount); @@ -232,6 +247,9 @@ class WalletCubit extends Cubit { ResponseString.RESPONSE_STRING_CRYPTO_ACCOUNT_ADDED, ), ); + + /// set new account as current + await setCurrentWalletAccount(cryptoAccountDataList.length - 1); } Future _createBlockchainAccount({ @@ -241,6 +259,7 @@ class WalletCubit extends Cubit { required bool isSecretKey, required BlockchainType blockchainType, required int totalAccountsYet, + required bool showStatus, }) async { final AccountType accountType = blockchainType.accountType; @@ -327,6 +346,7 @@ class WalletCubit extends Cubit { await credentialsCubit.insertCredential( credential: credential, showMessage: false, + showStatus: showStatus, ); } From c947d06838c78feb4d6425638c403467f461b0ca Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Mon, 3 Jul 2023 17:04:42 +0545 Subject: [PATCH 08/13] feat: Add disconnect session function call only --- .../wallet_connect/cubit/wallet_connect_cubit.dart | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index d2a83c9d6..3bf3e3df0 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -553,6 +553,14 @@ class WalletConnectCubit extends Cubit { return result; } + Future disconnectSession(PairingInfo pairing) async { + log.i('rdisconnectSession: ${pairing.topic}'); + await _web3Wallet!.disconnectSession( + topic: pairing.topic, + reason: Errors.getSdkError(Errors.USER_DISCONNECTED), + ); + } + Future dispose() async { log.i('web3wallet dispose'); _web3Wallet!.core.pairing.onPairingInvalid.unsubscribe(_onPairingInvalid); From d86d8d32c4bf3ade5c82dce0facf620c5f6226c4 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Tue, 4 Jul 2023 12:28:39 +0545 Subject: [PATCH 09/13] feat: saved paired dApp via wallet connect --- .../model/saved_dapp_data.dart | 25 ++++-- .../repository/connected_dapp_repository.dart | 77 +++++++++++-------- .../cubit/wallet_connect_cubit.dart | 8 +- .../cubit/confirm_connection_cubit.dart | 4 +- 4 files changed, 74 insertions(+), 40 deletions(-) diff --git a/lib/connection_bridge/model/saved_dapp_data.dart b/lib/connection_bridge/model/saved_dapp_data.dart index a6dfe7718..66061ab0e 100644 --- a/lib/connection_bridge/model/saved_dapp_data.dart +++ b/lib/connection_bridge/model/saved_dapp_data.dart @@ -3,6 +3,7 @@ import 'package:beacon_flutter/beacon_flutter.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wallet_connect/wallet_connect.dart'; +import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; part 'saved_dapp_data.g.dart'; @@ -10,22 +11,34 @@ part 'saved_dapp_data.g.dart'; class SavedDappData extends Equatable { const SavedDappData({ this.peer, - required this.walletAddress, - required this.blockchainType, + this.walletAddress, + this.blockchainType, this.wcSessionStore, + + //v2 + this.sessionConnect, }); factory SavedDappData.fromJson(Map json) => _$SavedDappDataFromJson(json); final P2PPeer? peer; - final String walletAddress; - final BlockchainType blockchainType; + final String? walletAddress; + final BlockchainType? blockchainType; final WCSessionStore? wcSessionStore; + //v2 + @JsonKey(includeFromJson: false, includeToJson: false) + final SessionConnect? sessionConnect; + Map toJson() => _$SavedDappDataToJson(this); @override - List get props => - [peer, walletAddress, blockchainType, wcSessionStore]; + List get props => [ + peer, + walletAddress, + blockchainType, + wcSessionStore, + sessionConnect, + ]; } diff --git a/lib/connection_bridge/repository/connected_dapp_repository.dart b/lib/connection_bridge/repository/connected_dapp_repository.dart index f4c14dd04..cefc24394 100644 --- a/lib/connection_bridge/repository/connected_dapp_repository.dart +++ b/lib/connection_bridge/repository/connected_dapp_repository.dart @@ -89,41 +89,56 @@ class ConnectedDappRepository { Future insert(SavedDappData savedDappData) async { final List savedPeerDatas = await findAll(); - final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( - (SavedDappData savedData) { - switch (savedDappData.blockchainType) { - case BlockchainType.ethereum: - case BlockchainType.fantom: - case BlockchainType.polygon: - case BlockchainType.binance: - return savedData.walletAddress == savedDappData.walletAddress && - savedData.wcSessionStore!.remotePeerMeta.name == - savedDappData.wcSessionStore!.remotePeerMeta.name; - case BlockchainType.tezos: - return savedData.walletAddress == savedDappData.walletAddress && - savedData.peer!.name == savedDappData.peer!.name; - } - }, - - /// Note: Assumption - name is always unique - ); - - if (matchedData != null) { - await delete(matchedData); + // final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( + // (SavedDappData savedData) { + // switch (savedDappData.blockchainType) { + // case BlockchainType.ethereum: + // case BlockchainType.fantom: + // case BlockchainType.polygon: + // case BlockchainType.binance: + // return false; + // case BlockchainType.tezos: + // return savedData.walletAddress == savedDappData.walletAddress && + // savedData.peer!.name == savedDappData.peer!.name; + // } + // }, + + // /// Note: Assumption - name is always unique + // ); + + if (savedDappData.blockchainType != null && + savedDappData.blockchainType == BlockchainType.tezos) { + final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( + (SavedDappData savedData) => + savedData.walletAddress == savedDappData.walletAddress && + savedData.peer!.name == savedDappData.peer!.name, + + /// Note: Assumption - name is always unique + ); + if (matchedData != null) { + await delete(matchedData); + } } log.i('saving dapp Data'); late String id; - switch (savedDappData.blockchainType) { - case BlockchainType.ethereum: - case BlockchainType.fantom: - case BlockchainType.polygon: - case BlockchainType.binance: - id = savedDappData.wcSessionStore!.session.topic; - break; - case BlockchainType.tezos: - id = savedDappData.peer!.publicKey; - break; + // switch (savedDappData.blockchainType) { + // case BlockchainType.ethereum: + // case BlockchainType.fantom: + // case BlockchainType.polygon: + // case BlockchainType.binance: + // id = savedDappData.wcSessionStore!.session.topic; + // break; + // case BlockchainType.tezos: + // id = savedDappData.peer!.publicKey; + // break; + // } + + if (savedDappData.blockchainType != null && + savedDappData.blockchainType == BlockchainType.tezos) { + id = savedDappData.peer!.publicKey; + } else { + id = savedDappData.sessionConnect!.session.pairingTopic; } await _secureStorageProvider.set( diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 3bf3e3df0..74892a7dc 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -328,8 +328,12 @@ class WalletConnectCubit extends Cubit { void _onSessionConnect(SessionConnect? args) { if (args != null) { log.i(args); - log.i(args.session); //sessions.value.add(args.session); + + final savedDappData = SavedDappData(sessionConnect: args); + + log.i(savedDappData.toJson()); + unawaited(connectedDappRepository.insert(savedDappData)); } } @@ -554,7 +558,7 @@ class WalletConnectCubit extends Cubit { } Future disconnectSession(PairingInfo pairing) async { - log.i('rdisconnectSession: ${pairing.topic}'); + log.i('disconnectSession: ${pairing.topic}'); await _web3Wallet!.disconnectSession( topic: pairing.topic, reason: Errors.getSdkError(Errors.USER_DISCONNECTED), diff --git a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart index 866a64a7a..0e2c45015 100644 --- a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart +++ b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart @@ -119,7 +119,6 @@ class ConfirmConnectionCubit extends Cubit { // log.i(savedDappData.toJson()); // await connectedDappRepository.insert(savedDappData); - /// v2 final SessionProposalEvent? sessionProposalEvent = walletConnectState.sessionProposalEvent; @@ -128,6 +127,9 @@ class ConfirmConnectionCubit extends Cubit { namespaces: sessionProposalEvent.params.generatedNamespaces!, ); + /// v2 + /// dApp saved onSessionConnect function in wallet connect cubit + break; } emit( From 04076ac1284f954bb6592e4d411e798252fb39a3 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Tue, 4 Jul 2023 14:09:41 +0545 Subject: [PATCH 10/13] feat: Add wallet connect connect dapps andd disconnect --- .../model/saved_dapp_data.dart | 7 +- .../repository/connected_dapp_repository.dart | 41 +++--- .../cubit/wallet_connect_cubit.dart | 10 +- .../cubit/connected_dapps_cubit.dart | 2 + .../view/connected_dapps_page.dart | 6 +- .../connection/rights/cubit/rights_cubit.dart | 129 ++++++++++++------ .../connection/rights/view/rights_page.dart | 4 +- 7 files changed, 125 insertions(+), 74 deletions(-) diff --git a/lib/connection_bridge/model/saved_dapp_data.dart b/lib/connection_bridge/model/saved_dapp_data.dart index 66061ab0e..9c8b87802 100644 --- a/lib/connection_bridge/model/saved_dapp_data.dart +++ b/lib/connection_bridge/model/saved_dapp_data.dart @@ -16,7 +16,7 @@ class SavedDappData extends Equatable { this.wcSessionStore, //v2 - this.sessionConnect, + this.sessionData, }); factory SavedDappData.fromJson(Map json) => @@ -28,8 +28,7 @@ class SavedDappData extends Equatable { final WCSessionStore? wcSessionStore; //v2 - @JsonKey(includeFromJson: false, includeToJson: false) - final SessionConnect? sessionConnect; + final SessionData? sessionData; Map toJson() => _$SavedDappDataToJson(this); @@ -39,6 +38,6 @@ class SavedDappData extends Equatable { walletAddress, blockchainType, wcSessionStore, - sessionConnect, + sessionData, ]; } diff --git a/lib/connection_bridge/repository/connected_dapp_repository.dart b/lib/connection_bridge/repository/connected_dapp_repository.dart index cefc24394..5f5cee64e 100644 --- a/lib/connection_bridge/repository/connected_dapp_repository.dart +++ b/lib/connection_bridge/repository/connected_dapp_repository.dart @@ -64,23 +64,30 @@ class ConnectedDappRepository { Future delete(SavedDappData savedDappData) async { late String id; - switch (savedDappData.blockchainType) { - case BlockchainType.ethereum: - id = savedDappData.wcSessionStore!.session.topic; - break; - case BlockchainType.tezos: - id = savedDappData.peer!.publicKey; - break; - case BlockchainType.fantom: - id = savedDappData.wcSessionStore!.session.topic; - break; - case BlockchainType.polygon: - id = savedDappData.wcSessionStore!.session.topic; - break; - case BlockchainType.binance: - id = savedDappData.wcSessionStore!.session.topic; - break; + + if (savedDappData.blockchainType != null && + savedDappData.blockchainType == BlockchainType.tezos) { + id = savedDappData.peer!.publicKey; + } else { + id = savedDappData.sessionData!.pairingTopic; } + // switch (savedDappData.blockchainType) { + // case BlockchainType.ethereum: + // id = savedDappData.wcSessionStore!.session.topic; + // break; + // case BlockchainType.tezos: + // id = savedDappData.peer!.publicKey; + // break; + // case BlockchainType.fantom: + // id = savedDappData.wcSessionStore!.session.topic; + // break; + // case BlockchainType.polygon: + // id = savedDappData.wcSessionStore!.session.topic; + // break; + // case BlockchainType.binance: + // id = savedDappData.wcSessionStore!.session.topic; + // break; + // } log.i('deleteing dapp data - ${SecureStorageKeys.savedDaaps}/$id'); await _secureStorageProvider.delete('${SecureStorageKeys.savedDaaps}/$id'); return true; @@ -138,7 +145,7 @@ class ConnectedDappRepository { savedDappData.blockchainType == BlockchainType.tezos) { id = savedDappData.peer!.publicKey; } else { - id = savedDappData.sessionConnect!.session.pairingTopic; + id = savedDappData.sessionData!.pairingTopic; } await _secureStorageProvider.set( diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 74892a7dc..1c2799cd1 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -330,10 +330,10 @@ class WalletConnectCubit extends Cubit { log.i(args); //sessions.value.add(args.session); - final savedDappData = SavedDappData(sessionConnect: args); + final savedDappData = SavedDappData(sessionData: args.session); log.i(savedDappData.toJson()); - unawaited(connectedDappRepository.insert(savedDappData)); + connectedDappRepository.insert(savedDappData); } } @@ -557,10 +557,10 @@ class WalletConnectCubit extends Cubit { return result; } - Future disconnectSession(PairingInfo pairing) async { - log.i('disconnectSession: ${pairing.topic}'); + Future disconnectSession(String topic) async { + log.i('disconnectSession: $topic'); await _web3Wallet!.disconnectSession( - topic: pairing.topic, + topic: topic, reason: Errors.getSdkError(Errors.USER_DISCONNECTED), ); } diff --git a/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart b/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart index ba268bed7..a703ac30e 100644 --- a/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart +++ b/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart @@ -115,6 +115,8 @@ class ConnectedDappsCubit extends Cubit { /// display data for selected walletAddress only if (walletAddress == savedData.walletAddress) { peersListToShow.add(savedData); + } else if (savedData.walletAddress == null) { + peersListToShow.add(savedData); } } diff --git a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart index 09b13c6b2..012505202 100644 --- a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart +++ b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart @@ -163,8 +163,10 @@ class _ConnectedDappsViewState extends State { savedDappData.blockchainType == BlockchainType.tezos ? savedDappData.peer!.name - : savedDappData.wcSessionStore! - .remotePeerMeta.name, + : savedDappData.sessionData! + .peer.metadata.name, + // : savedDappData.wcSessionStore! + // .remotePeerMeta.name, style: Theme.of(context) .textTheme .dappName, diff --git a/lib/dashboard/connection/rights/cubit/rights_cubit.dart b/lib/dashboard/connection/rights/cubit/rights_cubit.dart index d40430bc8..968516cbf 100644 --- a/lib/dashboard/connection/rights/cubit/rights_cubit.dart +++ b/lib/dashboard/connection/rights/cubit/rights_cubit.dart @@ -36,25 +36,18 @@ class RightsCubit extends Cubit { ); } - switch (savedDappData.blockchainType) { - case BlockchainType.ethereum: - case BlockchainType.fantom: - case BlockchainType.polygon: - case BlockchainType.binance: - final walletConnectState = walletConnectCubit.state; - final wcClient = walletConnectState.wcClients.firstWhereOrNull( - (element) => - element.remotePeerId == - walletConnectCubit.state.currentDappPeerId, - ); - if (wcClient != null) { - log.i( - '''disconnected - ${savedDappData.wcSessionStore!.remotePeerMeta}''', - ); - wcClient.disconnect(); - //remove from collection - } + if (savedDappData.blockchainType != null && + savedDappData.blockchainType == BlockchainType.tezos) { + final Map response = + await beacon.removePeerUsingPublicKey( + publicKey: savedDappData.peer!.publicKey, + ); + + final bool success = + json.decode(response['success'].toString()) as bool; + if (success) { + log.i('Disconnect success'); await connectedDappRepository.delete(savedDappData); emit( state.copyWith( @@ -64,35 +57,83 @@ class RightsCubit extends Cubit { ), ), ); - break; - case BlockchainType.tezos: - final Map response = - await beacon.removePeerUsingPublicKey( - publicKey: savedDappData.peer!.publicKey, + } else { + throw ResponseMessage( + ResponseString.RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, ); + } + } else { + await walletConnectCubit + .disconnectSession(savedDappData.sessionData!.pairingTopic); - final bool success = - json.decode(response['success'].toString()) as bool; - - if (success) { - log.i('Disconnect success'); - await connectedDappRepository.delete(savedDappData); - emit( - state.copyWith( - appStatus: AppStatus.success, - messageHandler: ResponseMessage( - ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, - ), - ), - ); - } else { - throw ResponseMessage( - ResponseString - .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - ); - } - break; + await connectedDappRepository.delete(savedDappData); + emit( + state.copyWith( + appStatus: AppStatus.success, + messageHandler: ResponseMessage( + ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, + ), + ), + ); } + + // switch (savedDappData.blockchainType) { + // case BlockchainType.ethereum: + // case BlockchainType.fantom: + // case BlockchainType.polygon: + // case BlockchainType.binance: + // final walletConnectState = walletConnectCubit.state; + // final wcClient = walletConnectState.wcClients.firstWhereOrNull( + // (element) => + // element.remotePeerId == + // walletConnectCubit.state.currentDappPeerId, + // ); + // if (wcClient != null) { + // log.i( + // '''disconnected - ${savedDappData.wcSessionStore!.remotePeerMeta}''', + // ); + // wcClient.disconnect(); + // //remove from collection + // } + + // await connectedDappRepository.delete(savedDappData); + // emit( + // state.copyWith( + // appStatus: AppStatus.success, + // messageHandler: ResponseMessage( + // ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, + // ), + // ), + // ); + // break; + // case BlockchainType.tezos: + // final Map response = + // await beacon.removePeerUsingPublicKey( + // publicKey: savedDappData.peer!.publicKey, + // ); + + // final bool success = + // json.decode(response['success'].toString()) as bool; + + // if (success) { + // log.i('Disconnect success'); + // await connectedDappRepository.delete(savedDappData); + // emit( + // state.copyWith( + // appStatus: AppStatus.success, + // messageHandler: ResponseMessage( + // ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, + // ), + // ), + // ); + // } else { + // throw ResponseMessage( + // ResponseString + // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, + // ); + // } + // break; + // } } catch (e, s) { log.e('disconnect failure , e: $e, s: $s'); if (e is MessageHandler) { diff --git a/lib/dashboard/connection/rights/view/rights_page.dart b/lib/dashboard/connection/rights/view/rights_page.dart index a9a9102f7..5c44f86fb 100644 --- a/lib/dashboard/connection/rights/view/rights_page.dart +++ b/lib/dashboard/connection/rights/view/rights_page.dart @@ -85,7 +85,7 @@ class RightsView extends StatelessWidget { Text( savedDappData.peer != null ? savedDappData.peer!.name - : savedDappData.wcSessionStore!.remotePeerMeta.name, + : savedDappData.sessionData!.peer.metadata.name, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), @@ -112,7 +112,7 @@ class RightsView extends StatelessWidget { context: context, title: l10n.revokeAllRights, subtitle: - '''${l10n.revokeSubtitleMessage} on ${savedDappData.peer != null ? savedDappData.peer!.name : savedDappData.wcSessionStore!.remotePeerMeta.name}?''', + '''${l10n.revokeSubtitleMessage} on ${savedDappData.peer != null ? savedDappData.peer!.name : savedDappData.sessionData!.peer.metadata.name}?''', no: l10n.cancel, yes: l10n.revokeAll, onContinueClick: () { From 5dbef6e030cf0f239eed051ac7ad7bc2f16c2a4a Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Tue, 4 Jul 2023 14:21:17 +0545 Subject: [PATCH 11/13] refactor: remove dependency of blockchain type for beacon and wallet connect --- lib/connection_bridge/model/saved_dapp_data.dart | 3 --- .../repository/connected_dapp_repository.dart | 9 +++------ .../cubit/confirm_connection_cubit.dart | 1 - .../connected_dapps/view/connected_dapps_page.dart | 3 +-- lib/dashboard/connection/rights/cubit/rights_cubit.dart | 3 +-- 5 files changed, 5 insertions(+), 14 deletions(-) diff --git a/lib/connection_bridge/model/saved_dapp_data.dart b/lib/connection_bridge/model/saved_dapp_data.dart index 9c8b87802..24b3fb95d 100644 --- a/lib/connection_bridge/model/saved_dapp_data.dart +++ b/lib/connection_bridge/model/saved_dapp_data.dart @@ -12,7 +12,6 @@ class SavedDappData extends Equatable { const SavedDappData({ this.peer, this.walletAddress, - this.blockchainType, this.wcSessionStore, //v2 @@ -24,7 +23,6 @@ class SavedDappData extends Equatable { final P2PPeer? peer; final String? walletAddress; - final BlockchainType? blockchainType; final WCSessionStore? wcSessionStore; //v2 @@ -36,7 +34,6 @@ class SavedDappData extends Equatable { List get props => [ peer, walletAddress, - blockchainType, wcSessionStore, sessionData, ]; diff --git a/lib/connection_bridge/repository/connected_dapp_repository.dart b/lib/connection_bridge/repository/connected_dapp_repository.dart index 5f5cee64e..6bc5e4d23 100644 --- a/lib/connection_bridge/repository/connected_dapp_repository.dart +++ b/lib/connection_bridge/repository/connected_dapp_repository.dart @@ -65,8 +65,7 @@ class ConnectedDappRepository { Future delete(SavedDappData savedDappData) async { late String id; - if (savedDappData.blockchainType != null && - savedDappData.blockchainType == BlockchainType.tezos) { + if (savedDappData.walletAddress != null) { id = savedDappData.peer!.publicKey; } else { id = savedDappData.sessionData!.pairingTopic; @@ -113,8 +112,7 @@ class ConnectedDappRepository { // /// Note: Assumption - name is always unique // ); - if (savedDappData.blockchainType != null && - savedDappData.blockchainType == BlockchainType.tezos) { + if (savedDappData.walletAddress != null) { final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( (SavedDappData savedData) => savedData.walletAddress == savedDappData.walletAddress && @@ -141,8 +139,7 @@ class ConnectedDappRepository { // break; // } - if (savedDappData.blockchainType != null && - savedDappData.blockchainType == BlockchainType.tezos) { + if (savedDappData.walletAddress != null) { id = savedDappData.peer!.publicKey; } else { id = savedDappData.sessionData!.pairingTopic; diff --git a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart index 0e2c45015..895e3ca35 100644 --- a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart +++ b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart @@ -71,7 +71,6 @@ class ConfirmConnectionCubit extends Cubit { final savedPeerData = SavedDappData( peer: beaconCubit.state.beaconRequest!.peer, walletAddress: currentAccount.walletAddress, - blockchainType: BlockchainType.tezos, ); await connectedDappRepository.insert(savedPeerData); } else { diff --git a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart index 012505202..58bd99321 100644 --- a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart +++ b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart @@ -160,8 +160,7 @@ class _ConnectedDappsViewState extends State { children: [ Expanded( child: Text( - savedDappData.blockchainType == - BlockchainType.tezos + savedDappData.walletAddress != null ? savedDappData.peer!.name : savedDappData.sessionData! .peer.metadata.name, diff --git a/lib/dashboard/connection/rights/cubit/rights_cubit.dart b/lib/dashboard/connection/rights/cubit/rights_cubit.dart index 968516cbf..9e261f71d 100644 --- a/lib/dashboard/connection/rights/cubit/rights_cubit.dart +++ b/lib/dashboard/connection/rights/cubit/rights_cubit.dart @@ -36,8 +36,7 @@ class RightsCubit extends Cubit { ); } - if (savedDappData.blockchainType != null && - savedDappData.blockchainType == BlockchainType.tezos) { + if (savedDappData.walletAddress != null) { final Map response = await beacon.removePeerUsingPublicKey( publicKey: savedDappData.peer!.publicKey, From 94df47426cd8986094af6d8eec67d626113e5c50 Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Tue, 4 Jul 2023 14:34:43 +0545 Subject: [PATCH 12/13] refactor: remove walletconnect v1 code --- .../model/ethereum_transaction.dart | 21 ++- .../model/saved_dapp_data.dart | 9 -- .../repository/connected_dapp_repository.dart | 46 +----- .../cubit/wallet_connect_cubit.dart | 145 +---------------- .../cubit/wallet_connect_state.dart | 61 +------ .../cubit/confirm_connection_cubit.dart | 49 ------ .../view/confirm_connection_page.dart | 5 - .../view/connected_dapps_page.dart | 2 - .../operation/cubit/operation_cubit.dart | 150 ------------------ .../operation/view/operation_page.dart | 8 +- .../connection/rights/cubit/rights_cubit.dart | 58 ------- .../cubit/sign_payload_cubit.dart | 106 ------------- .../sign_payload/view/sign_payload_page.dart | 7 +- .../credential_widget/voucher_widget.dart | 4 +- .../tab_bar/nft/widgets/nft_item_shimmer.dart | 4 +- pubspec.lock | 9 -- pubspec.yaml | 4 - 17 files changed, 23 insertions(+), 665 deletions(-) diff --git a/lib/connection_bridge/model/ethereum_transaction.dart b/lib/connection_bridge/model/ethereum_transaction.dart index 9b3e27bfd..4ba5613ca 100644 --- a/lib/connection_bridge/model/ethereum_transaction.dart +++ b/lib/connection_bridge/model/ethereum_transaction.dart @@ -4,17 +4,6 @@ part 'ethereum_transaction.g.dart'; @JsonSerializable(includeIfNull: false) class EthereumTransaction { - final String from; - final String to; - final String value; - final String? nonce; - final String? gasPrice; - final String? maxFeePerGas; - final String? maxPriorityFeePerGas; - final String? gas; - final String? gasLimit; - final String? data; - EthereumTransaction({ required this.from, required this.to, @@ -30,6 +19,16 @@ class EthereumTransaction { factory EthereumTransaction.fromJson(Map json) => _$EthereumTransactionFromJson(json); + final String from; + final String to; + final String value; + final String? nonce; + final String? gasPrice; + final String? maxFeePerGas; + final String? maxPriorityFeePerGas; + final String? gas; + final String? gasLimit; + final String? data; Map toJson() => _$EthereumTransactionToJson(this); diff --git a/lib/connection_bridge/model/saved_dapp_data.dart b/lib/connection_bridge/model/saved_dapp_data.dart index 24b3fb95d..3b4682655 100644 --- a/lib/connection_bridge/model/saved_dapp_data.dart +++ b/lib/connection_bridge/model/saved_dapp_data.dart @@ -1,8 +1,6 @@ -import 'package:altme/app/app.dart'; import 'package:beacon_flutter/beacon_flutter.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; -import 'package:wallet_connect/wallet_connect.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; part 'saved_dapp_data.g.dart'; @@ -12,9 +10,6 @@ class SavedDappData extends Equatable { const SavedDappData({ this.peer, this.walletAddress, - this.wcSessionStore, - - //v2 this.sessionData, }); @@ -23,9 +18,6 @@ class SavedDappData extends Equatable { final P2PPeer? peer; final String? walletAddress; - final WCSessionStore? wcSessionStore; - - //v2 final SessionData? sessionData; Map toJson() => _$SavedDappDataToJson(this); @@ -34,7 +26,6 @@ class SavedDappData extends Equatable { List get props => [ peer, walletAddress, - wcSessionStore, sessionData, ]; } diff --git a/lib/connection_bridge/repository/connected_dapp_repository.dart b/lib/connection_bridge/repository/connected_dapp_repository.dart index 6bc5e4d23..d7a566851 100644 --- a/lib/connection_bridge/repository/connected_dapp_repository.dart +++ b/lib/connection_bridge/repository/connected_dapp_repository.dart @@ -70,23 +70,7 @@ class ConnectedDappRepository { } else { id = savedDappData.sessionData!.pairingTopic; } - // switch (savedDappData.blockchainType) { - // case BlockchainType.ethereum: - // id = savedDappData.wcSessionStore!.session.topic; - // break; - // case BlockchainType.tezos: - // id = savedDappData.peer!.publicKey; - // break; - // case BlockchainType.fantom: - // id = savedDappData.wcSessionStore!.session.topic; - // break; - // case BlockchainType.polygon: - // id = savedDappData.wcSessionStore!.session.topic; - // break; - // case BlockchainType.binance: - // id = savedDappData.wcSessionStore!.session.topic; - // break; - // } + log.i('deleteing dapp data - ${SecureStorageKeys.savedDaaps}/$id'); await _secureStorageProvider.delete('${SecureStorageKeys.savedDaaps}/$id'); return true; @@ -95,23 +79,6 @@ class ConnectedDappRepository { Future insert(SavedDappData savedDappData) async { final List savedPeerDatas = await findAll(); - // final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( - // (SavedDappData savedData) { - // switch (savedDappData.blockchainType) { - // case BlockchainType.ethereum: - // case BlockchainType.fantom: - // case BlockchainType.polygon: - // case BlockchainType.binance: - // return false; - // case BlockchainType.tezos: - // return savedData.walletAddress == savedDappData.walletAddress && - // savedData.peer!.name == savedDappData.peer!.name; - // } - // }, - - // /// Note: Assumption - name is always unique - // ); - if (savedDappData.walletAddress != null) { final SavedDappData? matchedData = savedPeerDatas.firstWhereOrNull( (SavedDappData savedData) => @@ -127,17 +94,6 @@ class ConnectedDappRepository { log.i('saving dapp Data'); late String id; - // switch (savedDappData.blockchainType) { - // case BlockchainType.ethereum: - // case BlockchainType.fantom: - // case BlockchainType.polygon: - // case BlockchainType.binance: - // id = savedDappData.wcSessionStore!.session.topic; - // break; - // case BlockchainType.tezos: - // id = savedDappData.peer!.publicKey; - // break; - // } if (savedDappData.walletAddress != null) { id = savedDappData.peer!.publicKey; diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 1c2799cd1..0e478d823 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -11,7 +11,6 @@ import 'package:equatable/equatable.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:secure_storage/secure_storage.dart'; -import 'package:wallet_connect/wallet_connect.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; import 'package:web3dart/web3dart.dart'; @@ -22,7 +21,7 @@ class WalletConnectCubit extends Cubit { WalletConnectCubit({ required this.connectedDappRepository, required this.secureStorageProvider, - }) : super(WalletConnectState()) { + }) : super(const WalletConnectState()) { initialise(); } @@ -38,33 +37,6 @@ class WalletConnectCubit extends Cubit { Future initialise() async { try { _web3Wallet = null; - //log.i('initialise'); - // final List savedDapps = - // await connectedDappRepository.findAll(); - - // final connectedDapps = List.of(savedDapps).where( - // (element) => element.blockchainType != BlockchainType.tezos, - // ); - - // Await the initialization of the web3wallet - - // final List wcClients = List.empty(growable: true); - // for (final element in connectedDapps) { - // final sessionStore = element.wcSessionStore; - - // final WCClient? wcClient = createWCClient(element.wcSessionStore); - - // await wcClient!.connectFromSessionStore(sessionStore!); - // log.i('sessionStore: ${wcClient.sessionStore.toJson()}'); - // wcClients.add(wcClient); - //} - - // emit( - // state.copyWith( - // status: WalletConnectStatus.idle, - // // wcClients: wcClients, - // ), - // ); final String? savedCryptoAccount = await secureStorageProvider.get(SecureStorageKeys.cryptoAccount); @@ -176,30 +148,7 @@ class WalletConnectCubit extends Cubit { Future connect(String walletConnectUri) async { log.i('walletConnectUri - $walletConnectUri'); - // final WCSession session = WCSession.from(walletConnectUri); - // final WCPeerMeta walletPeerMeta = WCPeerMeta( - // name: 'Altme', - // url: 'https://altme.io', - // description: 'Altme Wallet', - // icons: [], - // ); - - // final WCClient? wcClient = createWCClient(null); - // log.i('wcClient: $wcClient'); - // if (wcClient == null) return; - - // await wcClient.connectNewSession( - // session: session, - // peerMeta: walletPeerMeta, - // ); - - // final wcClients = List.of(state.wcClients)..add(wcClient); - // emit( - // state.copyWith( - // status: WalletConnectStatus.idle, - // wcClients: wcClients, - // ), - // ); + final Uri uriData = Uri.parse(walletConnectUri); final PairingInfo pairingInfo = await _web3Wallet!.pair( uri: uriData, @@ -207,94 +156,6 @@ class WalletConnectCubit extends Cubit { log.i(pairingInfo); } - WCClient? createWCClient(WCSessionStore? sessionStore) { - WCPeerMeta? currentPeerMeta = sessionStore?.remotePeerMeta; - String? currentPeerId = sessionStore?.remotePeerId; - return WCClient( - onConnect: () { - log.i('connected'); - }, - onDisconnect: (code, reason) { - log.i('onDisconnect - code: $code reason: $reason'); - }, - onFailure: (dynamic error) { - log.e('Failed to connect: $error'); - }, - onSessionRequest: (int id, String dAppPeerId, WCPeerMeta dAppPeerMeta) { - log.i('onSessionRequest'); - log.i('id: $id'); - - currentPeerId = dAppPeerId; - currentPeerMeta = dAppPeerMeta; - - log.i('dAppPeerId: $currentPeerId'); - log.i('currentDAppPeerMeta: $currentPeerMeta'); - emit( - state.copyWith( - sessionId: id, - status: WalletConnectStatus.permission, - currentDappPeerId: dAppPeerId, - currentDAppPeerMeta: currentPeerMeta, - ), - ); - }, - onEthSign: (int id, WCEthereumSignMessage message) { - log.i('onEthSign'); - log.i('id: $id'); - //log.i('message: ${message.raw}'); - log.i('data: ${message.data}'); - log.i('type: ${message.type}'); - log.i('dAppPeerId: $currentPeerId'); - log.i('currentDAppPeerMeta: $currentPeerMeta'); - - switch (message.type) { - case WCSignType.MESSAGE: - case WCSignType.TYPED_MESSAGE: - final wcClient = state.wcClients.firstWhereOrNull( - (element) => element.remotePeerId == currentPeerId, - ); - if (wcClient != null) { - wcClient.rejectRequest(id: id); - } - break; - case WCSignType.PERSONAL_MESSAGE: - emit( - state.copyWith( - signId: id, - status: WalletConnectStatus.signPayload, - signMessage: message, - currentDappPeerId: currentPeerId, - currentDAppPeerMeta: currentPeerMeta, - ), - ); - break; - } - }, - onEthSendTransaction: (int id, WCEthereumTransaction wcTransaction) { - log.i('onEthSendTransaction'); - log.i('id: $id'); - log.i('tx: $wcTransaction'); - log.i('dAppPeerId: $currentPeerId'); - log.i('currentDAppPeerMeta: $currentPeerMeta'); - emit( - state.copyWith( - signId: id, - status: WalletConnectStatus.operation, - transactionId: id, - wcTransaction: wcTransaction, - currentDappPeerId: currentPeerId, - currentDAppPeerMeta: currentPeerMeta, - ), - ); - }, - onEthSignTransaction: (id, tx) { - log.i('onEthSignTransaction'); - log.i('id: $id'); - log.i('tx: $tx'); - }, - ); - } - void _onPairingInvalid(PairingInvalidEvent? args) { log.i('Pairing Invalid Event: $args'); } @@ -343,7 +204,7 @@ class WalletConnectCubit extends Cubit { Future _onAuthRequest(AuthRequest? args) async { if (args != null) { - print(args); + log.i(args); // List chainKeys = GetIt.I().getKeysForChain( // 'eip155:1', // ); diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index 02f0ce38e..872d04f41 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -2,49 +2,20 @@ part of 'wallet_connect_cubit.dart'; @JsonSerializable() class WalletConnectState extends Equatable { - WalletConnectState({ + const WalletConnectState({ this.status = WalletConnectStatus.init, this.message, - - /// v1 - this.isWalletConnectStarted = false, - this.sessionId, - List? wcClients, - this.currentDappPeerId, - this.currentDAppPeerMeta, - this.signId, - this.signMessage, - this.transactionId, - this.wcTransaction, - - /// v2 this.sessionProposalEvent, this.parameters, this.signType, this.transaction, - }) : wcClients = wcClients ?? []; + }); factory WalletConnectState.fromJson(Map json) => _$WalletConnectStateFromJson(json); final WalletConnectStatus? status; final StateMessage? message; - - /// v1 - final bool isWalletConnectStarted; - final int? sessionId; - final String? currentDappPeerId; - final WCPeerMeta? currentDAppPeerMeta; - @JsonKey(includeFromJson: false, includeToJson: false) - final List wcClients; - final int? signId; - @JsonKey(includeFromJson: false, includeToJson: false) - final WCEthereumSignMessage? signMessage; - final int? transactionId; - @JsonKey(includeFromJson: false, includeToJson: false) - final WCEthereumTransaction? wcTransaction; - - /// v2 @JsonKey(includeFromJson: false, includeToJson: false) final SessionProposalEvent? sessionProposalEvent; final dynamic parameters; @@ -68,15 +39,6 @@ class WalletConnectState extends Equatable { WalletConnectState copyWith({ WalletConnectStatus status = WalletConnectStatus.idle, StateMessage? message, - bool? isWalletConnectStarted, - int? sessionId, - String? currentDappPeerId, - WCPeerMeta? currentDAppPeerMeta, - List? wcClients, - int? signId, - WCEthereumSignMessage? signMessage, - int? transactionId, - WCEthereumTransaction? wcTransaction, SessionProposalEvent? sessionProposalEvent, dynamic parameters, String? signType, @@ -85,16 +47,6 @@ class WalletConnectState extends Equatable { return WalletConnectState( status: status, message: message, - isWalletConnectStarted: - isWalletConnectStarted ?? this.isWalletConnectStarted, - currentDAppPeerMeta: currentDAppPeerMeta ?? this.currentDAppPeerMeta, - currentDappPeerId: currentDappPeerId ?? this.currentDappPeerId, - sessionId: sessionId ?? this.sessionId, - wcClients: wcClients ?? this.wcClients, - signId: signId ?? this.signId, - signMessage: signMessage ?? this.signMessage, - transactionId: transactionId ?? this.transactionId, - wcTransaction: wcTransaction ?? this.wcTransaction, sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, parameters: parameters ?? this.parameters, signType: signType ?? this.signType, @@ -106,15 +58,6 @@ class WalletConnectState extends Equatable { List get props => [ status, message, - isWalletConnectStarted, - sessionId, - currentDappPeerId, - currentDAppPeerMeta, - wcClients, - signId, - signMessage, - transactionId, - wcTransaction, sessionProposalEvent, parameters, signType, diff --git a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart index 895e3ca35..227f70b80 100644 --- a/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart +++ b/lib/dashboard/connection/confirm_connection/cubit/confirm_connection_cubit.dart @@ -8,7 +8,6 @@ import 'package:bloc/bloc.dart'; import 'package:dartez/dartez.dart'; import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; -import 'package:wallet_connect/wallet_connect.dart'; import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; part 'confirm_connection_cubit.g.dart'; @@ -80,43 +79,7 @@ class ConfirmConnectionCubit extends Cubit { } break; case ConnectionBridgeType.walletconnect: - // final List walletAddresses = [currentAccount.walletAddress]; - final walletConnectState = walletConnectCubit.state; - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - // if (wcClient == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // wcClient.approveSession( - // accounts: walletAddresses, - // chainId: currentAccount.blockchainType.chainId, - // ); - - // log.i('Connected to walletconnect'); - - // final savedDappData = SavedDappData( - // walletAddress: currentAccount.walletAddress, - // blockchainType: currentAccount.blockchainType, - // wcSessionStore: WCSessionStore( - // session: wcClient.session!, - // peerMeta: wcClient.peerMeta!, - // peerId: wcClient.peerId!, - // remotePeerId: wcClient.remotePeerId!, - // remotePeerMeta: wcClient.remotePeerMeta!, - // chainId: currentAccount.blockchainType.chainId, - // ), - // ); - - // log.i(savedDappData.toJson()); - // await connectedDappRepository.insert(savedDappData); final SessionProposalEvent? sessionProposalEvent = walletConnectState.sessionProposalEvent; @@ -126,7 +89,6 @@ class ConfirmConnectionCubit extends Cubit { namespaces: sessionProposalEvent.params.generatedNamespaces!, ); - /// v2 /// dApp saved onSessionConnect function in wallet connect cubit break; @@ -173,17 +135,6 @@ class ConfirmConnectionCubit extends Cubit { log.i('walletconnect connection rejected'); final walletConnectState = walletConnectCubit.state; - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - - // if (wcClient != null) { - // wcClient.rejectRequest(id: walletConnectState.sessionId!); - // } - - /// v2 final SessionProposalEvent? sessionProposalEvent = walletConnectState.sessionProposalEvent; diff --git a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart index e6e115d2d..e4d2d7495 100644 --- a/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart +++ b/lib/dashboard/connection/confirm_connection/view/confirm_connection_page.dart @@ -119,11 +119,6 @@ class ConfirmConnectionView extends StatelessWidget { .request! .appMetadata! .name! - // : context - // .read() - // .state - // .currentDAppPeerMeta! - // .name, : walletConnectCubit.state.sessionProposalEvent! .params.proposer.metadata.name, textAlign: TextAlign.center, diff --git a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart index 58bd99321..c1c9029be 100644 --- a/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart +++ b/lib/dashboard/connection/connected_dapps/view/connected_dapps_page.dart @@ -164,8 +164,6 @@ class _ConnectedDappsViewState extends State { ? savedDappData.peer!.name : savedDappData.sessionData! .peer.metadata.name, - // : savedDappData.wcSessionStore! - // .remotePeerMeta.name, style: Theme.of(context) .textTheme .dappName, diff --git a/lib/dashboard/connection/operation/cubit/operation_cubit.dart b/lib/dashboard/connection/operation/cubit/operation_cubit.dart index 940febaf7..887b77efa 100644 --- a/lib/dashboard/connection/operation/cubit/operation_cubit.dart +++ b/lib/dashboard/connection/operation/cubit/operation_cubit.dart @@ -12,7 +12,6 @@ import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:key_generator/key_generator.dart'; import 'package:tezart/tezart.dart'; -//import 'package:wallet_connect/wallet_connect.dart'; import 'package:web3dart/web3dart.dart'; part 'operation_cubit.g.dart'; @@ -56,63 +55,6 @@ class OperationCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: final walletConnectState = walletConnectCubit.state; - // wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - - // log.i('wcClient -$wcClient'); - // if (wcClient == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // final List savedDapps = - // await connectedDappRepository.findAll(); - - // final SavedDappData? dappData = savedDapps.firstWhereOrNull( - // (element) { - // return element.wcSessionStore != null && - // element.wcSessionStore!.session.key == - // wcClient!.sessionStore.session.key; - // }, - // ); - - // log.i('dappData -$dappData'); - // if (dappData == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // if (walletConnectState.transaction!.from != dappData.walletAddress) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // final CryptoAccountData? cryptoAccountData = - // walletCubit.state.cryptoAccount.data.firstWhereOrNull( - // (element) => - // element.walletAddress == dappData.walletAddress && - // element.blockchainType == dappData.blockchainType, - // ); - - // log.i('cryptoAccountData -$cryptoAccountData'); - // if (cryptoAccountData == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } else { - // emit(state.copyWith(cryptoAccountData: cryptoAccountData)); - // await getUsdPrice(connectionBridgeType); - // } final publicKey = walletConnectState.parameters[0]['from'].toString(); @@ -242,33 +184,6 @@ class OperationCubit extends Cubit { 1e6; break; case ConnectionBridgeType.walletconnect: - // final WCEthereumTransaction transaction = - // walletConnectCubit.state.wcTransaction!; - - // late EtherAmount ethAmount; - - // if (transaction.value != null) { - // ethAmount = EtherAmount.fromBase10String( - // EtherUnit.wei, - // transaction.value!, - // ); - // } else { - // ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); - // } - - // amount = MWeb3Client.formatEthAmount(amount: ethAmount.getInWei); - - // final String web3RpcURL = await web3RpcMainnetInfuraURL(); - - // final feeData = await MWeb3Client.estimateEthereumFee( - // web3RpcURL: web3RpcURL, - // sender: EthereumAddress.fromHex(transaction.from), - // reciever: EthereumAddress.fromHex(transaction.to!), - // amount: ethAmount, - // data: transaction.data, - // ); - // fee = MWeb3Client.formatEthAmount(amount: feeData); - final EtherAmount ethAmount = walletConnectCubit.state.transaction!.value!; amount = MWeb3Client.formatEthAmount(amount: ethAmount.getInWei); @@ -409,60 +324,6 @@ class OperationCubit extends Cubit { success = json.decode(response['success'].toString()) as bool; break; case ConnectionBridgeType.walletconnect: - // final CryptoAccountData transactionAccountData = - // state.cryptoAccountData!; - - // final WCEthereumTransaction transaction = - // walletConnectCubit.state.wcTransaction!; - - // late EtherAmount ethAmount; - - // if (transaction.value != null) { - // ethAmount = EtherAmount.fromBase10String( - // EtherUnit.wei, - // transaction.value!, - // ); - // } else { - // ethAmount = EtherAmount.fromInt(EtherUnit.wei, 0); - // } - - // late String rpcUrl; - - // switch (transactionAccountData.blockchainType) { - // case BlockchainType.tezos: - // throw Exception(); - // case BlockchainType.ethereum: - // rpcUrl = await web3RpcMainnetInfuraURL(); - // break; - // case BlockchainType.fantom: - // rpcUrl = FantomNetwork.mainNet().rpcNodeUrl; - // break; - // case BlockchainType.polygon: - // rpcUrl = PolygonNetwork.mainNet().rpcNodeUrl; - // break; - // case BlockchainType.binance: - // rpcUrl = BinanceNetwork.mainNet().rpcNodeUrl; - // break; - // } - - // log.i('rpcUrl - $rpcUrl'); - - // final String transactionHash = - // await MWeb3Client.sendEthereumTransaction( - // chainId: transactionAccountData.blockchainType.chainId, - // web3RpcURL: rpcUrl, - // privateKey: transactionAccountData.secretKey, - // sender: EthereumAddress.fromHex(transaction.from), - // reciever: EthereumAddress.fromHex(transaction.to!), - // amount: ethAmount, - // data: transaction.data, - // ); - - // wcClient!.approveRequest( - // id: walletConnectCubit.state.transactionId!, - // result: transactionHash, - // ); - final CryptoAccountData transactionAccountData = state.cryptoAccountData!; @@ -581,17 +442,6 @@ class OperationCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: log.i('walletconnect connection rejected'); - // final walletConnectState = walletConnectCubit.state; - - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - - // if (wcClient != null) { - // wcClient.rejectRequest(id: walletConnectState.transactionId!); - // } walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! .complete('Failed'); break; diff --git a/lib/dashboard/connection/operation/view/operation_page.dart b/lib/dashboard/connection/operation/view/operation_page.dart index 06115b6d4..e3bc42307 100644 --- a/lib/dashboard/connection/operation/view/operation_page.dart +++ b/lib/dashboard/connection/operation/view/operation_page.dart @@ -125,12 +125,8 @@ class _OperationViewState extends State { break; case ConnectionBridgeType.walletconnect: - // dAppName = walletConnectState.currentDAppPeerMeta?.name ?? ''; - // symbol = state.cryptoAccountData?.blockchainType.symbol; - // sender = walletConnectState.wcTransaction!.from; - // reciever = walletConnectState.wcTransaction!.to ?? ''; - - dAppName = walletConnectState.currentDAppPeerMeta?.name ?? '--'; + // TODO(bibash): add name + dAppName = '--'; symbol = state.cryptoAccountData?.blockchainType.symbol; sender = walletConnectState.transaction!.from!.toString(); reciever = walletConnectState.transaction!.to!.toString(); diff --git a/lib/dashboard/connection/rights/cubit/rights_cubit.dart b/lib/dashboard/connection/rights/cubit/rights_cubit.dart index 9e261f71d..9d1213e09 100644 --- a/lib/dashboard/connection/rights/cubit/rights_cubit.dart +++ b/lib/dashboard/connection/rights/cubit/rights_cubit.dart @@ -75,64 +75,6 @@ class RightsCubit extends Cubit { ), ); } - - // switch (savedDappData.blockchainType) { - // case BlockchainType.ethereum: - // case BlockchainType.fantom: - // case BlockchainType.polygon: - // case BlockchainType.binance: - // final walletConnectState = walletConnectCubit.state; - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - // if (wcClient != null) { - // log.i( - // '''disconnected - ${savedDappData.wcSessionStore!.remotePeerMeta}''', - // ); - // wcClient.disconnect(); - // //remove from collection - // } - - // await connectedDappRepository.delete(savedDappData); - // emit( - // state.copyWith( - // appStatus: AppStatus.success, - // messageHandler: ResponseMessage( - // ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, - // ), - // ), - // ); - // break; - // case BlockchainType.tezos: - // final Map response = - // await beacon.removePeerUsingPublicKey( - // publicKey: savedDappData.peer!.publicKey, - // ); - - // final bool success = - // json.decode(response['success'].toString()) as bool; - - // if (success) { - // log.i('Disconnect success'); - // await connectedDappRepository.delete(savedDappData); - // emit( - // state.copyWith( - // appStatus: AppStatus.success, - // messageHandler: ResponseMessage( - // ResponseString.RESPONSE_STRING_DISCONNECTED_FROM_DAPP, - // ), - // ), - // ); - // } else { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - // break; - // } } catch (e, s) { log.e('disconnect failure , e: $e, s: $s'); if (e is MessageHandler) { diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index 5f869de1c..11af3ca37 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -182,102 +182,6 @@ class SignPayloadCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: final walletConnectState = walletConnectCubit.state; - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - - // log.i('wcClient -$wcClient'); - // if (wcClient == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // final List savedDapps = - // await connectedDappRepository.findAll(); - - // final SavedDappData? dappData = savedDapps.firstWhereOrNull( - // (element) { - // return element.wcSessionStore != null && - // element.wcSessionStore!.session.key == - // wcClient.sessionStore.session.key; - // }, - // ); - - // log.i('dappData -$dappData'); - // if (dappData == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // final CryptoAccountData? currentAccount = - // walletCubit.state.cryptoAccount.data.firstWhereOrNull( - // (element) => - // element.walletAddress == dappData.walletAddress && - // element.blockchainType == dappData.blockchainType, - // ); - - // log.i('currentAccount -$currentAccount'); - // // ignore: invariant_booleans - // if (currentAccount == null) { - // throw ResponseMessage( - // ResponseString - // .RESPONSE_STRING_SOMETHING_WENT_WRONG_TRY_AGAIN_LATER, - // ); - // } - - // log.i('type -${walletConnectCubit.state.signMessage!.type}}'); - - // switch (walletConnectCubit.state.signMessage!.type) { - // /// rejected in wallet_connect_cubit - // case WCSignType.MESSAGE: - // break; - - // /// rejected in wallet_connect_cubit - // case WCSignType.TYPED_MESSAGE: - // break; - - // case WCSignType.PERSONAL_MESSAGE: - // const messagePrefix = '\u0019Ethereum Signed Message:\n'; - - // final payloadBytes = hexToBytes(encodedPayload); - - // final prefix = messagePrefix + payloadBytes.length.toString(); - // final prefixBytes = ascii.encode(prefix); - - // final concatPayload = - // Uint8List.fromList(prefixBytes + payloadBytes); - - // final Credentials credentials = - // EthPrivateKey.fromHex(currentAccount.secretKey); - - // final MsgSignature signature = - // credentials.signToEcSignature(concatPayload); - - // final String r = signature.r.toRadixString(16); - // log.i('r -$r'); - // final String s = signature.s.toRadixString(16); - // log.i('s -$s'); - // final String v = signature.v.toRadixString(16); - // log.i('v -$v'); - - // final signedDataAsHex = '0x$r$s$v'; - // log.i('signedDataAsHex -$signedDataAsHex'); - - // wcClient.approveRequest( - // id: walletConnectState.signId!, - // result: signedDataAsHex, - // ); - // success = true; - // break; - // } - - //v2 final String publicKey; @@ -438,17 +342,7 @@ class SignPayloadCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: log.i('walletconnect Signing rejected'); - // final walletConnectState = walletConnectCubit.state; - // final wcClient = walletConnectState.wcClients.firstWhereOrNull( - // (element) => - // element.remotePeerId == - // walletConnectCubit.state.currentDappPeerId, - // ); - - // if (wcClient != null) { - // wcClient.rejectRequest(id: walletConnectState.signId!); - // } walletConnectCubit.completer[walletConnectCubit.completer.length - 1]! .complete('Failed'); break; diff --git a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart index 175cb670f..829cc3e3e 100644 --- a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart +++ b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart @@ -131,12 +131,7 @@ class _SignPayloadViewState extends State { widget.connectionBridgeType == ConnectionBridgeType.beacon ? beaconRequest!.request!.appMetadata!.name! - : context - .read() - .state - .currentDAppPeerMeta - ?.name ?? - '', + : '', // TOOD(bibash): add name textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), diff --git a/lib/dashboard/home/tab_bar/credentials/widgets/credential_widget/voucher_widget.dart b/lib/dashboard/home/tab_bar/credentials/widgets/credential_widget/voucher_widget.dart index 7a417a1f4..4d0b259a2 100644 --- a/lib/dashboard/home/tab_bar/credentials/widgets/credential_widget/voucher_widget.dart +++ b/lib/dashboard/home/tab_bar/credentials/widgets/credential_widget/voucher_widget.dart @@ -12,8 +12,8 @@ class VoucherWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return Column( - children: const [ + return const Column( + children: [ CardAnimation( recto: VoucherRecto(), verso: VoucherVerso(), diff --git a/lib/dashboard/home/tab_bar/nft/widgets/nft_item_shimmer.dart b/lib/dashboard/home/tab_bar/nft/widgets/nft_item_shimmer.dart index b1086949c..a119eabf4 100644 --- a/lib/dashboard/home/tab_bar/nft/widgets/nft_item_shimmer.dart +++ b/lib/dashboard/home/tab_bar/nft/widgets/nft_item_shimmer.dart @@ -10,9 +10,9 @@ class NftItemShimmer extends StatelessWidget { return BackgroundCard( color: Theme.of(context).colorScheme.surfaceContainer, padding: const EdgeInsets.all(10), - child: Column( + child: const Column( crossAxisAlignment: CrossAxisAlignment.start, - children: const [ + children: [ AspectRatio( aspectRatio: 1, child: ShimmerWidget.rectangular(height: 0), diff --git a/pubspec.lock b/pubspec.lock index 7ea4ef6d3..8e96e3fe2 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -2477,15 +2477,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.0.12+1" - wallet_connect: - dependency: "direct main" - description: - path: "." - ref: "5d3003d51ee5afb9911d04d15b6b2aa2f12989c8" - resolved-ref: "5d3003d51ee5afb9911d04d15b6b2aa2f12989c8" - url: "https://github.com/bibash28/wallet-connect-dart.git" - source: git - version: "1.0.4" walletconnect_flutter_v2: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 23733c9e6..201a9338b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -107,10 +107,6 @@ dependencies: url_launcher: ^6.1.11 uuid: ^3.0.7 visibility_detector: ^0.4.0+2 - wallet_connect: - git: - url: https://github.com/bibash28/wallet-connect-dart.git - ref: 5d3003d51ee5afb9911d04d15b6b2aa2f12989c8 walletconnect_flutter_v2: ^2.0.10 webview_flutter: ^4.2.1 webview_flutter_android: ^3.7.1 From 2d81c117ab85f278415fa2e12a661f994d4a385f Mon Sep 17 00:00:00 2001 From: Bibash Shrestha Date: Tue, 4 Jul 2023 17:14:37 +0545 Subject: [PATCH 13/13] feat: Loading app name using topic and saved data --- .../cubit/wallet_connect_cubit.dart | 5 ++ .../cubit/wallet_connect_state.dart | 4 ++ .../cubit/connected_dapps_cubit.dart | 4 +- .../operation/cubit/operation_cubit.dart | 28 +++++++++ .../operation/cubit/operation_state.dart | 19 +++---- .../operation/view/operation_page.dart | 10 +--- .../cubit/sign_payload_cubit.dart | 57 +++++++++++++------ .../cubit/sign_payload_state.dart | 23 ++++---- .../sign_payload/view/sign_payload_page.dart | 7 +-- 9 files changed, 101 insertions(+), 56 deletions(-) diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart index 0e478d823..ff28b31e9 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_cubit.dart @@ -280,6 +280,7 @@ class WalletConnectCubit extends Cubit { state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, + sessionTopic: topic, signType: Parameters.PERSONAL_SIGN, ), ); @@ -300,6 +301,7 @@ class WalletConnectCubit extends Cubit { state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, + sessionTopic: topic, signType: Parameters.ETH_SIGN, ), ); @@ -322,6 +324,7 @@ class WalletConnectCubit extends Cubit { state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, + sessionTopic: topic, signType: Parameters.ETH_SIGN_TRANSACTION, transaction: transaction, ), @@ -345,6 +348,7 @@ class WalletConnectCubit extends Cubit { state.copyWith( status: WalletConnectStatus.operation, parameters: parameters, + sessionTopic: topic, signType: Parameters.ETH_SIGN_TRANSACTION, transaction: transaction, ), @@ -408,6 +412,7 @@ class WalletConnectCubit extends Cubit { state.copyWith( status: WalletConnectStatus.signPayload, parameters: parameters, + sessionTopic: topic, signType: Parameters.ETH_SIGN_TYPE_DATA, ), ); diff --git a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart index 872d04f41..747d694b8 100644 --- a/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart +++ b/lib/connection_bridge/wallet_connect/cubit/wallet_connect_state.dart @@ -5,6 +5,7 @@ class WalletConnectState extends Equatable { const WalletConnectState({ this.status = WalletConnectStatus.init, this.message, + this.sessionTopic, this.sessionProposalEvent, this.parameters, this.signType, @@ -18,6 +19,7 @@ class WalletConnectState extends Equatable { final StateMessage? message; @JsonKey(includeFromJson: false, includeToJson: false) final SessionProposalEvent? sessionProposalEvent; + final String? sessionTopic; final dynamic parameters; final String? signType; @JsonKey(includeFromJson: false, includeToJson: false) @@ -40,6 +42,7 @@ class WalletConnectState extends Equatable { WalletConnectStatus status = WalletConnectStatus.idle, StateMessage? message, SessionProposalEvent? sessionProposalEvent, + String? sessionTopic, dynamic parameters, String? signType, Transaction? transaction, @@ -48,6 +51,7 @@ class WalletConnectState extends Equatable { status: status, message: message, sessionProposalEvent: sessionProposalEvent ?? this.sessionProposalEvent, + sessionTopic: sessionTopic ?? this.sessionTopic, parameters: parameters ?? this.parameters, signType: signType ?? this.signType, transaction: transaction ?? this.transaction, diff --git a/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart b/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart index a703ac30e..f602c6b4c 100644 --- a/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart +++ b/lib/dashboard/connection/connected_dapps/cubit/connected_dapps_cubit.dart @@ -120,9 +120,7 @@ class ConnectedDappsCubit extends Cubit { } } - emit( - state.copyWith(status: AppStatus.idle, savedDapps: peersListToShow), - ); + emit(state.copyWith(status: AppStatus.idle, savedDapps: peersListToShow)); } catch (e) { log.e('getPeers failure , e: $e'); if (e is MessageHandler) { diff --git a/lib/dashboard/connection/operation/cubit/operation_cubit.dart b/lib/dashboard/connection/operation/cubit/operation_cubit.dart index 887b77efa..9b8c72e36 100644 --- a/lib/dashboard/connection/operation/cubit/operation_cubit.dart +++ b/lib/dashboard/connection/operation/cubit/operation_cubit.dart @@ -49,6 +49,34 @@ class OperationCubit extends Cubit { try { emit(state.loading()); + + String dAppName = ''; + switch (connectionBridgeType) { + case ConnectionBridgeType.beacon: + dAppName = + beaconCubit.state.beaconRequest?.request?.appMetadata?.name ?? ''; + break; + case ConnectionBridgeType.walletconnect: + final List savedDapps = + await connectedDappRepository.findAll(); + + final SavedDappData? savedDappData = + savedDapps.firstWhereOrNull((SavedDappData element) { + return walletConnectCubit.state.sessionTopic == + element.sessionData!.topic; + }); + + if (savedDappData != null) { + dAppName = savedDappData.sessionData!.peer.metadata.name; + } + + break; + } + + log.i('dAppName - $dAppName'); + + emit(state.copyWith(dAppName: dAppName)); + switch (connectionBridgeType) { case ConnectionBridgeType.beacon: await getUsdPrice(connectionBridgeType); diff --git a/lib/dashboard/connection/operation/cubit/operation_state.dart b/lib/dashboard/connection/operation/cubit/operation_state.dart index 402fe3c6c..17dc436c6 100644 --- a/lib/dashboard/connection/operation/cubit/operation_state.dart +++ b/lib/dashboard/connection/operation/cubit/operation_state.dart @@ -9,6 +9,7 @@ class OperationState extends Equatable { this.fee = 0, this.usdRate = 0, this.cryptoAccountData, + this.dAppName = '', }); factory OperationState.fromJson(Map json) => @@ -20,27 +21,18 @@ class OperationState extends Equatable { final double fee; final double usdRate; final CryptoAccountData? cryptoAccountData; + final String dAppName; OperationState loading() { - return OperationState( - status: AppStatus.loading, - amount: amount, - fee: fee, - usdRate: usdRate, - cryptoAccountData: cryptoAccountData, - ); + return copyWith(status: AppStatus.loading); } OperationState error({ required MessageHandler messageHandler, }) { - return OperationState( + return copyWith( status: AppStatus.error, message: StateMessage.error(messageHandler: messageHandler), - amount: amount, - fee: fee, - usdRate: usdRate, - cryptoAccountData: cryptoAccountData, ); } @@ -52,6 +44,7 @@ class OperationState extends Equatable { double? usdRate, int? selectedIndex, CryptoAccountData? cryptoAccountData, + String? dAppName, }) { return OperationState( status: status ?? this.status, @@ -60,6 +53,7 @@ class OperationState extends Equatable { fee: fee ?? this.usdRate, usdRate: usdRate ?? this.usdRate, cryptoAccountData: cryptoAccountData ?? this.cryptoAccountData, + dAppName: dAppName ?? this.dAppName, ); } @@ -73,5 +67,6 @@ class OperationState extends Equatable { fee, usdRate, cryptoAccountData, + dAppName, ]; } diff --git a/lib/dashboard/connection/operation/view/operation_page.dart b/lib/dashboard/connection/operation/view/operation_page.dart index e3bc42307..29594c0cc 100644 --- a/lib/dashboard/connection/operation/view/operation_page.dart +++ b/lib/dashboard/connection/operation/view/operation_page.dart @@ -110,7 +110,6 @@ class _OperationViewState extends State { final WalletConnectState walletConnectState = context.read().state; - late String dAppName; late String sender; late String reciever; @@ -118,15 +117,12 @@ class _OperationViewState extends State { switch (widget.connectionBridgeType) { case ConnectionBridgeType.beacon: - dAppName = beaconRequest!.request!.appMetadata!.name!; symbol = 'XTZ'; - sender = beaconRequest.request!.sourceAddress!; + sender = beaconRequest!.request!.sourceAddress!; reciever = beaconRequest.operationDetails!.first.destination!; break; case ConnectionBridgeType.walletconnect: - // TODO(bibash): add name - dAppName = '--'; symbol = state.cryptoAccountData?.blockchainType.symbol; sender = walletConnectState.transaction!.from!.toString(); reciever = walletConnectState.transaction!.to!.toString(); @@ -176,7 +172,7 @@ class _OperationViewState extends State { mainAxisSize: MainAxisSize.max, children: [ Text( - dAppName, + state.dAppName, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ), @@ -202,7 +198,7 @@ class _OperationViewState extends State { SenderReceiver( from: sender, to: reciever, - dAppName: dAppName, + dAppName: state.dAppName, ), const SizedBox(height: Sizes.spaceNormal), Image.asset( diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart index 11af3ca37..6426d24e6 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_cubit.dart @@ -43,9 +43,9 @@ class SignPayloadCubit extends Cubit { late String encodedPayload; SigningType signingType = SigningType.micheline; - void decodeMessage({ + Future init({ required ConnectionBridgeType connectionBridgeType, - }) { + }) async { if (isClosed) return; try { emit(state.loading()); @@ -76,13 +76,6 @@ class SignPayloadCubit extends Cubit { break; case ConnectionBridgeType.walletconnect: - // encodedPayload = walletConnectCubit.state.signMessage!.data!; - // signingType = SigningType.raw; - // final bytes = hexToBytes(encodedPayload); - // payloadMessage = utf8.decode(bytes, allowMalformed: true); - - // v2 - if (walletConnectCubit.state.signType == Parameters.PERSONAL_SIGN) { payloadMessage = getUtf8Message( walletConnectCubit.state.parameters[0] as String, @@ -109,10 +102,36 @@ class SignPayloadCubit extends Cubit { log.i('payloadMessage - $payloadMessage'); + String dAppName = ''; + switch (connectionBridgeType) { + case ConnectionBridgeType.beacon: + dAppName = + beaconCubit.state.beaconRequest?.request?.appMetadata?.name ?? ''; + break; + case ConnectionBridgeType.walletconnect: + final List savedDapps = + await connectedDappRepository.findAll(); + + final SavedDappData? savedDappData = + savedDapps.firstWhereOrNull((SavedDappData element) { + return walletConnectCubit.state.sessionTopic == + element.sessionData!.topic; + }); + + if (savedDappData != null) { + dAppName = savedDappData.sessionData!.peer.metadata.name; + } + + break; + } + + log.i('dAppName - $dAppName'); + emit( state.copyWith( - appStatus: AppStatus.idle, + status: AppStatus.idle, payloadMessage: payloadMessage, + dAppName: dAppName, ), ); } catch (e) { @@ -284,9 +303,11 @@ class SignPayloadCubit extends Cubit { final uri = Uri.parse(url); emit( state.copyWith( - appStatus: AppStatus.success, - messageHandler: ResponseMessage( - ResponseString.RESPONSE_STRING_SUCCESSFULLY_SIGNED_PAYLOAD, + status: AppStatus.success, + message: StateMessage.success( + messageHandler: ResponseMessage( + ResponseString.RESPONSE_STRING_SUCCESSFULLY_SIGNED_PAYLOAD, + ), ), ), ); @@ -294,9 +315,11 @@ class SignPayloadCubit extends Cubit { } else { emit( state.copyWith( - appStatus: AppStatus.success, - messageHandler: ResponseMessage( - ResponseString.RESPONSE_STRING_SUCCESSFULLY_SIGNED_PAYLOAD, + status: AppStatus.success, + message: StateMessage.success( + messageHandler: ResponseMessage( + ResponseString.RESPONSE_STRING_SUCCESSFULLY_SIGNED_PAYLOAD, + ), ), ), ); @@ -347,6 +370,6 @@ class SignPayloadCubit extends Cubit { .complete('Failed'); break; } - emit(state.copyWith(appStatus: AppStatus.goBack)); + emit(state.copyWith(status: AppStatus.goBack)); } } diff --git a/lib/dashboard/connection/sign_payload/cubit/sign_payload_state.dart b/lib/dashboard/connection/sign_payload/cubit/sign_payload_state.dart index 90923686e..dd506b723 100644 --- a/lib/dashboard/connection/sign_payload/cubit/sign_payload_state.dart +++ b/lib/dashboard/connection/sign_payload/cubit/sign_payload_state.dart @@ -6,6 +6,7 @@ class SignPayloadState extends Equatable { this.status = AppStatus.init, this.message, this.payloadMessage, + this.dAppName = '', }); factory SignPayloadState.fromJson(Map json) => @@ -14,35 +15,32 @@ class SignPayloadState extends Equatable { final AppStatus status; final StateMessage? message; final String? payloadMessage; + final String dAppName; SignPayloadState loading() { - return SignPayloadState( - status: AppStatus.loading, - payloadMessage: payloadMessage, - ); + return copyWith(status: AppStatus.loading); } SignPayloadState error({ required MessageHandler messageHandler, }) { - return SignPayloadState( + return copyWith( status: AppStatus.error, message: StateMessage.error(messageHandler: messageHandler), - payloadMessage: payloadMessage, ); } SignPayloadState copyWith({ - AppStatus appStatus = AppStatus.idle, - MessageHandler? messageHandler, + AppStatus status = AppStatus.idle, + StateMessage? message, String? payloadMessage, + String? dAppName, }) { return SignPayloadState( - status: appStatus, - message: messageHandler == null - ? null - : StateMessage.success(messageHandler: messageHandler), + status: status, + message: message, payloadMessage: payloadMessage ?? this.payloadMessage, + dAppName: dAppName ?? this.dAppName, ); } @@ -53,5 +51,6 @@ class SignPayloadState extends Equatable { status, message, payloadMessage, + dAppName, ]; } diff --git a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart index 829cc3e3e..5466be02d 100644 --- a/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart +++ b/lib/dashboard/connection/sign_payload/view/sign_payload_page.dart @@ -64,7 +64,7 @@ class _SignPayloadViewState extends State { void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback( - (_) => context.read().decodeMessage( + (_) => context.read().init( connectionBridgeType: widget.connectionBridgeType, ), ); @@ -128,10 +128,7 @@ class _SignPayloadViewState extends State { mainAxisSize: MainAxisSize.max, children: [ Text( - widget.connectionBridgeType == - ConnectionBridgeType.beacon - ? beaconRequest!.request!.appMetadata!.name! - : '', // TOOD(bibash): add name + state.dAppName, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge, ),