From c37bfb2e83d2fe2ff48d911256b689dd8b53a03d Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 5 Oct 2022 15:57:17 +0200 Subject: [PATCH 01/49] Add Advanced privacy settings page and initial view model --- .../advanced_privacy_settings_page.dart | 173 ++++++++++++++++++ .../privacy_settings_view_model.dart | 54 ++++++ 2 files changed, 227 insertions(+) create mode 100644 lib/src/screens/new_wallet/advanced_privacy_settings_page.dart create mode 100644 lib/view_model/privacy_settings_view_model.dart diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart new file mode 100644 index 000000000..149b65d2e --- /dev/null +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -0,0 +1,173 @@ +import 'package:cake_wallet/entities/generate_name.dart'; +import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; +import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; +import 'package:flutter_mobx/flutter_mobx.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:cake_wallet/generated/i18n.dart'; +import 'package:cake_wallet/core/wallet_name_validator.dart'; +import 'package:cake_wallet/src/screens/base_page.dart'; +import 'package:cake_wallet/src/widgets/primary_button.dart'; +import 'package:cake_wallet/src/widgets/scollable_with_bottom_section.dart'; + +class AdvancedPrivacySettingsPage extends BasePage { + AdvancedPrivacySettingsPage(this.privacySettingsViewModel); + + final PrivacySettingsViewModel privacySettingsViewModel; + + @override + String get title => S.current.privacy_settings; + + @override + Widget body(BuildContext context) => + AdvancedPrivacySettingsBody(privacySettingsViewModel); +} + +class AdvancedPrivacySettingsBody extends StatefulWidget { + const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, {Key key}) + : super(key: key); + + final PrivacySettingsViewModel privacySettingsViewModel; + + @override + _AdvancedPrivacySettingsBodyState createState() => + _AdvancedPrivacySettingsBodyState(privacySettingsViewModel); +} + +class _AdvancedPrivacySettingsBodyState + extends State { + _AdvancedPrivacySettingsBodyState(this.privacySettingsViewModel); + + final PrivacySettingsViewModel privacySettingsViewModel; + + final _formKey = GlobalKey(); + + final TextEditingController _controller = TextEditingController(); + + @override + Widget build(BuildContext context) { + return Container( + padding: EdgeInsets.only(top: 24), + child: ScrollableWithBottomSection( + contentPadding: EdgeInsets.only(left: 24, right: 24, bottom: 24), + content: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + ...privacySettingsViewModel.settings.map( + (item) => Observer( + builder: (_) => SettingsSwitcherCell( + title: item.title, + value: item.value(), + onValueChange: item.onValueChange, + ), + ), + ), + Observer( + builder: (_) { + if (privacySettingsViewModel.addCustomNode) { + return Padding( + padding: EdgeInsets.only(top: 24), + child: Form( + key: _formKey, + child: TextFormField( + onChanged: (value) {}, + controller: _controller, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.w600, + color: + Theme.of(context).primaryTextTheme.title.color), + decoration: InputDecoration( + hintStyle: TextStyle( + fontSize: 18.0, + fontWeight: FontWeight.w500, + color: Theme.of(context) + .accentTextTheme + .display3 + .color), + hintText: S.of(context).wallet_name, + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context) + .accentTextTheme + .display3 + .decorationColor, + width: 1.0), + ), + enabledBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context) + .accentTextTheme + .display3 + .decorationColor, + width: 1.0), + ), + suffixIcon: IconButton( + onPressed: () async { + final rName = await generateName(); + FocusManager.instance.primaryFocus?.unfocus(); + + setState(() { + _controller.text = rName; + _controller.selection = + TextSelection.fromPosition( + TextPosition(offset: _controller.text.length), + ); + }); + }, + icon: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6.0), + color: Theme.of(context).hintColor, + ), + width: 34, + height: 34, + child: Image.asset( + 'assets/images/refresh_icon.png', + color: Theme.of(context) + .primaryTextTheme + .display1 + .decorationColor, + ), + ), + ), + ), + validator: WalletNameValidator(), + ), + ), + ); + } + return const SizedBox(); + }, + ), + ], + ), + bottomSectionPadding: EdgeInsets.all(24), + bottomSection: Column( + children: [ + LoadingPrimaryButton( + onPressed: () {}, + text: S.of(context).continue_text, + color: Theme.of(context).accentTextTheme.body2.color, + textColor: Colors.white, + ), + const SizedBox(height: 25), + Padding( + padding: EdgeInsets.symmetric( + horizontal: MediaQuery.of(context).size.width * 0.15), + child: Text( + S.of(context).settings_can_be_changed_later, + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of(context).accentTextTheme.display3.color, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view_model/privacy_settings_view_model.dart b/lib/view_model/privacy_settings_view_model.dart new file mode 100644 index 000000000..ce5a3f7a6 --- /dev/null +++ b/lib/view_model/privacy_settings_view_model.dart @@ -0,0 +1,54 @@ +import 'package:cake_wallet/view_model/settings/switcher_list_item.dart'; +import 'package:cw_core/wallet_type.dart'; +import 'package:mobx/mobx.dart'; +import 'package:cake_wallet/generated/i18n.dart'; + +part 'privacy_settings_view_model.g.dart'; + +class PrivacySettingsViewModel = PrivacySettingsViewModelBase + with _$PrivacySettingsViewModel; + +abstract class PrivacySettingsViewModelBase with Store { + PrivacySettingsViewModelBase(this.type) { + _disableFiat = false; + _disableExchange = false; + _addCustomNode = false; + + settings = [ + SwitcherListItem( + title: "Disable Fiat API", + // title: S.current.disable_fiat, + value: () => _disableFiat, + onValueChange: (_, bool value) => _disableFiat = value, + ), + SwitcherListItem( + title: "Disable Exchange", + // title: S.current.disable_exchange, + value: () => _disableExchange, + onValueChange: (_, bool value) => _disableExchange = value, + ), + SwitcherListItem( + title: "Add New Custom Node", + // title: S.current.add_custom_node, + value: () => _addCustomNode, + onValueChange: (_, bool value) => _addCustomNode = value, + ), + ]; + } + + List settings; + + @observable + bool _disableFiat; + + @observable + bool _disableExchange; + + @observable + bool _addCustomNode; + + final WalletType type; + + @computed + bool get addCustomNode => _addCustomNode; +} From 6bbedde9b7920ec090037a4ed16a89bf5f7a9b64 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 5 Oct 2022 15:58:25 +0200 Subject: [PATCH 02/49] Add privacy settings route Add text translation --- lib/di.dart | 4 +++ lib/router.dart | 9 +++++ lib/routes.dart | 1 + .../screens/new_wallet/new_wallet_page.dart | 35 ++++++++++++------- res/values/strings_de.arb | 5 ++- res/values/strings_en.arb | 5 ++- res/values/strings_es.arb | 5 ++- res/values/strings_fr.arb | 5 ++- res/values/strings_hi.arb | 5 ++- res/values/strings_hr.arb | 5 ++- res/values/strings_it.arb | 5 ++- res/values/strings_ja.arb | 5 ++- res/values/strings_ko.arb | 5 ++- res/values/strings_nl.arb | 5 ++- res/values/strings_pl.arb | 5 ++- res/values/strings_pt.arb | 5 ++- res/values/strings_ru.arb | 5 ++- res/values/strings_uk.arb | 5 ++- res/values/strings_zh.arb | 5 ++- 19 files changed, 97 insertions(+), 27 deletions(-) diff --git a/lib/di.dart b/lib/di.dart index 5cc698d27..8dfbfd788 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -25,6 +25,7 @@ import 'package:cake_wallet/src/screens/dashboard/widgets/balance_page.dart'; import 'package:cake_wallet/view_model/ionia/ionia_account_view_model.dart'; import 'package:cake_wallet/view_model/ionia/ionia_gift_cards_list_view_model.dart'; import 'package:cake_wallet/view_model/ionia/ionia_purchase_merch_view_model.dart'; +import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; import 'package:cw_core/unspent_coins_info.dart'; import 'package:cake_wallet/core/backup_service.dart'; import 'package:cw_core/wallet_service.dart'; @@ -786,5 +787,8 @@ Future setup( (IoniaAnyPayPaymentInfo paymentInfo, AnyPayPaymentCommittedInfo committedInfo) => IoniaPaymentStatusPage(getIt.get(param1: paymentInfo, param2: committedInfo))); + getIt.registerFactoryParam((type, _) => + PrivacySettingsViewModel(type)); + _isSetupFinished = true; } diff --git a/lib/router.dart b/lib/router.dart index 051e07cb0..b19fb198e 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -10,6 +10,7 @@ import 'package:cake_wallet/src/screens/ionia/cards/ionia_custom_redeem_page.dar import 'package:cake_wallet/src/screens/ionia/cards/ionia_custom_tip_page.dart'; import 'package:cake_wallet/src/screens/ionia/cards/ionia_gift_card_detail_page.dart'; import 'package:cake_wallet/src/screens/ionia/cards/ionia_more_options_page.dart'; +import 'package:cake_wallet/src/screens/new_wallet/advanced_privacy_settings_page.dart'; import 'package:cake_wallet/src/screens/order_details/order_details_page.dart'; import 'package:cake_wallet/src/screens/pin_code/pin_code_widget.dart'; import 'package:cake_wallet/src/screens/restore/restore_from_backup_page.dart'; @@ -19,6 +20,7 @@ import 'package:cake_wallet/src/screens/support/support_page.dart'; import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_details_page.dart'; import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_list_page.dart'; import 'package:cake_wallet/view_model/monero_account_list/account_list_item.dart'; +import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:cake_wallet/routes.dart'; @@ -471,6 +473,13 @@ Route createRoute(RouteSettings settings) { param1: paymentInfo, param2: commitedInfo)); + case Routes.privacySettings: + final type = settings.arguments as WalletType; + final privacySettingsViewModel = getIt.get(param1: type); + + return CupertinoPageRoute( + builder: (_) => AdvancedPrivacySettingsPage(privacySettingsViewModel)); + default: return MaterialPageRoute( builder: (_) => Scaffold( diff --git a/lib/routes.dart b/lib/routes.dart index 7431d71df..8b0a6ca03 100644 --- a/lib/routes.dart +++ b/lib/routes.dart @@ -76,4 +76,5 @@ class Routes { static const ioniaPaymentStatusPage = '/ionia_payment_status_page'; static const ioniaMoreOptionsPage = '/ionia_more_options_page'; static const ioniaCustomRedeemPage = '/ionia_custom_redeem_page'; + static const privacySettings = '/privacy_settings'; } diff --git a/lib/src/screens/new_wallet/new_wallet_page.dart b/lib/src/screens/new_wallet/new_wallet_page.dart index 2ea1eca94..8aef74445 100644 --- a/lib/src/screens/new_wallet/new_wallet_page.dart +++ b/lib/src/screens/new_wallet/new_wallet_page.dart @@ -198,18 +198,29 @@ class _WalletNameFormState extends State { ] ]), bottomSectionPadding: - EdgeInsets.only(left: 24, right: 24, bottom: 24), - bottomSection: Observer( - builder: (context) { - return LoadingPrimaryButton( - onPressed: _confirmForm, - text: S.of(context).seed_language_next, - color: Colors.green, - textColor: Colors.white, - isLoading: _walletNewVM.state is IsExecutingState, - isDisabled: _walletNewVM.name.isEmpty, - ); - }, + EdgeInsets.all(24), + bottomSection: Column( + children: [ + Observer( + builder: (context) { + return LoadingPrimaryButton( + onPressed: _confirmForm, + text: S.of(context).seed_language_next, + color: Colors.green, + textColor: Colors.white, + isLoading: _walletNewVM.state is IsExecutingState, + isDisabled: _walletNewVM.name.isEmpty, + ); + }, + ), + const SizedBox(height: 25), + GestureDetector( + onTap: () { + Navigator.of(context).pushNamed(Routes.privacySettings); + }, + child: Text(S.of(context).advanced_privacy_settings), + ), + ], )), ); } diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index fa04a6a8e..fa896eb97 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Wähle aus verfügbaren Optionen:", "custom_redeem_amount": "Benutzerdefinierter Einlösungsbetrag", "add_custom_redemption": "Benutzerdefinierte Einlösung hinzufügen", - "remaining": "Rest" + "remaining": "Rest", + "advanced_privacy_settings": "Erweiterte Datenschutzeinstellungen", + "privacy_settings": "Datenschutzeinstellungen", + "settings_can_be_changed_later": "Diese Einstellungen können später in den App-Einstellungen geändert werden" } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 4a46d36c8..a79f66cc2 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Choose from the available options:", "custom_redeem_amount": "Custom Redeem Amount", "add_custom_redemption": "Add Custom Redemption", - "remaining": "remaining" + "remaining": "remaining", + "advanced_privacy_settings": "Advanced Privacy Settings", + "privacy_settings": "Privacy Settings", + "settings_can_be_changed_later": "These settings can be changed later in the app settings" } diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 756ac3e11..b953ccd45 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Elija entre las opciones disponibles:", "custom_redeem_amount": "Cantidad de canje personalizada", "add_custom_redemption": "Agregar redención personalizada", - "remaining": "restante" + "remaining": "restante", + "advanced_privacy_settings": "Configuración avanzada de privacidad", + "privacy_settings": "La configuración de privacidad", + "settings_can_be_changed_later": "Estas configuraciones se pueden cambiar más tarde en la configuración de la aplicación" } diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index 04462943e..b62ae92a4 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -642,5 +642,8 @@ "choose_from_available_options": "Choisissez parmi les options disponibles :", "custom_redeem_amount": "Montant d'échange personnalisé", "add_custom_redemption": "Ajouter un remboursement personnalisé", - "remaining": "restant" + "remaining": "restant", + "advanced_privacy_settings": "Paramètres de confidentialité avancés", + "privacy_settings": "Paramètres de confidentialité", + "settings_can_be_changed_later": "Ces paramètres peuvent être modifiés ultérieurement dans les paramètres de l'application" } diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index f8bad76e2..932118e9a 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "उपलब्ध विकल्पों में से चुनें:", "custom_redeem_amount": "कस्टम रिडीम राशि", "add_custom_redemption": "कस्टम रिडेम्पशन जोड़ें", - "remaining": "शेष" + "remaining": "शेष", + "advanced_privacy_settings": "उन्नत गोपनीयता सेटिंग्स", + "privacy_settings": "गोपनीय सेटिंग", + "settings_can_be_changed_later": "इन सेटिंग्स को बाद में ऐप सेटिंग में बदला जा सकता है" } diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index 0e27e3a2c..7eebebdc9 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Odaberite neku od dostupnih opcija:", "custom_redeem_amount": "Prilagođeni iznos otkupa", "add_custom_redemption": "Dodaj prilagođeni otkup", - "remaining": "preostalo" + "remaining": "preostalo", + "advanced_privacy_settings": "Napredne postavke privatnosti", + "privacy_settings": "Postavke privatnosti", + "settings_can_be_changed_later": "Te se postavke mogu promijeniti kasnije u postavkama aplikacije" } diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index ea9bbd5be..a1333dae4 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Scegli tra le opzioni disponibili:", "custom_redeem_amount": "Importo di riscatto personalizzato", "add_custom_redemption": "Aggiungi riscatto personalizzato", - "remaining": "rimanente" + "remaining": "rimanente", + "advanced_privacy_settings": "Impostazioni avanzate sulla privacy", + "privacy_settings": "Impostazioni della privacy", + "settings_can_be_changed_later": "Queste impostazioni possono essere modificate in seguito nelle impostazioni dell'app" } diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index 5ae3a5a1a..733dc4a00 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "利用可能なオプションから選択してください:", "custom_redeem_amount": "カスタム交換金額", "add_custom_redemption": "カスタム引き換えを追加", - "remaining": "残り" + "remaining": "残り", + "advanced_privacy_settings": "高度なプライバシー設定", + "privacy_settings": "プライバシー設定", + "settings_can_be_changed_later": "これらの設定は、後でアプリの設定で変更できます" } diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index f934784ba..c1069c003 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "사용 가능한 옵션에서 선택:", "custom_redeem_amount": "사용자 지정 상환 금액", "add_custom_redemption": "사용자 지정 상환 추가", - "remaining": "남은" + "remaining": "남은", + "advanced_privacy_settings": "고급 개인 정보 설정", + "privacy_settings": "개인 정보 설정", + "settings_can_be_changed_later": "이 설정은 나중에 앱 설정에서 변경할 수 있습니다." } diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index 428da3d76..fc3ab96cd 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Kies uit de beschikbare opties:", "custom_redeem_amount": "Aangepast inwisselbedrag", "add_custom_redemption": "Voeg aangepaste inwisseling toe", - "remaining": "resterende" + "remaining": "resterende", + "advanced_privacy_settings": "Geavanceerde privacy-instellingen", + "privacy_settings": "Privacy instellingen", + "settings_can_be_changed_later": "Deze instellingen kunnen later worden gewijzigd in de app-instellingen" } diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index fda0ea721..eb5f9d06c 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Wybierz z dostępnych opcji:", "custom_redeem_amount": "Niestandardowa kwota wykorzystania", "add_custom_redemption": "Dodaj niestandardowe wykorzystanie", - "remaining": "pozostałe" + "remaining": "pozostałe", + "advanced_privacy_settings": "Zaawansowane ustawienia prywatności", + "privacy_settings": "Ustawienia prywatności", + "settings_can_be_changed_later": "Te ustawienia można później zmienić w ustawieniach aplikacji" } diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 6a55cf534..a33bbb060 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -643,5 +643,8 @@ "choose_from_available_options": "Escolha entre as opções disponíveis:", "custom_redeem_amount": "Valor de resgate personalizado", "add_custom_redemption": "Adicionar resgate personalizado", - "remaining": "restante" + "remaining": "restante", + "advanced_privacy_settings": "Configurações de privacidade avançadas", + "privacy_settings": "Configurações de privacidade", + "settings_can_be_changed_later": "Essas configurações podem ser alteradas posteriormente nas configurações do aplicativo" } diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index ebc4a615c..efa90deec 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -644,5 +644,8 @@ "choose_from_available_options": "Выберите из доступных вариантов:", "custom_redeem_amount": "Пользовательская сумма погашения", "add_custom_redemption": "Добавить пользовательское погашение", - "remaining": "осталось" + "remaining": "осталось", + "advanced_privacy_settings": "Расширенные настройки конфиденциальности", + "privacy_settings": "Настройки конфиденциальности", + "settings_can_be_changed_later": "Эти настройки можно изменить позже в настройках приложения." } diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index efbd5a3b8..fbc47a619 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -643,5 +643,8 @@ "choose_from_available_options": "Виберіть із доступних варіантів:", "custom_redeem_amount": "Власна сума викупу", "add_custom_redemption": "Додати спеціальне погашення", - "remaining": "залишилося" + "remaining": "залишилося", + "advanced_privacy_settings": "Розширені налаштування конфіденційності", + "privacy_settings": "Параметри конфіденційності", + "settings_can_be_changed_later": "Ці параметри можна змінити пізніше в налаштуваннях програми" } diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index 83990cf2e..ae2acd73a 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -642,5 +642,8 @@ "choose_from_available_options": "从可用选项中选择:", "custom_redeem_amount": "自定义兑换金额", "add_custom_redemption": "添加自定义兑换", - "remaining": "剩余" + "remaining": "剩余", + "advanced_privacy_settings": "高级隐私设置", + "privacy_settings": "隐私设置", + "settings_can_be_changed_later": "稍后可以在应用设置中更改这些设置" } From 299df3c087ace7f188d204db8c1623222cbd2f20 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 5 Oct 2022 19:28:11 +0200 Subject: [PATCH 03/49] Separate node form to be more reusable Add node form to privacy settings --- lib/di.dart | 25 +-- lib/router.dart | 4 +- .../advanced_privacy_settings_page.dart | 91 ++--------- .../nodes/node_create_or_edit_page.dart | 94 +---------- lib/src/screens/nodes/widgets/node_form.dart | 151 ++++++++++++++++++ .../node_create_or_edit_view_model.dart | 13 +- 6 files changed, 191 insertions(+), 187 deletions(-) create mode 100644 lib/src/screens/nodes/widgets/node_form.dart diff --git a/lib/di.dart b/lib/di.dart index 8dfbfd788..b7f8ce949 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -343,7 +343,7 @@ Future setup( onAuthenticationFinished: onAuthFinished, closable: closable ?? false)); - getIt.registerFactory(() => + getIt.registerFactory(() => BalancePage(dashboardViewModel: getIt.get(), settingsStore: getIt.get())); getIt.registerFactory(() => DashboardPage( balancePage: getIt.get(), walletViewModel: getIt.get(), addressListViewModel: getIt.get())); @@ -478,8 +478,9 @@ Future setup( getIt.registerFactory(() => NodeListPage(getIt.get())); - getIt.registerFactory(() => - NodeCreateOrEditViewModel(_nodeSource, getIt.get().wallet)); + getIt.registerFactoryParam( + (WalletType type, _) => + NodeCreateOrEditViewModel(_nodeSource, type ?? getIt.get().wallet.type)); getIt.registerFactory( () => NodeCreateOrEditPage(getIt.get())); @@ -672,7 +673,7 @@ Future setup( getIt.registerFactoryParam( (String qrData, bool isLight) => FullscreenQRPage(qrData: qrData, isLight: isLight,)); - + getIt.registerFactory(() => IoniaApi()); getIt.registerFactory(() => AnyPayApi()); @@ -692,7 +693,7 @@ Future setup( getIt.registerFactoryParam((double amount, merchant) { return IoniaMerchPurchaseViewModel( - ioniaAnyPayService: getIt.get(), + ioniaAnyPayService: getIt.get(), amount: amount, ioniaMerchant: merchant, ); @@ -734,31 +735,31 @@ Future setup( ioniaService: getIt.get(), giftCard: giftCard); }); - + getIt.registerFactoryParam((List args, _) { final amount = args[0] as double; final merchant = args[1] as IoniaMerchant; final tip = args[2] as IoniaTip; - + return IoniaCustomTipViewModel(amount: amount, tip: tip, ioniaMerchant: merchant); }); - + getIt.registerFactoryParam((IoniaGiftCard giftCard, _) { return IoniaGiftCardDetailPage(getIt.get(param1: giftCard)); }); getIt.registerFactoryParam((List args, _){ final giftCard = args.first as IoniaGiftCard; - - return IoniaMoreOptionsPage(giftCard); + + return IoniaMoreOptionsPage(giftCard); }); getIt.registerFactoryParam((IoniaGiftCard giftCard, _) => IoniaCustomRedeemViewModel(giftCard)); getIt.registerFactoryParam((List args, _){ final giftCard = args.first as IoniaGiftCard; - - return IoniaCustomRedeemPage(getIt.get(param1: giftCard) ); + + return IoniaCustomRedeemPage(getIt.get(param1: giftCard) ); }); diff --git a/lib/router.dart b/lib/router.dart index b19fb198e..fd820b764 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -20,6 +20,7 @@ import 'package:cake_wallet/src/screens/support/support_page.dart'; import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_details_page.dart'; import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_list_page.dart'; import 'package:cake_wallet/view_model/monero_account_list/account_list_item.dart'; +import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -476,9 +477,10 @@ Route createRoute(RouteSettings settings) { case Routes.privacySettings: final type = settings.arguments as WalletType; final privacySettingsViewModel = getIt.get(param1: type); + final nodeCreateViewModel = getIt.get(param1: type); return CupertinoPageRoute( - builder: (_) => AdvancedPrivacySettingsPage(privacySettingsViewModel)); + builder: (_) => AdvancedPrivacySettingsPage(privacySettingsViewModel, nodeCreateViewModel)); default: return MaterialPageRoute( diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index 149b65d2e..e22afeb92 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -1,49 +1,50 @@ -import 'package:cake_wallet/entities/generate_name.dart'; +import 'package:cake_wallet/src/screens/nodes/widgets/node_form.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; +import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:cake_wallet/generated/i18n.dart'; -import 'package:cake_wallet/core/wallet_name_validator.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; import 'package:cake_wallet/src/widgets/primary_button.dart'; import 'package:cake_wallet/src/widgets/scollable_with_bottom_section.dart'; class AdvancedPrivacySettingsPage extends BasePage { - AdvancedPrivacySettingsPage(this.privacySettingsViewModel); + AdvancedPrivacySettingsPage(this.privacySettingsViewModel, this.nodeViewModel); final PrivacySettingsViewModel privacySettingsViewModel; + final NodeCreateOrEditViewModel nodeViewModel; @override String get title => S.current.privacy_settings; @override Widget body(BuildContext context) => - AdvancedPrivacySettingsBody(privacySettingsViewModel); + AdvancedPrivacySettingsBody(privacySettingsViewModel, nodeViewModel); } class AdvancedPrivacySettingsBody extends StatefulWidget { - const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, {Key key}) + const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, this.nodeViewModel, {Key key}) : super(key: key); final PrivacySettingsViewModel privacySettingsViewModel; + final NodeCreateOrEditViewModel nodeViewModel; @override _AdvancedPrivacySettingsBodyState createState() => - _AdvancedPrivacySettingsBodyState(privacySettingsViewModel); + _AdvancedPrivacySettingsBodyState(privacySettingsViewModel, nodeViewModel); } class _AdvancedPrivacySettingsBodyState extends State { - _AdvancedPrivacySettingsBodyState(this.privacySettingsViewModel); + _AdvancedPrivacySettingsBodyState(this.privacySettingsViewModel, this.nodeViewModel); final PrivacySettingsViewModel privacySettingsViewModel; + final NodeCreateOrEditViewModel nodeViewModel; final _formKey = GlobalKey(); - final TextEditingController _controller = TextEditingController(); - @override Widget build(BuildContext context) { return Container( @@ -67,75 +68,9 @@ class _AdvancedPrivacySettingsBodyState if (privacySettingsViewModel.addCustomNode) { return Padding( padding: EdgeInsets.only(top: 24), - child: Form( - key: _formKey, - child: TextFormField( - onChanged: (value) {}, - controller: _controller, - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 20.0, - fontWeight: FontWeight.w600, - color: - Theme.of(context).primaryTextTheme.title.color), - decoration: InputDecoration( - hintStyle: TextStyle( - fontSize: 18.0, - fontWeight: FontWeight.w500, - color: Theme.of(context) - .accentTextTheme - .display3 - .color), - hintText: S.of(context).wallet_name, - focusedBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context) - .accentTextTheme - .display3 - .decorationColor, - width: 1.0), - ), - enabledBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context) - .accentTextTheme - .display3 - .decorationColor, - width: 1.0), - ), - suffixIcon: IconButton( - onPressed: () async { - final rName = await generateName(); - FocusManager.instance.primaryFocus?.unfocus(); - - setState(() { - _controller.text = rName; - _controller.selection = - TextSelection.fromPosition( - TextPosition(offset: _controller.text.length), - ); - }); - }, - icon: Container( - padding: const EdgeInsets.all(8), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(6.0), - color: Theme.of(context).hintColor, - ), - width: 34, - height: 34, - child: Image.asset( - 'assets/images/refresh_icon.png', - color: Theme.of(context) - .primaryTextTheme - .display1 - .decorationColor, - ), - ), - ), - ), - validator: WalletNameValidator(), - ), + child: NodeForm( + formKey: _formKey, + nodeViewModel: nodeViewModel, ), ); } diff --git a/lib/src/screens/nodes/node_create_or_edit_page.dart b/lib/src/screens/nodes/node_create_or_edit_page.dart index 857bde023..e4864cc91 100644 --- a/lib/src/screens/nodes/node_create_or_edit_page.dart +++ b/lib/src/screens/nodes/node_create_or_edit_page.dart @@ -1,16 +1,13 @@ import 'package:cake_wallet/core/execution_state.dart'; +import 'package:cake_wallet/src/screens/nodes/widgets/node_form.dart'; import 'package:cake_wallet/src/widgets/alert_with_one_action.dart'; -import 'package:cake_wallet/src/widgets/standard_checkbox.dart'; import 'package:cake_wallet/utils/show_pop_up.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:mobx/mobx.dart'; import 'package:cake_wallet/generated/i18n.dart'; -import 'package:cake_wallet/core/node_address_validator.dart'; -import 'package:cake_wallet/core/node_port_validator.dart'; import 'package:cake_wallet/src/widgets/primary_button.dart'; -import 'package:cake_wallet/src/widgets/base_text_form_field.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; import 'package:cake_wallet/src/widgets/scollable_with_bottom_section.dart'; import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; @@ -108,91 +105,10 @@ class NodeCreateOrEditPage extends BasePage { padding: EdgeInsets.only(left: 24, right: 24), child: ScrollableWithBottomSection( contentPadding: EdgeInsets.only(bottom: 24.0), - content: Form( - key: _formKey, - child: Column( - children: [ - Row( - children: [ - Expanded( - child: BaseTextFormField( - controller: _addressController, - hintText: S.of(context).node_address, - validator: NodeAddressValidator(), - ) - ) - ], - ), - SizedBox(height: 10.0), - Row( - children: [ - Expanded( - child: BaseTextFormField( - controller: _portController, - hintText: S.of(context).node_port, - keyboardType: TextInputType.numberWithOptions( - signed: false, decimal: false), - validator: NodePortValidator(), - ) - ) - ], - ), - SizedBox(height: 10.0), - if (nodeCreateOrEditViewModel.hasAuthCredentials) ...[ - Row( - children: [ - Expanded( - child: BaseTextFormField( - controller: _loginController, - hintText: S.of(context).login, - ) - ) - ], - ), - SizedBox(height: 10.0), - Row( - children: [ - Expanded( - child: BaseTextFormField( - controller: _passwordController, - hintText: S.of(context).password, - ) - ) - ], - ), - Padding( - padding: EdgeInsets.only(top: 20), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - Observer( - builder: (_) => StandardCheckbox( - value: nodeCreateOrEditViewModel.useSSL, - onChanged: (value) => - nodeCreateOrEditViewModel.useSSL = value, - caption: S.of(context).use_ssl, - )) - ], - )), - Padding( - padding: EdgeInsets.only(top: 20), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - Observer( - builder: (_) => StandardCheckbox( - value: nodeCreateOrEditViewModel.trusted, - onChanged: (value) => - nodeCreateOrEditViewModel.trusted = value, - caption: S.of(context).trusted, - )) - ], - )), - ] - ], - )), + content: NodeForm( + formKey: _formKey, + nodeViewModel: nodeCreateOrEditViewModel, + ), bottomSectionPadding: EdgeInsets.only(bottom: 24), bottomSection: Observer( builder: (_) => Row( diff --git a/lib/src/screens/nodes/widgets/node_form.dart b/lib/src/screens/nodes/widgets/node_form.dart new file mode 100644 index 000000000..757032a2a --- /dev/null +++ b/lib/src/screens/nodes/widgets/node_form.dart @@ -0,0 +1,151 @@ +import 'package:cake_wallet/core/node_address_validator.dart'; +import 'package:cake_wallet/core/node_port_validator.dart'; +import 'package:cake_wallet/src/widgets/base_text_form_field.dart'; +import 'package:cake_wallet/src/widgets/standard_checkbox.dart'; +import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_mobx/flutter_mobx.dart'; +import 'package:cake_wallet/generated/i18n.dart'; +import 'package:mobx/mobx.dart'; + +class NodeForm extends StatelessWidget { + NodeForm({ + @required this.nodeViewModel, + @required this.formKey, + }) : _addressController = TextEditingController(), + _portController = TextEditingController(), + _loginController = TextEditingController(), + _passwordController = TextEditingController() { + reaction((_) => nodeViewModel.address, (String address) { + if (address != _addressController.text) { + _addressController.text = address; + } + }); + + reaction((_) => nodeViewModel.port, (String port) { + if (port != _portController.text) { + _portController.text = port; + } + }); + + if (nodeViewModel.hasAuthCredentials) { + reaction((_) => nodeViewModel.login, (String login) { + if (login != _loginController.text) { + _loginController.text = login; + } + }); + + reaction((_) => nodeViewModel.password, (String password) { + if (password != _passwordController.text) { + _passwordController.text = password; + } + }); + } + + _addressController + .addListener(() => nodeViewModel.address = _addressController.text); + _portController + .addListener(() => nodeViewModel.port = _portController.text); + _loginController + .addListener(() => nodeViewModel.login = _loginController.text); + _passwordController + .addListener(() => nodeViewModel.password = _passwordController.text); + } + + final NodeCreateOrEditViewModel nodeViewModel; + final GlobalKey formKey; + + final TextEditingController _addressController; + final TextEditingController _portController; + final TextEditingController _loginController; + final TextEditingController _passwordController; + + @override + Widget build(BuildContext context) { + return Form( + key: formKey, + child: Column( + children: [ + Row( + children: [ + Expanded( + child: BaseTextFormField( + controller: _addressController, + hintText: S.of(context).node_address, + validator: NodeAddressValidator(), + ), + ) + ], + ), + SizedBox(height: 10.0), + Row( + children: [ + Expanded( + child: BaseTextFormField( + controller: _portController, + hintText: S.of(context).node_port, + keyboardType: TextInputType.numberWithOptions( + signed: false, decimal: false), + validator: NodePortValidator(), + )) + ], + ), + SizedBox(height: 10.0), + if (nodeViewModel.hasAuthCredentials) ...[ + Row( + children: [ + Expanded( + child: BaseTextFormField( + controller: _loginController, + hintText: S.of(context).login, + )) + ], + ), + SizedBox(height: 10.0), + Row( + children: [ + Expanded( + child: BaseTextFormField( + controller: _passwordController, + hintText: S.of(context).password, + )) + ], + ), + Padding( + padding: EdgeInsets.only(top: 20), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.max, + children: [ + Observer( + builder: (_) => StandardCheckbox( + value: nodeViewModel.useSSL, + onChanged: (value) => nodeViewModel.useSSL = value, + caption: S.of(context).use_ssl, + ), + ) + ], + ), + ), + Padding( + padding: EdgeInsets.only(top: 20), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.max, + children: [ + Observer( + builder: (_) => StandardCheckbox( + value: nodeViewModel.trusted, + onChanged: (value) => nodeViewModel.trusted = value, + caption: S.of(context).trusted, + ), + ), + ], + ), + ), + ] + ], + ), + ); + } +} diff --git a/lib/view_model/node_list/node_create_or_edit_view_model.dart b/lib/view_model/node_list/node_create_or_edit_view_model.dart index c14bdda5e..be6e3e316 100644 --- a/lib/view_model/node_list/node_create_or_edit_view_model.dart +++ b/lib/view_model/node_list/node_create_or_edit_view_model.dart @@ -1,7 +1,6 @@ import 'package:cake_wallet/core/execution_state.dart'; import 'package:hive/hive.dart'; import 'package:mobx/mobx.dart'; -import 'package:cw_core/wallet_base.dart'; import 'package:cw_core/node.dart'; import 'package:cw_core/wallet_type.dart'; @@ -11,7 +10,7 @@ class NodeCreateOrEditViewModel = NodeCreateOrEditViewModelBase with _$NodeCreateOrEditViewModel; abstract class NodeCreateOrEditViewModelBase with Store { - NodeCreateOrEditViewModelBase(this._nodeSource, this._wallet) + NodeCreateOrEditViewModelBase(this._nodeSource, this._walletType) : state = InitialExecutionState(), connectionState = InitialExecutionState(), useSSL = false, @@ -45,8 +44,8 @@ abstract class NodeCreateOrEditViewModelBase with Store { bool get isReady => (address?.isNotEmpty ?? false) && (port?.isNotEmpty ?? false); - bool get hasAuthCredentials => _wallet.type == WalletType.monero || - _wallet.type == WalletType.haven; + bool get hasAuthCredentials => _walletType == WalletType.monero || + _walletType == WalletType.haven; String get uri { var uri = address; @@ -58,7 +57,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { return uri; } - final WalletBase _wallet; + final WalletType _walletType; final Box _nodeSource; @action @@ -76,7 +75,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { try { state = IsExecutingState(); final node = - Node(uri: uri, type: _wallet.type, login: login, password: password, + Node(uri: uri, type: _walletType, login: login, password: password, useSSL: useSSL, trusted: trusted); await _nodeSource.add(node); state = ExecutedSuccessfullyState(); @@ -90,7 +89,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { try { connectionState = IsExecutingState(); final node = - Node(uri: uri, type: _wallet.type, login: login, password: password); + Node(uri: uri, type: _walletType, login: login, password: password); final isAlive = await node.requestNode(); connectionState = ExecutedSuccessfullyState(payload: isAlive); } catch (e) { From 3c04bd9aa5899f3e626876af28adc4c270ab6546 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 5 Oct 2022 20:07:16 +0200 Subject: [PATCH 04/49] Pass wallet type when navigating Fix UI padding --- .../screens/new_wallet/advanced_privacy_settings_page.dart | 4 ++-- lib/src/screens/new_wallet/new_wallet_page.dart | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index e22afeb92..cb3e4e8dc 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -50,7 +50,7 @@ class _AdvancedPrivacySettingsBodyState return Container( padding: EdgeInsets.only(top: 24), child: ScrollableWithBottomSection( - contentPadding: EdgeInsets.only(left: 24, right: 24, bottom: 24), + contentPadding: EdgeInsets.only(bottom: 24), content: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ @@ -67,7 +67,7 @@ class _AdvancedPrivacySettingsBodyState builder: (_) { if (privacySettingsViewModel.addCustomNode) { return Padding( - padding: EdgeInsets.only(top: 24), + padding: EdgeInsets.only(left: 24, right: 24, top: 24), child: NodeForm( formKey: _formKey, nodeViewModel: nodeViewModel, diff --git a/lib/src/screens/new_wallet/new_wallet_page.dart b/lib/src/screens/new_wallet/new_wallet_page.dart index 8aef74445..6bbd9e72d 100644 --- a/lib/src/screens/new_wallet/new_wallet_page.dart +++ b/lib/src/screens/new_wallet/new_wallet_page.dart @@ -216,7 +216,8 @@ class _WalletNameFormState extends State { const SizedBox(height: 25), GestureDetector( onTap: () { - Navigator.of(context).pushNamed(Routes.privacySettings); + Navigator.of(context) + .pushNamed(Routes.privacySettings, arguments: _walletNewVM.type); }, child: Text(S.of(context).advanced_privacy_settings), ), From d4c7004a3cd7785d5f452cbc96089d7d0712cb4e Mon Sep 17 00:00:00 2001 From: Serhii Date: Fri, 4 Nov 2022 13:58:04 +0200 Subject: [PATCH 05/49] add Disable fiat mode --- lib/entities/default_settings_migration.dart | 1 + lib/entities/preferences_key.dart | 1 + lib/reactions/fiat_rate_update.dart | 4 +++- .../dashboard/widgets/transactions_page.dart | 4 +++- .../exchange_trade/exchange_trade_page.dart | 11 +++++++--- lib/src/screens/send/send_page.dart | 14 ++++++------- lib/src/screens/send/widgets/send_card.dart | 6 ++++-- lib/src/screens/settings/settings.dart | 13 +++++++----- lib/store/settings_store.dart | 14 +++++++++++++ .../dashboard/balance_view_model.dart | 19 ++++++++++------- .../settings/settings_view_model.dart | 21 +++++++++++++++---- 11 files changed, 76 insertions(+), 32 deletions(-) diff --git a/lib/entities/default_settings_migration.dart b/lib/entities/default_settings_migration.dart index b2036c3f6..ff8ffc2ed 100644 --- a/lib/entities/default_settings_migration.dart +++ b/lib/entities/default_settings_migration.dart @@ -61,6 +61,7 @@ Future defaultSettingsMigration( await sharedPreferences.setInt( PreferencesKey.currentBalanceDisplayModeKey, BalanceDisplayMode.availableBalance.raw); + await sharedPreferences.setBool('disable_fiat', false); await sharedPreferences.setBool('save_recipient_address', true); await resetToDefault(nodes); await changeMoneroCurrentNodeToDefault( diff --git a/lib/entities/preferences_key.dart b/lib/entities/preferences_key.dart index 6cf7e5608..62c458fa0 100644 --- a/lib/entities/preferences_key.dart +++ b/lib/entities/preferences_key.dart @@ -9,6 +9,7 @@ class PreferencesKey { static const currentTransactionPriorityKeyLegacy = 'current_fee_priority'; static const currentBalanceDisplayModeKey = 'current_balance_display_mode'; static const shouldSaveRecipientAddressKey = 'save_recipient_address'; + static const shouldDisableFiatKey = 'disable_fiat'; static const allowBiometricalAuthenticationKey = 'allow_biometrical_authentication'; static const currentTheme = 'current_theme'; diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index 784a14e82..fb40a26e3 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -27,7 +27,9 @@ Future startFiatRateUpdate(AppStore appStore, SettingsStore settingsStore, if (appStore.wallet!.type == WalletType.haven) { await updateHavenRate(fiatConversionStore); } else { - fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( + fiatConversionStore.prices[appStore.wallet!.currency] = + settingsStore.shouldDisableFiat ? 0.0 + : await FiatConversionService.fetchPrice( appStore.wallet!.currency, settingsStore.fiatCurrency); } } catch(e) { diff --git a/lib/src/screens/dashboard/widgets/transactions_page.dart b/lib/src/screens/dashboard/widgets/transactions_page.dart index 8ab7c0efb..9e09bae8c 100644 --- a/lib/src/screens/dashboard/widgets/transactions_page.dart +++ b/lib/src/screens/dashboard/widgets/transactions_page.dart @@ -57,7 +57,9 @@ class TransactionsPage extends StatelessWidget { formattedDate: DateFormat('HH:mm') .format(transaction.date), formattedAmount: item.formattedCryptoAmount, - formattedFiatAmount: item.formattedFiatAmount, + formattedFiatAmount: + dashboardViewModel.balanceViewModel.disableFiat + ? '' : item.formattedFiatAmount, isPending: transaction.isPending)); } diff --git a/lib/src/screens/exchange_trade/exchange_trade_page.dart b/lib/src/screens/exchange_trade/exchange_trade_page.dart index aa3079197..4128fb9f2 100644 --- a/lib/src/screens/exchange_trade/exchange_trade_page.dart +++ b/lib/src/screens/exchange_trade/exchange_trade_page.dart @@ -74,9 +74,12 @@ class ExchangeTradePage extends BasePage { } class ExchangeTradeForm extends StatefulWidget { - ExchangeTradeForm(this.exchangeTradeViewModel); + ExchangeTradeForm(this.exchangeTradeViewModel) + : disableFiat = + exchangeTradeViewModel.sendViewModel.balanceViewModel.disableFiat; final ExchangeTradeViewModel exchangeTradeViewModel; + final bool disableFiat; @override ExchangeTradeState createState() => ExchangeTradeState(); @@ -378,9 +381,11 @@ class ExchangeTradeState extends State { }); }, actionLeftButton: () => Navigator.of(context).pop(), - feeFiatAmount: widget.exchangeTradeViewModel.sendViewModel.pendingTransactionFeeFiatAmount + feeFiatAmount: widget.disableFiat ? '' + : widget.exchangeTradeViewModel.sendViewModel.pendingTransactionFeeFiatAmount + ' ' + widget.exchangeTradeViewModel.sendViewModel.fiat.title, - fiatAmountValue: widget.exchangeTradeViewModel.sendViewModel + fiatAmountValue: widget.disableFiat ? '' + : widget.exchangeTradeViewModel.sendViewModel .pendingTransactionFiatAmount + ' ' + widget.exchangeTradeViewModel.sendViewModel.fiat.title, diff --git a/lib/src/screens/send/send_page.dart b/lib/src/screens/send/send_page.dart index e0cfff517..8815d8c58 100644 --- a/lib/src/screens/send/send_page.dart +++ b/lib/src/screens/send/send_page.dart @@ -386,16 +386,14 @@ class SendPage extends BasePage { amount: S.of(context).send_amount, amountValue: sendViewModel.pendingTransaction!.amountFormatted, - fiatAmountValue: - sendViewModel.pendingTransactionFiatAmount + - ' ' + - sendViewModel.fiat.title, + fiatAmountValue: sendViewModel.balanceViewModel.disableFiat + ? '' : sendViewModel.pendingTransactionFiatAmount + + ' ' + sendViewModel.fiat.title, fee: S.of(context).send_fee, feeValue: sendViewModel.pendingTransaction!.feeFormatted, - feeFiatAmount: - sendViewModel.pendingTransactionFeeFiatAmount + - ' ' + - sendViewModel.fiat.title, + feeFiatAmount: sendViewModel.balanceViewModel.disableFiat + ? '' : sendViewModel.pendingTransactionFeeFiatAmount + + ' ' + sendViewModel.fiat.title, outputs: sendViewModel.outputs, rightButtonText: S.of(context).ok, leftButtonText: S.of(context).cancel, diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index dc589923f..7e7194f88 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -332,6 +332,8 @@ class SendCardState extends State ], ), )), + sendViewModel.balanceViewModel.disableFiat ? + Container () : Padding( padding: const EdgeInsets.only(top: 20), child: BaseTextFormField( @@ -438,8 +440,8 @@ class SendCardState extends State Padding( padding: EdgeInsets.only(top: 5), - child: Text( - output + child: sendViewModel.balanceViewModel.disableFiat ? + Container () : Text(output .estimatedFeeFiatAmount + ' ' + sendViewModel diff --git a/lib/src/screens/settings/settings.dart b/lib/src/screens/settings/settings.dart index 3f6f41e7b..4a1f6bcb0 100644 --- a/lib/src/screens/settings/settings.dart +++ b/lib/src/screens/settings/settings.dart @@ -29,18 +29,20 @@ class SettingsPage extends BasePage { @override Widget body(BuildContext context) { // FIX-ME: Added `context` it was not used here before, maby bug ? - return SectionStandardList( + return Observer(builder: (_) { + final sections = settingsViewModel.getSections(); + return SectionStandardList( context: context, - sectionCount: settingsViewModel.sections.length, + sectionCount: sections.length, itemCounter: (int sectionIndex) { - if (sectionIndex < settingsViewModel.sections.length) { - return settingsViewModel.sections[sectionIndex].length; + if (sectionIndex < sections.length) { + return sections[sectionIndex].length; } return 0; }, itemBuilder: (_, sectionIndex, itemIndex) { - final item = settingsViewModel.sections[sectionIndex][itemIndex]; + final item = sections[sectionIndex][itemIndex]; if (item is PickerListItem) { return Observer(builder: (_) { @@ -94,5 +96,6 @@ class SettingsPage extends BasePage { return Container(); }); + }); } } diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index 2b3105a34..5afd2c107 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -29,6 +29,7 @@ abstract class SettingsStoreBase with Store { required FiatCurrency initialFiatCurrency, required BalanceDisplayMode initialBalanceDisplayMode, required bool initialSaveRecipientAddress, + required bool initialDisableFiat, required bool initialAllowBiometricalAuthentication, required ThemeBase initialTheme, required int initialPinLength, @@ -46,6 +47,7 @@ abstract class SettingsStoreBase with Store { fiatCurrency = initialFiatCurrency, balanceDisplayMode = initialBalanceDisplayMode, shouldSaveRecipientAddress = initialSaveRecipientAddress, + shouldDisableFiat = initialDisableFiat, allowBiometricalAuthentication = initialAllowBiometricalAuthentication, currentTheme = initialTheme, pinCodeLength = initialPinLength, @@ -87,6 +89,12 @@ abstract class SettingsStoreBase with Store { PreferencesKey.shouldSaveRecipientAddressKey, shouldSaveRecipientAddress)); + reaction( + (_) => shouldDisableFiat, + (bool shouldDisableFiat) => sharedPreferences.setBool( + PreferencesKey.shouldDisableFiatKey, + shouldDisableFiat)); + reaction( (_) => currentTheme, (ThemeBase theme) => @@ -140,6 +148,9 @@ abstract class SettingsStoreBase with Store { @observable bool shouldSaveRecipientAddress; + @observable + bool shouldDisableFiat; + @observable bool allowBiometricalAuthentication; @@ -218,6 +229,8 @@ abstract class SettingsStoreBase with Store { // FIX-ME: Check for which default value we should have here final shouldSaveRecipientAddress = sharedPreferences.getBool(PreferencesKey.shouldSaveRecipientAddressKey) ?? false; + final shouldDisableFiat = + sharedPreferences.getBool(PreferencesKey.shouldDisableFiatKey) ?? false; final allowBiometricalAuthentication = sharedPreferences .getBool(PreferencesKey.allowBiometricalAuthenticationKey) ?? false; @@ -283,6 +296,7 @@ abstract class SettingsStoreBase with Store { initialFiatCurrency: currentFiatCurrency, initialBalanceDisplayMode: currentBalanceDisplayMode, initialSaveRecipientAddress: shouldSaveRecipientAddress, + initialDisableFiat: shouldDisableFiat, initialAllowBiometricalAuthentication: allowBiometricalAuthentication, initialTheme: savedTheme, actionlistDisplayMode: actionListDisplayMode, diff --git a/lib/view_model/dashboard/balance_view_model.dart b/lib/view_model/dashboard/balance_view_model.dart index 75d107b89..40502bb84 100644 --- a/lib/view_model/dashboard/balance_view_model.dart +++ b/lib/view_model/dashboard/balance_view_model.dart @@ -71,6 +71,9 @@ abstract class BalanceViewModelBase with Store { @computed BalanceDisplayMode get savedDisplayMode => settingsStore.balanceDisplayMode; + @computed + bool get disableFiat => settingsStore.shouldDisableFiat; + @computed String get asset { final typeFormatted = walletTypeToString(appStore.wallet!.type); @@ -180,8 +183,8 @@ abstract class BalanceViewModelBase with Store { return MapEntry(key, BalanceRecord( availableBalance: '---', additionalBalance: '---', - fiatAdditionalBalance: '---', - fiatAvailableBalance: '---', + fiatAdditionalBalance: disableFiat ? '' : '---', + fiatAvailableBalance: disableFiat ? '' : '---', asset: key, formattedAssetTitle: _formatterAsset(key))); } @@ -192,17 +195,17 @@ abstract class BalanceViewModelBase with Store { // throw Exception('Price is null for: $key'); // } - final additionalFiatBalance = fiatCurrency.toString() - + ' ' + final additionalFiatBalance = disableFiat ? '' : (fiatCurrency.toString() + + ' ' + _getFiatBalance( price: price, - cryptoAmount: value.formattedAdditionalBalance); + cryptoAmount: value.formattedAdditionalBalance)); - final availableFiatBalance = fiatCurrency.toString() - + ' ' + final availableFiatBalance = disableFiat ? '' : (fiatCurrency.toString() + + ' ' + _getFiatBalance( price: price, - cryptoAmount: value.formattedAvailableBalance); + cryptoAmount: value.formattedAvailableBalance)); return MapEntry(key, BalanceRecord( availableBalance: value.formattedAvailableBalance, diff --git a/lib/view_model/settings/settings_view_model.dart b/lib/view_model/settings/settings_view_model.dart index 96b2e7bdd..23ea0fded 100644 --- a/lib/view_model/settings/settings_view_model.dart +++ b/lib/view_model/settings/settings_view_model.dart @@ -61,7 +61,6 @@ abstract class SettingsViewModelBase with Store { : itemHeaders = {}, _walletType = wallet.type, _biometricAuth = BiometricAuth(), - sections = >[], currentVersion = '' { PackageInfo.fromPlatform().then( (PackageInfo packageInfo) => currentVersion = packageInfo.version); @@ -98,7 +97,7 @@ abstract class SettingsViewModelBase with Store { //} - sections = [ + getSections = () => [ [ SwitcherListItem( title: S.current.settings_display_balance, @@ -111,7 +110,7 @@ abstract class SettingsViewModelBase with Store { } }, ), - if (!isHaven) + if (!isHaven && !shouldDisableFiat) PickerListItem( title: S.current.settings_currency, searchHintText: S.current.search_currency, @@ -183,6 +182,11 @@ abstract class SettingsViewModelBase with Store { return LanguageService.list[code]?.toLowerCase().contains(searchText) ?? false; }, ), + SwitcherListItem( + title: 'S.current.disable_fiat', + value: () => shouldDisableFiat, + onValueChange: (_, bool value) => + setShouldDisableFiat(value)), SwitcherListItem( title: S.current.settings_allow_biometrical_authentication, value: () => allowBiometricalAuthentication, @@ -208,6 +212,7 @@ abstract class SettingsViewModelBase with Store { setAllowBiometricalAuthentication(value); } }), + ChoicesListItem( title: S.current.color_theme, items: ThemeList.all, @@ -275,6 +280,10 @@ abstract class SettingsViewModelBase with Store { bool get shouldSaveRecipientAddress => _settingsStore.shouldSaveRecipientAddress; + @computed + bool get shouldDisableFiat => + _settingsStore.shouldDisableFiat; + @computed bool get allowBiometricalAuthentication => _settingsStore.allowBiometricalAuthentication; @@ -285,7 +294,7 @@ abstract class SettingsViewModelBase with Store { bool get isBitcoinBuyEnabled => _settingsStore.isBitcoinBuyEnabled; final Map itemHeaders; - List> sections; + late List> Function() getSections; final SettingsStore _settingsStore; final YatStore _yatStore; final WalletType _walletType; @@ -303,6 +312,10 @@ abstract class SettingsViewModelBase with Store { void setShouldSaveRecipientAddress(bool value) => _settingsStore.shouldSaveRecipientAddress = value; + @action + void setShouldDisableFiat(bool value) => + _settingsStore.shouldDisableFiat = value; + @action void setAllowBiometricalAuthentication(bool value) => _settingsStore.allowBiometricalAuthentication = value; From b5e74874cef3a2f63105baca116d69e16b95e3ca Mon Sep 17 00:00:00 2001 From: Serhii Date: Fri, 4 Nov 2022 14:11:06 +0200 Subject: [PATCH 06/49] update localization files --- res/values/strings_de.arb | 3 ++- res/values/strings_en.arb | 3 ++- res/values/strings_es.arb | 3 ++- res/values/strings_fr.arb | 3 ++- res/values/strings_hi.arb | 3 ++- res/values/strings_hr.arb | 3 ++- res/values/strings_it.arb | 3 ++- res/values/strings_ja.arb | 3 ++- res/values/strings_ko.arb | 3 ++- res/values/strings_nl.arb | 3 ++- res/values/strings_pl.arb | 3 ++- res/values/strings_pt.arb | 3 ++- res/values/strings_ru.arb | 3 ++- res/values/strings_uk.arb | 3 ++- res/values/strings_zh.arb | 3 ++- 15 files changed, 30 insertions(+), 15 deletions(-) diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index a580ab90a..e5d12d80b 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -651,5 +651,6 @@ "ignor": "Ignorieren", "use_suggested": "Vorgeschlagen verwenden", "do_not_share_warning_text" : "Teilen Sie diese nicht mit anderen, einschließlich des Supports.\n\nSie werden Ihr Geld stehlen!", - "help": "hilfe" + "help": "hilfe", + "disable_fiat": "Fiat deaktivieren" } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 877d09231..aa995606f 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -651,5 +651,6 @@ "ignor": "Ignore", "use_suggested": "Use Suggested", "do_not_share_warning_text" : "Do not share these with anyone else, including support.\n\nThey will steal your money!", - "help": "help" + "help": "help", + "disable_fiat": "Disable fiat" } diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 505f3ffa8..843e7c9f9 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -651,5 +651,6 @@ "ignor": "Pasar por alto", "use_suggested": "Usar sugerido", "do_not_share_warning_text" : "No comparta estos con nadie más, incluido el soporte.\n\n¡Te robarán tu dinero!", - "help": "ayuda" + "help": "ayuda", + "disable_fiat": "Deshabilitar fiat" } diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index 941016c0b..d4b36dc4d 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -649,5 +649,6 @@ "ignor": "Ignorer", "use_suggested": "Utilisation suggérée", "do_not_share_warning_text" : "Ne les partagez avec personne d'autre, y compris avec l'assistance.\n\nIls vont voler votre argent!", - "help": "aider" + "help": "aider", + "disable_fiat": "Désactiver fiat" } diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index 7faa06f7f..a94bfb628 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -651,5 +651,6 @@ "ignor": "नज़रअंदाज़ करना", "use_suggested": "सुझाए गए का प्रयोग करें", "do_not_share_warning_text" : "इन्हें समर्थन सहित किसी और के साथ साझा न करें।\n\nवे आपका पैसा चुरा लेंगे!", - "help": "मदद करना" + "help": "मदद करना", + "disable_fiat": "िएट अक्षम करें" } diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index 4fa77948a..dac4b5f23 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -651,5 +651,6 @@ "ignor": "Zanemariti", "use_suggested": "Koristite predloženo", "do_not_share_warning_text" : "Nemojte ih dijeliti ni s kim, uključujući podršku.\n\nUkrast će vam novac!", - "help": "pomozite" + "help": "pomozite", + "disable_fiat": "Isključi, fiat" } diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index 9a42a588b..e14c4c7d4 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -651,5 +651,6 @@ "ignor": "Ignorare", "use_suggested": "Usa suggerito", "do_not_share_warning_text" : "Non condividerli con nessun altro, incluso il supporto.\n\nTi ruberanno i soldi!", - "help": "aiuto" + "help": "aiuto", + "disable_fiat": "Disabilita fiat" } diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index c1d0de4e3..62b12033a 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -651,5 +651,6 @@ "ignor": "無視", "use_suggested": "推奨を使用", "do_not_share_warning_text" : "サポートを含め、これらを他の誰とも共有しないでください。\n\n彼らはあなたのお金を盗みます!", - "help": "ヘルプ" + "help": "ヘルプ", + "disable_fiat": "フィアットを無効にする" } diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index 127aa949e..35f0520d4 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -651,5 +651,6 @@ "ignor": "무시하다", "use_suggested": "추천 사용", "do_not_share_warning_text" : "지원을 포함하여 다른 사람과 이러한 정보를 공유하지 마십시오.\n\n그들은 당신의 돈을 훔칠 것입니다!", - "help": "돕다" + "help": "돕다", + "disable_fiat": "법정화폐 비활성화" } diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index bc53337a8..d8ced1592 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -651,5 +651,6 @@ "ignor": "Negeren", "use_suggested": "Gebruik aanbevolen", "do_not_share_warning_text" : "Deel deze met niemand anders, ook niet met support.\n\nZe zullen je geld stelen!", - "help": "helpen" + "help": "helpen", + "disable_fiat": "법정화폐 비활성화" } diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index 454fe9717..59f7c227e 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -651,5 +651,6 @@ "ignor": "Ignorować", "use_suggested": "Użyj sugerowane", "do_not_share_warning_text" : "Nie udostępniaj ich nikomu innemu, w tym wsparcia.\n\nUkradną twoje pieniądze!", - "help": "pomoc" + "help": "pomoc", + "disable_fiat": "Wyłącz fiat" } diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 04a0a3ff2..defbf6ac1 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -651,5 +651,6 @@ "ignor": "Ignorar", "use_suggested": "Uso sugerido", "do_not_share_warning_text" : "Não os compartilhe com mais ninguém, incluindo suporte.\n\nEles vão roubar seu dinheiro!", - "help": "ajuda" + "help": "ajuda", + "disable_fiat": "Desativar fiat" } diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index 632b0990c..9fa39b59b 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -651,5 +651,6 @@ "ignor": "Игнорировать", "use_suggested": "Использовать предложенный", "do_not_share_warning_text" : "Не делитесь ими с кем-либо еще, в том числе со службой поддержки.\n\nОни украдут ваши деньги!", - "help": "помощь" + "help": "помощь", + "disable_fiat": "Отключить фиат" } diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index 5e0f0d18a..9e16d6696 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -650,5 +650,6 @@ "ignor": "Ігнорувати", "use_suggested": "Використати запропоноване", "do_not_share_warning_text" : "Не повідомляйте їх нікому, включно зі службою підтримки.\n\nВони вкрадуть ваші гроші!", - "help": "допомога" + "help": "допомога", + "disable_fiat": "Вимкнути фиат" } diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index c46d07d59..40ab71cad 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -649,5 +649,6 @@ "ignor": "忽视", "use_suggested": "使用建议", "do_not_share_warning_text" : "不要與其他任何人分享這些內容,包括支持。\n\n他們會偷你的錢!", - "help": "帮助" + "help": "帮助", + "disable_fiat": "禁用法令" } From c99e5f6f317ebbedd504c4068418a193acecbe34 Mon Sep 17 00:00:00 2001 From: Serhii Date: Fri, 4 Nov 2022 14:28:41 +0200 Subject: [PATCH 07/49] fix localization --- lib/view_model/settings/settings_view_model.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/view_model/settings/settings_view_model.dart b/lib/view_model/settings/settings_view_model.dart index 23ea0fded..4d0e9221a 100644 --- a/lib/view_model/settings/settings_view_model.dart +++ b/lib/view_model/settings/settings_view_model.dart @@ -183,7 +183,7 @@ abstract class SettingsViewModelBase with Store { }, ), SwitcherListItem( - title: 'S.current.disable_fiat', + title: S.current.disable_fiat, value: () => shouldDisableFiat, onValueChange: (_, bool value) => setShouldDisableFiat(value)), From 2cd748c151488a8378d1e28c25a98588ad163c6e Mon Sep 17 00:00:00 2001 From: Serhii Date: Sat, 5 Nov 2022 20:05:55 +0200 Subject: [PATCH 08/49] filter contacts and wallets by type --- lib/di.dart | 9 ++++--- lib/router.dart | 8 ++++-- .../screens/contact/contact_list_page.dart | 25 +++++++++++-------- .../exchange/widgets/exchange_card.dart | 3 ++- lib/src/screens/send/widgets/send_card.dart | 1 + lib/src/widgets/address_text_field.dart | 7 ++++-- .../contact_list/contact_list_view_model.dart | 17 +++++++++++++ 7 files changed, 51 insertions(+), 19 deletions(-) diff --git a/lib/di.dart b/lib/di.dart index 7ce2ff6d9..01d77b881 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -153,6 +153,7 @@ import 'package:cake_wallet/anypay/any_pay_payment_committed_info.dart'; import 'package:cake_wallet/ionia/ionia_any_pay_payment_info.dart'; import 'package:cake_wallet/src/screens/receive/fullscreen_qr_page.dart'; import 'package:cake_wallet/core/wallet_loading_service.dart'; +import 'package:cw_core/crypto_currency.dart'; final getIt = GetIt.instance; @@ -461,9 +462,11 @@ Future setup( getIt.registerFactory( () => ContactListViewModel(_contactSource, _walletInfoSource)); - getIt.registerFactoryParam( - (bool isEditable, _) => ContactListPage(getIt.get(), - isEditable: isEditable)); + getIt.registerFactoryParam((bool isEditable, CryptoCurrency? cur) + => ContactListPage( + getIt.get(), + isEditable: isEditable, + selectedCurrency: cur)); getIt.registerFactoryParam( (ContactRecord? contact, _) => diff --git a/lib/router.dart b/lib/router.dart index b255ce8b9..8b43fbaf5 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -74,6 +74,7 @@ import 'package:cake_wallet/src/screens/ionia/ionia.dart'; import 'package:cake_wallet/src/screens/ionia/cards/ionia_payment_status_page.dart'; import 'package:cake_wallet/anypay/any_pay_payment_committed_info.dart'; import 'package:cake_wallet/ionia/ionia_any_pay_payment_info.dart'; +import 'package:cw_core/crypto_currency.dart'; late RouteSettings currentRouteSettings; @@ -298,11 +299,14 @@ Route createRoute(RouteSettings settings) { case Routes.addressBook: return MaterialPageRoute( - builder: (_) => getIt.get(param1: true)); + builder: (_) => + getIt.get(param1: true, param2: null)); case Routes.pickerAddressBook: + final selectedCurrency = settings.arguments as CryptoCurrency; return MaterialPageRoute( - builder: (_) => getIt.get(param1: false)); + builder: (_) => getIt.get(param1: false, + param2: selectedCurrency)); case Routes.addressBookAddContact: return CupertinoPageRoute( diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 7912472d8..6d23518b8 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -16,10 +16,12 @@ import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart import 'package:cake_wallet/src/widgets/collapsible_standart_list.dart'; class ContactListPage extends BasePage { - ContactListPage(this.contactListViewModel, {this.isEditable = true}); + ContactListPage(this.contactListViewModel, + {this.isEditable = true, required this.selectedCurrency}); final ContactListViewModel contactListViewModel; final bool isEditable; + final CryptoCurrency? selectedCurrency; @override String get title => S.current.address_book; @@ -60,11 +62,13 @@ class ContactListPage extends BasePage { @override Widget body(BuildContext context) { + final contacts = + contactListViewModel.getContacts(isEditable, selectedCurrency); + final walletContacts = + contactListViewModel.getWallets(isEditable, selectedCurrency); return Container( padding: EdgeInsets.only(top: 20.0, bottom: 20.0), - child: Observer( - builder: (_) { - return CollapsibleSectionList( + child: CollapsibleSectionList( context: context, sectionCount: 2, themeColor: Theme.of(context).primaryTextTheme.headline6!.color!, @@ -82,15 +86,15 @@ class ContactListPage extends BasePage { child: Text(title, style: TextStyle(fontSize: 36))); }, itemCounter: (int sectionIndex) => sectionIndex == 0 - ? contactListViewModel.walletContacts.length - : contactListViewModel.contacts.length, + ? walletContacts.length + : contacts.length, itemBuilder: (_, sectionIndex, index) { if (sectionIndex == 0) { - final walletInfo = contactListViewModel.walletContacts[index]; + final walletInfo = walletContacts[index]; return generateRaw(context, walletInfo); } - final contact = contactListViewModel.contacts[index]; + final contact = contacts[index]; final content = generateRaw(context, contact); return !isEditable ? content @@ -100,9 +104,8 @@ class ContactListPage extends BasePage { child: content, ); }, - ); - }, - )); + ) + ); } Widget generateRaw(BuildContext context, ContactBase contact) { diff --git a/lib/src/screens/exchange/widgets/exchange_card.dart b/lib/src/screens/exchange/widgets/exchange_card.dart index 98843b1fb..40aa679a4 100644 --- a/lib/src/screens/exchange/widgets/exchange_card.dart +++ b/lib/src/screens/exchange/widgets/exchange_card.dart @@ -395,7 +395,8 @@ class ExchangeCardState extends State { buttonColor: widget.addressButtonsColor, validator: widget.addressTextFieldValidator, onPushPasteButton: widget.onPushPasteButton, - onPushAddressBookButton: widget.onPushAddressBookButton + onPushAddressBookButton: widget.onPushAddressBookButton, + selectedCurrency: _selectedCurrency ), ) diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index dc589923f..03e4471fe 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -155,6 +155,7 @@ class SendCardState extends State await output.fetchParsedAddress(context); }, validator: validator, + selectedCurrency: sendViewModel.currency, ); }), if (output.isParsedAddress) Padding( diff --git a/lib/src/widgets/address_text_field.dart b/lib/src/widgets/address_text_field.dart index 35bf3ed85..7e0727312 100644 --- a/lib/src/widgets/address_text_field.dart +++ b/lib/src/widgets/address_text_field.dart @@ -4,6 +4,7 @@ import 'package:cake_wallet/routes.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/entities/qr_scanner.dart'; import 'package:cake_wallet/entities/contact_base.dart'; +import 'package:cw_core/crypto_currency.dart'; enum AddressTextFieldOption { paste, qrCode, addressBook } @@ -26,7 +27,8 @@ class AddressTextField extends StatelessWidget { this.hintStyle, this.validator, this.onPushPasteButton, - this.onPushAddressBookButton}); + this.onPushAddressBookButton, + this.selectedCurrency}); static const prefixIconWidth = 34.0; static const prefixIconHeight = 34.0; @@ -47,6 +49,7 @@ class AddressTextField extends StatelessWidget { final FocusNode? focusNode; final Function(BuildContext context)? onPushPasteButton; final Function(BuildContext context)? onPushAddressBookButton; + final CryptoCurrency? selectedCurrency; @override Widget build(BuildContext context) { @@ -207,7 +210,7 @@ class AddressTextField extends StatelessWidget { Future _presetAddressBookPicker(BuildContext context) async { final contact = await Navigator.of(context, rootNavigator: true) - .pushNamed(Routes.pickerAddressBook); + .pushNamed(Routes.pickerAddressBook,arguments: selectedCurrency); if (contact is ContactBase && contact.address != null) { controller?.text = contact.address; diff --git a/lib/view_model/contact_list/contact_list_view_model.dart b/lib/view_model/contact_list/contact_list_view_model.dart index ec145ad44..0f67245af 100644 --- a/lib/view_model/contact_list/contact_list_view_model.dart +++ b/lib/view_model/contact_list/contact_list_view_model.dart @@ -7,6 +7,7 @@ import 'package:mobx/mobx.dart'; import 'package:cake_wallet/entities/contact_record.dart'; import 'package:cake_wallet/entities/contact.dart'; import 'package:cake_wallet/utils/mobx.dart'; +import 'package:cw_core/crypto_currency.dart'; part 'contact_list_view_model.g.dart'; @@ -44,4 +45,20 @@ abstract class ContactListViewModelBase with Store { StreamSubscription? _subscription; Future delete(ContactRecord contact) async => contact.original.delete(); + + List getContacts(bool isEditable, CryptoCurrency? cur) { + if (!isEditable) { + return contacts.where((element) => element.type == cur).toList(); + } + + return contacts; + } + + List getWallets(bool isEditable, CryptoCurrency? cur) { + if (!isEditable) { + return walletContacts.where((element) => element.type == cur).toList(); + } + + return walletContacts; + } } From ba783982e43216fea584cc2cea096020adcf491b Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 9 Nov 2022 17:53:50 +0200 Subject: [PATCH 09/49] Update branch to null safety Fix Conflicts with main --- cw_core/lib/node.dart | 6 ++---- lib/di.dart | 5 +++-- .../advanced_privacy_settings_page.dart | 7 +++---- lib/src/screens/nodes/widgets/node_form.dart | 4 ++-- .../node_create_or_edit_view_model.dart | 13 ++++++------- .../privacy_settings_view_model.dart | 18 +++++++++--------- 6 files changed, 25 insertions(+), 28 deletions(-) diff --git a/cw_core/lib/node.dart b/cw_core/lib/node.dart index 28a54947c..5fce69a8e 100644 --- a/cw_core/lib/node.dart +++ b/cw_core/lib/node.dart @@ -17,7 +17,7 @@ class Node extends HiveObject with Keyable { {this.login, this.password, this.useSSL, - this.trusted, + this.trusted = false, String? uri, WalletType? type,}) { if (uri != null) { @@ -33,7 +33,7 @@ class Node extends HiveObject with Keyable { login = map['login'] as String?, password = map['password'] as String?, useSSL = map['useSSL'] as bool?, - useSSL = map['trusted'] as bool? ?? false; + trusted = map['trusted'] as bool? ?? false; static const typeId = 1; static const boxName = 'Nodes'; @@ -58,8 +58,6 @@ class Node extends HiveObject with Keyable { bool get isSSL => useSSL ?? false; - bool get isTrusted => trusted ?? false; - Uri get uri { switch (type) { case WalletType.monero: diff --git a/lib/di.dart b/lib/di.dart index 73421c989..7a3a8631c 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -478,8 +478,9 @@ Future setup( getIt.registerFactory(() => NodeListPage(getIt.get())); - getIt.registerFactory(() => - NodeCreateOrEditViewModel(_nodeSource, getIt.get().wallet!)); + getIt.registerFactoryParam( + (WalletType? type, _) => + NodeCreateOrEditViewModel(_nodeSource, type ?? getIt.get().wallet!.type)); getIt.registerFactory( () => NodeCreateOrEditPage(getIt.get())); diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index cb3e4e8dc..58adc9d99 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -4,7 +4,6 @@ import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model. import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/cupertino.dart'; import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; import 'package:cake_wallet/src/widgets/primary_button.dart'; @@ -25,7 +24,7 @@ class AdvancedPrivacySettingsPage extends BasePage { } class AdvancedPrivacySettingsBody extends StatefulWidget { - const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, this.nodeViewModel, {Key key}) + const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, this.nodeViewModel, {Key? key}) : super(key: key); final PrivacySettingsViewModel privacySettingsViewModel; @@ -85,7 +84,7 @@ class _AdvancedPrivacySettingsBodyState LoadingPrimaryButton( onPressed: () {}, text: S.of(context).continue_text, - color: Theme.of(context).accentTextTheme.body2.color, + color: Theme.of(context).accentTextTheme.bodyText1!.color!, textColor: Colors.white, ), const SizedBox(height: 25), @@ -96,7 +95,7 @@ class _AdvancedPrivacySettingsBodyState S.of(context).settings_can_be_changed_later, textAlign: TextAlign.center, style: TextStyle( - color: Theme.of(context).accentTextTheme.display3.color, + color: Theme.of(context).accentTextTheme.headline2?.color, ), ), ), diff --git a/lib/src/screens/nodes/widgets/node_form.dart b/lib/src/screens/nodes/widgets/node_form.dart index 757032a2a..52851e063 100644 --- a/lib/src/screens/nodes/widgets/node_form.dart +++ b/lib/src/screens/nodes/widgets/node_form.dart @@ -10,8 +10,8 @@ import 'package:mobx/mobx.dart'; class NodeForm extends StatelessWidget { NodeForm({ - @required this.nodeViewModel, - @required this.formKey, + required this.nodeViewModel, + required this.formKey, }) : _addressController = TextEditingController(), _portController = TextEditingController(), _loginController = TextEditingController(), diff --git a/lib/view_model/node_list/node_create_or_edit_view_model.dart b/lib/view_model/node_list/node_create_or_edit_view_model.dart index 7137cdd2c..34167ae0a 100644 --- a/lib/view_model/node_list/node_create_or_edit_view_model.dart +++ b/lib/view_model/node_list/node_create_or_edit_view_model.dart @@ -1,7 +1,6 @@ import 'package:cake_wallet/core/execution_state.dart'; import 'package:hive/hive.dart'; import 'package:mobx/mobx.dart'; -import 'package:cw_core/wallet_base.dart'; import 'package:cw_core/node.dart'; import 'package:cw_core/wallet_type.dart'; @@ -11,7 +10,7 @@ class NodeCreateOrEditViewModel = NodeCreateOrEditViewModelBase with _$NodeCreateOrEditViewModel; abstract class NodeCreateOrEditViewModelBase with Store { - NodeCreateOrEditViewModelBase(this._nodeSource, this._wallet) + NodeCreateOrEditViewModelBase(this._nodeSource, this._walletType) : state = InitialExecutionState(), connectionState = InitialExecutionState(), useSSL = false, @@ -49,8 +48,8 @@ abstract class NodeCreateOrEditViewModelBase with Store { bool get isReady => address.isNotEmpty && port.isNotEmpty; - bool get hasAuthCredentials => _wallet.type == WalletType.monero || - _wallet.type == WalletType.haven; + bool get hasAuthCredentials => _walletType == WalletType.monero || + _walletType == WalletType.haven; String get uri { var uri = address; @@ -62,7 +61,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { return uri; } - final WalletBase _wallet; + final WalletType _walletType; final Box _nodeSource; @action @@ -80,7 +79,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { try { state = IsExecutingState(); final node = - Node(uri: uri, type: _wallet.type, login: login, password: password, + Node(uri: uri, type: _walletType, login: login, password: password, useSSL: useSSL, trusted: trusted); await _nodeSource.add(node); state = ExecutedSuccessfullyState(); @@ -94,7 +93,7 @@ abstract class NodeCreateOrEditViewModelBase with Store { try { connectionState = IsExecutingState(); final node = - Node(uri: uri, type: _wallet.type, login: login, password: password); + Node(uri: uri, type: _walletType, login: login, password: password); final isAlive = await node.requestNode(); connectionState = ExecutedSuccessfullyState(payload: isAlive); } catch (e) { diff --git a/lib/view_model/privacy_settings_view_model.dart b/lib/view_model/privacy_settings_view_model.dart index ce5a3f7a6..760c577ef 100644 --- a/lib/view_model/privacy_settings_view_model.dart +++ b/lib/view_model/privacy_settings_view_model.dart @@ -9,13 +9,13 @@ class PrivacySettingsViewModel = PrivacySettingsViewModelBase with _$PrivacySettingsViewModel; abstract class PrivacySettingsViewModelBase with Store { - PrivacySettingsViewModelBase(this.type) { - _disableFiat = false; - _disableExchange = false; - _addCustomNode = false; - + PrivacySettingsViewModelBase(this.type) + : _disableFiat = false, + _disableExchange = false, + _addCustomNode = false { settings = [ SwitcherListItem( + // TODO: replace when Disable Fiat PR is merged title: "Disable Fiat API", // title: S.current.disable_fiat, value: () => _disableFiat, @@ -36,16 +36,16 @@ abstract class PrivacySettingsViewModelBase with Store { ]; } - List settings; + late List settings; @observable - bool _disableFiat; + bool _disableFiat = false; @observable - bool _disableExchange; + bool _disableExchange = false; @observable - bool _addCustomNode; + bool _addCustomNode = false; final WalletType type; From ec10732eda3296cd4878bd94b02e8df8f2f87c2c Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 9 Nov 2022 19:40:12 +0200 Subject: [PATCH 10/49] Save node on continue --- .../screens/new_wallet/advanced_privacy_settings_page.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index 58adc9d99..da67d4511 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -82,7 +82,9 @@ class _AdvancedPrivacySettingsBodyState bottomSection: Column( children: [ LoadingPrimaryButton( - onPressed: () {}, + onPressed: () { + nodeViewModel.save(); + }, text: S.of(context).continue_text, color: Theme.of(context).accentTextTheme.bodyText1!.color!, textColor: Colors.white, From cf7c21946b4550d793158a753800857d5d859708 Mon Sep 17 00:00:00 2001 From: Justin Ehrenhofer Date: Thu, 10 Nov 2022 14:45:10 -0600 Subject: [PATCH 11/49] Improve warning wording Recommended in the Telegram testing group --- res/values/strings_de.arb | 2 +- res/values/strings_en.arb | 2 +- res/values/strings_es.arb | 2 +- res/values/strings_fr.arb | 2 +- res/values/strings_hi.arb | 2 +- res/values/strings_hr.arb | 2 +- res/values/strings_it.arb | 2 +- res/values/strings_ja.arb | 2 +- res/values/strings_ko.arb | 2 +- res/values/strings_nl.arb | 2 +- res/values/strings_pl.arb | 2 +- res/values/strings_pt.arb | 2 +- res/values/strings_ru.arb | 2 +- res/values/strings_uk.arb | 2 +- res/values/strings_zh.arb | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index 685d817d5..dda932168 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -650,6 +650,6 @@ "low_fee_alert": "Sie verwenden derzeit eine niedrige Netzwerkgebührenpriorität. Dies kann zu langen Wartezeiten, unterschiedlichen Kursen oder stornierten Trades führen. Wir empfehlen, für ein besseres Erlebnis eine höhere Gebühr festzulegen.", "ignor": "Ignorieren", "use_suggested": "Vorgeschlagen verwenden", - "do_not_share_warning_text" : "Teilen Sie diese nicht mit anderen, einschließlich des Supports.\n\nSie werden Ihr Geld stehlen!", + "do_not_share_warning_text" : "Teilen Sie diese nicht mit anderen, einschließlich Support.\n\nIhr Geld kann und wird gestohlen werden!", "help": "hilfe" } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 877d09231..464f9ee06 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -650,6 +650,6 @@ "low_fee_alert": "You currently are using a low network fee priority. This could cause long waits, different rates, or canceled trades. We recommend setting a higher fee for a better experience.", "ignor": "Ignore", "use_suggested": "Use Suggested", - "do_not_share_warning_text" : "Do not share these with anyone else, including support.\n\nThey will steal your money!", + "do_not_share_warning_text" : "Do not share these with anyone else, including support.\n\nYour funds can and will be stolen!", "help": "help" } diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 505f3ffa8..45a2a6ae7 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -650,6 +650,6 @@ "low_fee_alert": "Actualmente está utilizando una prioridad de tarifa de red baja. Esto podría causar largas esperas, tarifas diferentes o transacciones canceladas. Recomendamos establecer una tarifa más alta para una mejor experiencia.", "ignor": "Pasar por alto", "use_suggested": "Usar sugerido", - "do_not_share_warning_text" : "No comparta estos con nadie más, incluido el soporte.\n\n¡Te robarán tu dinero!", + "do_not_share_warning_text" : "No comparta estos con nadie más, incluido el soporte.\n\n¡Sus fondos pueden ser y serán robados!", "help": "ayuda" } diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index 941016c0b..fda7904b9 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -648,6 +648,6 @@ "low_fee_alert": "Vous utilisez actuellement une priorité de frais de réseau peu élevés. Cela pourrait entraîner de longues attentes, des taux différents ou des transactions annulées. Nous vous recommandons de fixer des frais plus élevés pour une meilleure expérience.", "ignor": "Ignorer", "use_suggested": "Utilisation suggérée", - "do_not_share_warning_text" : "Ne les partagez avec personne d'autre, y compris avec l'assistance.\n\nIls vont voler votre argent!", + "do_not_share_warning_text" : "Ne les partagez avec personne d'autre, y compris avec l'assistance.\n\nVos fonds peuvent et seront volés!", "help": "aider" } diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index 7faa06f7f..5cd157c91 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -650,6 +650,6 @@ "low_fee_alert": "आप वर्तमान में कम नेटवर्क शुल्क प्राथमिकता का उपयोग कर रहे हैं। यह लंबे इंतजार, अलग-अलग दरों या रद्द किए गए ट्रेडों का कारण बन सकता है। हम बेहतर अनुभव के लिए अधिक शुल्क निर्धारित करने की सलाह देते हैं।", "ignor": "नज़रअंदाज़ करना", "use_suggested": "सुझाए गए का प्रयोग करें", - "do_not_share_warning_text" : "इन्हें समर्थन सहित किसी और के साथ साझा न करें।\n\nवे आपका पैसा चुरा लेंगे!", + "do_not_share_warning_text" : "समर्थन सहित, इन्हें किसी और के साथ साझा न करें।\n\nआपके धन की चोरी हो सकती है और होगी!", "help": "मदद करना" } diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index 4fa77948a..369e573d4 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -650,6 +650,6 @@ "low_fee_alert": "Trenutačno koristite niski prioritet mrežne naknade. To bi moglo uzrokovati duga čekanja, različite tečajeve ili otkazane trgovine. Preporučujemo postavljanje veće naknade za bolje iskustvo.", "ignor": "Zanemariti", "use_suggested": "Koristite predloženo", - "do_not_share_warning_text" : "Nemojte ih dijeliti ni s kim, uključujući podršku.\n\nUkrast će vam novac!", + "do_not_share_warning_text" : "Nemojte ih dijeliti ni s kim, uključujući podršku.\n\nVaša sredstva mogu i bit će ukradena!", "help": "pomozite" } diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index 9a42a588b..f1430aa5b 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -650,6 +650,6 @@ "low_fee_alert": "Attualmente stai utilizzando una priorità a tariffa di rete bassa. Ciò potrebbe causare lunghe attese, tariffe diverse o operazioni annullate. Ti consigliamo di impostare una tariffa più alta per un'esperienza migliore.", "ignor": "Ignorare", "use_suggested": "Usa suggerito", - "do_not_share_warning_text" : "Non condividerli con nessun altro, incluso il supporto.\n\nTi ruberanno i soldi!", + "do_not_share_warning_text" : "Non condividerli con nessun altro, incluso il supporto.\n\nI tuoi fondi possono e saranno rubati!", "help": "aiuto" } diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index c1d0de4e3..56622a2b2 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -650,6 +650,6 @@ "low_fee_alert": "現在、低ネットワーク料金優先度を使用しています。これにより、長い待ち時間、異なるレート、またはキャンセルされた取引が発生する可能性があります。より良い体験のために、より高い料金を設定することをお勧めします。", "ignor": "無視", "use_suggested": "推奨を使用", - "do_not_share_warning_text" : "サポートを含め、これらを他の誰とも共有しないでください。\n\n彼らはあなたのお金を盗みます!", + "do_not_share_warning_text" : "サポートを含め、これらを他の誰とも共有しないでください。\n\nあなたの資金は盗まれる可能性があります!", "help": "ヘルプ" } diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index 127aa949e..ea7a722f9 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -650,6 +650,6 @@ "low_fee_alert": "현재 낮은 네트워크 요금 우선 순위를 사용하고 있습니다. 이로 인해 긴 대기 시간, 다른 요금 또는 취소된 거래가 발생할 수 있습니다. 더 나은 경험을 위해 더 높은 요금을 설정하는 것이 좋습니다.", "ignor": "무시하다", "use_suggested": "추천 사용", - "do_not_share_warning_text" : "지원을 포함하여 다른 사람과 이러한 정보를 공유하지 마십시오.\n\n그들은 당신의 돈을 훔칠 것입니다!", + "do_not_share_warning_text" : "지원을 포함하여 다른 사람과 이러한 정보를 공유하지 마십시오.\n\n귀하의 자금은 도난당할 수 있고 도난당할 수 있습니다!", "help": "돕다" } diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index fa748b552..a25087498 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -650,6 +650,6 @@ "low_fee_alert": "U gebruikt momenteel een lage prioriteit voor netwerkkosten. Dit kan lange wachttijden, andere tarieven of geannuleerde transacties veroorzaken. We raden aan een hogere vergoeding in te stellen voor een betere ervaring.", "ignor": "Negeren", "use_suggested": "Gebruik aanbevolen", - "do_not_share_warning_text" : "Deel deze met niemand anders, ook niet met support.\n\nZe zullen je geld stelen!", + "do_not_share_warning_text" : "Deel deze met niemand anders, ook niet met support.\n\nUw geld kan en zal worden gestolen!", "help": "helpen" } diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index 454fe9717..d66c084e6 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -650,6 +650,6 @@ "low_fee_alert": "Obecnie korzystasz z niskiego priorytetu opłaty sieciowej. Może to spowodować długie oczekiwanie, różne stawki lub anulowane transakcje. Zalecamy ustawienie wyższej opłaty, aby zapewnić lepsze wrażenia.", "ignor": "Ignorować", "use_suggested": "Użyj sugerowane", - "do_not_share_warning_text" : "Nie udostępniaj ich nikomu innemu, w tym wsparcia.\n\nUkradną twoje pieniądze!", + "do_not_share_warning_text" : "Nie udostępniaj ich nikomu innemu, w tym pomocy.\n\nTwoje środki mogą i zostaną skradzione!", "help": "pomoc" } diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 04a0a3ff2..5db2e7a6a 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -650,6 +650,6 @@ "low_fee_alert": "No momento, você está usando uma prioridade de taxa de rede baixa. Isso pode causar longas esperas, taxas diferentes ou negociações canceladas. Recomendamos definir uma taxa mais alta para uma melhor experiência.", "ignor": "Ignorar", "use_suggested": "Uso sugerido", - "do_not_share_warning_text" : "Não os compartilhe com mais ninguém, incluindo suporte.\n\nEles vão roubar seu dinheiro!", + "do_not_share_warning_text" : "Não os compartilhe com mais ninguém, incluindo suporte.\n\nSeus fundos podem e serão roubados!", "help": "ajuda" } diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index 632b0990c..b454a4ffb 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -650,6 +650,6 @@ "low_fee_alert": "В настоящее время вы используете низкий приоритет платы за сеть. Это может привести к длительному ожиданию, изменению ставок или отмене сделок. Мы рекомендуем установить более высокую плату для лучшего опыта.", "ignor": "Игнорировать", "use_suggested": "Использовать предложенный", - "do_not_share_warning_text" : "Не делитесь ими с кем-либо еще, в том числе со службой поддержки.\n\nОни украдут ваши деньги!", + "do_not_share_warning_text" : "Не сообщайте их никому, включая техподдержку.\n\nВаши средства могут и будут украдены!", "help": "помощь" } diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index 5e0f0d18a..f8669f528 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -649,6 +649,6 @@ "low_fee_alert": "Зараз ви використовуєте низький пріоритет плати за мережу. Це може спричинити тривале очікування, інший курс або скасування угод. Ми рекомендуємо встановити вищу плату для кращого досвіду.", "ignor": "Ігнорувати", "use_suggested": "Використати запропоноване", - "do_not_share_warning_text" : "Не повідомляйте їх нікому, включно зі службою підтримки.\n\nВони вкрадуть ваші гроші!", + "do_not_share_warning_text" : "Не діліться цим нікому, включно зі службою підтримки.\n\nВаші кошти можуть і будуть вкрадені!", "help": "допомога" } diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index c46d07d59..c586315e4 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -648,6 +648,6 @@ "low_fee_alert": "您当前正在使用低网络费用优先级。这可能会导致长时间等待、不同的费率或取消交易。我们建议设置更高的费用以获得更好的体验。", "ignor": "忽视", "use_suggested": "使用建议", - "do_not_share_warning_text" : "不要與其他任何人分享這些內容,包括支持。\n\n他們會偷你的錢!", + "do_not_share_warning_text" : "请勿与其他任何人分享这些信息,包括支持人员。\n\n您的资金可能而且将会被盗!", "help": "帮助" } From 69886372660be5e204083e9e05e2dbb789a4c597 Mon Sep 17 00:00:00 2001 From: Serhii Date: Sun, 13 Nov 2022 20:06:45 +0200 Subject: [PATCH 12/49] fix fetching trade state for SideShift --- lib/exchange/sideshift/sideshift_exchange_provider.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index a732f7ef2..8cd4593c1 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -250,8 +250,10 @@ class SideShiftExchangeProvider extends ExchangeProvider { final deposits = responseJSON['deposits'] as List?; TradeState? state; - if (deposits != null && deposits.isNotEmpty) { - final status = deposits[0]['status'] as String; + if (deposits != null && deposits.isEmpty) { + state = TradeState.deserialize(raw: 'created'); + } else { + final status = deposits?[0]['status'] as String; state = TradeState.deserialize(raw: status); } From 9ce8a1944befb200a2afc2ab19ca7467ac479954 Mon Sep 17 00:00:00 2001 From: Serhii Date: Mon, 14 Nov 2022 22:50:07 +0200 Subject: [PATCH 13/49] fix empty containers --- lib/src/screens/send/widgets/send_card.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index 7e7194f88..384f4f2cc 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -332,8 +332,7 @@ class SendCardState extends State ], ), )), - sendViewModel.balanceViewModel.disableFiat ? - Container () : + if (sendViewModel.balanceViewModel.disableFiat) Padding( padding: const EdgeInsets.only(top: 20), child: BaseTextFormField( @@ -440,8 +439,9 @@ class SendCardState extends State Padding( padding: EdgeInsets.only(top: 5), - child: sendViewModel.balanceViewModel.disableFiat ? - Container () : Text(output + child: sendViewModel.balanceViewModel.disableFiat + ? const SizedBox(height: 14) + : Text(output .estimatedFeeFiatAmount + ' ' + sendViewModel From 05f1b17a732932ed12b2b93b751acf218160214b Mon Sep 17 00:00:00 2001 From: Serhii Date: Mon, 21 Nov 2022 22:41:09 +0200 Subject: [PATCH 14/49] fix contact list bug --- lib/router.dart | 2 +- lib/src/screens/contact/contact_list_page.dart | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/router.dart b/lib/router.dart index 8b43fbaf5..9fe22e22d 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -300,7 +300,7 @@ Route createRoute(RouteSettings settings) { case Routes.addressBook: return MaterialPageRoute( builder: (_) => - getIt.get(param1: true, param2: null)); + getIt.get(param1: true)); case Routes.pickerAddressBook: final selectedCurrency = settings.arguments as CryptoCurrency; diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 6d23518b8..8e9de23fd 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -68,7 +68,9 @@ class ContactListPage extends BasePage { contactListViewModel.getWallets(isEditable, selectedCurrency); return Container( padding: EdgeInsets.only(top: 20.0, bottom: 20.0), - child: CollapsibleSectionList( + child: Observer( + builder: (_) { + return CollapsibleSectionList( context: context, sectionCount: 2, themeColor: Theme.of(context).primaryTextTheme.headline6!.color!, @@ -104,7 +106,7 @@ class ContactListPage extends BasePage { child: content, ); }, - ) + );}) ); } From 2db75344802296ad6fe0d68c4bcedc997e9263af Mon Sep 17 00:00:00 2001 From: Serhii Date: Tue, 22 Nov 2022 00:07:27 +0200 Subject: [PATCH 15/49] small fix --- lib/src/screens/contact/contact_list_page.dart | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 8e9de23fd..7895a1df3 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -62,14 +62,15 @@ class ContactListPage extends BasePage { @override Widget body(BuildContext context) { - final contacts = - contactListViewModel.getContacts(isEditable, selectedCurrency); - final walletContacts = - contactListViewModel.getWallets(isEditable, selectedCurrency); + return Container( padding: EdgeInsets.only(top: 20.0, bottom: 20.0), child: Observer( builder: (_) { + final contacts = + contactListViewModel.getContacts(isEditable, selectedCurrency); + final walletContacts = + contactListViewModel.getWallets(isEditable, selectedCurrency); return CollapsibleSectionList( context: context, sectionCount: 2, From 92328c41029405800f9b18249debef54fbe404ef Mon Sep 17 00:00:00 2001 From: Serhii Date: Tue, 22 Nov 2022 19:33:24 +0200 Subject: [PATCH 16/49] move logic to viewmodels --- .../screens/exchange_trade/exchange_trade_page.dart | 12 ++++-------- lib/src/screens/send/send_page.dart | 8 ++------ .../exchange/exchange_trade_view_model.dart | 12 ++++++++++++ lib/view_model/send/send_view_model.dart | 10 ++++++++++ 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/lib/src/screens/exchange_trade/exchange_trade_page.dart b/lib/src/screens/exchange_trade/exchange_trade_page.dart index 4128fb9f2..001c13ba9 100644 --- a/lib/src/screens/exchange_trade/exchange_trade_page.dart +++ b/lib/src/screens/exchange_trade/exchange_trade_page.dart @@ -381,14 +381,10 @@ class ExchangeTradeState extends State { }); }, actionLeftButton: () => Navigator.of(context).pop(), - feeFiatAmount: widget.disableFiat ? '' - : widget.exchangeTradeViewModel.sendViewModel.pendingTransactionFeeFiatAmount - + ' ' + widget.exchangeTradeViewModel.sendViewModel.fiat.title, - fiatAmountValue: widget.disableFiat ? '' - : widget.exchangeTradeViewModel.sendViewModel - .pendingTransactionFiatAmount + - ' ' + - widget.exchangeTradeViewModel.sendViewModel.fiat.title, + feeFiatAmount: widget.exchangeTradeViewModel + .pendingTransactionFeeFiatAmountFormatted, + fiatAmountValue: widget.exchangeTradeViewModel + .pendingTransactionFiatAmountValueFormatted, outputs: widget.exchangeTradeViewModel.sendViewModel .outputs); }); diff --git a/lib/src/screens/send/send_page.dart b/lib/src/screens/send/send_page.dart index 8815d8c58..b0891c6e5 100644 --- a/lib/src/screens/send/send_page.dart +++ b/lib/src/screens/send/send_page.dart @@ -386,14 +386,10 @@ class SendPage extends BasePage { amount: S.of(context).send_amount, amountValue: sendViewModel.pendingTransaction!.amountFormatted, - fiatAmountValue: sendViewModel.balanceViewModel.disableFiat - ? '' : sendViewModel.pendingTransactionFiatAmount + - ' ' + sendViewModel.fiat.title, + fiatAmountValue: sendViewModel.pendingTransactionFiatAmountFormatted, fee: S.of(context).send_fee, feeValue: sendViewModel.pendingTransaction!.feeFormatted, - feeFiatAmount: sendViewModel.balanceViewModel.disableFiat - ? '' : sendViewModel.pendingTransactionFeeFiatAmount + - ' ' + sendViewModel.fiat.title, + feeFiatAmount: sendViewModel.pendingTransactionFeeFiatAmountFormatted, outputs: sendViewModel.outputs, rightButtonText: S.of(context).ok, leftButtonText: S.of(context).cancel, diff --git a/lib/view_model/exchange/exchange_trade_view_model.dart b/lib/view_model/exchange/exchange_trade_view_model.dart index 796397429..133b4a228 100644 --- a/lib/view_model/exchange/exchange_trade_view_model.dart +++ b/lib/view_model/exchange/exchange_trade_view_model.dart @@ -72,6 +72,18 @@ abstract class ExchangeTradeViewModelBase with Store { ? '\n\n' + S.current.xrp_extra_info : ''; + @computed + String get pendingTransactionFiatAmountValueFormatted => + sendViewModel.balanceViewModel.disableFiat + ? '' : sendViewModel.pendingTransactionFiatAmount + + ' ' + sendViewModel.fiat.title; + + @computed + String get pendingTransactionFeeFiatAmountFormatted => + sendViewModel.balanceViewModel.disableFiat + ? '' : sendViewModel.pendingTransactionFeeFiatAmount + + ' ' + sendViewModel.fiat.title; + @observable ObservableList items; diff --git a/lib/view_model/send/send_view_model.dart b/lib/view_model/send/send_view_model.dart index cdef6faba..fbfba2313 100644 --- a/lib/view_model/send/send_view_model.dart +++ b/lib/view_model/send/send_view_model.dart @@ -139,6 +139,16 @@ abstract class SendViewModelBase with Store { @computed String get balance => balanceViewModel.availableBalance ?? '0.0'; + @computed + String get pendingTransactionFiatAmountFormatted => + balanceViewModel.disableFiat ? '' : pendingTransactionFiatAmount + + ' ' + fiat.title; + + @computed + String get pendingTransactionFeeFiatAmountFormatted => + balanceViewModel.disableFiat ? '' : pendingTransactionFeeFiatAmount + + ' ' + fiat.title; + @computed bool get isReadyForSend => _wallet.syncStatus is SyncedSyncStatus; From 5f1e8e9d33fa04bac655e870820620f059ffd4e7 Mon Sep 17 00:00:00 2001 From: Serhii Date: Fri, 2 Dec 2022 23:36:22 +0200 Subject: [PATCH 17/49] remove isEditable parameter --- lib/di.dart | 3 +-- lib/router.dart | 5 ++--- lib/src/screens/contact/contact_list_page.dart | 13 ++++++------- .../contact_list/contact_list_view_model.dart | 8 ++++---- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/lib/di.dart b/lib/di.dart index b84f98ad9..539681036 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -462,10 +462,9 @@ Future setup( getIt.registerFactory( () => ContactListViewModel(_contactSource, _walletInfoSource)); - getIt.registerFactoryParam((bool isEditable, CryptoCurrency? cur) + getIt.registerFactoryParam((CryptoCurrency? cur, _) => ContactListPage( getIt.get(), - isEditable: isEditable, selectedCurrency: cur)); getIt.registerFactoryParam( diff --git a/lib/router.dart b/lib/router.dart index 9fe22e22d..07e500544 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -300,13 +300,12 @@ Route createRoute(RouteSettings settings) { case Routes.addressBook: return MaterialPageRoute( builder: (_) => - getIt.get(param1: true)); + getIt.get()); case Routes.pickerAddressBook: final selectedCurrency = settings.arguments as CryptoCurrency; return MaterialPageRoute( - builder: (_) => getIt.get(param1: false, - param2: selectedCurrency)); + builder: (_) => getIt.get(param1: selectedCurrency)); case Routes.addressBookAddContact: return CupertinoPageRoute( diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 7895a1df3..8fcaf31a2 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -17,10 +17,9 @@ import 'package:cake_wallet/src/widgets/collapsible_standart_list.dart'; class ContactListPage extends BasePage { ContactListPage(this.contactListViewModel, - {this.isEditable = true, required this.selectedCurrency}); + {this.selectedCurrency}); final ContactListViewModel contactListViewModel; - final bool isEditable; final CryptoCurrency? selectedCurrency; @override @@ -28,7 +27,7 @@ class ContactListPage extends BasePage { @override Widget? trailing(BuildContext context) { - if (!isEditable) { + if (selectedCurrency != null) { return null; } @@ -68,9 +67,9 @@ class ContactListPage extends BasePage { child: Observer( builder: (_) { final contacts = - contactListViewModel.getContacts(isEditable, selectedCurrency); + contactListViewModel.getContacts(selectedCurrency); final walletContacts = - contactListViewModel.getWallets(isEditable, selectedCurrency); + contactListViewModel.getWallets(selectedCurrency); return CollapsibleSectionList( context: context, sectionCount: 2, @@ -99,7 +98,7 @@ class ContactListPage extends BasePage { final contact = contacts[index]; final content = generateRaw(context, contact); - return !isEditable + return selectedCurrency != null ? content : Slidable( key: Key('${contact.key}'), @@ -116,7 +115,7 @@ class ContactListPage extends BasePage { return GestureDetector( onTap: () async { - if (!isEditable) { + if (selectedCurrency != null) { Navigator.of(context).pop(contact); return; } diff --git a/lib/view_model/contact_list/contact_list_view_model.dart b/lib/view_model/contact_list/contact_list_view_model.dart index 0f67245af..3fa9a73a4 100644 --- a/lib/view_model/contact_list/contact_list_view_model.dart +++ b/lib/view_model/contact_list/contact_list_view_model.dart @@ -46,16 +46,16 @@ abstract class ContactListViewModelBase with Store { Future delete(ContactRecord contact) async => contact.original.delete(); - List getContacts(bool isEditable, CryptoCurrency? cur) { - if (!isEditable) { + List getContacts(CryptoCurrency? cur) { + if (cur != null) { return contacts.where((element) => element.type == cur).toList(); } return contacts; } - List getWallets(bool isEditable, CryptoCurrency? cur) { - if (!isEditable) { + List getWallets(CryptoCurrency? cur) { + if (cur != null) { return walletContacts.where((element) => element.type == cur).toList(); } From 4c7a0a8cb97a4e1af58127bd52e185a3ae60a4e5 Mon Sep 17 00:00:00 2001 From: Serhii Date: Sat, 3 Dec 2022 00:34:34 +0200 Subject: [PATCH 18/49] rework _getCurrencyImage func --- .../screens/contact/contact_list_page.dart | 74 ++----------------- 1 file changed, 6 insertions(+), 68 deletions(-) diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 8fcaf31a2..9d0d1ab5a 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -111,7 +111,10 @@ class ContactListPage extends BasePage { } Widget generateRaw(BuildContext context, ContactBase contact) { - final image = _getCurrencyImage(contact.type); + final image = contact.type.iconPath; + final currencyIcon = image != null ? Image.asset(image, height: 24, width: 24) + : const SizedBox(height: 24, width: 24); + return GestureDetector( onTap: () async { @@ -136,12 +139,10 @@ class ContactListPage extends BasePage { mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: [ - image ?? Offstage(), + currencyIcon, Expanded( child: Padding( - padding: image != null - ? EdgeInsets.only(left: 12) - : EdgeInsets.only(left: 0), + padding: EdgeInsets.only(left: 12), child: Text( contact.name, style: TextStyle( @@ -157,69 +158,6 @@ class ContactListPage extends BasePage { ); } - Image? _getCurrencyImage(CryptoCurrency currency) { - Image? image; - - switch (currency) { - case CryptoCurrency.xmr: - image = - Image.asset('assets/images/monero_logo.png', height: 24, width: 24); - break; - case CryptoCurrency.ada: - image = Image.asset('assets/images/ada.png', height: 24, width: 24); - break; - case CryptoCurrency.bch: - image = Image.asset('assets/images/bch.png', height: 24, width: 24); - break; - case CryptoCurrency.bnb: - image = Image.asset('assets/images/bnb.png', height: 24, width: 24); - break; - case CryptoCurrency.btc: - image = Image.asset('assets/images/bitcoin.png', height: 24, width: 24); - break; - case CryptoCurrency.dai: - image = Image.asset('assets/images/dai.png', height: 24, width: 24); - break; - case CryptoCurrency.dash: - image = Image.asset('assets/images/dash.png', height: 24, width: 24); - break; - case CryptoCurrency.eos: - image = Image.asset('assets/images/eos.png', height: 24, width: 24); - break; - case CryptoCurrency.eth: - image = Image.asset('assets/images/eth.png', height: 24, width: 24); - break; - case CryptoCurrency.ltc: - image = - Image.asset('assets/images/litecoin.png', height: 24, width: 24); - break; - case CryptoCurrency.nano: - image = Image.asset('assets/images/nano.png', height: 24, width: 24); - break; - case CryptoCurrency.trx: - image = Image.asset('assets/images/trx.png', height: 24, width: 24); - break; - case CryptoCurrency.usdt: - image = Image.asset('assets/images/usdt.png', height: 24, width: 24); - break; - case CryptoCurrency.usdterc20: - image = Image.asset('assets/images/usdterc.png', height: 24, width: 24); - break; - case CryptoCurrency.xlm: - image = Image.asset('assets/images/xlm.png', height: 24, width: 24); - break; - case CryptoCurrency.xrp: - image = Image.asset('assets/images/xrp.png', height: 24, width: 24); - break; - case CryptoCurrency.xhv: - image = Image.asset('assets/images/haven_logo.png', height: 24, width: 24); - break; - default: - image = null; - } - return image; - } - Future showAlertDialog(BuildContext context) async { return await showPopUp( context: context, From 11a5e9771197496ac08b72972daf25108c47707b Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Sat, 3 Dec 2022 23:34:23 +0200 Subject: [PATCH 19/49] Fix navigation error when state is changed to denied at app first start [skip_ci] --- lib/main.dart | 2 +- lib/reactions/bootstrap.dart | 6 +++--- lib/reactions/on_authentication_state_change.dart | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index e1fade7b4..11eee146b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -261,7 +261,7 @@ class AppState extends State with SingleTickerProviderStateMixin { final statusBarColor = Colors.transparent; final authenticationStore = getIt.get(); final initialRoute = - authenticationStore.state == AuthenticationState.denied + authenticationStore.state == AuthenticationState.uninitialized ? Routes.disclaimer : Routes.login; final currentTheme = settingsStore.currentTheme; diff --git a/lib/reactions/bootstrap.dart b/lib/reactions/bootstrap.dart index 8d9950e64..a40a17088 100644 --- a/lib/reactions/bootstrap.dart +++ b/lib/reactions/bootstrap.dart @@ -22,9 +22,9 @@ Future bootstrap(GlobalKey navigatorKey) async { final currentWalletName = getIt .get() .getString(PreferencesKey.currentWalletName); - authenticationStore.state = currentWalletName == null - ? AuthenticationState.denied - : AuthenticationState.installed; + if (currentWalletName != null) { + authenticationStore.state = AuthenticationState.installed; + } startAuthenticationStateChange(authenticationStore, navigatorKey); startCurrentWalletChangeReaction( diff --git a/lib/reactions/on_authentication_state_change.dart b/lib/reactions/on_authentication_state_change.dart index 560326cb5..c91f5277e 100644 --- a/lib/reactions/on_authentication_state_change.dart +++ b/lib/reactions/on_authentication_state_change.dart @@ -23,12 +23,12 @@ void startAuthenticationStateChange(AuthenticationStore authenticationStore, } if (state == AuthenticationState.allowed) { - await navigatorKey.currentState?.pushNamedAndRemoveUntil(Routes.dashboard, (route) => false); + await navigatorKey.currentState!.pushNamedAndRemoveUntil(Routes.dashboard, (route) => false); return; } if (state == AuthenticationState.denied) { - await navigatorKey.currentState?.pushNamedAndRemoveUntil(Routes.welcome, (_) => false); + await navigatorKey.currentState!.pushNamedAndRemoveUntil(Routes.welcome, (_) => false); return; } }); From 9d64789983dac6b90f3a5a1aa228ebf181fbc0a7 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Sun, 4 Dec 2022 05:08:42 +0200 Subject: [PATCH 20/49] Fix Conflict with main Rename classes to advanced privacy settings to avoid confusion between settings/privacy-settings --- lib/di.dart | 6 +-- lib/router.dart | 11 ++-- .../advanced_privacy_settings_page.dart | 9 ++-- .../screens/new_wallet/new_wallet_page.dart | 2 +- .../advanced_privacy_settings_view_model.dart | 51 ++++++++++++++++++ .../privacy_settings_view_model.dart | 54 ------------------- res/values/strings_de.arb | 3 +- res/values/strings_en.arb | 3 +- res/values/strings_es.arb | 3 +- res/values/strings_fr.arb | 3 +- res/values/strings_hi.arb | 3 +- res/values/strings_hr.arb | 3 +- res/values/strings_it.arb | 3 +- res/values/strings_ja.arb | 3 +- res/values/strings_ko.arb | 3 +- res/values/strings_nl.arb | 3 +- res/values/strings_pl.arb | 3 +- res/values/strings_pt.arb | 3 +- res/values/strings_ru.arb | 3 +- res/values/strings_uk.arb | 3 +- res/values/strings_zh.arb | 3 +- 21 files changed, 96 insertions(+), 82 deletions(-) create mode 100644 lib/view_model/advanced_privacy_settings_view_model.dart delete mode 100644 lib/view_model/privacy_settings_view_model.dart diff --git a/lib/di.dart b/lib/di.dart index a896bf1e4..7a7621203 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -35,7 +35,7 @@ import 'package:cake_wallet/view_model/settings/display_settings_view_model.dart import 'package:cake_wallet/view_model/settings/other_settings_view_model.dart'; import 'package:cake_wallet/view_model/settings/privacy_settings_view_model.dart'; import 'package:cake_wallet/view_model/settings/security_settings_view_model.dart'; -import 'package:cake_wallet/view_model/privacy_settings_view_model.dart' +import 'package:cake_wallet/view_model/advanced_privacy_settings_view_model.dart'; import 'package:cw_core/unspent_coins_info.dart'; import 'package:cake_wallet/core/backup_service.dart'; import 'package:cw_core/wallet_service.dart'; @@ -816,8 +816,8 @@ Future setup( (IoniaAnyPayPaymentInfo paymentInfo, AnyPayPaymentCommittedInfo committedInfo) => IoniaPaymentStatusPage(getIt.get(param1: paymentInfo, param2: committedInfo))); - getIt.registerFactoryParam((type, _) => - PrivacySettingsViewModel(type)) + getIt.registerFactoryParam((type, _) => + AdvancedPrivacySettingsViewModel(type, getIt.get())); _isSetupFinished = true; } diff --git a/lib/router.dart b/lib/router.dart index f22fd3e18..20e4d7632 100644 --- a/lib/router.dart +++ b/lib/router.dart @@ -27,7 +27,7 @@ import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_details_page import 'package:cake_wallet/src/screens/unspent_coins/unspent_coins_list_page.dart'; import 'package:cake_wallet/view_model/monero_account_list/account_list_item.dart'; import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; -import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; +import 'package:cake_wallet/view_model/advanced_privacy_settings_view_model.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:cake_wallet/routes.dart'; @@ -494,13 +494,14 @@ Route createRoute(RouteSettings settings) { case Routes.onramperPage: return CupertinoPageRoute(builder: (_) => getIt.get()); - case Routes.privacySettings: + case Routes.advancedPrivacySettings: final type = settings.arguments as WalletType; - final privacySettingsViewModel = getIt.get(param1: type); - final nodeCreateViewModel = getIt.get(param1: type); return CupertinoPageRoute( - builder: (_) => AdvancedPrivacySettingsPage(privacySettingsViewModel, nodeCreateViewModel)); + builder: (_) => AdvancedPrivacySettingsPage( + getIt.get(param1: type), + getIt.get(param1: type), + )); default: return MaterialPageRoute( diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index da67d4511..33aca0307 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -1,7 +1,7 @@ import 'package:cake_wallet/src/screens/nodes/widgets/node_form.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; import 'package:cake_wallet/view_model/node_list/node_create_or_edit_view_model.dart'; -import 'package:cake_wallet/view_model/privacy_settings_view_model.dart'; +import 'package:cake_wallet/view_model/advanced_privacy_settings_view_model.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:flutter/material.dart'; import 'package:cake_wallet/generated/i18n.dart'; @@ -12,7 +12,7 @@ import 'package:cake_wallet/src/widgets/scollable_with_bottom_section.dart'; class AdvancedPrivacySettingsPage extends BasePage { AdvancedPrivacySettingsPage(this.privacySettingsViewModel, this.nodeViewModel); - final PrivacySettingsViewModel privacySettingsViewModel; + final AdvancedPrivacySettingsViewModel privacySettingsViewModel; final NodeCreateOrEditViewModel nodeViewModel; @override @@ -27,7 +27,7 @@ class AdvancedPrivacySettingsBody extends StatefulWidget { const AdvancedPrivacySettingsBody(this.privacySettingsViewModel, this.nodeViewModel, {Key? key}) : super(key: key); - final PrivacySettingsViewModel privacySettingsViewModel; + final AdvancedPrivacySettingsViewModel privacySettingsViewModel; final NodeCreateOrEditViewModel nodeViewModel; @override @@ -39,7 +39,7 @@ class _AdvancedPrivacySettingsBodyState extends State { _AdvancedPrivacySettingsBodyState(this.privacySettingsViewModel, this.nodeViewModel); - final PrivacySettingsViewModel privacySettingsViewModel; + final AdvancedPrivacySettingsViewModel privacySettingsViewModel; final NodeCreateOrEditViewModel nodeViewModel; final _formKey = GlobalKey(); @@ -84,6 +84,7 @@ class _AdvancedPrivacySettingsBodyState LoadingPrimaryButton( onPressed: () { nodeViewModel.save(); + Navigator.pop(context); }, text: S.of(context).continue_text, color: Theme.of(context).accentTextTheme.bodyText1!.color!, diff --git a/lib/src/screens/new_wallet/new_wallet_page.dart b/lib/src/screens/new_wallet/new_wallet_page.dart index 0abeaede2..9e0cd898c 100644 --- a/lib/src/screens/new_wallet/new_wallet_page.dart +++ b/lib/src/screens/new_wallet/new_wallet_page.dart @@ -219,7 +219,7 @@ class _WalletNameFormState extends State { GestureDetector( onTap: () { Navigator.of(context) - .pushNamed(Routes.privacySettings, arguments: _walletNewVM.type); + .pushNamed(Routes.advancedPrivacySettings, arguments: _walletNewVM.type); }, child: Text(S.of(context).advanced_privacy_settings), ), diff --git a/lib/view_model/advanced_privacy_settings_view_model.dart b/lib/view_model/advanced_privacy_settings_view_model.dart new file mode 100644 index 000000000..ef9ab878f --- /dev/null +++ b/lib/view_model/advanced_privacy_settings_view_model.dart @@ -0,0 +1,51 @@ +import 'package:cake_wallet/store/settings_store.dart'; +import 'package:cake_wallet/view_model/settings/switcher_list_item.dart'; +import 'package:cw_core/wallet_type.dart'; +import 'package:mobx/mobx.dart'; +import 'package:cake_wallet/generated/i18n.dart'; + +part 'advanced_privacy_settings_view_model.g.dart'; + +class AdvancedPrivacySettingsViewModel = AdvancedPrivacySettingsViewModelBase + with _$AdvancedPrivacySettingsViewModel; + +abstract class AdvancedPrivacySettingsViewModelBase with Store { + AdvancedPrivacySettingsViewModelBase(this.type, this._settingsStore) + : _disableFiat = false, + _addCustomNode = false { + settings = [ + // TODO: uncomment when Disable Fiat PR is merged + // SwitcherListItem( + // title: S.current.disable_fiat, + // value: () => _disableFiat, + // onValueChange: (_, bool value) => _disableFiat = value, + // ), + SwitcherListItem( + title: S.current.disable_exchange, + value: () => _settingsStore.disableExchange, + onValueChange: (_, bool value) { + _settingsStore.disableExchange = value; + }, + ), + SwitcherListItem( + title: S.current.add_custom_node, + value: () => _addCustomNode, + onValueChange: (_, bool value) => _addCustomNode = value, + ), + ]; + } + + late List settings; + + @observable + bool _disableFiat = false; + + @observable + bool _addCustomNode = false; + + final WalletType type; + final SettingsStore _settingsStore; + + @computed + bool get addCustomNode => _addCustomNode; +} diff --git a/lib/view_model/privacy_settings_view_model.dart b/lib/view_model/privacy_settings_view_model.dart deleted file mode 100644 index 760c577ef..000000000 --- a/lib/view_model/privacy_settings_view_model.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:cake_wallet/view_model/settings/switcher_list_item.dart'; -import 'package:cw_core/wallet_type.dart'; -import 'package:mobx/mobx.dart'; -import 'package:cake_wallet/generated/i18n.dart'; - -part 'privacy_settings_view_model.g.dart'; - -class PrivacySettingsViewModel = PrivacySettingsViewModelBase - with _$PrivacySettingsViewModel; - -abstract class PrivacySettingsViewModelBase with Store { - PrivacySettingsViewModelBase(this.type) - : _disableFiat = false, - _disableExchange = false, - _addCustomNode = false { - settings = [ - SwitcherListItem( - // TODO: replace when Disable Fiat PR is merged - title: "Disable Fiat API", - // title: S.current.disable_fiat, - value: () => _disableFiat, - onValueChange: (_, bool value) => _disableFiat = value, - ), - SwitcherListItem( - title: "Disable Exchange", - // title: S.current.disable_exchange, - value: () => _disableExchange, - onValueChange: (_, bool value) => _disableExchange = value, - ), - SwitcherListItem( - title: "Add New Custom Node", - // title: S.current.add_custom_node, - value: () => _addCustomNode, - onValueChange: (_, bool value) => _addCustomNode = value, - ), - ]; - } - - late List settings; - - @observable - bool _disableFiat = false; - - @observable - bool _disableExchange = false; - - @observable - bool _addCustomNode = false; - - final WalletType type; - - @computed - bool get addCustomNode => _addCustomNode; -} diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index 8f339d090..d9eb8d78a 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -663,5 +663,6 @@ "other_settings": "Andere Einstellungen", "disable_exchange": "Exchange deaktivieren", "advanced_privacy_settings": "Erweiterte Datenschutzeinstellungen", - "settings_can_be_changed_later": "Diese Einstellungen können später in den App-Einstellungen geändert werden" + "settings_can_be_changed_later": "Diese Einstellungen können später in den App-Einstellungen geändert werden", + "add_custom_node": "Neuen benutzerdefinierten Knoten hinzufügen" } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index b50ba6c83..baf955fcd 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -663,5 +663,6 @@ "other_settings": "Other settings", "disable_exchange": "Disable exchange", "advanced_privacy_settings": "Advanced Privacy Settings", - "settings_can_be_changed_later": "These settings can be changed later in the app settings" + "settings_can_be_changed_later": "These settings can be changed later in the app settings", + "add_custom_node": "Add New Custom Node" } diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 738e64849..54b3fae18 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -663,5 +663,6 @@ "other_settings": "Otras configuraciones", "disable_exchange": "Deshabilitar intercambio", "advanced_privacy_settings": "Configuración avanzada de privacidad", - "settings_can_be_changed_later": "Estas configuraciones se pueden cambiar más tarde en la configuración de la aplicación" + "settings_can_be_changed_later": "Estas configuraciones se pueden cambiar más tarde en la configuración de la aplicación", + "add_custom_node": "Agregar nuevo nodo personalizado" } diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index f04a6181c..b6836ab18 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -661,5 +661,6 @@ "other_settings": "Autres paramètres", "disable_exchange": "Désactiver l'échange", "advanced_privacy_settings": "Paramètres de confidentialité avancés", - "settings_can_be_changed_later": "Ces paramètres peuvent être modifiés ultérieurement dans les paramètres de l'application" + "settings_can_be_changed_later": "Ces paramètres peuvent être modifiés ultérieurement dans les paramètres de l'application", + "add_custom_node": "Ajouter un nouveau nœud personnalisé" } diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index fdf565a7b..72a21f333 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -663,5 +663,6 @@ "other_settings": "अन्य सेटिंग्स", "disable_exchange": "एक्सचेंज अक्षम करें", "advanced_privacy_settings": "उन्नत गोपनीयता सेटिंग्स", - "settings_can_be_changed_later": "इन सेटिंग्स को बाद में ऐप सेटिंग में बदला जा सकता है" + "settings_can_be_changed_later": "इन सेटिंग्स को बाद में ऐप सेटिंग में बदला जा सकता है", + "add_custom_node": "नया कस्टम नोड जोड़ें" } diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index ece52e656..16b388a05 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -663,5 +663,6 @@ "other_settings": "Ostale postavke", "disable_exchange": "Onemogući exchange", "advanced_privacy_settings": "Napredne postavke privatnosti", - "settings_can_be_changed_later": "Te se postavke mogu promijeniti kasnije u postavkama aplikacije" + "settings_can_be_changed_later": "Te se postavke mogu promijeniti kasnije u postavkama aplikacije", + "add_custom_node": "Dodaj novi prilagođeni čvor" } diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index d5f591c64..28ad40d47 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -663,5 +663,6 @@ "other_settings": "Altre impostazioni", "disable_exchange": "Disabilita scambio", "advanced_privacy_settings": "Impostazioni avanzate sulla privacy", - "settings_can_be_changed_later": "Queste impostazioni possono essere modificate in seguito nelle impostazioni dell'app" + "settings_can_be_changed_later": "Queste impostazioni possono essere modificate in seguito nelle impostazioni dell'app", + "add_custom_node": "Aggiungi nuovo nodo personalizzato" } diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index 21c21c7a8..d79f58e7a 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -663,5 +663,6 @@ "other_settings": "その他の設定", "disable_exchange": "交換を無効にする", "advanced_privacy_settings": "高度なプライバシー設定", - "settings_can_be_changed_later": "これらの設定は、後でアプリの設定で変更できます" + "settings_can_be_changed_later": "これらの設定は、後でアプリの設定で変更できます", + "add_custom_node": "新しいカスタム ノードを追加" } diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index 0d2bc31bc..0652ffc54 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -663,5 +663,6 @@ "other_settings": "기타 설정", "disable_exchange": "교환 비활성화", "advanced_privacy_settings": "고급 개인 정보 설정", - "settings_can_be_changed_later": "이 설정은 나중에 앱 설정에서 변경할 수 있습니다." + "settings_can_be_changed_later": "이 설정은 나중에 앱 설정에서 변경할 수 있습니다.", + "add_custom_node": "새 사용자 정의 노드 추가" } diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index b7bb86d9c..2c6e528ca 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -663,5 +663,6 @@ "other_settings": "Andere instellingen", "disable_exchange": "Uitwisseling uitschakelen", "advanced_privacy_settings": "Geavanceerde privacy-instellingen", - "settings_can_be_changed_later": "Deze instellingen kunnen later worden gewijzigd in de app-instellingen" + "settings_can_be_changed_later": "Deze instellingen kunnen later worden gewijzigd in de app-instellingen", + "add_custom_node": "Voeg een nieuw aangepast knooppunt toe" } diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index 20a0b2f98..179f7267b 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -663,5 +663,6 @@ "other_settings": "Inne ustawienia", "disable_exchange": "Wyłącz wymianę", "advanced_privacy_settings": "Zaawansowane ustawienia prywatności", - "settings_can_be_changed_later": "Te ustawienia można później zmienić w ustawieniach aplikacji" + "settings_can_be_changed_later": "Te ustawienia można później zmienić w ustawieniach aplikacji", + "add_custom_node": "Dodaj nowy węzeł niestandardowy" } diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 65438a26c..cf0669585 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -662,5 +662,6 @@ "other_settings": "Outras configurações", "disable_exchange": "Desativar troca", "advanced_privacy_settings": "Configurações de privacidade avançadas", - "settings_can_be_changed_later": "Essas configurações podem ser alteradas posteriormente nas configurações do aplicativo" + "settings_can_be_changed_later": "Essas configurações podem ser alteradas posteriormente nas configurações do aplicativo", + "add_custom_node": "Adicionar novo nó personalizado" } diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index 4dcda3007..f73ad4564 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -663,5 +663,6 @@ "other_settings": "Другие настройки", "disable_exchange": "Отключить обмен", "advanced_privacy_settings": "Расширенные настройки конфиденциальности", - "settings_can_be_changed_later": "Эти настройки можно изменить позже в настройках приложения." + "settings_can_be_changed_later": "Эти настройки можно изменить позже в настройках приложения.", + "add_custom_node": "Добавить новый пользовательский узел" } diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index 61f6cfb0d..c52359d64 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -662,5 +662,6 @@ "other_settings": "Інші налаштування", "disable_exchange": "Вимкнути exchange", "advanced_privacy_settings": "Розширені налаштування конфіденційності", - "settings_can_be_changed_later": "Ці параметри можна змінити пізніше в налаштуваннях програми" + "settings_can_be_changed_later": "Ці параметри можна змінити пізніше в налаштуваннях програми", + "add_custom_node": "Додати новий спеціальний вузол" } diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index 750b4e605..a8f9119da 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -661,5 +661,6 @@ "other_settings": "其他设置", "disable_exchange": "禁用交换", "advanced_privacy_settings": "高级隐私设置", - "settings_can_be_changed_later": "稍后可以在应用设置中更改这些设置" + "settings_can_be_changed_later": "稍后可以在应用设置中更改这些设置", + "add_custom_node": "添加新的自定义节点" } From 7e6439947645fc197d74127d0c593161dcfffe8d Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Sun, 4 Dec 2022 05:27:49 +0200 Subject: [PATCH 21/49] remove un-necessary attributes passing --- .../advanced_privacy_settings_page.dart | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index 33aca0307..e0dd1a729 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -31,16 +31,11 @@ class AdvancedPrivacySettingsBody extends StatefulWidget { final NodeCreateOrEditViewModel nodeViewModel; @override - _AdvancedPrivacySettingsBodyState createState() => - _AdvancedPrivacySettingsBodyState(privacySettingsViewModel, nodeViewModel); + _AdvancedPrivacySettingsBodyState createState() => _AdvancedPrivacySettingsBodyState(); } -class _AdvancedPrivacySettingsBodyState - extends State { - _AdvancedPrivacySettingsBodyState(this.privacySettingsViewModel, this.nodeViewModel); - - final AdvancedPrivacySettingsViewModel privacySettingsViewModel; - final NodeCreateOrEditViewModel nodeViewModel; +class _AdvancedPrivacySettingsBodyState extends State { + _AdvancedPrivacySettingsBodyState(); final _formKey = GlobalKey(); @@ -53,7 +48,7 @@ class _AdvancedPrivacySettingsBodyState content: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ - ...privacySettingsViewModel.settings.map( + ...widget.privacySettingsViewModel.settings.map( (item) => Observer( builder: (_) => SettingsSwitcherCell( title: item.title, @@ -64,12 +59,12 @@ class _AdvancedPrivacySettingsBodyState ), Observer( builder: (_) { - if (privacySettingsViewModel.addCustomNode) { + if (widget.privacySettingsViewModel.addCustomNode) { return Padding( padding: EdgeInsets.only(left: 24, right: 24, top: 24), child: NodeForm( formKey: _formKey, - nodeViewModel: nodeViewModel, + nodeViewModel: widget.nodeViewModel, ), ); } @@ -83,7 +78,7 @@ class _AdvancedPrivacySettingsBodyState children: [ LoadingPrimaryButton( onPressed: () { - nodeViewModel.save(); + widget.nodeViewModel.save(); Navigator.pop(context); }, text: S.of(context).continue_text, @@ -92,8 +87,7 @@ class _AdvancedPrivacySettingsBodyState ), const SizedBox(height: 25), Padding( - padding: EdgeInsets.symmetric( - horizontal: MediaQuery.of(context).size.width * 0.15), + padding: EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width * 0.15), child: Text( S.of(context).settings_can_be_changed_later, textAlign: TextAlign.center, From 9eb8a442d813ece2f9f73b11142afc30faf96721 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Sun, 4 Dec 2022 17:30:09 +0200 Subject: [PATCH 22/49] Allow setting the new added node as the current selected node --- lib/di.dart | 7 +++++-- .../new_wallet/advanced_privacy_settings_page.dart | 8 ++++---- .../node_list/node_create_or_edit_view_model.dart | 11 +++++++++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/di.dart b/lib/di.dart index 7a7621203..a5c7702d8 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -500,8 +500,11 @@ Future setup( getIt.registerFactory(() => OtherSettingsPage(getIt.get())); getIt.registerFactoryParam( - (WalletType? type, _) => - NodeCreateOrEditViewModel(_nodeSource, type ?? getIt.get().wallet!.type)); + (WalletType? type, _) => NodeCreateOrEditViewModel( + _nodeSource, + type ?? getIt.get().wallet!.type, + getIt.get(), + )); getIt.registerFactory( () => NodeCreateOrEditPage(getIt.get())); diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index e0dd1a729..ff1c83f90 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -10,9 +10,9 @@ import 'package:cake_wallet/src/widgets/primary_button.dart'; import 'package:cake_wallet/src/widgets/scollable_with_bottom_section.dart'; class AdvancedPrivacySettingsPage extends BasePage { - AdvancedPrivacySettingsPage(this.privacySettingsViewModel, this.nodeViewModel); + AdvancedPrivacySettingsPage(this.advancedPrivacySettingsViewModel, this.nodeViewModel); - final AdvancedPrivacySettingsViewModel privacySettingsViewModel; + final AdvancedPrivacySettingsViewModel advancedPrivacySettingsViewModel; final NodeCreateOrEditViewModel nodeViewModel; @override @@ -20,7 +20,7 @@ class AdvancedPrivacySettingsPage extends BasePage { @override Widget body(BuildContext context) => - AdvancedPrivacySettingsBody(privacySettingsViewModel, nodeViewModel); + AdvancedPrivacySettingsBody(advancedPrivacySettingsViewModel, nodeViewModel); } class AdvancedPrivacySettingsBody extends StatefulWidget { @@ -78,7 +78,7 @@ class _AdvancedPrivacySettingsBodyState extends State _nodeSource; + final SettingsStore _settingsStore; @action void reset() { @@ -75,13 +77,18 @@ abstract class NodeCreateOrEditViewModelBase with Store { } @action - Future save() async { + Future save({bool saveAsCurrent = false}) async { try { state = IsExecutingState(); final node = Node(uri: uri, type: _walletType, login: login, password: password, useSSL: useSSL, trusted: trusted); await _nodeSource.add(node); + + if (saveAsCurrent) { + _settingsStore.nodes[_walletType] = node; + } + state = ExecutedSuccessfullyState(); } catch (e) { state = FailureState(e.toString()); From 3aa0e626ff2e1936bed9d9bbdb248d867d68e035 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Mon, 5 Dec 2022 18:37:35 +0200 Subject: [PATCH 23/49] Pass selected currency to the view model instead of the UI --- lib/di.dart | 8 ++-- .../screens/contact/contact_list_page.dart | 23 +++++------ .../contact_list/contact_list_view_model.dart | 39 ++++++++----------- 3 files changed, 28 insertions(+), 42 deletions(-) diff --git a/lib/di.dart b/lib/di.dart index 539681036..c37f4eeac 100644 --- a/lib/di.dart +++ b/lib/di.dart @@ -459,13 +459,11 @@ Future setup( (ContactRecord? contact, _) => ContactViewModel(_contactSource, contact: contact)); - getIt.registerFactory( - () => ContactListViewModel(_contactSource, _walletInfoSource)); + getIt.registerFactoryParam( + (CryptoCurrency? cur, _) => ContactListViewModel(_contactSource, _walletInfoSource, cur)); getIt.registerFactoryParam((CryptoCurrency? cur, _) - => ContactListPage( - getIt.get(), - selectedCurrency: cur)); + => ContactListPage(getIt.get(param1: cur))); getIt.registerFactoryParam( (ContactRecord? contact, _) => diff --git a/lib/src/screens/contact/contact_list_page.dart b/lib/src/screens/contact/contact_list_page.dart index 9d0d1ab5a..7cd7a0157 100644 --- a/lib/src/screens/contact/contact_list_page.dart +++ b/lib/src/screens/contact/contact_list_page.dart @@ -9,25 +9,22 @@ import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:cake_wallet/routes.dart'; import 'package:cake_wallet/generated/i18n.dart'; -import 'package:cw_core/crypto_currency.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; import 'package:cake_wallet/src/widgets/alert_with_two_actions.dart'; import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart'; import 'package:cake_wallet/src/widgets/collapsible_standart_list.dart'; class ContactListPage extends BasePage { - ContactListPage(this.contactListViewModel, - {this.selectedCurrency}); + ContactListPage(this.contactListViewModel); final ContactListViewModel contactListViewModel; - final CryptoCurrency? selectedCurrency; @override String get title => S.current.address_book; @override Widget? trailing(BuildContext context) { - if (selectedCurrency != null) { + if (!contactListViewModel.isEditable) { return null; } @@ -66,10 +63,8 @@ class ContactListPage extends BasePage { padding: EdgeInsets.only(top: 20.0, bottom: 20.0), child: Observer( builder: (_) { - final contacts = - contactListViewModel.getContacts(selectedCurrency); - final walletContacts = - contactListViewModel.getWallets(selectedCurrency); + final contacts = contactListViewModel.contactsToShow; + final walletContacts = contactListViewModel.walletContactsToShow; return CollapsibleSectionList( context: context, sectionCount: 2, @@ -98,13 +93,13 @@ class ContactListPage extends BasePage { final contact = contacts[index]; final content = generateRaw(context, contact); - return selectedCurrency != null - ? content - : Slidable( + return contactListViewModel.isEditable + ? Slidable( key: Key('${contact.key}'), endActionPane: _actionPane(context, contact), child: content, - ); + ) + : content; }, );}) ); @@ -118,7 +113,7 @@ class ContactListPage extends BasePage { return GestureDetector( onTap: () async { - if (selectedCurrency != null) { + if (!contactListViewModel.isEditable) { Navigator.of(context).pop(contact); return; } diff --git a/lib/view_model/contact_list/contact_list_view_model.dart b/lib/view_model/contact_list/contact_list_view_model.dart index 3fa9a73a4..5b0187fc8 100644 --- a/lib/view_model/contact_list/contact_list_view_model.dart +++ b/lib/view_model/contact_list/contact_list_view_model.dart @@ -11,24 +11,22 @@ import 'package:cw_core/crypto_currency.dart'; part 'contact_list_view_model.g.dart'; -class ContactListViewModel = ContactListViewModelBase - with _$ContactListViewModel; +class ContactListViewModel = ContactListViewModelBase with _$ContactListViewModel; abstract class ContactListViewModelBase with Store { - ContactListViewModelBase(this.contactSource, this.walletInfoSource) + ContactListViewModelBase(this.contactSource, this.walletInfoSource, this._currency) : contacts = ObservableList(), walletContacts = [] { walletInfoSource.values.forEach((info) { if (info.addresses?.isNotEmpty ?? false) { info.addresses?.forEach((address, label) { - final name = label.isNotEmpty - ? info.name + ' ($label)' - : info.name; + final name = label.isNotEmpty ? info.name + ' ($label)' : info.name; walletContacts.add(WalletContact( - address, - name, - walletTypeToCryptoCurrency(info.type))); + address, + name, + walletTypeToCryptoCurrency(info.type), + )); }); } }); @@ -42,23 +40,18 @@ abstract class ContactListViewModelBase with Store { final Box walletInfoSource; final ObservableList contacts; final List walletContacts; + final CryptoCurrency? _currency; StreamSubscription? _subscription; + bool get isEditable => _currency == null; + Future delete(ContactRecord contact) async => contact.original.delete(); - List getContacts(CryptoCurrency? cur) { - if (cur != null) { - return contacts.where((element) => element.type == cur).toList(); - } + @computed + List get contactsToShow => + contacts.where((element) => _currency == null || element.type == _currency).toList(); - return contacts; - } - - List getWallets(CryptoCurrency? cur) { - if (cur != null) { - return walletContacts.where((element) => element.type == cur).toList(); - } - - return walletContacts; - } + @computed + List get walletContactsToShow => + walletContacts.where((element) => _currency == null || element.type == _currency).toList(); } From d19f7b6d3896e39cd906c08bd7eb4358df661f70 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Mon, 5 Dec 2022 18:40:53 +0200 Subject: [PATCH 24/49] Remove unused state 'denied' from authentication state [skip ci] --- lib/reactions/on_authentication_state_change.dart | 5 ----- lib/store/authentication_store.dart | 5 +---- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/lib/reactions/on_authentication_state_change.dart b/lib/reactions/on_authentication_state_change.dart index c91f5277e..edadf33b0 100644 --- a/lib/reactions/on_authentication_state_change.dart +++ b/lib/reactions/on_authentication_state_change.dart @@ -26,10 +26,5 @@ void startAuthenticationStateChange(AuthenticationStore authenticationStore, await navigatorKey.currentState!.pushNamedAndRemoveUntil(Routes.dashboard, (route) => false); return; } - - if (state == AuthenticationState.denied) { - await navigatorKey.currentState!.pushNamedAndRemoveUntil(Routes.welcome, (_) => false); - return; - } }); } diff --git a/lib/store/authentication_store.dart b/lib/store/authentication_store.dart index 626ca2a91..b734d7acb 100644 --- a/lib/store/authentication_store.dart +++ b/lib/store/authentication_store.dart @@ -4,7 +4,7 @@ part 'authentication_store.g.dart'; class AuthenticationStore = AuthenticationStoreBase with _$AuthenticationStore; -enum AuthenticationState { uninitialized, installed, allowed, denied } +enum AuthenticationState { uninitialized, installed, allowed } abstract class AuthenticationStoreBase with Store { AuthenticationStoreBase() : state = AuthenticationState.uninitialized; @@ -17,7 +17,4 @@ abstract class AuthenticationStoreBase with Store { @action void allowed() => state = AuthenticationState.allowed; - - @action - void denied() => state = AuthenticationState.denied; } From 35b7c05bc1650d41b25c3cc67385cd7b5a8caf95 Mon Sep 17 00:00:00 2001 From: Serhii Date: Tue, 6 Dec 2022 11:41:25 +0200 Subject: [PATCH 25/49] fix null check --- .../sideshift/sideshift_exchange_provider.dart | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index 8cd4593c1..23e506858 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -249,12 +249,14 @@ class SideShiftExchangeProvider extends ExchangeProvider { final expectedSendAmount = responseJSON['depositAmount'].toString(); final deposits = responseJSON['deposits'] as List?; TradeState? state; - - if (deposits != null && deposits.isEmpty) { - state = TradeState.deserialize(raw: 'created'); - } else { - final status = deposits?[0]['status'] as String; - state = TradeState.deserialize(raw: status); + + if (deposits != null) { + if (deposits.isEmpty) { + state = TradeState.deserialize(raw: 'created'); + } else { + final status = deposits[0]['status'] as String; + state = TradeState.deserialize(raw: status); + } } final expiredAtRaw = responseJSON['expiresAtISO'] as String; From 36c27026881c4bbbd957fd65cfbfb64a9c76d301 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Tue, 6 Dec 2022 13:30:11 +0200 Subject: [PATCH 26/49] - Recalculate best rate if isFixedRate changed - check limits against the receive amount if isFixedRate --- .../exchange/exchange_view_model.dart | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index b19434166..cda65527a 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -44,7 +44,6 @@ abstract class ExchangeViewModelBase with Store { ExchangeViewModelBase(this.wallet, this.trades, this._exchangeTemplateStore, this.tradesStore, this._settingsStore, this.sharedPreferences) : _cryptoNumberFormat = NumberFormat(), - isReverse = false, isFixedRateMode = false, isReceiveAmountEntered = false, depositAmount = '', @@ -112,7 +111,11 @@ abstract class ExchangeViewModelBase with Store { loadLimits(); reaction( (_) => isFixedRateMode, - (Object _) => loadLimits()); + (Object _) { + loadLimits(); + _bestRate = 0; + _calculateBestRate(); + }); } final WalletBase wallet; @@ -227,8 +230,6 @@ abstract class ExchangeViewModelBase with Store { Limits limits; - bool isReverse; - NumberFormat _cryptoNumberFormat; final SettingsStore _settingsStore; @@ -258,7 +259,6 @@ abstract class ExchangeViewModelBase with Store { @action Future changeReceiveAmount({required String amount}) async { receiveAmount = amount; - isReverse = true; if (amount.isEmpty) { depositAmount = ''; @@ -283,7 +283,6 @@ abstract class ExchangeViewModelBase with Store { @action Future changeDepositAmount({required String amount}) async { depositAmount = amount; - isReverse = false; if (amount.isEmpty) { depositAmount = ''; @@ -307,7 +306,7 @@ abstract class ExchangeViewModelBase with Store { } Future _calculateBestRate() async { - final amount = double.tryParse(isFixedRateMode ? receiveAmount : depositAmount) ?? 1; + final amount = double.tryParse(depositAmount) ?? 1; final result = await Future.wait( _tradeAvailableProviders @@ -401,7 +400,7 @@ abstract class ExchangeViewModelBase with Store { settleAddress: receiveAddress, refundAddress: depositAddress, ); - amount = depositAmount; + amount = isFixedRateMode ? receiveAmount : depositAmount; } if (provider is SimpleSwapExchangeProvider) { @@ -412,7 +411,7 @@ abstract class ExchangeViewModelBase with Store { address: receiveAddress, refundAddress: depositAddress, ); - amount = depositAmount; + amount = isFixedRateMode ? receiveAmount : depositAmount; } if (provider is XMRTOExchangeProvider) { @@ -424,7 +423,7 @@ abstract class ExchangeViewModelBase with Store { address: receiveAddress, refundAddress: depositAddress, isBTCRequest: isReceiveAmountEntered); - amount = depositAmount; + amount = isFixedRateMode ? receiveAmount : depositAmount; } if (provider is ChangeNowExchangeProvider) { @@ -435,8 +434,8 @@ abstract class ExchangeViewModelBase with Store { toAmount: receiveAmount.replaceAll(',', '.'), refundAddress: depositAddress, address: receiveAddress, - isReverse: isReverse); - amount = isReverse ? receiveAmount : depositAmount; + isReverse: isFixedRateMode); + amount = isFixedRateMode ? receiveAmount : depositAmount; } if (provider is MorphTokenExchangeProvider) { @@ -446,13 +445,13 @@ abstract class ExchangeViewModelBase with Store { amount: depositAmount.replaceAll(',', '.'), refundAddress: depositAddress, address: receiveAddress); - amount = depositAmount; + amount = isFixedRateMode ? receiveAmount : depositAmount; } amount = amount.replaceAll(',', '.'); if (limitsState is LimitsLoadedSuccessfully) { - if (double.parse(amount) < limits.min!) { + if (limits.max != null && double.parse(amount) < limits.min!) { continue; } else if (limits.max != null && double.parse(amount) > limits.max!) { continue; From 8514887da6f48262b8f5ab6aed254167bf43502b Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Tue, 6 Dec 2022 15:40:40 +0200 Subject: [PATCH 27/49] Negate is Fixed rate mode in simpleswap --- .../simpleswap/simpleswap_exchange_provider.dart | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart index c6e1baeea..0fb799cec 100644 --- a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart +++ b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart @@ -20,8 +20,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { .where((i) => i != CryptoCurrency.zaddr) .map((i) => CryptoCurrency.all .where((i) => i != CryptoCurrency.zaddr) - .map((k) => ExchangePair(from: i, to: k, reverse: true)) - .where((c) => c != null)) + .map((k) => ExchangePair(from: i, to: k, reverse: true))) .expand((i) => i) .toList()); @@ -54,12 +53,12 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { 'currency_from': fromCurrency, 'currency_to': toCurrency, 'amount': amount.toString(), - 'fixed': isFixedRateMode.toString() + 'fixed': (!isFixedRateMode).toString() }; final uri = Uri.https(apiAuthority, getEstimatePath, params); final response = await get(uri); - if (response.body == null || response.body == "null") return 0.00; + if (response.body == "null") return 0.00; final data = json.decode(response.body) as String; return double.parse(data); } catch (_) { @@ -87,7 +86,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { "currency_from": _normalizeCryptoCurrency(_request.from), "currency_to": _normalizeCryptoCurrency(_request.to), "amount": _request.amount, - "fixed": isFixedRateMode, + "fixed": !isFixedRateMode, "user_refund_address": _request.refundAddress, "address_to": _request.address }; From f29f17476c0faf16dfc169067841c9b937511d66 Mon Sep 17 00:00:00 2001 From: Serhii Date: Tue, 6 Dec 2022 17:14:07 +0200 Subject: [PATCH 28/49] add null check [skip ci] --- .../sideshift/sideshift_exchange_provider.dart | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index 23e506858..0cd74061f 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -249,15 +249,12 @@ class SideShiftExchangeProvider extends ExchangeProvider { final expectedSendAmount = responseJSON['depositAmount'].toString(); final deposits = responseJSON['deposits'] as List?; TradeState? state; - - if (deposits != null) { - if (deposits.isEmpty) { - state = TradeState.deserialize(raw: 'created'); - } else { - final status = deposits[0]['status'] as String; - state = TradeState.deserialize(raw: status); - } + String? status; + + if (deposits?.isNotEmpty ?? false) { + status = deposits![0]['status'] as String; } + state = TradeState.deserialize(raw: status ?? 'created'); final expiredAtRaw = responseJSON['expiresAtISO'] as String; final expiredAt = From fa5c705bc888abea53703ca06589e344a63d7ee8 Mon Sep 17 00:00:00 2001 From: Omar Hatem Date: Tue, 6 Dec 2022 17:29:44 +0200 Subject: [PATCH 29/49] Add nullability to `status` String [skip ci] --- lib/exchange/sideshift/sideshift_exchange_provider.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index 0cd74061f..920dc9907 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -252,7 +252,7 @@ class SideShiftExchangeProvider extends ExchangeProvider { String? status; if (deposits?.isNotEmpty ?? false) { - status = deposits![0]['status'] as String; + status = deposits![0]['status'] as String?; } state = TradeState.deserialize(raw: status ?? 'created'); From f14c01303fa08dd0a8d80571bf61e16ac990da39 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Tue, 6 Dec 2022 19:23:46 +0200 Subject: [PATCH 30/49] - Add whether this provide supports fixed rate or not - Fix Change now fixed rate exchange due to wrong rate id --- .../changenow_exchange_provider.dart | 20 +++++++++++++------ lib/exchange/exchange_provider.dart | 2 +- .../morphtoken_exchange_provider.dart | 3 +++ .../sideshift_exchange_provider.dart | 10 +++++----- .../simpleswap_exchange_provider.dart | 3 +++ .../xmrto/xmrto_exchange_provider.dart | 3 +++ .../exchange/exchange_view_model.dart | 3 ++- 7 files changed, 31 insertions(+), 13 deletions(-) diff --git a/lib/exchange/changenow/changenow_exchange_provider.dart b/lib/exchange/changenow/changenow_exchange_provider.dart index 96b6142e6..8ef376370 100644 --- a/lib/exchange/changenow/changenow_exchange_provider.dart +++ b/lib/exchange/changenow/changenow_exchange_provider.dart @@ -11,7 +11,6 @@ import 'package:cake_wallet/exchange/trade_request.dart'; import 'package:cake_wallet/exchange/trade_state.dart'; import 'package:cake_wallet/exchange/changenow/changenow_request.dart'; import 'package:cake_wallet/exchange/exchange_provider_description.dart'; -import 'package:cake_wallet/exchange/trade_not_created_exeption.dart'; class ChangeNowExchangeProvider extends ExchangeProvider { ChangeNowExchangeProvider() @@ -21,8 +20,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { .where((i) => i != CryptoCurrency.xhv) .map((i) => CryptoCurrency.all .where((i) => i != CryptoCurrency.xhv) - .map((k) => ExchangePair(from: i, to: k, reverse: true)) - .where((c) => c != null)) + .map((k) => ExchangePair(from: i, to: k, reverse: true))) .expand((i) => i) .toList()); @@ -43,6 +41,9 @@ class ChangeNowExchangeProvider extends ExchangeProvider { @override bool get isEnabled => true; + @override + bool get supportsFixedRate => true; + @override ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow; @@ -109,6 +110,15 @@ class ChangeNowExchangeProvider extends ExchangeProvider { }; if (isFixedRateMode) { + // since we schedule to calculate the rate every 5 seconds we need to ensure that + // we have the latest rate id with the given inputs before creating the trade + await calculateAmount( + from: _request.to, + to: _request.from, + amount: double.tryParse(_request.toAmount) ?? 0, + isFixedRateMode: true, + isReceiveAmount: true, + ); body['rateId'] = _lastUsedRateId; } @@ -180,9 +190,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { final extraId = responseJSON['payinExtraId'] as String; final outputTransaction = responseJSON['payoutHash'] as String; final expiredAtRaw = responseJSON['validUntil'] as String; - final expiredAt = expiredAtRaw != null - ? DateTime.parse(expiredAtRaw).toLocal() - : null; + final expiredAt = DateTime.tryParse(expiredAtRaw)?.toLocal(); return Trade( id: id, diff --git a/lib/exchange/exchange_provider.dart b/lib/exchange/exchange_provider.dart index 14fba803f..108256015 100644 --- a/lib/exchange/exchange_provider.dart +++ b/lib/exchange/exchange_provider.dart @@ -1,4 +1,3 @@ -import 'package:flutter/foundation.dart'; import 'package:cw_core/crypto_currency.dart'; import 'package:cake_wallet/exchange/trade_request.dart'; import 'package:cake_wallet/exchange/exchange_pair.dart'; @@ -14,6 +13,7 @@ abstract class ExchangeProvider { ExchangeProviderDescription get description; bool get isAvailable; bool get isEnabled; + bool get supportsFixedRate; @override String toString() => title; diff --git a/lib/exchange/morphtoken/morphtoken_exchange_provider.dart b/lib/exchange/morphtoken/morphtoken_exchange_provider.dart index 1df4fef87..6650d4f3a 100644 --- a/lib/exchange/morphtoken/morphtoken_exchange_provider.dart +++ b/lib/exchange/morphtoken/morphtoken_exchange_provider.dart @@ -66,6 +66,9 @@ class MorphTokenExchangeProvider extends ExchangeProvider { @override bool get isEnabled => true; + @override + bool get supportsFixedRate => false; + @override ExchangeProviderDescription get description => ExchangeProviderDescription.morphToken; diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index 920dc9907..b93f0a80f 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -12,7 +12,6 @@ import 'package:cw_core/crypto_currency.dart'; import 'package:cake_wallet/exchange/trade_request.dart'; import 'package:cake_wallet/exchange/trade.dart'; import 'package:cake_wallet/exchange/limits.dart'; -import 'package:flutter/foundation.dart'; import 'package:http/http.dart'; class SideShiftExchangeProvider extends ExchangeProvider { @@ -48,8 +47,7 @@ class SideShiftExchangeProvider extends ExchangeProvider { return supportedCurrencies .map((i) => supportedCurrencies - .map((k) => ExchangePair(from: i, to: k, reverse: true)) - .where((c) => c != null)) + .map((k) => ExchangePair(from: i, to: k, reverse: true))) .expand((i) => i) .toList(); } @@ -257,8 +255,7 @@ class SideShiftExchangeProvider extends ExchangeProvider { state = TradeState.deserialize(raw: status ?? 'created'); final expiredAtRaw = responseJSON['expiresAtISO'] as String; - final expiredAt = - expiredAtRaw != null ? DateTime.parse(expiredAtRaw).toLocal() : null; + final expiredAt = DateTime.tryParse(expiredAtRaw)?.toLocal(); return Trade( id: id, @@ -278,6 +275,9 @@ class SideShiftExchangeProvider extends ExchangeProvider { @override bool get isEnabled => true; + @override + bool get supportsFixedRate => true; + @override String get title => 'SideShift'; diff --git a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart index 0fb799cec..97681f0aa 100644 --- a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart +++ b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart @@ -209,6 +209,9 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { @override bool get isEnabled => true; + @override + bool get supportsFixedRate => false; + @override String get title => 'SimpleSwap'; diff --git a/lib/exchange/xmrto/xmrto_exchange_provider.dart b/lib/exchange/xmrto/xmrto_exchange_provider.dart index d5f79361e..da367e4d4 100644 --- a/lib/exchange/xmrto/xmrto_exchange_provider.dart +++ b/lib/exchange/xmrto/xmrto_exchange_provider.dart @@ -48,6 +48,9 @@ class XMRTOExchangeProvider extends ExchangeProvider { @override bool get isEnabled => true; + @override + bool get supportsFixedRate => false; + @override ExchangeProviderDescription get description => ExchangeProviderDescription.xmrto; diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index cda65527a..49ee9ea95 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -306,10 +306,11 @@ abstract class ExchangeViewModelBase with Store { } Future _calculateBestRate() async { - final amount = double.tryParse(depositAmount) ?? 1; + final amount = double.tryParse(isFixedRateMode ? receiveAmount : depositAmount) ?? 1; final result = await Future.wait( _tradeAvailableProviders + .where((element) => element.supportsFixedRate) .map((element) => element.calculateAmount( from: depositCurrency, to: receiveCurrency, From 117a8beec403cd31d6570a576fdb533b4d270619 Mon Sep 17 00:00:00 2001 From: Omar Hatem Date: Tue, 6 Dec 2022 19:40:39 +0200 Subject: [PATCH 31/49] Fix localization generation error --- res/values/strings_de.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index e90803444..dd88cc042 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -662,5 +662,5 @@ "privacy_settings": "Datenschutzeinstellungen", "privacy": "Datenschutz", "display_settings": "Anzeigeeinstellungen", - "other_settings": "Andere Einstellungen", + "other_settings": "Andere Einstellungen" } From a9f0466825247f6e2a877aac3799851adb1bd142 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Tue, 6 Dec 2022 20:10:26 +0200 Subject: [PATCH 32/49] Revert SimpleSwap changes since we disabled it for fixed rate --- lib/exchange/simpleswap/simpleswap_exchange_provider.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart index 97681f0aa..4c42835ed 100644 --- a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart +++ b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart @@ -53,7 +53,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { 'currency_from': fromCurrency, 'currency_to': toCurrency, 'amount': amount.toString(), - 'fixed': (!isFixedRateMode).toString() + 'fixed': isFixedRateMode.toString() }; final uri = Uri.https(apiAuthority, getEstimatePath, params); final response = await get(uri); @@ -86,7 +86,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { "currency_from": _normalizeCryptoCurrency(_request.from), "currency_to": _normalizeCryptoCurrency(_request.to), "amount": _request.amount, - "fixed": !isFixedRateMode, + "fixed": isFixedRateMode, "user_refund_address": _request.refundAddress, "address_to": _request.address }; From f4148e0989a00081e20ed3f08154a98e5460a5ec Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 7 Dec 2022 01:38:36 +0200 Subject: [PATCH 33/49] [skip ci] rework UI for disable fiat mode --- lib/core/backup_service.dart | 7 ++++ lib/entities/default_settings_migration.dart | 18 ++++++++- lib/entities/fiat_api_mode.dart | 39 +++++++++++++++++++ lib/entities/preferences_key.dart | 2 +- lib/src/screens/send/widgets/send_card.dart | 2 +- lib/src/screens/settings/privacy_page.dart | 13 ++++++- lib/store/settings_store.dart | 24 ++++++------ .../dashboard/balance_view_model.dart | 4 +- .../settings/privacy_settings_view_model.dart | 7 ++++ 9 files changed, 98 insertions(+), 18 deletions(-) create mode 100644 lib/entities/fiat_api_mode.dart diff --git a/lib/core/backup_service.dart b/lib/core/backup_service.dart index 999b67120..46868cf1a 100644 --- a/lib/core/backup_service.dart +++ b/lib/core/backup_service.dart @@ -214,6 +214,7 @@ class BackupService { final currentBitcoinElectrumSererId = data[PreferencesKey.currentBitcoinElectrumSererIdKey] as int?; final currentLanguageCode = data[PreferencesKey.currentLanguageCode] as String?; final displayActionListMode = data[PreferencesKey.displayActionListModeKey] as int?; + final fiatApiMode = data[PreferencesKey.currentFiatApiModeKey] as int?; final currentPinLength = data[PreferencesKey.currentPinLength] as int?; final currentTheme = data[PreferencesKey.currentTheme] as int?; final currentDefaultSettingsMigrationVersion = data[PreferencesKey.currentDefaultSettingsMigrationVersion] as int?; @@ -266,6 +267,10 @@ class BackupService { await _sharedPreferences.setInt(PreferencesKey.displayActionListModeKey, displayActionListMode); + if (fiatApiMode != null) + await _sharedPreferences.setInt(PreferencesKey.currentFiatApiModeKey, + fiatApiMode); + if (currentPinLength != null) await _sharedPreferences.setInt(PreferencesKey.currentPinLength, currentPinLength); @@ -427,6 +432,8 @@ class BackupService { _sharedPreferences.getInt(PreferencesKey.bitcoinTransactionPriority), PreferencesKey.moneroTransactionPriority: _sharedPreferences.getInt(PreferencesKey.moneroTransactionPriority), + PreferencesKey.currentFiatApiModeKey: + _sharedPreferences.getInt(PreferencesKey.currentFiatApiModeKey), }; return json.encode(preferences); diff --git a/lib/entities/default_settings_migration.dart b/lib/entities/default_settings_migration.dart index 40d26b93f..d65b4401d 100644 --- a/lib/entities/default_settings_migration.dart +++ b/lib/entities/default_settings_migration.dart @@ -20,6 +20,8 @@ import 'package:cake_wallet/exchange/trade.dart'; import 'package:encrypt/encrypt.dart' as encrypt; import 'package:collection/collection.dart'; +import 'fiat_api_mode.dart'; + const newCakeWalletMoneroUri = 'xmr-node.cakewallet.com:18081'; const cakeWalletBitcoinElectrumUri = 'electrum.cakewallet.com:50002'; const cakeWalletLitecoinElectrumUri = 'ltc-electrum.cakewallet.com:50002'; @@ -61,7 +63,9 @@ Future defaultSettingsMigration( await sharedPreferences.setInt( PreferencesKey.currentBalanceDisplayModeKey, BalanceDisplayMode.availableBalance.raw); - await sharedPreferences.setBool('disable_fiat', false); + await sharedPreferences.setInt( + PreferencesKey.currentFiatApiModeKey, + FiatApiMode.enabled.raw); await sharedPreferences.setBool('save_recipient_address', true); await resetToDefault(nodes); await changeMoneroCurrentNodeToDefault( @@ -140,6 +144,10 @@ Future defaultSettingsMigration( await addOnionNode(nodes); break; + case 19: + await updateFiatApiModes(sharedPreferences); + break; + default: break; } @@ -350,6 +358,14 @@ Future updateDisplayModes(SharedPreferences sharedPreferences) async { PreferencesKey.currentBalanceDisplayModeKey, balanceDisplayMode); } +Future updateFiatApiModes(SharedPreferences sharedPreferences) async { + final currentFiatApiMode = + sharedPreferences.getInt(PreferencesKey.currentFiatApiModeKey) ?? -1; + final fiatApiMode = currentFiatApiMode < 1 ? 2 : 1; + await sharedPreferences.setInt( + PreferencesKey.currentFiatApiModeKey, fiatApiMode); +} + Future generateBackupPassword(FlutterSecureStorage secureStorage) async { final key = generateStoreKeyFor(key: SecretStoreKey.backupPassword); diff --git a/lib/entities/fiat_api_mode.dart b/lib/entities/fiat_api_mode.dart new file mode 100644 index 000000000..615784986 --- /dev/null +++ b/lib/entities/fiat_api_mode.dart @@ -0,0 +1,39 @@ +import 'package:cake_wallet/generated/i18n.dart'; +import 'package:cw_core/enumerable_item.dart'; + +class FiatApiMode extends EnumerableItem with Serializable { + const FiatApiMode({required String title, required int raw}) : super(title: title, raw: raw); + + static const all = [FiatApiMode.enabled, FiatApiMode.torOnly, FiatApiMode.disabled]; + + static const enabled = FiatApiMode(raw: 0, title: 'Enabled'); + static const torOnly = FiatApiMode(raw: 1, title: 'Tor only'); + static const disabled = FiatApiMode(raw: 2, title: 'Disabled'); + + static FiatApiMode deserialize({required int raw}) { + switch (raw) { + case 0: + return enabled; + case 1: + return torOnly; + case 2: + return disabled; + default: + throw Exception('Unexpected token: $raw for FiatApiMode deserialize'); + } + } + + @override + String toString() { + switch (this) { + case FiatApiMode.enabled: + return 'enable'; + case FiatApiMode.torOnly: + return 'torOnly'; + case FiatApiMode.disabled: + return 'disable'; + default: + return ''; + } + } +} diff --git a/lib/entities/preferences_key.dart b/lib/entities/preferences_key.dart index 0df7981bd..7d1d75000 100644 --- a/lib/entities/preferences_key.dart +++ b/lib/entities/preferences_key.dart @@ -9,7 +9,7 @@ class PreferencesKey { static const currentTransactionPriorityKeyLegacy = 'current_fee_priority'; static const currentBalanceDisplayModeKey = 'current_balance_display_mode'; static const shouldSaveRecipientAddressKey = 'save_recipient_address'; - static const shouldDisableFiatKey = 'disable_fiat'; + static const currentFiatApiModeKey = 'current_fiat_api_mode'; static const allowBiometricalAuthenticationKey = 'allow_biometrical_authentication'; static const disableExchangeKey = 'disable_exchange'; diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index 60da5a8ea..503494c92 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -331,7 +331,7 @@ class SendCardState extends State ], ), )), - if (sendViewModel.balanceViewModel.disableFiat) + if (!sendViewModel.balanceViewModel.disableFiat) Padding( padding: const EdgeInsets.only(top: 20), child: BaseTextFormField( diff --git a/lib/src/screens/settings/privacy_page.dart b/lib/src/screens/settings/privacy_page.dart index 128d864f4..34957fa4a 100644 --- a/lib/src/screens/settings/privacy_page.dart +++ b/lib/src/screens/settings/privacy_page.dart @@ -1,9 +1,12 @@ import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; +import 'package:cake_wallet/src/screens/settings/widgets/settings_choices_cell.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; import 'package:cake_wallet/view_model/settings/privacy_settings_view_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; +import 'package:cake_wallet/view_model/settings/choices_list_item.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; class PrivacyPage extends BasePage { PrivacyPage(this._privacySettingsViewModel); @@ -18,10 +21,17 @@ class PrivacyPage extends BasePage { return Container( padding: EdgeInsets.only(top: 10), child: Observer(builder: (_) { - return Observer(builder: (_) { return Column( mainAxisSize: MainAxisSize.min, children: [ + SettingsChoicesCell( + ChoicesListItem( + title: 'Fiat api', + items: FiatApiMode.all, + selectedItem: _privacySettingsViewModel.fiatApiMode, + onItemSelected: (FiatApiMode mode) => _privacySettingsViewModel.setFiatMode(mode), + ), + ), SettingsSwitcherCell( title: S.current.disable_exchange, value: _privacySettingsViewModel.disableExchange, @@ -36,7 +46,6 @@ class PrivacyPage extends BasePage { }) ], ); - }); }), ); } diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index 1f49be479..419b03e49 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -17,8 +17,10 @@ import 'package:cake_wallet/entities/fiat_currency.dart'; import 'package:cw_core/node.dart'; import 'package:cake_wallet/monero/monero.dart'; import 'package:cake_wallet/entities/action_list_display_mode.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/.secrets.g.dart' as secrets; + part 'settings_store.g.dart'; class SettingsStore = SettingsStoreBase with _$SettingsStore; @@ -29,7 +31,7 @@ abstract class SettingsStoreBase with Store { required FiatCurrency initialFiatCurrency, required BalanceDisplayMode initialBalanceDisplayMode, required bool initialSaveRecipientAddress, - required bool initialDisableFiat, + required FiatApiMode initialFiatMode, required bool initialAllowBiometricalAuthentication, required bool initialExchangeEnabled, required ThemeBase initialTheme, @@ -48,7 +50,7 @@ abstract class SettingsStoreBase with Store { fiatCurrency = initialFiatCurrency, balanceDisplayMode = initialBalanceDisplayMode, shouldSaveRecipientAddress = initialSaveRecipientAddress, - shouldDisableFiat = initialDisableFiat, + fiatApiMode = initialFiatMode, allowBiometricalAuthentication = initialAllowBiometricalAuthentication, disableExchange = initialExchangeEnabled, currentTheme = initialTheme, @@ -92,10 +94,9 @@ abstract class SettingsStoreBase with Store { shouldSaveRecipientAddress)); reaction( - (_) => shouldDisableFiat, - (bool shouldDisableFiat) => sharedPreferences.setBool( - PreferencesKey.shouldDisableFiatKey, - shouldDisableFiat)); + (_) => fiatApiMode, + (FiatApiMode mode) => sharedPreferences.setInt( + PreferencesKey.currentFiatApiModeKey, mode.serialize())); reaction( (_) => currentTheme, @@ -148,10 +149,10 @@ abstract class SettingsStoreBase with Store { BalanceDisplayMode balanceDisplayMode; @observable - bool shouldSaveRecipientAddress; + FiatApiMode fiatApiMode; @observable - bool shouldDisableFiat; + bool shouldSaveRecipientAddress; @observable bool allowBiometricalAuthentication; @@ -234,8 +235,9 @@ abstract class SettingsStoreBase with Store { // FIX-ME: Check for which default value we should have here final shouldSaveRecipientAddress = sharedPreferences.getBool(PreferencesKey.shouldSaveRecipientAddressKey) ?? false; - final shouldDisableFiat = - sharedPreferences.getBool(PreferencesKey.shouldDisableFiatKey) ?? false; + final currentFiatApiMode = FiatApiMode.deserialize( + raw: sharedPreferences + .getInt(PreferencesKey.currentFiatApiModeKey)!); final allowBiometricalAuthentication = sharedPreferences .getBool(PreferencesKey.allowBiometricalAuthenticationKey) ?? false; @@ -303,7 +305,7 @@ abstract class SettingsStoreBase with Store { initialFiatCurrency: currentFiatCurrency, initialBalanceDisplayMode: currentBalanceDisplayMode, initialSaveRecipientAddress: shouldSaveRecipientAddress, - initialDisableFiat: shouldDisableFiat, + initialFiatMode: currentFiatApiMode, initialAllowBiometricalAuthentication: allowBiometricalAuthentication, initialExchangeEnabled: disableExchange, initialTheme: savedTheme, diff --git a/lib/view_model/dashboard/balance_view_model.dart b/lib/view_model/dashboard/balance_view_model.dart index 40502bb84..6728859da 100644 --- a/lib/view_model/dashboard/balance_view_model.dart +++ b/lib/view_model/dashboard/balance_view_model.dart @@ -1,3 +1,4 @@ +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cw_core/transaction_history.dart'; import 'package:cw_core/wallet_base.dart'; import 'package:cw_core/balance.dart'; @@ -10,7 +11,6 @@ import 'package:cake_wallet/entities/calculate_fiat_amount.dart'; import 'package:cake_wallet/store/app_store.dart'; import 'package:cake_wallet/store/settings_store.dart'; import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; -import 'package:flutter/cupertino.dart'; import 'package:mobx/mobx.dart'; part 'balance_view_model.g.dart'; @@ -72,7 +72,7 @@ abstract class BalanceViewModelBase with Store { BalanceDisplayMode get savedDisplayMode => settingsStore.balanceDisplayMode; @computed - bool get disableFiat => settingsStore.shouldDisableFiat; + bool get disableFiat => settingsStore.fiatApiMode == FiatApiMode.disabled; @computed String get asset { diff --git a/lib/view_model/settings/privacy_settings_view_model.dart b/lib/view_model/settings/privacy_settings_view_model.dart index 88311bf1f..2d8418d11 100644 --- a/lib/view_model/settings/privacy_settings_view_model.dart +++ b/lib/view_model/settings/privacy_settings_view_model.dart @@ -1,5 +1,6 @@ import 'package:cake_wallet/store/settings_store.dart'; import 'package:mobx/mobx.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; part 'privacy_settings_view_model.g.dart'; @@ -16,9 +17,15 @@ abstract class PrivacySettingsViewModelBase with Store { @computed bool get shouldSaveRecipientAddress => _settingsStore.shouldSaveRecipientAddress; + @computed + FiatApiMode get fiatApiMode => _settingsStore.fiatApiMode; + @action void setShouldSaveRecipientAddress(bool value) => _settingsStore.shouldSaveRecipientAddress = value; @action void setEnableExchange(bool value) => _settingsStore.disableExchange = value; + + @action + void setFiatMode(FiatApiMode mode) => _settingsStore.fiatApiMode = mode; } From 228e157b3992db2efbba68fe5ef4f820422d5772 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 7 Dec 2022 14:04:14 +0200 Subject: [PATCH 34/49] [skip ci] Update localization --- lib/entities/fiat_api_mode.dart | 6 +++--- lib/reactions/fiat_rate_update.dart | 3 ++- lib/src/screens/settings/privacy_page.dart | 2 +- res/values/strings_de.arb | 7 +++++-- res/values/strings_en.arb | 7 +++++-- res/values/strings_es.arb | 7 +++++-- res/values/strings_fr.arb | 7 +++++-- res/values/strings_hi.arb | 7 +++++-- res/values/strings_hr.arb | 7 +++++-- res/values/strings_it.arb | 7 +++++-- res/values/strings_ja.arb | 7 +++++-- res/values/strings_ko.arb | 7 +++++-- res/values/strings_nl.arb | 7 +++++-- res/values/strings_pl.arb | 7 +++++-- res/values/strings_pt.arb | 7 +++++-- res/values/strings_ru.arb | 7 +++++-- res/values/strings_uk.arb | 7 +++++-- res/values/strings_zh.arb | 7 +++++-- 18 files changed, 81 insertions(+), 35 deletions(-) diff --git a/lib/entities/fiat_api_mode.dart b/lib/entities/fiat_api_mode.dart index 615784986..bb16ca5a4 100644 --- a/lib/entities/fiat_api_mode.dart +++ b/lib/entities/fiat_api_mode.dart @@ -27,11 +27,11 @@ class FiatApiMode extends EnumerableItem with Serializable { String toString() { switch (this) { case FiatApiMode.enabled: - return 'enable'; + return S.current.enabled; case FiatApiMode.torOnly: - return 'torOnly'; + return S.current.tor_only; case FiatApiMode.disabled: - return 'disable'; + return S.current.disabled; default: return ''; } diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index fb40a26e3..ff10a176c 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'package:cake_wallet/core/fiat_conversion_service.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/entities/update_haven_rate.dart'; import 'package:cake_wallet/store/app_store.dart'; import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; @@ -28,7 +29,7 @@ Future startFiatRateUpdate(AppStore appStore, SettingsStore settingsStore, await updateHavenRate(fiatConversionStore); } else { fiatConversionStore.prices[appStore.wallet!.currency] = - settingsStore.shouldDisableFiat ? 0.0 + settingsStore.fiatApiMode == FiatApiMode.disabled ? 0.0 : await FiatConversionService.fetchPrice( appStore.wallet!.currency, settingsStore.fiatCurrency); } diff --git a/lib/src/screens/settings/privacy_page.dart b/lib/src/screens/settings/privacy_page.dart index 34957fa4a..a0fc280b9 100644 --- a/lib/src/screens/settings/privacy_page.dart +++ b/lib/src/screens/settings/privacy_page.dart @@ -26,7 +26,7 @@ class PrivacyPage extends BasePage { children: [ SettingsChoicesCell( ChoicesListItem( - title: 'Fiat api', + title: S.current.fiat_api, items: FiatApiMode.all, selectedItem: _privacySettingsViewModel.fiatApiMode, onItemSelected: (FiatApiMode mode) => _privacySettingsViewModel.setFiatMode(mode), diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index dd88cc042..ecbd3838e 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -654,7 +654,7 @@ "use_suggested": "Vorgeschlagen verwenden", "do_not_share_warning_text" : "Teilen Sie diese nicht mit anderen, einschließlich des Supports.\n\nSie werden Ihr Geld stehlen!", "help": "hilfe", - "disable_fiat": "Fiat deaktivieren", + "fiat_api": "Fiat API", "disable_exchange": "Exchange deaktivieren", "connection_sync": "Verbindung und Synchronisierung", "security_and_backup": "Sicherheit und Datensicherung", @@ -662,5 +662,8 @@ "privacy_settings": "Datenschutzeinstellungen", "privacy": "Datenschutz", "display_settings": "Anzeigeeinstellungen", - "other_settings": "Andere Einstellungen" + "other_settings": "Andere Einstellungen", + "disabled": "Deaktiviert", + "enabled": "Ermöglicht", + "tor_only": "Nur Tor" } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 753ad18a9..c6d71a2b1 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -654,7 +654,7 @@ "use_suggested": "Use Suggested", "do_not_share_warning_text" : "Do not share these with anyone else, including support.\n\nThey will steal your money!", "help": "help", - "disable_fiat": "Disable fiat", + "fiat_api": "Fiat API", "disable_exchange": "Disable exchange", "connection_sync": "Connection and sync", "security_and_backup": "Security and backup", @@ -662,5 +662,8 @@ "privacy_settings": "Privacy settings", "privacy": "Privacy", "display_settings": "Display settings", - "other_settings": "Other settings" + "other_settings": "Other settings", + "disabled": "Disabled", + "enabled": "Enabled", + "tor_only": "Tor only" } diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 6efcb85a0..09878ede1 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -654,7 +654,7 @@ "use_suggested": "Usar sugerido", "do_not_share_warning_text" : "No comparta estos con nadie más, incluido el soporte.\n\n¡Te robarán tu dinero!", "help": "ayuda", - "disable_fiat": "Deshabilitar fiat", + "fiat_api": "Fiat API", "disable_exchange": "Deshabilitar intercambio", "connection_sync": "Conexión y sincronización", "security_and_backup": "Seguridad y respaldo", @@ -662,5 +662,8 @@ "privacy_settings": "Configuración de privacidad", "privacy": "Privacidad", "display_settings": "Configuración de pantalla", - "other_settings": "Otras configuraciones" + "other_settings": "Otras configuraciones", + "disabled": "Desactivado", + "enabled": "Activado", + "tor_only": "solo Tor" } diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index aefe68b96..66f60af81 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -652,7 +652,7 @@ "use_suggested": "Utilisation suggérée", "do_not_share_warning_text" : "Ne les partagez avec personne d'autre, y compris avec l'assistance.\n\nIls vont voler votre argent!", "help": "aider", - "disable_fiat": "Désactiver fiat", + "fiat_api": "Fiat API", "disable_exchange": "Désactiver l'échange", "connection_sync": "Connexion et synchronisation", "security_and_backup": "Sécurité et sauvegarde", @@ -660,5 +660,8 @@ "privacy_settings": "Paramètres de confidentialité", "privacy": "Confidentialité", "display_settings": "Paramètres d'affichage", - "other_settings": "Autres paramètres" + "other_settings": "Autres paramètres", + "disabled": "Handicapé", + "enabled": "Activé", + "tor_only": "Tor uniquement" } diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index 52b46ee60..a25b649c3 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -655,12 +655,15 @@ "do_not_share_warning_text" : "इन्हें समर्थन सहित किसी और के साथ साझा न करें।\n\nवे आपका पैसा चुरा लेंगे!", "help": "मदद करना", "disable_fiat": "िएट अक्षम करें", - "disable_exchange": "एक्सचेंज अक्षम करें", + "fiat_api": "फिएट पैसे API", "connection_sync": "कनेक्शन और सिंक", "security_and_backup": "सुरक्षा और बैकअप", "create_backup": "बैकअप बनाएँ", "privacy_settings": "गोपनीयता सेटिंग्स", "privacy": "गोपनीयता", "display_settings": "प्रदर्शन सेटिंग्स", - "other_settings": "अन्य सेटिंग्स" + "other_settings": "अन्य सेटिंग्स", + "disabled": "अक्षम", + "enabled": "सक्रिय", + "tor_only": "Tor केवल" } diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index f2181bca0..e7e0ff1e4 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -654,7 +654,7 @@ "use_suggested": "Koristite predloženo", "do_not_share_warning_text" : "Nemojte ih dijeliti ni s kim, uključujući podršku.\n\nUkrast će vam novac!", "help": "pomozite", - "disable_fiat": "Isključi, fiat", + "fiat_api": "Fiat API", "disable_exchange": "Onemogući exchange", "connection_sync": "Povezivanje i sinkronizacija", "security_and_backup": "Sigurnost i sigurnosna kopija", @@ -662,5 +662,8 @@ "privacy_settings": "Postavke privatnosti", "privacy": "Privatnost", "display_settings": "Postavke zaslona", - "other_settings": "Ostale postavke" + "other_settings": "Ostale postavke", + "disabled": "Onemogućeno", + "enabled": "Omogućeno", + "tor_only": "Samo Tor" } diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index 1ec0a9d81..80a0ea1fd 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -654,7 +654,7 @@ "use_suggested": "Usa suggerito", "do_not_share_warning_text" : "Non condividerli con nessun altro, incluso il supporto.\n\nTi ruberanno i soldi!", "help": "aiuto", - "disable_fiat": "Disabilita fiat", + "fiat_api": "Fiat API", "disable_exchange": "Disabilita scambio", "connection_sync": "Connessione e sincronizzazione", "security_and_backup": "Sicurezza e backup", @@ -662,5 +662,8 @@ "privacy_settings": "Impostazioni privacy", "privacy": "Privacy", "display_settings": "Impostazioni di visualizzazione", - "other_settings": "Altre impostazioni" + "other_settings": "Altre impostazioni", + "disabled": "Disabilitato", + "enabled": "Abilitato", + "tor_only": "Solo Tor" } diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index 6fde3fc91..b38066916 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -654,7 +654,7 @@ "use_suggested": "推奨を使用", "do_not_share_warning_text" : "サポートを含め、これらを他の誰とも共有しないでください。\n\n彼らはあなたのお金を盗みます!", "help": "ヘルプ", - "disable_fiat": "フィアットを無効にする", + "fiat_api": "不換紙幣 API", "disable_exchange": "交換を無効にする", "connection_sync": "接続と同期", "security_and_backup": "セキュリティとバックアップ", @@ -662,5 +662,8 @@ "privacy_settings": "プライバシー設定", "privacy": "プライバシー", "display_settings": "表示設定", - "other_settings": "その他の設定" + "other_settings": "その他の設定", + "disabled": "無効", + "enabled": "有効", + "tor_only": "Torのみ" } diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index 4f2e7da5e..e4915cbb0 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -654,7 +654,7 @@ "use_suggested": "추천 사용", "do_not_share_warning_text" : "지원을 포함하여 다른 사람과 이러한 정보를 공유하지 마십시오.\n\n그들은 당신의 돈을 훔칠 것입니다!", "help": "돕다", - "disable_fiat": "법정화폐 비활성화", + "fiat_api": "명목 화폐 API", "disable_exchange": "교환 비활성화", "connection_sync": "연결 및 동기화", "security_and_backup": "보안 및 백업", @@ -662,5 +662,8 @@ "privacy_settings": "개인정보 설정", "privacy": "프라이버시", "display_settings": "디스플레이 설정", - "other_settings": "기타 설정" + "other_settings": "기타 설정", + "disabled": "장애가 있는", + "enabled": "사용", + "tor_only": "Tor 뿐" } diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index 25e0e1e7a..59a816602 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -654,7 +654,7 @@ "use_suggested": "Gebruik aanbevolen", "do_not_share_warning_text" : "Deel deze met niemand anders, ook niet met support.\n\nZe zullen je geld stelen!", "help": "helpen", - "disable_fiat": "법정화폐 비활성화", + "fiat_api": "Fiat API", "disable_exchange": "Uitwisseling uitschakelen", "connection_sync": "Verbinding en synchronisatie", "security_and_backup": "Beveiliging en back-up", @@ -662,5 +662,8 @@ "privacy_settings": "Privacy-instellingen", "privacy": "Privacy", "display_settings": "Weergave-instellingen", - "other_settings": "Andere instellingen" + "other_settings": "Andere instellingen", + "disabled": "Gehandicapt", + "enabled": "Ingeschakeld", + "tor_only": "Alleen Tor" } diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index db3353bad..a2dc5c8fd 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -654,7 +654,7 @@ "use_suggested": "Użyj sugerowane", "do_not_share_warning_text" : "Nie udostępniaj ich nikomu innemu, w tym wsparcia.\n\nUkradną twoje pieniądze!", "help": "pomoc", - "disable_fiat": "Wyłącz fiat", + "fiat_api": "API Fiata", "disable_exchange": "Wyłącz wymianę", "connection_sync": "Połączenie i synchronizacja", "security_and_backup": "Bezpieczeństwo i kopia zapasowa", @@ -662,5 +662,8 @@ "privacy_settings": "Ustawienia prywatności", "privacy": "Prywatność", "display_settings": "Ustawienia wyświetlania", - "other_settings": "Inne ustawienia" + "other_settings": "Inne ustawienia", + "disabled": "Wyłączone", + "enabled": "Włączony", + "tor_only": "Tylko Tor" } diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index 692dd118a..f61ac5e67 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -653,7 +653,7 @@ "use_suggested": "Uso sugerido", "do_not_share_warning_text" : "Não os compartilhe com mais ninguém, incluindo suporte.\n\nEles vão roubar seu dinheiro!", "help": "ajuda", - "disable_fiat": "Desativar fiat", + "fiat_api": "API da Fiat", "disable_exchange": "Desativar troca", "connection_sync": "Conexão e sincronização", "security_and_backup": "Segurança e backup", @@ -661,5 +661,8 @@ "privacy_settings": "Configurações de privacidade", "privacy": "Privacidade", "display_settings": "Configurações de exibição", - "other_settings": "Outras configurações" + "other_settings": "Outras configurações", + "disabled": "Desabilitado", + "enabled": "Habilitado", + "tor_only": "Tor apenas" } diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index e6c10bd2b..c44e9af35 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -654,7 +654,7 @@ "use_suggested": "Использовать предложенный", "do_not_share_warning_text" : "Не делитесь ими с кем-либо еще, в том числе со службой поддержки.\n\nОни украдут ваши деньги!", "help": "помощь", - "disable_fiat": "Отключить фиат", + "fiat_api": "Фиат API", "disable_exchange": "Отключить обмен", "connection_sync": "Подключение и синхронизация", "security_and_backup": "Безопасность и резервное копирование", @@ -662,5 +662,8 @@ "privacy_settings": "Настройки конфиденциальности", "privacy": "Конфиденциальность", "display_settings": "Настройки отображения", - "other_settings": "Другие настройки" + "other_settings": "Другие настройки", + "disabled": "Отключено", + "enabled": "Включено", + "tor_only": "Только Tor" } diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index 3013dda6a..a766641d7 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -653,7 +653,7 @@ "use_suggested": "Використати запропоноване", "do_not_share_warning_text" : "Не повідомляйте їх нікому, включно зі службою підтримки.\n\nВони вкрадуть ваші гроші!", "help": "допомога", - "disable_fiat": "Вимкнути фиат", + "fiat_api": "Фіат API", "disable_exchange": "Вимкнути exchange", "connection_sync": "Підключення та синхронізація", "security_and_backup": "Безпека та резервне копіювання", @@ -661,6 +661,9 @@ "privacy_settings": "Налаштування конфіденційності", "privacy": "Конфіденційність", "display_settings": "Налаштування дисплея", - "other_settings": "Інші налаштування" + "other_settings": "Інші налаштування", + "disabled": "Вимкнено", + "enabled": "Увімкнено", + "tor_only": "Тільки Tor" } diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index a82a3ee9d..ae5ffbea5 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -652,7 +652,7 @@ "use_suggested": "使用建议", "do_not_share_warning_text" : "不要與其他任何人分享這些內容,包括支持。\n\n他們會偷你的錢!", "help": "帮助", - "disable_fiat": "禁用法令", + "fiat_api": "法币API", "disable_exchange": "禁用交换", "connection_sync": "连接和同步", "security_and_backup": "安全和备份", @@ -660,5 +660,8 @@ "privacy_settings": "隐私设置", "privacy":"隐私", "display_settings": "显示设置", - "other_settings": "其他设置" + "other_settings": "其他设置", + "disabled": "禁用", + "enabled": "启用", + "tor_only": "仅限 Tor" } From 37ca7957560c6b30efa717bd990152cd2aeda867 Mon Sep 17 00:00:00 2001 From: Serhii Date: Wed, 7 Dec 2022 15:31:33 +0200 Subject: [PATCH 35/49] [skip ci] change fiat api UI to swich mode --- lib/src/screens/settings/privacy_page.dart | 12 +++++------- .../settings/privacy_settings_view_model.dart | 11 +++++++++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/src/screens/settings/privacy_page.dart b/lib/src/screens/settings/privacy_page.dart index a0fc280b9..c779eb316 100644 --- a/lib/src/screens/settings/privacy_page.dart +++ b/lib/src/screens/settings/privacy_page.dart @@ -24,14 +24,12 @@ class PrivacyPage extends BasePage { return Column( mainAxisSize: MainAxisSize.min, children: [ - SettingsChoicesCell( - ChoicesListItem( + SettingsSwitcherCell( title: S.current.fiat_api, - items: FiatApiMode.all, - selectedItem: _privacySettingsViewModel.fiatApiMode, - onItemSelected: (FiatApiMode mode) => _privacySettingsViewModel.setFiatMode(mode), - ), - ), + value: _privacySettingsViewModel.fiatApiMode, + onValueChange: (BuildContext context, bool value) { + _privacySettingsViewModel.setFiatMode(value); + }), SettingsSwitcherCell( title: S.current.disable_exchange, value: _privacySettingsViewModel.disableExchange, diff --git a/lib/view_model/settings/privacy_settings_view_model.dart b/lib/view_model/settings/privacy_settings_view_model.dart index 2d8418d11..b5c58a1b7 100644 --- a/lib/view_model/settings/privacy_settings_view_model.dart +++ b/lib/view_model/settings/privacy_settings_view_model.dart @@ -18,7 +18,7 @@ abstract class PrivacySettingsViewModelBase with Store { bool get shouldSaveRecipientAddress => _settingsStore.shouldSaveRecipientAddress; @computed - FiatApiMode get fiatApiMode => _settingsStore.fiatApiMode; + bool get fiatApiMode => _settingsStore.fiatApiMode == FiatApiMode.disabled; @action void setShouldSaveRecipientAddress(bool value) => _settingsStore.shouldSaveRecipientAddress = value; @@ -27,5 +27,12 @@ abstract class PrivacySettingsViewModelBase with Store { void setEnableExchange(bool value) => _settingsStore.disableExchange = value; @action - void setFiatMode(FiatApiMode mode) => _settingsStore.fiatApiMode = mode; + void setFiatMode(bool value) { + if (value) { + _settingsStore.fiatApiMode = FiatApiMode.disabled; + return; + } + _settingsStore.fiatApiMode = FiatApiMode.enabled; + } + } From 8ff8cf38b87a577df232b231a4b84ea7f7cd2cb0 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 7 Dec 2022 18:15:30 +0200 Subject: [PATCH 36/49] Check if the provider supportsFixedRate only if fixed rate is applied [skip ci] --- lib/view_model/exchange/exchange_view_model.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index 49ee9ea95..510e0ac3a 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -310,7 +310,7 @@ abstract class ExchangeViewModelBase with Store { final result = await Future.wait( _tradeAvailableProviders - .where((element) => element.supportsFixedRate) + .where((element) => !isFixedRateMode || element.supportsFixedRate) .map((element) => element.calculateAmount( from: depositCurrency, to: receiveCurrency, From 0da48f66fef74b94270ef77767c64182dbb4f08e Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Wed, 7 Dec 2022 21:09:15 +0200 Subject: [PATCH 37/49] Delegate returning rate to each provider to handle its logic internally --- .../changenow/changenow_exchange_provider.dart | 14 +++++++------- .../sideshift/sideshift_exchange_provider.dart | 4 +--- .../simpleswap/simpleswap_exchange_provider.dart | 2 +- lib/view_model/exchange/exchange_view_model.dart | 4 ++-- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/exchange/changenow/changenow_exchange_provider.dart b/lib/exchange/changenow/changenow_exchange_provider.dart index 8ef376370..ca245923f 100644 --- a/lib/exchange/changenow/changenow_exchange_provider.dart +++ b/lib/exchange/changenow/changenow_exchange_provider.dart @@ -113,8 +113,8 @@ class ChangeNowExchangeProvider extends ExchangeProvider { // since we schedule to calculate the rate every 5 seconds we need to ensure that // we have the latest rate id with the given inputs before creating the trade await calculateAmount( - from: _request.to, - to: _request.from, + from: _request.from, + to: _request.to, amount: double.tryParse(_request.toAmount) ?? 0, isFixedRateMode: true, isReceiveAmount: true, @@ -222,10 +222,10 @@ class ChangeNowExchangeProvider extends ExchangeProvider { final type = isReverse ? 'reverse' : 'direct'; final flow = getFlow(isFixedRateMode); final params = { - 'fromCurrency': isReverse ? normalizeCryptoCurrency(to) : normalizeCryptoCurrency(from), - 'toCurrency': isReverse ? normalizeCryptoCurrency(from) : normalizeCryptoCurrency(to), - 'fromNetwork': isReverse ? networkFor(to) : networkFor(from), - 'toNetwork': isReverse ? networkFor(from) : networkFor(to), + 'fromCurrency': normalizeCryptoCurrency(from), + 'toCurrency': normalizeCryptoCurrency(to), + 'fromNetwork': networkFor(from), + 'toNetwork': networkFor(to), 'type': type, 'flow': flow}; @@ -246,7 +246,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { _lastUsedRateId = rateId; } - return isReverse ? fromAmount : toAmount; + return isReverse ? (amount / fromAmount) : (toAmount / amount); } catch(e) { print(e.toString()); return 0.0; diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index b93f0a80f..912ad89c5 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -79,9 +79,7 @@ class SideShiftExchangeProvider extends ExchangeProvider { if (amount > max) return 0.00; - final estimatedAmount = rate * amount; - - return estimatedAmount; + return rate; } catch (_) { return 0.00; } diff --git a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart index 4c42835ed..0c1027000 100644 --- a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart +++ b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart @@ -60,7 +60,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { if (response.body == "null") return 0.00; final data = json.decode(response.body) as String; - return double.parse(data); + return double.parse(data) / amount; } catch (_) { return 0.00; } diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index 510e0ac3a..80551304f 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -316,7 +316,7 @@ abstract class ExchangeViewModelBase with Store { to: receiveCurrency, amount: amount, isFixedRateMode: isFixedRateMode, - isReceiveAmount: false)) + isReceiveAmount: isFixedRateMode)) ); _sortedAvailableProviders.clear(); @@ -324,7 +324,7 @@ abstract class ExchangeViewModelBase with Store { for (int i=0;i Date: Wed, 7 Dec 2022 22:07:32 +0200 Subject: [PATCH 38/49] - Make getters to ease attribute access - Add the old 'disable_fiat' translation - rename getters to be more bool like names --- lib/entities/default_settings_migration.dart | 17 ----------------- .../dashboard/widgets/transactions_page.dart | 2 +- .../exchange_trade/exchange_trade_page.dart | 5 +---- lib/src/screens/send/widgets/send_card.dart | 6 +++--- lib/src/screens/settings/privacy_page.dart | 7 ++----- lib/store/settings_store.dart | 2 +- .../dashboard/balance_view_model.dart | 10 +++++----- .../exchange/exchange_trade_view_model.dart | 4 ++-- lib/view_model/send/send_view_model.dart | 7 +++++-- .../settings/privacy_settings_view_model.dart | 2 +- res/values/strings_de.arb | 3 ++- res/values/strings_en.arb | 3 ++- res/values/strings_es.arb | 3 ++- res/values/strings_fr.arb | 3 ++- res/values/strings_hi.arb | 3 ++- res/values/strings_hr.arb | 3 ++- res/values/strings_it.arb | 3 ++- res/values/strings_ja.arb | 3 ++- res/values/strings_ko.arb | 3 ++- res/values/strings_nl.arb | 3 ++- res/values/strings_pl.arb | 3 ++- res/values/strings_pt.arb | 3 ++- res/values/strings_ru.arb | 3 ++- res/values/strings_uk.arb | 3 ++- res/values/strings_zh.arb | 3 ++- 25 files changed, 51 insertions(+), 56 deletions(-) diff --git a/lib/entities/default_settings_migration.dart b/lib/entities/default_settings_migration.dart index d65b4401d..9aff05500 100644 --- a/lib/entities/default_settings_migration.dart +++ b/lib/entities/default_settings_migration.dart @@ -20,8 +20,6 @@ import 'package:cake_wallet/exchange/trade.dart'; import 'package:encrypt/encrypt.dart' as encrypt; import 'package:collection/collection.dart'; -import 'fiat_api_mode.dart'; - const newCakeWalletMoneroUri = 'xmr-node.cakewallet.com:18081'; const cakeWalletBitcoinElectrumUri = 'electrum.cakewallet.com:50002'; const cakeWalletLitecoinElectrumUri = 'ltc-electrum.cakewallet.com:50002'; @@ -63,9 +61,6 @@ Future defaultSettingsMigration( await sharedPreferences.setInt( PreferencesKey.currentBalanceDisplayModeKey, BalanceDisplayMode.availableBalance.raw); - await sharedPreferences.setInt( - PreferencesKey.currentFiatApiModeKey, - FiatApiMode.enabled.raw); await sharedPreferences.setBool('save_recipient_address', true); await resetToDefault(nodes); await changeMoneroCurrentNodeToDefault( @@ -144,10 +139,6 @@ Future defaultSettingsMigration( await addOnionNode(nodes); break; - case 19: - await updateFiatApiModes(sharedPreferences); - break; - default: break; } @@ -358,14 +349,6 @@ Future updateDisplayModes(SharedPreferences sharedPreferences) async { PreferencesKey.currentBalanceDisplayModeKey, balanceDisplayMode); } -Future updateFiatApiModes(SharedPreferences sharedPreferences) async { - final currentFiatApiMode = - sharedPreferences.getInt(PreferencesKey.currentFiatApiModeKey) ?? -1; - final fiatApiMode = currentFiatApiMode < 1 ? 2 : 1; - await sharedPreferences.setInt( - PreferencesKey.currentFiatApiModeKey, fiatApiMode); -} - Future generateBackupPassword(FlutterSecureStorage secureStorage) async { final key = generateStoreKeyFor(key: SecretStoreKey.backupPassword); diff --git a/lib/src/screens/dashboard/widgets/transactions_page.dart b/lib/src/screens/dashboard/widgets/transactions_page.dart index 9e09bae8c..64f02c73c 100644 --- a/lib/src/screens/dashboard/widgets/transactions_page.dart +++ b/lib/src/screens/dashboard/widgets/transactions_page.dart @@ -58,7 +58,7 @@ class TransactionsPage extends StatelessWidget { .format(transaction.date), formattedAmount: item.formattedCryptoAmount, formattedFiatAmount: - dashboardViewModel.balanceViewModel.disableFiat + dashboardViewModel.balanceViewModel.isFiatDisabled ? '' : item.formattedFiatAmount, isPending: transaction.isPending)); } diff --git a/lib/src/screens/exchange_trade/exchange_trade_page.dart b/lib/src/screens/exchange_trade/exchange_trade_page.dart index 001c13ba9..7c9fc1be7 100644 --- a/lib/src/screens/exchange_trade/exchange_trade_page.dart +++ b/lib/src/screens/exchange_trade/exchange_trade_page.dart @@ -74,12 +74,9 @@ class ExchangeTradePage extends BasePage { } class ExchangeTradeForm extends StatefulWidget { - ExchangeTradeForm(this.exchangeTradeViewModel) - : disableFiat = - exchangeTradeViewModel.sendViewModel.balanceViewModel.disableFiat; + ExchangeTradeForm(this.exchangeTradeViewModel); final ExchangeTradeViewModel exchangeTradeViewModel; - final bool disableFiat; @override ExchangeTradeState createState() => ExchangeTradeState(); diff --git a/lib/src/screens/send/widgets/send_card.dart b/lib/src/screens/send/widgets/send_card.dart index 503494c92..261f5dde5 100644 --- a/lib/src/screens/send/widgets/send_card.dart +++ b/lib/src/screens/send/widgets/send_card.dart @@ -331,8 +331,8 @@ class SendCardState extends State ], ), )), - if (!sendViewModel.balanceViewModel.disableFiat) - Padding( + if (!sendViewModel.isFiatDisabled) + Padding( padding: const EdgeInsets.only(top: 20), child: BaseTextFormField( focusNode: fiatAmountFocus, @@ -438,7 +438,7 @@ class SendCardState extends State Padding( padding: EdgeInsets.only(top: 5), - child: sendViewModel.balanceViewModel.disableFiat + child: sendViewModel.isFiatDisabled ? const SizedBox(height: 14) : Text(output .estimatedFeeFiatAmount diff --git a/lib/src/screens/settings/privacy_page.dart b/lib/src/screens/settings/privacy_page.dart index c779eb316..2f15cc225 100644 --- a/lib/src/screens/settings/privacy_page.dart +++ b/lib/src/screens/settings/privacy_page.dart @@ -1,12 +1,9 @@ import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/src/screens/base_page.dart'; -import 'package:cake_wallet/src/screens/settings/widgets/settings_choices_cell.dart'; import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart'; import 'package:cake_wallet/view_model/settings/privacy_settings_view_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; -import 'package:cake_wallet/view_model/settings/choices_list_item.dart'; -import 'package:cake_wallet/entities/fiat_api_mode.dart'; class PrivacyPage extends BasePage { PrivacyPage(this._privacySettingsViewModel); @@ -25,8 +22,8 @@ class PrivacyPage extends BasePage { mainAxisSize: MainAxisSize.min, children: [ SettingsSwitcherCell( - title: S.current.fiat_api, - value: _privacySettingsViewModel.fiatApiMode, + title: S.current.disable_fiat, + value: _privacySettingsViewModel.isFiatDisabled, onValueChange: (BuildContext context, bool value) { _privacySettingsViewModel.setFiatMode(value); }), diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index 419b03e49..237846495 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -237,7 +237,7 @@ abstract class SettingsStoreBase with Store { sharedPreferences.getBool(PreferencesKey.shouldSaveRecipientAddressKey) ?? false; final currentFiatApiMode = FiatApiMode.deserialize( raw: sharedPreferences - .getInt(PreferencesKey.currentFiatApiModeKey)!); + .getInt(PreferencesKey.currentFiatApiModeKey) ?? FiatApiMode.enabled.raw); final allowBiometricalAuthentication = sharedPreferences .getBool(PreferencesKey.allowBiometricalAuthenticationKey) ?? false; diff --git a/lib/view_model/dashboard/balance_view_model.dart b/lib/view_model/dashboard/balance_view_model.dart index 6728859da..33fe01ba9 100644 --- a/lib/view_model/dashboard/balance_view_model.dart +++ b/lib/view_model/dashboard/balance_view_model.dart @@ -72,7 +72,7 @@ abstract class BalanceViewModelBase with Store { BalanceDisplayMode get savedDisplayMode => settingsStore.balanceDisplayMode; @computed - bool get disableFiat => settingsStore.fiatApiMode == FiatApiMode.disabled; + bool get isFiatDisabled => settingsStore.fiatApiMode == FiatApiMode.disabled; @computed String get asset { @@ -183,8 +183,8 @@ abstract class BalanceViewModelBase with Store { return MapEntry(key, BalanceRecord( availableBalance: '---', additionalBalance: '---', - fiatAdditionalBalance: disableFiat ? '' : '---', - fiatAvailableBalance: disableFiat ? '' : '---', + fiatAdditionalBalance: isFiatDisabled ? '' : '---', + fiatAvailableBalance: isFiatDisabled ? '' : '---', asset: key, formattedAssetTitle: _formatterAsset(key))); } @@ -195,13 +195,13 @@ abstract class BalanceViewModelBase with Store { // throw Exception('Price is null for: $key'); // } - final additionalFiatBalance = disableFiat ? '' : (fiatCurrency.toString() + final additionalFiatBalance = isFiatDisabled ? '' : (fiatCurrency.toString() + ' ' + _getFiatBalance( price: price, cryptoAmount: value.formattedAdditionalBalance)); - final availableFiatBalance = disableFiat ? '' : (fiatCurrency.toString() + final availableFiatBalance = isFiatDisabled ? '' : (fiatCurrency.toString() + ' ' + _getFiatBalance( price: price, diff --git a/lib/view_model/exchange/exchange_trade_view_model.dart b/lib/view_model/exchange/exchange_trade_view_model.dart index 133b4a228..10ddf25e4 100644 --- a/lib/view_model/exchange/exchange_trade_view_model.dart +++ b/lib/view_model/exchange/exchange_trade_view_model.dart @@ -74,13 +74,13 @@ abstract class ExchangeTradeViewModelBase with Store { @computed String get pendingTransactionFiatAmountValueFormatted => - sendViewModel.balanceViewModel.disableFiat + sendViewModel.isFiatDisabled ? '' : sendViewModel.pendingTransactionFiatAmount + ' ' + sendViewModel.fiat.title; @computed String get pendingTransactionFeeFiatAmountFormatted => - sendViewModel.balanceViewModel.disableFiat + sendViewModel.isFiatDisabled ? '' : sendViewModel.pendingTransactionFeeFiatAmount + ' ' + sendViewModel.fiat.title; diff --git a/lib/view_model/send/send_view_model.dart b/lib/view_model/send/send_view_model.dart index 096f4e9f0..fd783cf6f 100644 --- a/lib/view_model/send/send_view_model.dart +++ b/lib/view_model/send/send_view_model.dart @@ -142,14 +142,17 @@ abstract class SendViewModelBase with Store { @computed String get balance => balanceViewModel.availableBalance; + @computed + bool get isFiatDisabled => balanceViewModel.isFiatDisabled; + @computed String get pendingTransactionFiatAmountFormatted => - balanceViewModel.disableFiat ? '' : pendingTransactionFiatAmount + + isFiatDisabled ? '' : pendingTransactionFiatAmount + ' ' + fiat.title; @computed String get pendingTransactionFeeFiatAmountFormatted => - balanceViewModel.disableFiat ? '' : pendingTransactionFeeFiatAmount + + isFiatDisabled ? '' : pendingTransactionFeeFiatAmount + ' ' + fiat.title; @computed diff --git a/lib/view_model/settings/privacy_settings_view_model.dart b/lib/view_model/settings/privacy_settings_view_model.dart index b5c58a1b7..f8c3e5b50 100644 --- a/lib/view_model/settings/privacy_settings_view_model.dart +++ b/lib/view_model/settings/privacy_settings_view_model.dart @@ -18,7 +18,7 @@ abstract class PrivacySettingsViewModelBase with Store { bool get shouldSaveRecipientAddress => _settingsStore.shouldSaveRecipientAddress; @computed - bool get fiatApiMode => _settingsStore.fiatApiMode == FiatApiMode.disabled; + bool get isFiatDisabled => _settingsStore.fiatApiMode == FiatApiMode.disabled; @action void setShouldSaveRecipientAddress(bool value) => _settingsStore.shouldSaveRecipientAddress = value; diff --git a/res/values/strings_de.arb b/res/values/strings_de.arb index ecbd3838e..915e43e5d 100644 --- a/res/values/strings_de.arb +++ b/res/values/strings_de.arb @@ -654,7 +654,6 @@ "use_suggested": "Vorgeschlagen verwenden", "do_not_share_warning_text" : "Teilen Sie diese nicht mit anderen, einschließlich des Supports.\n\nSie werden Ihr Geld stehlen!", "help": "hilfe", - "fiat_api": "Fiat API", "disable_exchange": "Exchange deaktivieren", "connection_sync": "Verbindung und Synchronisierung", "security_and_backup": "Sicherheit und Datensicherung", @@ -663,6 +662,8 @@ "privacy": "Datenschutz", "display_settings": "Anzeigeeinstellungen", "other_settings": "Andere Einstellungen", + "disable_fiat": "Fiat deaktivieren", + "fiat_api": "Fiat API", "disabled": "Deaktiviert", "enabled": "Ermöglicht", "tor_only": "Nur Tor" diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index c6d71a2b1..a997b9f1f 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -654,7 +654,6 @@ "use_suggested": "Use Suggested", "do_not_share_warning_text" : "Do not share these with anyone else, including support.\n\nThey will steal your money!", "help": "help", - "fiat_api": "Fiat API", "disable_exchange": "Disable exchange", "connection_sync": "Connection and sync", "security_and_backup": "Security and backup", @@ -663,6 +662,8 @@ "privacy": "Privacy", "display_settings": "Display settings", "other_settings": "Other settings", + "disable_fiat": "Disable fiat", + "fiat_api": "Fiat API", "disabled": "Disabled", "enabled": "Enabled", "tor_only": "Tor only" diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index 09878ede1..959b2a9a2 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -654,7 +654,6 @@ "use_suggested": "Usar sugerido", "do_not_share_warning_text" : "No comparta estos con nadie más, incluido el soporte.\n\n¡Te robarán tu dinero!", "help": "ayuda", - "fiat_api": "Fiat API", "disable_exchange": "Deshabilitar intercambio", "connection_sync": "Conexión y sincronización", "security_and_backup": "Seguridad y respaldo", @@ -663,6 +662,8 @@ "privacy": "Privacidad", "display_settings": "Configuración de pantalla", "other_settings": "Otras configuraciones", + "disable_fiat": "Deshabilitar fiat", + "fiat_api": "Fiat API", "disabled": "Desactivado", "enabled": "Activado", "tor_only": "solo Tor" diff --git a/res/values/strings_fr.arb b/res/values/strings_fr.arb index 66f60af81..d82cad2f9 100644 --- a/res/values/strings_fr.arb +++ b/res/values/strings_fr.arb @@ -652,7 +652,6 @@ "use_suggested": "Utilisation suggérée", "do_not_share_warning_text" : "Ne les partagez avec personne d'autre, y compris avec l'assistance.\n\nIls vont voler votre argent!", "help": "aider", - "fiat_api": "Fiat API", "disable_exchange": "Désactiver l'échange", "connection_sync": "Connexion et synchronisation", "security_and_backup": "Sécurité et sauvegarde", @@ -661,6 +660,8 @@ "privacy": "Confidentialité", "display_settings": "Paramètres d'affichage", "other_settings": "Autres paramètres", + "disable_fiat": "Désactiver fiat", + "fiat_api": "Fiat API", "disabled": "Handicapé", "enabled": "Activé", "tor_only": "Tor uniquement" diff --git a/res/values/strings_hi.arb b/res/values/strings_hi.arb index a25b649c3..42f408229 100644 --- a/res/values/strings_hi.arb +++ b/res/values/strings_hi.arb @@ -655,7 +655,6 @@ "do_not_share_warning_text" : "इन्हें समर्थन सहित किसी और के साथ साझा न करें।\n\nवे आपका पैसा चुरा लेंगे!", "help": "मदद करना", "disable_fiat": "िएट अक्षम करें", - "fiat_api": "फिएट पैसे API", "connection_sync": "कनेक्शन और सिंक", "security_and_backup": "सुरक्षा और बैकअप", "create_backup": "बैकअप बनाएँ", @@ -663,6 +662,8 @@ "privacy": "गोपनीयता", "display_settings": "प्रदर्शन सेटिंग्स", "other_settings": "अन्य सेटिंग्स", + "disable_exchange": "एक्सचेंज अक्षम करें", + "fiat_api": "फिएट पैसे API", "disabled": "अक्षम", "enabled": "सक्रिय", "tor_only": "Tor केवल" diff --git a/res/values/strings_hr.arb b/res/values/strings_hr.arb index e7e0ff1e4..0e026e97d 100644 --- a/res/values/strings_hr.arb +++ b/res/values/strings_hr.arb @@ -654,7 +654,6 @@ "use_suggested": "Koristite predloženo", "do_not_share_warning_text" : "Nemojte ih dijeliti ni s kim, uključujući podršku.\n\nUkrast će vam novac!", "help": "pomozite", - "fiat_api": "Fiat API", "disable_exchange": "Onemogući exchange", "connection_sync": "Povezivanje i sinkronizacija", "security_and_backup": "Sigurnost i sigurnosna kopija", @@ -663,6 +662,8 @@ "privacy": "Privatnost", "display_settings": "Postavke zaslona", "other_settings": "Ostale postavke", + "disable_fiat": "Isključi, fiat", + "fiat_api": "Fiat API", "disabled": "Onemogućeno", "enabled": "Omogućeno", "tor_only": "Samo Tor" diff --git a/res/values/strings_it.arb b/res/values/strings_it.arb index 80a0ea1fd..db2a98658 100644 --- a/res/values/strings_it.arb +++ b/res/values/strings_it.arb @@ -654,7 +654,6 @@ "use_suggested": "Usa suggerito", "do_not_share_warning_text" : "Non condividerli con nessun altro, incluso il supporto.\n\nTi ruberanno i soldi!", "help": "aiuto", - "fiat_api": "Fiat API", "disable_exchange": "Disabilita scambio", "connection_sync": "Connessione e sincronizzazione", "security_and_backup": "Sicurezza e backup", @@ -663,6 +662,8 @@ "privacy": "Privacy", "display_settings": "Impostazioni di visualizzazione", "other_settings": "Altre impostazioni", + "disable_fiat": "Disabilita fiat", + "fiat_api": "Fiat API", "disabled": "Disabilitato", "enabled": "Abilitato", "tor_only": "Solo Tor" diff --git a/res/values/strings_ja.arb b/res/values/strings_ja.arb index b38066916..21fe513e9 100644 --- a/res/values/strings_ja.arb +++ b/res/values/strings_ja.arb @@ -654,7 +654,6 @@ "use_suggested": "推奨を使用", "do_not_share_warning_text" : "サポートを含め、これらを他の誰とも共有しないでください。\n\n彼らはあなたのお金を盗みます!", "help": "ヘルプ", - "fiat_api": "不換紙幣 API", "disable_exchange": "交換を無効にする", "connection_sync": "接続と同期", "security_and_backup": "セキュリティとバックアップ", @@ -663,6 +662,8 @@ "privacy": "プライバシー", "display_settings": "表示設定", "other_settings": "その他の設定", + "disable_fiat": "フィアットを無効にする", + "fiat_api": "不換紙幣 API", "disabled": "無効", "enabled": "有効", "tor_only": "Torのみ" diff --git a/res/values/strings_ko.arb b/res/values/strings_ko.arb index e4915cbb0..38f001df0 100644 --- a/res/values/strings_ko.arb +++ b/res/values/strings_ko.arb @@ -654,7 +654,6 @@ "use_suggested": "추천 사용", "do_not_share_warning_text" : "지원을 포함하여 다른 사람과 이러한 정보를 공유하지 마십시오.\n\n그들은 당신의 돈을 훔칠 것입니다!", "help": "돕다", - "fiat_api": "명목 화폐 API", "disable_exchange": "교환 비활성화", "connection_sync": "연결 및 동기화", "security_and_backup": "보안 및 백업", @@ -663,6 +662,8 @@ "privacy": "프라이버시", "display_settings": "디스플레이 설정", "other_settings": "기타 설정", + "disable_fiat": "법정화폐 비활성화", + "fiat_api": "명목 화폐 API", "disabled": "장애가 있는", "enabled": "사용", "tor_only": "Tor 뿐" diff --git a/res/values/strings_nl.arb b/res/values/strings_nl.arb index 59a816602..6283518f6 100644 --- a/res/values/strings_nl.arb +++ b/res/values/strings_nl.arb @@ -654,7 +654,6 @@ "use_suggested": "Gebruik aanbevolen", "do_not_share_warning_text" : "Deel deze met niemand anders, ook niet met support.\n\nZe zullen je geld stelen!", "help": "helpen", - "fiat_api": "Fiat API", "disable_exchange": "Uitwisseling uitschakelen", "connection_sync": "Verbinding en synchronisatie", "security_and_backup": "Beveiliging en back-up", @@ -663,6 +662,8 @@ "privacy": "Privacy", "display_settings": "Weergave-instellingen", "other_settings": "Andere instellingen", + "disable_fiat": "Schakel Fiat uit", + "fiat_api": "Fiat API", "disabled": "Gehandicapt", "enabled": "Ingeschakeld", "tor_only": "Alleen Tor" diff --git a/res/values/strings_pl.arb b/res/values/strings_pl.arb index a2dc5c8fd..e768d7d4d 100644 --- a/res/values/strings_pl.arb +++ b/res/values/strings_pl.arb @@ -654,7 +654,6 @@ "use_suggested": "Użyj sugerowane", "do_not_share_warning_text" : "Nie udostępniaj ich nikomu innemu, w tym wsparcia.\n\nUkradną twoje pieniądze!", "help": "pomoc", - "fiat_api": "API Fiata", "disable_exchange": "Wyłącz wymianę", "connection_sync": "Połączenie i synchronizacja", "security_and_backup": "Bezpieczeństwo i kopia zapasowa", @@ -663,6 +662,8 @@ "privacy": "Prywatność", "display_settings": "Ustawienia wyświetlania", "other_settings": "Inne ustawienia", + "disable_fiat": "Wyłącz fiat", + "fiat_api": "API Fiata", "disabled": "Wyłączone", "enabled": "Włączony", "tor_only": "Tylko Tor" diff --git a/res/values/strings_pt.arb b/res/values/strings_pt.arb index f61ac5e67..bd9c5e474 100644 --- a/res/values/strings_pt.arb +++ b/res/values/strings_pt.arb @@ -653,7 +653,6 @@ "use_suggested": "Uso sugerido", "do_not_share_warning_text" : "Não os compartilhe com mais ninguém, incluindo suporte.\n\nEles vão roubar seu dinheiro!", "help": "ajuda", - "fiat_api": "API da Fiat", "disable_exchange": "Desativar troca", "connection_sync": "Conexão e sincronização", "security_and_backup": "Segurança e backup", @@ -662,6 +661,8 @@ "privacy": "Privacidade", "display_settings": "Configurações de exibição", "other_settings": "Outras configurações", + "disable_fiat": "Desativar fiat", + "fiat_api": "API da Fiat", "disabled": "Desabilitado", "enabled": "Habilitado", "tor_only": "Tor apenas" diff --git a/res/values/strings_ru.arb b/res/values/strings_ru.arb index c44e9af35..8e1e0f21c 100644 --- a/res/values/strings_ru.arb +++ b/res/values/strings_ru.arb @@ -654,7 +654,6 @@ "use_suggested": "Использовать предложенный", "do_not_share_warning_text" : "Не делитесь ими с кем-либо еще, в том числе со службой поддержки.\n\nОни украдут ваши деньги!", "help": "помощь", - "fiat_api": "Фиат API", "disable_exchange": "Отключить обмен", "connection_sync": "Подключение и синхронизация", "security_and_backup": "Безопасность и резервное копирование", @@ -663,6 +662,8 @@ "privacy": "Конфиденциальность", "display_settings": "Настройки отображения", "other_settings": "Другие настройки", + "disable_fiat": "Отключить фиат", + "fiat_api": "Фиат API", "disabled": "Отключено", "enabled": "Включено", "tor_only": "Только Tor" diff --git a/res/values/strings_uk.arb b/res/values/strings_uk.arb index a766641d7..1f72c1052 100644 --- a/res/values/strings_uk.arb +++ b/res/values/strings_uk.arb @@ -653,7 +653,6 @@ "use_suggested": "Використати запропоноване", "do_not_share_warning_text" : "Не повідомляйте їх нікому, включно зі службою підтримки.\n\nВони вкрадуть ваші гроші!", "help": "допомога", - "fiat_api": "Фіат API", "disable_exchange": "Вимкнути exchange", "connection_sync": "Підключення та синхронізація", "security_and_backup": "Безпека та резервне копіювання", @@ -662,6 +661,8 @@ "privacy": "Конфіденційність", "display_settings": "Налаштування дисплея", "other_settings": "Інші налаштування", + "disable_fiat": "Вимкнути фиат", + "fiat_api": "Фіат API", "disabled": "Вимкнено", "enabled": "Увімкнено", "tor_only": "Тільки Tor" diff --git a/res/values/strings_zh.arb b/res/values/strings_zh.arb index ae5ffbea5..12655af5a 100644 --- a/res/values/strings_zh.arb +++ b/res/values/strings_zh.arb @@ -652,7 +652,6 @@ "use_suggested": "使用建议", "do_not_share_warning_text" : "不要與其他任何人分享這些內容,包括支持。\n\n他們會偷你的錢!", "help": "帮助", - "fiat_api": "法币API", "disable_exchange": "禁用交换", "connection_sync": "连接和同步", "security_and_backup": "安全和备份", @@ -661,6 +660,8 @@ "privacy":"隐私", "display_settings": "显示设置", "other_settings": "其他设置", + "disable_fiat": "禁用法令", + "fiat_api": "法币API", "disabled": "禁用", "enabled": "启用", "tor_only": "仅限 Tor" From dac0b02c7dabaaacb59d853fb8d23fe19eaace88 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 00:11:09 +0200 Subject: [PATCH 39/49] Disable updating fiat rate if the option is disabled [skip ci] --- lib/reactions/on_current_fiat_change.dart | 3 ++- lib/reactions/on_current_wallet_change.dart | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/reactions/on_current_fiat_change.dart b/lib/reactions/on_current_fiat_change.dart index 86a5ee881..5170c4576 100644 --- a/lib/reactions/on_current_fiat_change.dart +++ b/lib/reactions/on_current_fiat_change.dart @@ -1,3 +1,4 @@ +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:mobx/mobx.dart'; import 'package:cake_wallet/core/fiat_conversion_service.dart'; import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; @@ -12,7 +13,7 @@ void startCurrentFiatChangeReaction(AppStore appStore, _onCurrentFiatCurrencyChangeDisposer?.reaction.dispose(); _onCurrentFiatCurrencyChangeDisposer = reaction( (_) => settingsStore.fiatCurrency, (FiatCurrency fiatCurrency) async { - if (appStore.wallet == null) { + if (appStore.wallet == null || settingsStore.fiatApiMode == FiatApiMode.disabled) { return; } diff --git a/lib/reactions/on_current_wallet_change.dart b/lib/reactions/on_current_wallet_change.dart index cce972368..270415820 100644 --- a/lib/reactions/on_current_wallet_change.dart +++ b/lib/reactions/on_current_wallet_change.dart @@ -1,3 +1,4 @@ +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/entities/fiat_currency.dart'; import 'package:cake_wallet/entities/update_haven_rate.dart'; import 'package:cw_core/transaction_history.dart'; @@ -87,7 +88,7 @@ void startCurrentWalletChangeReaction(AppStore appStore, TransactionHistoryBase, TransactionInfo>? wallet) async { try { - if (wallet == null) { + if (wallet == null || settingsStore.fiatApiMode == FiatApiMode.disabled) { return; } From d2fe7b26e001a82a560625a891bb01f88df89353 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 00:26:19 +0200 Subject: [PATCH 40/49] Remove unused fiat_rate_update.dart [skip ci] --- lib/reactions/fiat_rate_update.dart | 40 ----------------------------- 1 file changed, 40 deletions(-) delete mode 100644 lib/reactions/fiat_rate_update.dart diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart deleted file mode 100644 index ff10a176c..000000000 --- a/lib/reactions/fiat_rate_update.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'dart:async'; -import 'package:cake_wallet/core/fiat_conversion_service.dart'; -import 'package:cake_wallet/entities/fiat_api_mode.dart'; -import 'package:cake_wallet/entities/update_haven_rate.dart'; -import 'package:cake_wallet/store/app_store.dart'; -import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; -import 'package:cake_wallet/store/settings_store.dart'; -import 'package:cw_core/wallet_type.dart'; - -Timer? _timer; - -Future startFiatRateUpdate(AppStore appStore, SettingsStore settingsStore, - FiatConversionStore fiatConversionStore) async { - if (_timer != null) { - return; - } - - if (appStore.wallet != null) { - fiatConversionStore.prices[appStore.wallet!.currency] = - await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); - } - - _timer = Timer.periodic( - Duration(seconds: 30), - (_) async { - try { - if (appStore.wallet!.type == WalletType.haven) { - await updateHavenRate(fiatConversionStore); - } else { - fiatConversionStore.prices[appStore.wallet!.currency] = - settingsStore.fiatApiMode == FiatApiMode.disabled ? 0.0 - : await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); - } - } catch(e) { - print(e); - } - }); -} From d0c22aa082b5f61ad534544afd0ecf33b286aebc Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 01:21:45 +0200 Subject: [PATCH 41/49] - Fix Change now request missing type - Only send either to or from amount depending on fixed rate - take the trade amount from the response --- lib/exchange/changenow/changenow_exchange_provider.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/exchange/changenow/changenow_exchange_provider.dart b/lib/exchange/changenow/changenow_exchange_provider.dart index ca245923f..ee49855e4 100644 --- a/lib/exchange/changenow/changenow_exchange_provider.dart +++ b/lib/exchange/changenow/changenow_exchange_provider.dart @@ -97,15 +97,17 @@ class ChangeNowExchangeProvider extends ExchangeProvider { apiHeaderKey: apiKey, 'Content-Type': 'application/json'}; final flow = getFlow(isFixedRateMode); + final type = isFixedRateMode ? 'reverse' : 'direct'; final body = { 'fromCurrency': normalizeCryptoCurrency(_request.from), 'toCurrency': normalizeCryptoCurrency(_request.to), 'fromNetwork': networkFor(_request.from), 'toNetwork': networkFor(_request.to), - 'fromAmount': _request.fromAmount, - 'toAmount': _request.toAmount, + if (!isFixedRateMode) 'fromAmount': _request.fromAmount, + if (isFixedRateMode) 'toAmount': _request.toAmount, 'address': _request.address, 'flow': flow, + 'type': type, 'refundAddress': _request.refundAddress }; @@ -151,7 +153,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { refundAddress: refundAddress, extraId: extraId, createdAt: DateTime.now(), - amount: _request.fromAmount, + amount: responseJSON['fromAmount']?.toString() ?? _request.fromAmount, state: TradeState.created); } From a1dd22232b93235dffa06d46fd81a9dba20353b9 Mon Sep 17 00:00:00 2001 From: Serhii Date: Thu, 8 Dec 2022 09:56:04 +0200 Subject: [PATCH 42/49] [skip ci] fix fiat settings display --- lib/src/screens/settings/display_settings_page.dart | 3 ++- lib/view_model/settings/display_settings_view_model.dart | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/src/screens/settings/display_settings_page.dart b/lib/src/screens/settings/display_settings_page.dart index cd413ff45..39123a7eb 100644 --- a/lib/src/screens/settings/display_settings_page.dart +++ b/lib/src/screens/settings/display_settings_page.dart @@ -34,7 +34,8 @@ class DisplaySettingsPage extends BasePage { onValueChange: (_, bool value) { _displaySettingsViewModel.setShouldDisplayBalance(value); }), - if (!isHaven) + //if (!isHaven) it does not work correctly + if(!_displaySettingsViewModel.disabledFiatApiMode) SettingsPickerCell( title: S.current.settings_currency, searchHintText: S.current.search_currency, diff --git a/lib/view_model/settings/display_settings_view_model.dart b/lib/view_model/settings/display_settings_view_model.dart index 4e73b3399..bac6d9994 100644 --- a/lib/view_model/settings/display_settings_view_model.dart +++ b/lib/view_model/settings/display_settings_view_model.dart @@ -3,6 +3,7 @@ import 'package:cake_wallet/entities/fiat_currency.dart'; import 'package:cake_wallet/store/settings_store.dart'; import 'package:cake_wallet/themes/theme_base.dart'; import 'package:mobx/mobx.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; part 'display_settings_view_model.g.dart'; @@ -30,6 +31,9 @@ abstract class DisplaySettingsViewModelBase with Store { @computed ThemeBase get theme => _settingsStore.currentTheme; + @computed + bool get disabledFiatApiMode => _settingsStore.fiatApiMode == FiatApiMode.disabled; + @action void setBalanceDisplayMode(BalanceDisplayMode value) => _settingsStore.balanceDisplayMode = value; From 6395d6b2f76a33bab65323ee4f46faf1d6dd3d72 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 14:10:58 +0200 Subject: [PATCH 43/49] - Add Disable fiat API option to advanced privacy settings --- .../advanced_privacy_settings_view_model.dart | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/lib/view_model/advanced_privacy_settings_view_model.dart b/lib/view_model/advanced_privacy_settings_view_model.dart index ef9ab878f..f800e3418 100644 --- a/lib/view_model/advanced_privacy_settings_view_model.dart +++ b/lib/view_model/advanced_privacy_settings_view_model.dart @@ -1,3 +1,4 @@ +import 'package:cake_wallet/entities/fiat_api_mode.dart'; import 'package:cake_wallet/store/settings_store.dart'; import 'package:cake_wallet/view_model/settings/switcher_list_item.dart'; import 'package:cw_core/wallet_type.dart'; @@ -11,15 +12,13 @@ class AdvancedPrivacySettingsViewModel = AdvancedPrivacySettingsViewModelBase abstract class AdvancedPrivacySettingsViewModelBase with Store { AdvancedPrivacySettingsViewModelBase(this.type, this._settingsStore) - : _disableFiat = false, - _addCustomNode = false { + : _addCustomNode = false { settings = [ - // TODO: uncomment when Disable Fiat PR is merged - // SwitcherListItem( - // title: S.current.disable_fiat, - // value: () => _disableFiat, - // onValueChange: (_, bool value) => _disableFiat = value, - // ), + SwitcherListItem( + title: S.current.disable_fiat, + value: () => _settingsStore.fiatApiMode == FiatApiMode.disabled, + onValueChange: (_, bool value) => setFiatMode(value), + ), SwitcherListItem( title: S.current.disable_exchange, value: () => _settingsStore.disableExchange, @@ -37,9 +36,6 @@ abstract class AdvancedPrivacySettingsViewModelBase with Store { late List settings; - @observable - bool _disableFiat = false; - @observable bool _addCustomNode = false; @@ -48,4 +44,13 @@ abstract class AdvancedPrivacySettingsViewModelBase with Store { @computed bool get addCustomNode => _addCustomNode; + + @action + void setFiatMode(bool value) { + if (value) { + _settingsStore.fiatApiMode = FiatApiMode.disabled; + return; + } + _settingsStore.fiatApiMode = FiatApiMode.enabled; + } } From ce19be56a05d6cb8861e103f1c8778df6256656f Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 17:23:17 +0200 Subject: [PATCH 44/49] - Fix haven and litecoin fee transaction priority issue - Revert removing fiat rate update and use it to update fiat rate periodically if Fiat API is not disabled --- lib/bitcoin/cw_bitcoin.dart | 4 ++ lib/entities/preferences_key.dart | 2 + lib/reactions/bootstrap.dart | 2 + lib/reactions/fiat_rate_update.dart | 40 +++++++++++++++ lib/store/settings_store.dart | 79 ++++++++++++++++++++--------- tool/configure.dart | 1 + 6 files changed, 104 insertions(+), 24 deletions(-) create mode 100644 lib/reactions/fiat_rate_update.dart diff --git a/lib/bitcoin/cw_bitcoin.dart b/lib/bitcoin/cw_bitcoin.dart index f224efde6..630ecf27f 100644 --- a/lib/bitcoin/cw_bitcoin.dart +++ b/lib/bitcoin/cw_bitcoin.dart @@ -51,6 +51,10 @@ class CWBitcoin extends Bitcoin { TransactionPriority deserializeBitcoinTransactionPriority(int raw) => BitcoinTransactionPriority.deserialize(raw: raw); + @override + TransactionPriority deserializeLitecoinTransactionPriority(int raw) + => LitecoinTransactionPriority.deserialize(raw: raw); + @override int getFeeRate(Object wallet, TransactionPriority priority) { final bitcoinWallet = wallet as ElectrumWallet; diff --git a/lib/entities/preferences_key.dart b/lib/entities/preferences_key.dart index 7d1d75000..6d9e93de6 100644 --- a/lib/entities/preferences_key.dart +++ b/lib/entities/preferences_key.dart @@ -22,6 +22,8 @@ class PreferencesKey { 'current_default_settings_migration_version'; static const moneroTransactionPriority = 'current_fee_priority_monero'; static const bitcoinTransactionPriority = 'current_fee_priority_bitcoin'; + static const havenTransactionPriority = 'current_fee_priority_haven'; + static const litecoinTransactionPriority = 'current_fee_priority_litecoin'; static const shouldShowReceiveWarning = 'should_show_receive_warning'; static const shouldShowYatPopup = 'should_show_yat_popup'; static const moneroWalletPasswordUpdateV1Base = 'monero_wallet_update_v1'; diff --git a/lib/reactions/bootstrap.dart b/lib/reactions/bootstrap.dart index a40a17088..4b65ed9d2 100644 --- a/lib/reactions/bootstrap.dart +++ b/lib/reactions/bootstrap.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'package:cake_wallet/reactions/fiat_rate_update.dart'; import 'package:cake_wallet/reactions/on_current_node_change.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/widgets.dart'; @@ -31,4 +32,5 @@ Future bootstrap(GlobalKey navigatorKey) async { appStore, settingsStore, fiatConversionStore); startCurrentFiatChangeReaction(appStore, settingsStore, fiatConversionStore); startOnCurrentNodeChangeReaction(appStore); + startFiatRateUpdate(appStore, settingsStore, fiatConversionStore); } diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart new file mode 100644 index 000000000..99a3bc4ae --- /dev/null +++ b/lib/reactions/fiat_rate_update.dart @@ -0,0 +1,40 @@ +import 'dart:async'; +import 'package:cake_wallet/core/fiat_conversion_service.dart'; +import 'package:cake_wallet/entities/fiat_api_mode.dart'; +import 'package:cake_wallet/entities/update_haven_rate.dart'; +import 'package:cake_wallet/store/app_store.dart'; +import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart'; +import 'package:cake_wallet/store/settings_store.dart'; +import 'package:cw_core/wallet_type.dart'; + +Timer? _timer; + +Future startFiatRateUpdate( + AppStore appStore, SettingsStore settingsStore, FiatConversionStore fiatConversionStore) async { + if (_timer != null) { + return; + } + + if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { + fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( + appStore.wallet!.currency, settingsStore.fiatCurrency); + } + + _timer = Timer.periodic(Duration(seconds: 30), (_) async { + if (settingsStore.fiatApiMode == FiatApiMode.disabled) { + return; + } + + try { + if (appStore.wallet!.type == WalletType.haven) { + await updateHavenRate(fiatConversionStore); + } else { + fiatConversionStore.prices[appStore.wallet!.currency] = + await FiatConversionService.fetchPrice( + appStore.wallet!.currency, settingsStore.fiatCurrency); + } + } catch (e) { + print(e); + } + }); +} diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index 237846495..283fff1e0 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -44,7 +44,9 @@ abstract class SettingsStoreBase with Store { required this.isBitcoinBuyEnabled, required this.actionlistDisplayMode, TransactionPriority? initialBitcoinTransactionPriority, - TransactionPriority? initialMoneroTransactionPriority}) + TransactionPriority? initialMoneroTransactionPriority, + TransactionPriority? initialHavenTransactionPriority, + TransactionPriority? initialLitecoinTransactionPriority}) : nodes = ObservableMap.of(nodes), _sharedPreferences = sharedPreferences, fiatCurrency = initialFiatCurrency, @@ -67,6 +69,14 @@ abstract class SettingsStoreBase with Store { priority[WalletType.bitcoin] = initialBitcoinTransactionPriority; } + if (initialHavenTransactionPriority != null) { + priority[WalletType.haven] = initialHavenTransactionPriority; + } + + if (initialLitecoinTransactionPriority != null) { + priority[WalletType.litecoin] = initialLitecoinTransactionPriority; + } + reaction( (_) => fiatCurrency, (FiatCurrency fiatCurrency) => sharedPreferences.setString( @@ -78,11 +88,25 @@ abstract class SettingsStoreBase with Store { .setBool(PreferencesKey.shouldShowYatPopup, shouldShowYatPopup)); priority.observe((change) { - final key = change.key == WalletType.monero - ? PreferencesKey.moneroTransactionPriority - : PreferencesKey.bitcoinTransactionPriority; + final String? key; + switch (change.key) { + case WalletType.monero: + key = PreferencesKey.moneroTransactionPriority; + break; + case WalletType.bitcoin: + key = PreferencesKey.bitcoinTransactionPriority; + break; + case WalletType.litecoin: + key = PreferencesKey.litecoinTransactionPriority; + break; + case WalletType.haven: + key = PreferencesKey.havenTransactionPriority; + break; + default: + key = null; + } - if (change.newValue != null) { + if (change.newValue != null && key != null) { sharedPreferences.setInt(key, change.newValue!.serialize()); } }); @@ -202,33 +226,39 @@ abstract class SettingsStoreBase with Store { static Future load( {required Box nodeSource, required bool isBitcoinBuyEnabled, - TransactionPriority? initialMoneroTransactionPriority, - TransactionPriority? initialBitcoinTransactionPriority, FiatCurrency initialFiatCurrency = FiatCurrency.usd, BalanceDisplayMode initialBalanceDisplayMode = BalanceDisplayMode.availableBalance}) async { - if (initialBitcoinTransactionPriority == null) { - initialBitcoinTransactionPriority = bitcoin?.getMediumTransactionPriority(); - } - - if (initialMoneroTransactionPriority == null) { - initialMoneroTransactionPriority = monero?.getDefaultTransactionPriority(); - } final sharedPreferences = await getIt.getAsync(); final currentFiatCurrency = FiatCurrency.deserialize(raw: sharedPreferences.getString(PreferencesKey.currentFiatCurrencyKey)!); - final savedMoneroTransactionPriority = + + TransactionPriority? moneroTransactionPriority = monero?.deserializeMoneroTransactionPriority( raw: sharedPreferences .getInt(PreferencesKey.moneroTransactionPriority)!); - final savedBitcoinTransactionPriority = + TransactionPriority? bitcoinTransactionPriority = bitcoin?.deserializeBitcoinTransactionPriority(sharedPreferences .getInt(PreferencesKey.bitcoinTransactionPriority)!); - final moneroTransactionPriority = - savedMoneroTransactionPriority ?? initialMoneroTransactionPriority; - final bitcoinTransactionPriority = - savedBitcoinTransactionPriority ?? initialBitcoinTransactionPriority; + + TransactionPriority? havenTransactionPriority; + TransactionPriority? litecoinTransactionPriority; + + if (sharedPreferences.getInt(PreferencesKey.havenTransactionPriority) != null) { + havenTransactionPriority = monero?.deserializeMoneroTransactionPriority( + raw: sharedPreferences.getInt(PreferencesKey.havenTransactionPriority)!); + } + if (sharedPreferences.getInt(PreferencesKey.litecoinTransactionPriority) != null) { + litecoinTransactionPriority = bitcoin?.deserializeLitecoinTransactionPriority( + sharedPreferences.getInt(PreferencesKey.litecoinTransactionPriority)!); + } + + moneroTransactionPriority ??= monero?.getDefaultTransactionPriority(); + bitcoinTransactionPriority ??= bitcoin?.getMediumTransactionPriority(); + havenTransactionPriority ??= monero?.getDefaultTransactionPriority(); + litecoinTransactionPriority ??= bitcoin?.getLitecoinTransactionPriorityMedium(); + final currentBalanceDisplayMode = BalanceDisplayMode.deserialize( raw: sharedPreferences .getInt(PreferencesKey.currentBalanceDisplayModeKey)!); @@ -249,8 +279,7 @@ abstract class SettingsStoreBase with Store { : ThemeType.bright.index; final savedTheme = ThemeList.deserialize( raw: sharedPreferences.getInt(PreferencesKey.currentTheme) ?? - legacyTheme ?? - 0); + legacyTheme); final actionListDisplayMode = ObservableList(); actionListDisplayMode.addAll(deserializeActionlistDisplayModes( sharedPreferences.getInt(PreferencesKey.displayActionListModeKey) ?? @@ -296,7 +325,7 @@ abstract class SettingsStoreBase with Store { if (havenNode != null) { nodes[WalletType.haven] = havenNode; } - + return SettingsStore( sharedPreferences: sharedPreferences, nodes: nodes, @@ -314,6 +343,8 @@ abstract class SettingsStoreBase with Store { initialLanguageCode: savedLanguageCode, initialMoneroTransactionPriority: moneroTransactionPriority, initialBitcoinTransactionPriority: bitcoinTransactionPriority, + initialHavenTransactionPriority: havenTransactionPriority, + initialLitecoinTransactionPriority: litecoinTransactionPriority, shouldShowYatPopup: shouldShowYatPopup); } @@ -326,7 +357,7 @@ abstract class SettingsStoreBase with Store { // TransactionPriority? initialBitcoinTransactionPriority, // BalanceDisplayMode initialBalanceDisplayMode = // BalanceDisplayMode.availableBalance}) async { - + // if (initialBitcoinTransactionPriority == null) { // initialBitcoinTransactionPriority = bitcoin?.getMediumTransactionPriority(); // } diff --git a/tool/configure.dart b/tool/configure.dart index 0d3d175c4..5ae5a2111 100644 --- a/tool/configure.dart +++ b/tool/configure.dart @@ -75,6 +75,7 @@ abstract class Bitcoin { List getTransactionPriorities(); List getLitecoinTransactionPriorities(); TransactionPriority deserializeBitcoinTransactionPriority(int raw); + TransactionPriority deserializeLitecoinTransactionPriority(int raw); int getFeeRate(Object wallet, TransactionPriority priority); Future generateNewAddress(Object wallet); Object createBitcoinTransactionCredentials(List outputs, {required TransactionPriority priority, int? feeRate}); From 4b1e9a10ebd84daff704f27c88bf4f8a88cafd45 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 21:14:42 +0200 Subject: [PATCH 45/49] - Rename calculateAmount to fetchRate to be more descriptive - Add Disable Exchange change reaction to save in shared prefs [skip ci] --- lib/exchange/changenow/changenow_exchange_provider.dart | 4 ++-- lib/exchange/exchange_provider.dart | 2 +- lib/exchange/morphtoken/morphtoken_exchange_provider.dart | 2 +- lib/exchange/sideshift/sideshift_exchange_provider.dart | 2 +- lib/exchange/simpleswap/simpleswap_exchange_provider.dart | 2 +- lib/exchange/xmrto/xmrto_exchange_provider.dart | 2 +- lib/store/settings_store.dart | 5 +++++ lib/view_model/exchange/exchange_view_model.dart | 2 +- 8 files changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/exchange/changenow/changenow_exchange_provider.dart b/lib/exchange/changenow/changenow_exchange_provider.dart index ee49855e4..a9fb7c9ca 100644 --- a/lib/exchange/changenow/changenow_exchange_provider.dart +++ b/lib/exchange/changenow/changenow_exchange_provider.dart @@ -114,7 +114,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { if (isFixedRateMode) { // since we schedule to calculate the rate every 5 seconds we need to ensure that // we have the latest rate id with the given inputs before creating the trade - await calculateAmount( + await fetchRate( from: _request.from, to: _request.to, amount: double.tryParse(_request.toAmount) ?? 0, @@ -208,7 +208,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { } @override - Future calculateAmount( + Future fetchRate( {required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/exchange/exchange_provider.dart b/lib/exchange/exchange_provider.dart index 108256015..763350c94 100644 --- a/lib/exchange/exchange_provider.dart +++ b/lib/exchange/exchange_provider.dart @@ -26,7 +26,7 @@ abstract class ExchangeProvider { required TradeRequest request, required bool isFixedRateMode}); Future findTradeById({required String id}); - Future calculateAmount({ + Future fetchRate({ required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/exchange/morphtoken/morphtoken_exchange_provider.dart b/lib/exchange/morphtoken/morphtoken_exchange_provider.dart index 6650d4f3a..a2a72b24f 100644 --- a/lib/exchange/morphtoken/morphtoken_exchange_provider.dart +++ b/lib/exchange/morphtoken/morphtoken_exchange_provider.dart @@ -203,7 +203,7 @@ class MorphTokenExchangeProvider extends ExchangeProvider { } @override - Future calculateAmount( + Future fetchRate( {required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/exchange/sideshift/sideshift_exchange_provider.dart b/lib/exchange/sideshift/sideshift_exchange_provider.dart index 912ad89c5..98f18f058 100644 --- a/lib/exchange/sideshift/sideshift_exchange_provider.dart +++ b/lib/exchange/sideshift/sideshift_exchange_provider.dart @@ -57,7 +57,7 @@ class SideShiftExchangeProvider extends ExchangeProvider { ExchangeProviderDescription.sideShift; @override - Future calculateAmount( + Future fetchRate( {required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart index 0c1027000..2521c1486 100644 --- a/lib/exchange/simpleswap/simpleswap_exchange_provider.dart +++ b/lib/exchange/simpleswap/simpleswap_exchange_provider.dart @@ -36,7 +36,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider { ExchangeProviderDescription.simpleSwap; @override - Future calculateAmount( + Future fetchRate( {required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/exchange/xmrto/xmrto_exchange_provider.dart b/lib/exchange/xmrto/xmrto_exchange_provider.dart index da367e4d4..536754e18 100644 --- a/lib/exchange/xmrto/xmrto_exchange_provider.dart +++ b/lib/exchange/xmrto/xmrto_exchange_provider.dart @@ -194,7 +194,7 @@ class XMRTOExchangeProvider extends ExchangeProvider { } @override - Future calculateAmount( + Future fetchRate( {required CryptoCurrency from, required CryptoCurrency to, required double amount, diff --git a/lib/store/settings_store.dart b/lib/store/settings_store.dart index 534ea67e9..e1ff316f4 100644 --- a/lib/store/settings_store.dart +++ b/lib/store/settings_store.dart @@ -115,6 +115,11 @@ abstract class SettingsStoreBase with Store { (BalanceDisplayMode mode) => sharedPreferences.setInt( PreferencesKey.currentBalanceDisplayModeKey, mode.serialize())); + reaction( + (_) => disableExchange, + (bool disableExchange) => sharedPreferences.setBool( + PreferencesKey.disableExchangeKey, disableExchange)); + this .nodes .observe((change) { diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index 80551304f..5c1f696b8 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -311,7 +311,7 @@ abstract class ExchangeViewModelBase with Store { final result = await Future.wait( _tradeAvailableProviders .where((element) => !isFixedRateMode || element.supportsFixedRate) - .map((element) => element.calculateAmount( + .map((element) => element.fetchRate( from: depositCurrency, to: receiveCurrency, amount: amount, From ae1d2a3bec79d2f3ba394232fda84db7e06fd1c2 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Thu, 8 Dec 2022 21:33:14 +0200 Subject: [PATCH 46/49] Add validation on node input in advanced privacy settings --- .../new_wallet/advanced_privacy_settings_page.dart | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart index ff1c83f90..6c2f996df 100644 --- a/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart +++ b/lib/src/screens/new_wallet/advanced_privacy_settings_page.dart @@ -78,7 +78,14 @@ class _AdvancedPrivacySettingsBodyState extends State Date: Fri, 9 Dec 2022 19:41:54 +0200 Subject: [PATCH 47/49] Separate update fiat rate in a function to enhance readability [skip ci] --- lib/reactions/fiat_rate_update.dart | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index 99a3bc4ae..70387be97 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -15,26 +15,28 @@ Future startFiatRateUpdate( return; } - if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { - fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); - } + _updateFiatRate(appStore, settingsStore, fiatConversionStore); _timer = Timer.periodic(Duration(seconds: 30), (_) async { - if (settingsStore.fiatApiMode == FiatApiMode.disabled) { - return; - } - try { if (appStore.wallet!.type == WalletType.haven) { await updateHavenRate(fiatConversionStore); } else { - fiatConversionStore.prices[appStore.wallet!.currency] = - await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); + _updateFiatRate(appStore, settingsStore, fiatConversionStore); } } catch (e) { print(e); } }); } + +void _updateFiatRate( + AppStore appStore, + SettingsStore settingsStore, + FiatConversionStore fiatConversionStore, +) async { + if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { + fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( + appStore.wallet!.currency, settingsStore.fiatCurrency); + } +} From fde1ea74de2ece5f333c7c90b75075f181f5b2b4 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Fri, 9 Dec 2022 19:55:23 +0200 Subject: [PATCH 48/49] Remove duplicate fetching for fiat rate [skip ci] --- lib/reactions/fiat_rate_update.dart | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index 70387be97..04276b567 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -15,28 +15,18 @@ Future startFiatRateUpdate( return; } - _updateFiatRate(appStore, settingsStore, fiatConversionStore); - _timer = Timer.periodic(Duration(seconds: 30), (_) async { try { if (appStore.wallet!.type == WalletType.haven) { await updateHavenRate(fiatConversionStore); } else { - _updateFiatRate(appStore, settingsStore, fiatConversionStore); + if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { + fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( + appStore.wallet!.currency, settingsStore.fiatCurrency); + } } } catch (e) { print(e); } }); } - -void _updateFiatRate( - AppStore appStore, - SettingsStore settingsStore, - FiatConversionStore fiatConversionStore, -) async { - if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { - fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); - } -} From 899e999d78d366b86cbc528c5f0f2f3df0fc2840 Mon Sep 17 00:00:00 2001 From: OmarHatem Date: Fri, 9 Dec 2022 20:04:44 +0200 Subject: [PATCH 49/49] check nullability of wallet and disable fiat api state before updating rates [skip ci] --- lib/reactions/fiat_rate_update.dart | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/reactions/fiat_rate_update.dart b/lib/reactions/fiat_rate_update.dart index 04276b567..48c61d8ca 100644 --- a/lib/reactions/fiat_rate_update.dart +++ b/lib/reactions/fiat_rate_update.dart @@ -17,13 +17,16 @@ Future startFiatRateUpdate( _timer = Timer.periodic(Duration(seconds: 30), (_) async { try { + if (appStore.wallet == null || settingsStore.fiatApiMode == FiatApiMode.disabled) { + return; + } + if (appStore.wallet!.type == WalletType.haven) { await updateHavenRate(fiatConversionStore); } else { - if (appStore.wallet != null && settingsStore.fiatApiMode == FiatApiMode.enabled) { - fiatConversionStore.prices[appStore.wallet!.currency] = await FiatConversionService.fetchPrice( - appStore.wallet!.currency, settingsStore.fiatCurrency); - } + fiatConversionStore.prices[appStore.wallet!.currency] = + await FiatConversionService.fetchPrice( + appStore.wallet!.currency, settingsStore.fiatCurrency); } } catch (e) { print(e);