Skip to content
This repository has been archived by the owner on Sep 17, 2024. It is now read-only.

Commit

Permalink
Merge pull request #277 from MXCzkEVM/blueberry_ring
Browse files Browse the repository at this point in the history
Blueberry ring
  • Loading branch information
reasje authored Aug 6, 2024
2 parents 7918c52 + 26e914c commit 9a793ee
Show file tree
Hide file tree
Showing 12 changed files with 271 additions and 49 deletions.
3 changes: 2 additions & 1 deletion assets/flutter_i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -447,5 +447,6 @@
"already_synced_ring": "Blueberry Ring #{0}: Already synced. ℹ️",
"data_synced_successfully_ring": "Blueberry Ring #{0}: Data synced successfully. ✅",
"data_syncing_failed": "Blueberry Ring #{0}: Data syncing process failed. ❌",
"blueberry_hooks": "Blueberry hooks"
"blueberry_hooks": "Blueberry hooks",
"message": "Message"
}
16 changes: 8 additions & 8 deletions lib/core/src/background_process/dapp_hooks_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class DAppHooksService {
}
}

static void blueberryAutoSyncServiceCallBackDispatcherForeground(
static void blueberryAutoSyncServiceCallBackDispatcherForeground(
String taskId) async {
try {
await loadProviders();
Expand All @@ -113,18 +113,18 @@ class DAppHooksService {
final isLoggedIn = authUseCase.loggedIn;
final account = accountUseCase.account.value;
// final serviceEnabled = dappHooksData.enabled;
final minerHooksEnabled = dappHooksData.minerHooks.enabled;
final minerHooksTime = dappHooksData.minerHooks.time;
final selectedMiners = dappHooksData.minerHooks.selectedMiners;
final autoSyncEnabled = dappHooksData.blueberryRingHooks.enabled;
final ringHooksTime = dappHooksData.blueberryRingHooks.time;
final selectedRings = dappHooksData.blueberryRingHooks.selectedRings;
// Make sure user is logged in
if (isLoggedIn && MXCChains.isMXCChains(chainId) && minerHooksEnabled) {
if (isLoggedIn && MXCChains.isMXCChains(chainId) && autoSyncEnabled) {
await AXSNotification()
.setupFlutterNotifications(shouldInitFirebase: false);

await dAppHooksUseCase.executeMinerAutoClaim(
await dAppHooksUseCase.syncBlueberryRingSync(
account: account!,
selectedMinerListId: selectedMiners,
minerAutoClaimTime: minerHooksTime);
selectedRingsListId: selectedRings,
ringAutoSyncTime: ringHooksTime);
BackgroundFetch.finish(taskId);
} else {
// terminate background fetch
Expand Down
13 changes: 13 additions & 0 deletions lib/core/src/providers/providers_use_cases.dart
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ final Provider<DAppHooksUseCase> dAppHooksUseCaseProvider = Provider(
),
ref.watch(errorUseCaseProvider),
ref.watch(contextLessTranslationUseCaseProvider),
ref.watch(blueberryRingBackgroundSyncUseCase),
),
);

Expand Down Expand Up @@ -286,3 +287,15 @@ final Provider<BlueberryRingBackgroundNotificationsUseCase>
ref.watch(contextLessTranslationUseCaseProvider),
),
);

final Provider<BlueberryRingBackgroundSyncUseCase>
blueberryRingBackgroundSyncUseCase = Provider(
(ref) => BlueberryRingBackgroundSyncUseCase(
ref.watch(web3RepositoryProvider),
ref.watch(chainConfigurationUseCaseProvider),
ref.watch(bluetoothUseCaseProvider),
ref.watch(blueberryRingUseCaseProvider),
ref.watch(accountUseCaseProvider),
ref.watch(contextLessTranslationUseCaseProvider),
),
);
5 changes: 5 additions & 0 deletions lib/features/common/contract/token_contract_use_case.dart
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,11 @@ class TokenContractUseCase extends ReactiveUseCase {
.getTokenTransferData(tokenHash, toAddress, amount);
}

String signMessage({required String privateKey, required String message}) {
return _repository.tokenContract
.signMessage(privateKey: privateKey, message: message);
}

String signTypedMessage({required String privateKey, required String data}) {
return _repository.tokenContract
.signTypedMessage(privateKey: privateKey, data: data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import 'package:datadashwallet/features/settings/subfeatures/chain_configuration

import '../../../../../../app/logger.dart';

class BlueberryRingBackgroundNotificationsUseCase extends ReactiveUseCase {
BlueberryRingBackgroundNotificationsUseCase(
class BlueberryRingBackgroundSyncUseCase extends ReactiveUseCase {
BlueberryRingBackgroundSyncUseCase(
this._repository,
this._chainConfigurationUseCase,
this._bluetoothUseCase,
Expand All @@ -30,16 +30,35 @@ class BlueberryRingBackgroundNotificationsUseCase extends ReactiveUseCase {
_contextLessTranslationUseCase.translate(key);


Future<void> sendSyncTransaction({
required BlueberryRingMiner ring,
Future<bool> syncRings({
required List<String> selectedRingsListId,
required Account account,
required void Function(String title, String? text) showNotification,
required String Function(
String key,
)
translate,
}) async {
// Get miner from cache
// for (String ring in selectedRings) {

// }
// Get rings list
// Get the data from contract
// async function arrayFilterDate<T>(array: T[], date?: number) {
// if (!date)
// return array
// return array.filter((item: any) => item.date > (date || 0)) as T[]
// }
// arrayFilterDate(arr, detail.steps.at(-1)?.date)
// List<T> arrayFilterDate<T>(List<T> array, {int? date}) {
// if (date == null) return array;

// return array.where((item) {
// var itemDate = (item as dynamic).date; // Use 'dynamic' to access the 'date' property
// return itemDate > (date ?? 0);
// }).toList();
// }

// showNotification(
// translate('no_token_to_claim_miner')
Expand All @@ -51,27 +70,29 @@ class BlueberryRingBackgroundNotificationsUseCase extends ReactiveUseCase {
// already_synced_ring
// data_synced_successfully_ring
// data_syncing_failed
final memo = await fetchRingData();
// final memo = await fetchRingData();

final postClaimRequest = PostClaimRequestModel(
sncode: ring.sncode,
sender: account.address,
);
final postClaimResponse = await _repository.blueberryRingRepository.postClaim(
postClaimRequest,
);

final txSig = await _repository.blueberryRingRepository.sendSyncTransaction(account.privateKey, ring, postClaimResponse, memo);

// showNotification(
// translate('no_token_to_claim_miner')
// .replaceFirst('{0}', miner.mep1004TokenId!),
// null,
// final postClaimRequest = PostClaimRequestModel(
// sncode: ring.sncode,
// sender: account.address,
// );
// final postClaimResponse = await _repository.blueberryRingRepository.postClaim(
// postClaimRequest,
// );

// final txSig = await _repository.blueberryRingRepository.sendSyncTransaction(account.privateKey, ring, postClaimResponse, memo);

// // showNotification(
// // translate('no_token_to_claim_miner')
// // .replaceFirst('{0}', miner.mep1004TokenId!),
// // null,
// // );

return true;
}

Future<void> syncRing(BlueberryRingMiner ring) async{}


Future<String> fetchRingData() async {
collectLog('fetchRingData');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export 'blueberry_repository.dart';
export 'blueberry_ring_use_case.dart';
export 'blueberry_ring_background_notifications_use_case.dart';
export 'blueberry_ring_background_sync_use_case.dart';
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ class OpenDAppPresenter extends CompletePresenter<OpenDAppState> {
return res.hash;
}

String? _signMessage(
String hexData,
) {
loading = true;
try {
final res = _tokenContractUseCase.signMessage(
privateKey: state.account!.privateKey, message: hexData);
return res;
} catch (e, s) {
addError(e, s);
} finally {
loading = false;
}
}

String? _signTypedMessage(
String hexData,
) {
Expand Down Expand Up @@ -410,6 +425,38 @@ class OpenDAppPresenter extends CompletePresenter<OpenDAppState> {

void signPersonalMessage() {}

void signMessage({
required Map<String, dynamic> object,
required VoidCallback cancel,
required Function(String hash) success,
}) async {
final hexData = object['data'] as String;
String message = MXCType.hexToString(hexData);
int chainId = state.network!.chainId;
String name = state.network!.symbol;

try {
final result = await showSignMessageDialog(
context!,
title: translate('signature_request')!,
message: message,
networkName: '$name ($chainId)',
);

if (result != null && result) {
final hash = _signMessage(
hexData,
);
if (hash != null) success.call(hash);
} else {
cancel.call();
}
} catch (e, s) {
cancel.call();
addError(e, s);
}
}

void signTypedMessage({
required Map<String, dynamic> object,
required VoidCallback cancel,
Expand Down Expand Up @@ -740,7 +787,6 @@ class OpenDAppPresenter extends CompletePresenter<OpenDAppState> {
Future<Map<String, dynamic>> handleBluetoothRemoteGATTServerConnect(
Map<String, dynamic> data) async {
collectLog('handleBluetoothRemoteGATTServerConnect : $data');

await _bluetoothUseCase.connectionHandler(state.selectedScanResult!.device);

return BluetoothRemoteGATTServer(
Expand Down
78 changes: 78 additions & 0 deletions lib/features/dapps/subfeatures/open_dapp/widgets/message_info.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import 'package:datadashwallet/common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mxc_ui/mxc_ui.dart';

import '../open_dapp_presenter.dart';

class MessageInfo extends ConsumerWidget {
const MessageInfo({
Key? key,
required this.networkName,
required this.message,
this.onTap,
}) : super(key: key);

final String networkName;
final String message;
final VoidCallback? onTap;

@override
Widget build(BuildContext context, WidgetRef ref) {
final presenter = ref.read(openDAppPageContainer.actions);
return Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Column(
children: [
titleItem(context),
messageItem(context, presenter, message),
],
),
),
const SizedBox(height: 8),
signButton(context),
],
);
}

Widget signButton(BuildContext context) {
String titleText = 'sign';
AxsButtonType type = AxsButtonType.primary;

return MxcButton.primary(
key: const ValueKey('signButton'),
size: AxsButtonSize.xl,
title: FlutterI18n.translate(context, titleText),
type: type,
onTap: () {
if (onTap != null) onTap!();
Navigator.of(context).pop(true);
},
);
}

Widget titleItem(BuildContext context) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
networkName,
style: FontTheme.of(context).body2.secondary(),
softWrap: true,
),
const SizedBox(height: 4),
],
)
],
);
}

Widget messageItem(BuildContext context, OpenDAppPresenter presenter, String message) {
return SingleLineInfoItem(title: FlutterI18n.translate(context, 'message'), value: message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'package:flutter/material.dart';
import 'package:mxc_ui/mxc_ui.dart';

import 'message_info.dart';

Future<bool?> showSignMessageDialog(
BuildContext context, {
String? title,
required String networkName,
required String message,
VoidCallback? onTap,
}) {
return showModalBottomSheet<bool>(
context: context,
useRootNavigator: true,
isScrollControlled: true,
isDismissible: false,
useSafeArea: true,
backgroundColor: Colors.transparent,
builder: (BuildContext context) => Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 44),
decoration: BoxDecoration(
color: ColorsTheme.of(context).screenBackground,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
MxcAppBarEvenly.title(
titleText: title ?? '',
action: Container(
alignment: Alignment.centerRight,
child: InkWell(
child: const Icon(Icons.close),
onTap: () => Navigator.of(context).pop(false),
),
),
),
MessageInfo(
message: message,
networkName: networkName,
onTap: onTap,
),
const SizedBox(height: 10),
],
),
),
);
}
2 changes: 2 additions & 0 deletions lib/features/dapps/subfeatures/open_dapp/widgets/widgets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ export 'transaction_dialog.dart';
export 'transaction_info.dart';
export 'typed_message_bottom_sheet.dart';
export 'typed_message_info.dart';
export 'message_info.dart';
export 'sign_message_bottom_sheet.dart';
Loading

0 comments on commit 9a793ee

Please sign in to comment.