Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chores/fixes and coverage #302

Merged
merged 3 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
.pub/
pubspec.lock
/build/
coverage/

# Web related
lib/generated_plugin_registrant.dart
Expand Down
15 changes: 12 additions & 3 deletions example/wallet/lib/dependencies/chains/common.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,24 @@ class CommonMethods {
}
}

static Future<bool> requestApproval(String text, {String? title}) async {
static Future<bool> requestApproval(
String text, {
String? title,
String? method,
String? chainId,
String? address,
}) async {
final bottomSheetService = GetIt.I<IBottomSheetService>();
final WCBottomSheetResult rs = (await bottomSheetService.queueBottomSheet(
widget: WCRequestWidget(
child: WCConnectionWidget(
title: 'Approve Request',
title: title ?? 'Approve Request',
info: [
WCConnectionModel(
title: title,
title: 'Method: $method\n'
'Chain ID: $chainId\n'
'Address: $address\n\n'
'Message:',
elements: [
text,
],
Expand Down
62 changes: 47 additions & 15 deletions example/wallet/lib/dependencies/chains/evm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,21 @@ class EVMService {
// personal_sign is handled using onSessionRequest event for demo purposes
Future<void> personalSign(String topic, dynamic parameters) async {
debugPrint('[WALLET] personalSign request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last;
final address = EthUtils.getAddressFromSessionRequest(pRequest);
final data = EthUtils.getDataFromSessionRequest(pRequest);
final message = EthUtils.getUtf8Message(data.toString());
var response = JsonRpcResponse(
id: pRequest.id,
jsonrpc: '2.0',
);

if (await CommonMethods.requestApproval(message)) {
if (await CommonMethods.requestApproval(
message,
method: pRequest.method,
chainId: pRequest.chainId,
address: address,
)) {
try {
// Load the private key
final keys = GetIt.I<IKeyService>().getKeysForChain(
Expand Down Expand Up @@ -145,7 +151,7 @@ class EVMService {
Future<void> ethSign(String topic, dynamic parameters) async {
debugPrint('[WALLET] ethSign request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final data = EthUtils.getDataFromSessionRequest(pRequest);
final message = EthUtils.getUtf8Message(data.toString());
var response = JsonRpcResponse(
id: pRequest.id,
Expand Down Expand Up @@ -192,7 +198,7 @@ class EVMService {
Future<void> ethSignTypedData(String topic, dynamic parameters) async {
debugPrint('[WALLET] ethSignTypedData request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final data = EthUtils.getDataFromSessionRequest(pRequest);
var response = JsonRpcResponse(
id: pRequest.id,
jsonrpc: '2.0',
Expand Down Expand Up @@ -234,7 +240,7 @@ class EVMService {
Future<void> ethSignTypedDataV4(String topic, dynamic parameters) async {
debugPrint('[WALLET] ethSignTypedDataV4 request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final data = EthUtils.getDataFromSessionRequest(pRequest);
var response = JsonRpcResponse(
id: pRequest.id,
jsonrpc: '2.0',
Expand Down Expand Up @@ -275,15 +281,21 @@ class EVMService {

Future<void> ethSignTransaction(String topic, dynamic parameters) async {
debugPrint('[WALLET] ethSignTransaction request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getTransactionFromParams(parameters);
final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last;

final data = EthUtils.getTransactionFromSessionRequest(pRequest);
if (data == null) return;

var response = JsonRpcResponse(
id: pRequest.id,
jsonrpc: '2.0',
);

final transaction = await _approveTransaction(data);
final transaction = await _approveTransaction(
data,
method: pRequest.method,
chainId: pRequest.chainId,
);
if (transaction is Transaction) {
try {
// Load the private key
Expand Down Expand Up @@ -329,15 +341,21 @@ class EVMService {

Future<void> ethSendTransaction(String topic, dynamic parameters) async {
debugPrint('[WALLET] ethSendTransaction request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getTransactionFromParams(parameters);
final SessionRequest pRequest = _web3Wallet.pendingRequests.getAll().last;

final data = EthUtils.getTransactionFromSessionRequest(pRequest);
if (data == null) return;

var response = JsonRpcResponse(
id: pRequest.id,
jsonrpc: '2.0',
);

final transaction = await _approveTransaction(data);
final transaction = await _approveTransaction(
data,
method: pRequest.method,
chainId: pRequest.chainId,
);
if (transaction is Transaction) {
try {
// Load the private key
Expand Down Expand Up @@ -430,7 +448,12 @@ class EVMService {
// CommonMethods.goBackToDapp(topic, true);
// }

Future<dynamic> _approveTransaction(Map<String, dynamic> tJson) async {
Future<dynamic> _approveTransaction(
Map<String, dynamic> tJson, {
String? title,
String? method,
String? chainId,
}) async {
Transaction transaction = tJson.toTransaction();

final gasPrice = await ethClient.getGasPrice();
Expand Down Expand Up @@ -480,12 +503,21 @@ class EVMService {
final gweiGasPrice = (transaction.gasPrice?.getInWei ?? BigInt.zero) /
BigInt.from(1000000000);

const encoder = JsonEncoder.withIndent(' ');
final trx = encoder.convert(tJson);
final WCBottomSheetResult rs = (await _bottomSheetService.queueBottomSheet(
widget: WCRequestWidget(
child: WCConnectionWidget(
title: 'Approve Transaction',
title: title ?? 'Approve Transaction',
info: [
WCConnectionModel(elements: [jsonEncode(tJson)]),
WCConnectionModel(
title: 'Method: $method\n'
'Chain ID: $chainId\n\n'
'Transaction:',
elements: [
trx,
],
),
WCConnectionModel(
title: 'Gas price',
elements: ['${gweiGasPrice.toStringAsFixed(2)} GWEI'],
Expand Down
65 changes: 43 additions & 22 deletions example/wallet/lib/pages/apps_page.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import 'package:fl_toast/fl_toast.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
Expand Down Expand Up @@ -215,31 +217,50 @@ class AppsPageState extends State<AppsPage> with GetItStateMixin {
DeepLinkHandler.waiting.value = true;
final Uri uriData = Uri.parse(uri!);
await _web3Wallet.pair(uri: uriData);
} catch (e) {
DeepLinkHandler.waiting.value = false;
showPlatformToast(
child: Container(
padding: const EdgeInsets.all(StyleConstants.linear8),
margin: const EdgeInsets.only(
bottom: StyleConstants.magic40,
),
decoration: BoxDecoration(
color: StyleConstants.errorColor,
borderRadius: BorderRadius.circular(
StyleConstants.linear16,
),
),
child: const Text(
StringConstants.invalidUri,
style: StyleConstants.bodyTextBold,
),
),
// ignore: use_build_context_synchronously
context: context,
);
} on WalletConnectError catch (e) {
_showErrorDialog('${e.code}: ${e.message}');
} on TimeoutException catch (_) {
_showErrorDialog('Time out error. Check your connection.');
}
}

void _showErrorDialog(String message) {
DeepLinkHandler.waiting.value = false;
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text(
'Error',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
content: Text(
message,
style: const TextStyle(
color: Colors.black,
),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Close',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
)
],
);
});
}

void _onListItemTap(PairingInfo pairing) {
Navigator.push(
context,
Expand Down
65 changes: 42 additions & 23 deletions example/wallet/lib/utils/eth_utils.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:convert';

import 'package:convert/convert.dart';
import 'package:flutter/foundation.dart';
import 'package:get_it/get_it.dart';
import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart';
import 'package:walletconnect_flutter_v2_wallet/dependencies/i_web3wallet_service.dart';
Expand All @@ -22,36 +23,54 @@ class EthUtils {
return maybeHex;
}

static dynamic getAddressFromParamsList(dynamic params) {
return (params as List).firstWhere((p) {
try {
if (addressRegEx.hasMatch(p)) {
static String? getAddressFromSessionRequest(SessionRequest request) {
try {
final paramsList = List.from((request.params as List));
if (request.method == 'personal_sign') {
// for `personal_sign` first value in params has to be always the message
paramsList.removeAt(0);
}

return paramsList.firstWhere((p) {
try {
EthereumAddress.fromHex(p);
return true;
} catch (e) {
return false;
}
return false;
} catch (e) {
return false;
}
}, orElse: () => null);
});
} catch (e) {
debugPrint(e.toString());
return null;
}
}

static dynamic getDataFromParamsList(dynamic params) {
final address = getAddressFromParamsList(params);
final param = (params as List).firstWhere(
(p) => p != address,
orElse: () => null,
);
return param;
static dynamic getDataFromSessionRequest(SessionRequest request) {
try {
final paramsList = List.from((request.params as List));
if (request.method == 'personal_sign') {
return paramsList.first;
}
return paramsList.firstWhere((p) {
final address = getAddressFromSessionRequest(request);
return p != address;
});
} catch (e) {
debugPrint(e.toString());
return null;
}
}

static Map<String, dynamic>? getTransactionFromParams(dynamic params) {
final address = getAddressFromParamsList(params);
final param = params.firstWhere(
(p) => p != address,
orElse: () => null,
);
return param as Map<String, dynamic>?;
static Map<String, dynamic>? getTransactionFromSessionRequest(
SessionRequest request,
) {
try {
final param = (request.params as List<dynamic>).first;
return param as Map<String, dynamic>;
} catch (e) {
debugPrint(e.toString());
return null;
}
}

static Future<dynamic> decodeMessageEvent(MessageEvent event) async {
Expand Down
30 changes: 18 additions & 12 deletions lib/apis/core/pairing/pairing.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,19 +194,25 @@ class Pairing implements IPairing {
rethrow;
}

await pairings.set(topic, pairing);
await core.crypto.setSymKey(symKey, overrideTopic: topic);
await core.relayClient.subscribe(topic: topic);
await core.expirer.set(topic, expiry);

onPairingCreate.broadcast(
PairingEvent(
topic: topic,
),
);
try {
await pairings.set(topic, pairing);
await core.crypto.setSymKey(symKey, overrideTopic: topic);
await core.relayClient.subscribe(topic: topic).timeout(
const Duration(seconds: 15),
);
await core.expirer.set(topic, expiry);

onPairingCreate.broadcast(
PairingEvent(
topic: topic,
),
);

if (activatePairing) {
await activate(topic: topic);
if (activatePairing) {
await activate(topic: topic);
}
} catch (e) {
rethrow;
}

return pairing;
Expand Down
4 changes: 1 addition & 3 deletions lib/apis/utils/walletconnect_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import 'dart:io';

import 'package:package_info_plus/package_info_plus.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:walletconnect_flutter_v2/apis/core/relay_client/relay_client_models.dart';
import 'package:walletconnect_flutter_v2/apis/models/basic_models.dart';
import 'package:walletconnect_flutter_v2/apis/models/uri_parse_result.dart';
import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart';

class WalletConnectUtils {
static bool isExpired(int expiry) {
Expand Down
Loading