Skip to content

Commit

Permalink
Merge pull request #284 from WalletConnect/chores/wallet_sample_enhan…
Browse files Browse the repository at this point in the history
…cements

Chores/wallet sample enhancements
  • Loading branch information
quetool authored Apr 11, 2024
2 parents 133febc + d3512c0 commit 42d758c
Show file tree
Hide file tree
Showing 13 changed files with 316 additions and 255 deletions.
106 changes: 56 additions & 50 deletions example/wallet/lib/dependencies/chains/evm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,26 @@ import 'package:walletconnect_flutter_v2_wallet/widgets/wc_request_widget.dart/w
class EVMService {
final _bottomSheetService = GetIt.I<IBottomSheetService>();
final _web3WalletService = GetIt.I<IWeb3WalletService>();
final _web3Wallet = GetIt.I<IWeb3WalletService>().getWeb3Wallet();
final _web3Wallet = GetIt.I<IWeb3WalletService>().web3wallet;

final ChainMetadata chainSupported;
late final Web3Client ethClient;

Map<String, dynamic Function(String, dynamic)> get sessionRequestHandlers => {
'personal_sign': personalSign,
};

Map<String, dynamic Function(String, dynamic)> get methodRequestHandlers => {
// 'personal_sign': personalSign,
'eth_sign': ethSign,
'eth_signTransaction': ethSignTransaction,
'eth_sendTransaction': ethSendTransaction,
'eth_signTypedData': ethSignTypedData,
'eth_signTypedData_v4': ethSignTypedDataV4,
'wallet_switchEthereumChain': switchChain,
'wallet_addEthereumChain': addChain,
};

Map<String, dynamic Function(String, dynamic)> get methodRequestHandlers => {
'personal_sign': personalSign,
'eth_sendTransaction': ethSendTransaction,
};

EVMService({required this.chainSupported}) {
final supportedId = chainSupported.chainId;
final chainMetadata = ChainData.allChains.firstWhere(
Expand All @@ -54,6 +55,13 @@ class EVMService {
);
}

for (var handler in sessionRequestHandlers.entries) {
_web3Wallet.registerRequestHandler(
chainId: chainSupported.chainId,
method: handler.key,
handler: handler.value,
);
}
for (var handler in methodRequestHandlers.entries) {
_web3Wallet.registerRequestHandler(
chainId: chainSupported.chainId,
Expand All @@ -66,8 +74,8 @@ class EVMService {
}

void _onSessionRequest(SessionRequestEvent? args) async {
if (args?.chainId == chainSupported.chainId) {
debugPrint('[$runtimeType] onSessionRequest ${args!}');
if (args != null && args.chainId == chainSupported.chainId) {
debugPrint('[WALLET] _onSessionRequest ${args.toString()}');
final handler = sessionRequestHandlers[args.method];
if (handler != null) {
await handler(args.topic, args.params);
Expand All @@ -77,7 +85,7 @@ class EVMService {

// personal_sign is handled using onSessionRequest event for demo purposes
Future<void> personalSign(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] personalSign request: $parameters');
debugPrint('[WALLET] personalSign request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final message = EthUtils.getUtf8Message(data.toString());
Expand All @@ -100,7 +108,7 @@ class EVMService {

response = response.copyWith(result: signature);
} catch (e) {
debugPrint('[$runtimeType] personalSign error $e');
debugPrint('[WALLET] personalSign error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -111,16 +119,16 @@ class EVMService {
);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> ethSign(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] ethSign request: $parameters');
debugPrint('[WALLET] ethSign request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
final message = EthUtils.getUtf8Message(data.toString());
Expand All @@ -143,7 +151,7 @@ class EVMService {

response = response.copyWith(result: signature);
} catch (e) {
debugPrint('[$runtimeType] ethSign error $e');
debugPrint('[WALLET] ethSign error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -154,16 +162,16 @@ class EVMService {
);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> ethSignTypedData(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] ethSignTypedData request: $parameters');
debugPrint('[WALLET] ethSignTypedData request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
var response = JsonRpcResponse(
Expand All @@ -184,7 +192,7 @@ class EVMService {
);
response = response.copyWith(result: signature);
} catch (e) {
debugPrint('[$runtimeType] ethSignTypedData error $e');
debugPrint('[WALLET] ethSignTypedData error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -195,16 +203,16 @@ class EVMService {
);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> ethSignTypedDataV4(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] ethSignTypedDataV4 request: $parameters');
debugPrint('[WALLET] ethSignTypedDataV4 request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getDataFromParamsList(parameters);
var response = JsonRpcResponse(
Expand All @@ -225,7 +233,7 @@ class EVMService {
);
response = response.copyWith(result: signature);
} catch (e) {
debugPrint('[$runtimeType] ethSignTypedDataV4 error $e');
debugPrint('[WALLET] ethSignTypedDataV4 error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -236,16 +244,16 @@ class EVMService {
);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> ethSignTransaction(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] ethSignTransaction request: $parameters');
debugPrint('[WALLET] ethSignTransaction request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getTransactionFromParams(parameters);
if (data == null) return;
Expand All @@ -263,7 +271,7 @@ class EVMService {
);
final credentials = EthPrivateKey.fromHex('0x${keys[0].privateKey}');
final chainId = chainSupported.chainId.split(':').last;
debugPrint('[$runtimeType] ethSignTransaction chainId: $chainId');
debugPrint('[WALLET] ethSignTransaction chainId: $chainId');

final signature = await ethClient.signTransaction(
credentials,
Expand All @@ -275,12 +283,12 @@ class EVMService {

response = response.copyWith(result: '0x$signedTx');
} on RPCError catch (e) {
debugPrint('[$runtimeType] ethSignTransaction error $e');
debugPrint('[WALLET] ethSignTransaction error $e');
response = response.copyWith(
error: JsonRpcError(code: e.errorCode, message: e.message),
);
} catch (e) {
debugPrint('[$runtimeType] ethSignTransaction error $e');
debugPrint('[WALLET] ethSignTransaction error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -289,16 +297,16 @@ class EVMService {
response = response.copyWith(error: result as JsonRpcError);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> ethSendTransaction(String topic, dynamic parameters) async {
debugPrint('[$runtimeType] ethSendTransaction request: $parameters');
debugPrint('[WALLET] ethSendTransaction request: $parameters');
final pRequest = _web3Wallet.pendingRequests.getAll().last;
final data = EthUtils.getTransactionFromParams(parameters);
if (data == null) return;
Expand All @@ -316,7 +324,7 @@ class EVMService {
);
final credentials = EthPrivateKey.fromHex('0x${keys[0].privateKey}');
final chainId = chainSupported.chainId.split(':').last;
debugPrint('[$runtimeType] ethSendTransaction chainId: $chainId');
debugPrint('[WALLET] ethSendTransaction chainId: $chainId');

final signedTx = await ethClient.sendTransaction(
credentials,
Expand All @@ -326,12 +334,12 @@ class EVMService {

response = response.copyWith(result: '0x$signedTx');
} on RPCError catch (e) {
debugPrint('[$runtimeType] ethSendTransaction error $e');
debugPrint('[WALLET] ethSendTransaction error $e');
response = response.copyWith(
error: JsonRpcError(code: e.errorCode, message: e.message),
);
} catch (e) {
debugPrint('[$runtimeType] ethSendTransaction error $e');
debugPrint('[WALLET] ethSendTransaction error $e');
response = response.copyWith(
error: JsonRpcError(code: 0, message: e.toString()),
);
Expand All @@ -340,20 +348,20 @@ class EVMService {
response = response.copyWith(error: result as JsonRpcError);
}

_goBackToDapp(topic, response.result ?? response.error);

return _web3Wallet.respondSessionRequest(
await _web3Wallet.respondSessionRequest(
topic: topic,
response: response,
);

_goBackToDapp(topic, response.result ?? response.error);
}

Future<void> switchChain(String topic, dynamic parameters) async {
debugPrint('received switchChain request: $topic $parameters');
debugPrint('[WALLET] switchChain request: $topic $parameters');
final params = (parameters as List).first as Map<String, dynamic>;
final hexChainId = params['chainId'].toString().replaceFirst('0x', '');
final chainId = int.parse(hexChainId, radix: 16);
final web3wallet = _web3WalletService.getWeb3Wallet();
final web3wallet = _web3WalletService.web3wallet;
await web3wallet.emitSessionEvent(
topic: topic,
chainId: 'eip155:$chainId',
Expand All @@ -369,24 +377,22 @@ class EVMService {
final session = _web3Wallet.sessions.get(topic);
final scheme = session?.peer.metadata.redirect?.native ?? '';
if (result is String) {
DeepLinkHandler.goTo(scheme, delay: 300, modalTitle: 'Success');
DeepLinkHandler.goTo(scheme, modalTitle: 'Success');
} else {
DeepLinkHandler.goTo(
scheme,
delay: 300,
modalTitle: 'Error',
modalMessage: result.toString(),
success: false,
);
}
} catch (e, s) {
debugPrint(e.toString());
print(s);
} catch (e) {
debugPrint('[WALLET] ${e.toString()}');
}
}

Future<void> addChain(String topic, dynamic parameters) async {
debugPrint('received addChain request: $topic $parameters');
debugPrint('[WALLET] addChain request: $topic $parameters');
}

Future<bool> requestApproval(String text) async {
Expand Down
17 changes: 12 additions & 5 deletions example/wallet/lib/dependencies/deep_link_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,36 @@ class DeepLinkHandler {
_eventChannel.receiveBroadcastStream().listen(_onLink, onError: _onError);
}

static final ValueNotifier<bool> waiting = ValueNotifier(false);

static void checkInitialLink() {
try {
_methodChannel.invokeMethod('initialLink').then(
_onLink,
onError: _onError,
);
} catch (e) {
debugPrint('[DeepLinkHandler] checkInitialLink $e');
debugPrint('[WALLET] [DeepLinkHandler] checkInitialLink $e');
}
}

static Stream<String> get onLink => _linksController.stream;

static Future<void> goTo(
static void goTo(
String scheme, {
int delay = 0,
int delay = 100,
String? modalTitle,
String? modalMessage,
bool success = true,
}) async {
waiting.value = false;
if (scheme.isEmpty) return;
await Future.delayed(Duration(milliseconds: delay));
try {
await launchUrlString(scheme, mode: LaunchMode.externalApplication);
} catch (e) {
debugPrint('[DeepLinkHandler] error re-opening dapp ($scheme). $e');
debugPrint(
'[WALLET] [DeepLinkHandler] error re-opening dapp ($scheme). $e');
_goBackModal(
title: modalTitle,
message: modalMessage,
Expand All @@ -62,18 +66,21 @@ class DeepLinkHandler {
if (!pairingUri.toString().startsWith('wc:')) {
return;
}
waiting.value = true;
_linksController.sink.add(pairingUri);
}

static void _onError(Object error) {
debugPrint('[DeepLinkHandler] _onError $error');
waiting.value = false;
debugPrint('[WALLET] [DeepLinkHandler] _onError $error');
}

static void _goBackModal({
String? title,
String? message,
bool success = true,
}) async {
waiting.value = false;
await GetIt.I<IBottomSheetService>().queueBottomSheet(
closeAfter: success ? 3 : 0,
widget: Container(
Expand Down
14 changes: 8 additions & 6 deletions example/wallet/lib/dependencies/i_web3wallet_service.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart';

abstract class IWeb3WalletService extends Disposable {
abstract ValueNotifier<List<PairingInfo>> pairings;
abstract ValueNotifier<List<SessionData>> sessions;
abstract ValueNotifier<List<StoredCacao>> auth;
class UpdateEvent extends EventArgs {
final bool loading;

UpdateEvent({required this.loading});
}

abstract class IWeb3WalletService extends Disposable {
void create();
Future<void> init();
Web3Wallet getWeb3Wallet();

Web3Wallet get web3wallet;
}
Loading

0 comments on commit 42d758c

Please sign in to comment.